⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 property.java

📁 java开源的企业总线.xmlBlaster
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
        return Double.parseDouble(str);      }      catch (Exception e) {        return defaultVal;      }   }   /**   * Try to find the given key.   * @param key the key to look for   * @param defaultVal the default value to return if key is not found   * @return The float value for the given key   */   public final float get(String key, float defaultVal) {      String str = get_(key);      if (str == null)        return defaultVal;      try {        return Float.parseFloat(str);      }      catch (Exception e) {        return defaultVal;      }   }   /**   * Try to find the given key.   * <p />   * See toBool() for a list of recognized strings.   * @param key the key to look for   * @param defaultVal the default value to return if key is not found   * @return The boolean value for the given key   */   public final boolean get(String key, boolean defaultVal) {      String str = get_(key);      if (str == null)        return defaultVal;      try {        return toBool(str);      }      catch (Exception e) {        return defaultVal;      }   }   /**   * Try to find the given key.   * <p />   * Example:   * <pre>   *   Map map = get(key, (Map)null);   *   if (map != null) {   *      ...   *   }   * </pre>   * @param key the key to look for   * @param defaultVal the default Map to return if key is not found   * @return The Map or null if not found   */   public final Map get(String key, Map defaultVal) {      Map map = getMap_(key);      if (map == null)        return defaultVal;      else        return map;   }   /**   * Try to find the given key.   * <p />   * @param key the parameter key to look for   * @return true if the property exists   */   public final boolean propertyExists(String key) {      String str = get_(key);      if (str == null)        return false;      return true;   }   /**   * Remove the given property.   * <p />   * This method does nothing if the key is not in the property hashtable.   * @param key the key to remove   * @return The removed value   */   public final String removeProperty(String key) {      String oldValue = (String)properties.remove(key);      fireChangeEvent(key, oldValue, (String)null);      return oldValue;   }   /**   * If set to true user wants you to display a usage text.   * @return true if the option '--help' or '-help' or '-h' or '-?' was given.   */   public final boolean wantsHelp() {      return wantsHelp;   }   /**   * Use this method only the first time to initialize everything.   * @param argsProps This key/value parameter array is added to the properties object (see addArgs2Props()).   * @return the initialized Properties   */   public final Properties loadProps(FileInfo info, Properties argsProps) throws XmlBlasterException {      if (properties != null) {        if (verbose>=1) System.out.println("Property: reload loadProps()");      }      // set default      properties = new Properties();      try {         // 1. Read user supplied properties file         if (info != null) {            InputStream inputStream = info.getInputStream();            if (inputStream != null) {               try {                  properties.load(inputStream);                  if (verbose>=2) System.out.println("Property: Loaded file " + propertyFileName);               } finally {                  info.closeInputStream();               }            }            else {               if (verbose>=1) System.out.println("Property: No property file given.");            }         } else {            if (verbose>=0 && propertyFileName!=null) System.err.println("Property: Please copy " + propertyFileName + " to your home directory. We continue with default settings.");         }        // 2. Read system environment, e.g. java -Dname=joe        if (scanSystemProperties == true) {         Properties env = System.getProperties();         for (Enumeration e = env.propertyNames(); e.hasMoreElements();) {            String key = (String) e.nextElement();            String value = System.getProperty(key);            properties.put(key, value);            fireChangeEvent(key, null, value);         }        }        else {           if (verbose>=1) System.out.println("Property: No system properties scanned.");         }        // 3. read user supplied String[], e.g. command line parameters        if (argsProps != null) {         addArgs2Props(properties, argsProps);        }        else {           if (verbose>=1) System.out.println("Property: No args array given.");        }        // 4. Substitute dynamic variables, e.g. ${user.dir}        if (replaceVariables == true)         replaceVariables();         // 5. Scan variables containing []        if (supportArrays == true)         scanArrays();      }      catch (IOException e) {        throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".Error", "Unable to initialize " + propertyFileName + ": " + e);      }      return properties;   }   /**     * Replace all dynamic variables, e.g. ${XY} with their values.     */   private final void replaceVariables() throws XmlBlasterException {      if (replaceVariables == false)        return;      for (Enumeration e = properties.keys(); e.hasMoreElements();) {        String key = (String) e.nextElement();        String value = get_(key);        //        // ${PROJECT_HOME} is the actual directory        // replace it with the home directory        if (value.equals("${PROJECT_HOME}")) {           properties.put(key, new File("").getAbsolutePath());        }        else {           String replaced = replaceVariable(key, value);           if (replaced != null && !replaced.equals(value)) {              properties.put(key, replaced);              fireChangeEvent(key, value, replaced);           }        }      }   }   /**     * We look for keys containing [] brackets and collect them into a map     * <pre>     *  val[A]=AAA     *  val[B]=BBB     *  ->     *   get("val", (Map)null);     *   Returns a Map containing keys { "A", "B" }     *   and values { "AAA", "BBB" }     * </pre>     * Two dimensional arrays are supported as well:     * <pre>     *   val[C][1]=cccc   -> map entry with key "C:1" and value "cccc"     * </pre>     */   private final void scanArrays() throws XmlBlasterException {      if (supportArrays == false)         return;      for (Enumeration e = properties.keys(); e.hasMoreElements();) {         String key = (String) e.nextElement();         String value = get_(key);         scanArray(key, value);      }   }   /**    * @see #scanArrays()    */   private final void scanArray(String key, String value) throws XmlBlasterException {      int posOpen = key.indexOf("[");      if (posOpen < 0)         return;      int posClose = key.indexOf("]", posOpen);      if (posClose < 0)         throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".scanArray", "Invalid array, missing closing ']' bracket for key='" + key + "'");      if (posClose <= posOpen)         throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".scanArray", "Invalid array, closing ']' bracket before '[' for key='" + key + "'");      String prefix = key.substring(0, posOpen);      Map map = getMap_(prefix);      if (map == null) {         map = new TreeMap();         /*String oldValue = (String)*/propMap.put(prefix, map);      }      String arg = key.substring(posOpen+1, posClose);      int posOpen2 = key.indexOf("[", posClose+1);      if (posOpen2 >= 0) {         int posClose2 = key.indexOf("]", posOpen2);         if (posClose2 < 0)            throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".scanArrays", "Invalid array, missing closing ']' braket for key='" + key + "'");         arg += ":";         arg += key.substring(posOpen2+1, posClose2);      }      arg = replaceVariable(key, arg);      String oldValue = (String)map.put(arg, value);      fireChangeEvent(arg, oldValue, value);   }   /**    * Notifies registered listeners when a property has changed or is created or is deleted    * If key or values are null, no event is fired    */   private void fireChangeEvent(String key, String oldValue, String newValue) {      if ( key == null || (newValue != null && newValue.equals(oldValue)) || (newValue == null && oldValue == null) ) {         return;      }      Object obj = changeListenerMap.get(key);      if ( obj != null ) {         Set listenerSet = (Set)obj;         Iterator it = listenerSet.iterator();         PropertyChangeEvent ev = new PropertyChangeEvent(key, oldValue, newValue);         while (it.hasNext()) {            I_PropertyChangeListener l = (I_PropertyChangeListener)it.next();            l.propertyChanged(ev);         }      }   }   /**     * Replace dynamic variables, e.g. ${XY} with their values.     * <p />     * The maximum replacement (nesting) depth is 50.     * @param key For logging only     * @value The value string which may contain zero to many ${...} variables     * @return The new value where all ${} are replaced.     */   private final String replaceVariable(String key, String value) throws XmlBlasterException {      value = replaceVariableWithException(key, value);      return replaceVariableNoException(key, value);   }   /**    * Replace dynamic variables, e.g. ${XY} with their values.    * <p />    * The maximum replacement (nesting) depth is 50.    * @param key For logging only    * @value The value string which may contain zero to many ${...} variables, if null we return null    * @return The new value where all ${} are replaced.    * @throws XmlBlasterException if a variable ${...} is not found of max nesting depth is reached or matching "}" is missing    */   public final String replaceVariableWithException(String key, String value) throws XmlBlasterException {      if (value == null) return null;      if (replaceVariables == false)        return value;      String origValue = value;      for (int ii = 0;; ii++) {         int from = value.indexOf("${");         if (from != -1) {            int to = value.indexOf("}", from);            if (to == -1) {               throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".InvalidVariable", "Invalid variable '" + value.substring(from) + "', expecting ${} syntax.");            }            String sub = value.substring(from, to + 1); // "${XY}"            String subKey = sub.substring(2, sub.length() - 1); // "XY"            String subValue = get_(subKey);            if (subValue == null) {               throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".UnknownVariable", "Unknown variable " + sub + "");            }            value = ReplaceVariable.replaceAll(value, sub, subValue);         }         else {            if (ii > 0 && verbose>=2) {               System.out.println("Property: Replacing '" + key + "=" + origValue + "' to '" + value + "'");            }            return value;         }         if (ii > MAX_NEST) {            throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".MaxNest", "Maximum nested depth of " + MAX_NEST + " reached for variable '" + get_(key) + "'.");         }      }   }   /**    * Replace dynamic variables, e.g. ${XY} with their values.    * <p />    * The maximum replacement (nesting) depth is 50.    * @param key For logging only    * @value The value string which may contain zero to many ${...} variables    * @return The new value where all resolvable ${} are replaced.    * @throws XmlBlasterException if matching "}" is missing    */   public final String replaceVariableNoException(String key, String value) throws XmlBlasterException {      if (replaceVariables == false)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -