📄 configcontainer.java
字号:
* @param pid * numeric protocol identifier. * @return name of the protocol that has the given id. null if no protocols * have the given id. */public String lookupPid(int pid){ if (!protocols.containsValue(pid)) return null; for (Map.Entry<String, Integer> i : protocols.entrySet()) { if (i.getValue().intValue() == pid) return i.getKey(); } // never reached but java needs it... return null;}// -------------------------------------------------------------------/** * Reads given configuration property. If not found, throws a * {@link MissingParameterException}. When creating the Class object, a * few attempts are done to resolve the classname. See * {@link Configuration} for details. * @param name * Name of configuration property */public Class getClass(String name){ try { return getClazz(name); } catch (RuntimeException e) { manageException(name, e); return null; }}private Class getClazz(String name){ String classname = config.getProperty(name); if (classname == null) { throw new MissingParameterException(name);// "\nPossibly incorrect property: " + getSimilarProperty(name)); } debug(name, classname); Class c = null; try { // Maybe classname is just a fully-qualified name c = Class.forName(classname); } catch (ClassNotFoundException e) { } if (c == null) { // Maybe classname is a non-qualified name? String fullname = ClassFinder.getQualifiedName(classname); if (fullname != null) { try { c = Class.forName(fullname); } catch (ClassNotFoundException e) { } } } if (c == null) { // Maybe there are multiple classes with the same // non-qualified name. String fullname = ClassFinder.getQualifiedName(classname); if (fullname != null) { String[] names = fullname.split(","); if (names.length > 1) { for (int i = 0; i < names.length; i++) { for (int j = i + 1; j < names.length; j++) { if (names[i].equals(names[j])) { throw new IllegalParameterException(name, "The class " + names[i] + " appears more than once in the classpath; please check" + " your classpath to avoid duplications."); } } } throw new IllegalParameterException(name, "The non-qualified class name " + classname + "corresponds to multiple fully-qualified classes:" + fullname); } } } if (c == null) { // Last attempt: maybe the fully classified name is wrong, // but the classname is correct. String shortname = ClassFinder.getShortName(classname); String fullname = ClassFinder.getQualifiedName(shortname); if (fullname != null) { throw new IllegalParameterException(name, "Class " + classname + " does not exist. Possible candidate(s): " + fullname); } } if (c == null) { throw new IllegalParameterException(name, "Class " + classname + " not found"); } return c;}// -------------------------------------------------------------------/** * Reads given configuration property. If not found, returns the default * value. * @param name * Name of configuration property * @param def * default value * @see #getClass(String) */public Class getClass(String name, Class def){ try { return Configuration.getClass(name); } catch (RuntimeException e) { manageDefault(name, def, e); return def; }}// -------------------------------------------------------------------/** * Reads given configuration property for a class name. It returns an * instance of the class. The class must implement a constructor that takes * a String as an argument. The value of this string will be <tt>name</tt>. * The constructor of the class can see the configuration so it can make * use of this name to read its own parameters from it. * @param name * Name of configuration property * @throws MissingParameterException * if the given property is not defined * @throws IllegalParameterException * if there is any problem creating the instance */public Object getInstance(String name){ try { return getInst(name); } catch (RuntimeException e) { manageException(name, e); return null; }}/** * The actual method implementing getInstance(). */private Object getInst(String name){ Class c = getClass(name); if (c == null) return null; final String classname = c.getSimpleName(); try { Class pars[] = {String.class}; Constructor cons = c.getConstructor(pars); Object objpars[] = {name}; return cons.newInstance(objpars); } catch (NoSuchMethodException e) { throw new IllegalParameterException(name, "Class " + classname + " has no " + classname + "(String) constructor"); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } else { e.getTargetException().printStackTrace(); throw new RuntimeException("" + e.getTargetException()); } } catch (Exception e) { throw new IllegalParameterException(name, e + ""); }}// -------------------------------------------------------------------/** * Reads given configuration property for a class name. It returns an * instance of the class. The class must implement a constructor that takes * a String as an argument. The value of this string will be <tt>name</tt>. * The constructor of the class can see the configuration so it can make * use of this name to read its own parameters from it. * @param name * Name of configuration property * @param def * The default object that is returned if there is no property * defined with the given name * @throws IllegalParameterException * if the given name is defined but there is a problem creating * the instance. */public Object getInstance(String name, Object def){ try { return getInst(name); } catch (RuntimeException e) { manageDefault(name, def, e); return def; }}// -------------------------------------------------------------------/** * It returns an array of class instances. The instances are constructed by * calling {@link #getInstance(String)} on the names returned by * {@link #getNames(String)}. * @param name * The component type (i.e. prefix of the list of configuration * properties) which will be passed to {@link #getNames(String)}. */public Object[] getInstanceArray(String name){ String names[] = getNames(name); Object[] result = new Object[names.length]; for (int i = 0; i < names.length; ++i) { result[i] = getInstance(names[i]); } return result;}// -------------------------------------------------------------------/** * Returns an array of names prefixed by the specified name. The array is * sorted as follows. If there is no config entry * <code>{@value peersim.config.Configuration#PAR_INCLUDE}+"."+name</code> or * <code>{@value peersim.config.Configuration#PAR_ORDER}+"."+name</code> then the order is * alphabetical. Otherwise this entry defines the order. For more * information see {@link Configuration}. * @param name * the component type (i.e., the prefix) * @return the full property names in the order specified by the * configuration */public String[] getNames(String name){ ArrayList<String> ll = new ArrayList<String>(); final String pref = name + "."; Enumeration e = config.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); if (key.startsWith(pref) && key.indexOf(".", pref.length()) < 0) ll.add(key); } String[] ret = ll.toArray(new String[ll.size()]); return order(ret, name);}// -------------------------------------------------------------------/** * The input of this method is a set of property <code>names</code> (e.g. * initializers, controls and protocols) and a string specifying the type * (prefix) of these. The output is in <code>names</code>, which will * contain a permutation of the original array. Parameter * PAR_INCLUDE+"."+type, or if not present, PAR_ORDER+"."+type is read from * the configuration. If none of them are defined then the order is * identical to that of <code>names</code>. Otherwise the configuration * entry must contain entries from <code>names</code>. It is assumed * that the entries in <code>names</code> contain only word characters * (alphanumeric and underscore '_'. The order configuration entry thus * contains a list of entries from <code>names</code> separated by any * non-word characters. * <p> * It is not required that all entries are listed. If PAR_INCLUDE is used, * then only those entries are returned that are listed. If PAR_ORDER is * used, then all names are returned, but the array will start with those * that are listed. The rest of the names follow in alphabetical order. * * * @param names * the set of property names to be searched * @param type * the string identifying the particular set of properties to be * inspected */private String[] order(String[] names, String type){ String order = getString(Configuration.PAR_INCLUDE + "." + type, null); boolean include = order != null; if (!include) order = getString(Configuration.PAR_ORDER + "." + type, null); int i = 0; if (order != null && !order.equals("")) { // split around non-word characters String[] sret = order.split("\\W+"); for (; i < sret.length; i++) { int j = i; for (; j < names.length; ++j) if (names[j].equals(type + "." + sret[i])) break; if (j == names.length) { throw new IllegalParameterException( (include ? Configuration.PAR_INCLUDE : Configuration.PAR_ORDER) + "." + type, type + "." + sret[i] + " is not defined."); } else // swap the element to current position { String tmps = names[j]; names[j] = names[i]; names[i] = tmps; } } } Arrays.sort(names, i, names.length); int retsize = (include ? i : names.length); String[] ret = new String[retsize]; for (int j = 0; j < retsize; ++j) ret[j] = names[j]; return ret;}// -------------------------------------------------------------------/** * Print debug information for configuration. The amount of information * depends on the debug level DEBUG. 0 = nothing 1 = just the config name 2 = * config name plus method calling * * @param name */private void debug(String name, String result){ if (debugLevel == DEBUG_NO) return; StringBuffer buffer = new StringBuffer(); buffer.append("DEBUG "); buffer.append(name); buffer.append(" = "); buffer.append(result); // Additional info if (debugLevel == DEBUG_CONTEXT) { buffer.append("\n at "); // Obtain the stack trace StackTraceElement[] stack = null; try { throw new Exception(); } catch (Exception e) { stack = e.getStackTrace(); } // Search the element that invoked Configuration // It's the first whose class is different from Configuration int pos; for (pos = 0; pos < stack.length; pos++) { if (!stack[pos].getClassName().equals(Configuration.class.getName())) break; } buffer.append(stack[pos].getClassName()); buffer.append(":"); buffer.append(stack[pos].getLineNumber()); buffer.append(", method "); buffer.append(stack[pos - 1].getMethodName()); buffer.append("()"); } System.err.println(buffer);}// -------------------------------------------------------------------/** * @return an array of adjacent letter pairs contained in the input string * http://www.catalysoft.com/articles/StrikeAMatch.html */private String[] letterPairs(String str){ int numPairs = str.length() - 1; String[] pairs = new String[numPairs]; for (int i = 0; i < numPairs; i++) { pairs[i] = str.substring(i, i + 2); } return pairs;}// -------------------------------------------------------------------/** * @return an ArrayList of 2-character Strings. * http://www.catalysoft.com/articles/StrikeAMatch.html */private ArrayList<String> wordLetterPairs(String str){ ArrayList<String> allPairs = new ArrayList<String>(); // Tokenize the string and put the tokens/words into an array String[] words = str.split("\\s"); // For each word for (int w = 0; w < words.length; w++) { // Find the pairs of characters String[] pairsInWord = letterPairs(words[w]); for (int p = 0; p < pairsInWord.length; p++) { allPairs.add(pairsInWord[p]); } } return allPairs;}// -------------------------------------------------------------------/** * @return lexical similarity value in the range [0,1] * http://www.catalysoft.com/articles/StrikeAMatch.html */private double compareStrings(String str1, String str2){ ArrayList pairs1 = wordLetterPairs(str1.toUpperCase()); ArrayList pairs2 = wordLetterPairs(str2.toUpperCase()); int intersection = 0; int union_ = pairs1.size() + pairs2.size(); for (int i = 0; i < pairs1.size(); i++) { Object pair1 = pairs1.get(i); for (int j = 0; j < pairs2.size(); j++) { Object pair2 = pairs2.get(j); if (pair1.equals(pair2)) { intersection++; pairs2.remove(j); break; } } } return (2.0 * intersection) / union_;}// -------------------------------------------------------------------/** * Among the defined properties, returns the one more similar to String * property */private String getSimilarProperty(String property){ String bestProperty = null; double bestValue = 0.0; Enumeration e = config.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); double compare = compareStrings(key, property); if (compare > bestValue) { bestValue = compare; bestProperty = key; } } return bestProperty;}//-------------------------------------------------------------------private void manageDefault(String name, Object def, RuntimeException e){ debug(name, "" + def + " (DEFAULT)"); if (check) { System.out.println("Warning: Property " + name + " = " + def + " (DEFAULT)"); } if (e instanceof MissingParameterException) { // Do nothing } else { manageException(name, e); }}//-------------------------------------------------------------------private void manageException(String name, RuntimeException e){ if (check) { if (e instanceof MissingParameterException) { // Print just the short message in this case System.out.println("Error: " + ((MissingParameterException) e).getShortMessage()); } else if (e instanceof IllegalParameterException) { // Print just the short message in this case System.out.println("Error: " + ((IllegalParameterException) e).getShortMessage()); } else { System.out.println("Error: " + e.getMessage()); } } else { throw e; }}//-------------------------------------------------------------------}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -