📄 property.java
字号:
for (int ii = 0; ii < args.length; ii++) { String arg = args[ii]; if (arg != null && arg.startsWith("-")) { // only parameters starting with "-" are recognized String key = arg; if (arg.equals("--help") || arg.equals("-?") || arg.equals("-h") || arg.equals("-help")) { if (props == null) props = new Properties(); props.put("---help", "true"); continue; // ignore } if (arg.startsWith("--")) key = arg.substring(2); // strip "--" else if (arg.startsWith("-")) key = arg.substring(1); // strip "-" if (key.length() < 1) { throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".Invalid", "Ignoring argument <" + arg + ">."); } if ((ii + 1) >= args.length) { // System.err.println("Property: The property '" + arg + "' has no value"); throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".MissingValue", "The property '" + arg + "' has no value."); } String arg2 = args[ii + 1]; if (arg2 == null) arg2 = ""; if (props == null) props = new Properties(); //if (key.equals("property.verbose")) { // try { verbose = Integer.parseInt(arg2.trim()); } catch(NumberFormatException e) { System.err.println("-property.verbose expects a number"); } //} props.put(key, arg2); ii++; // System.out.println("Property: Setting command line argument " + key + " with value " + arg2); } else { throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, ME + ".Invalid", "Ignoring unknown argument <" + arg + ">, it should start with '-'."); } } return props; } /** * Listen on change or creation events of the given key. * Note that no initial event is sent. * @return The listener you provided (nice if it is an anonymous class) */ public final I_PropertyChangeListener addPropertyChangeListener(String key, I_PropertyChangeListener l) { return addPropertyChangeListener(key, null, l); } /** * Listen on change or creation events of the given key * @param defaultValue If not null an initial event is sent: If the property is known its value is used else the defaultValue is used. * The defaultValue is not stored in this case, only bounced back. * @return The listener you provided (nice if it is an anonymous class) */ public final I_PropertyChangeListener addPropertyChangeListener(String key, String defaultValue, I_PropertyChangeListener l) { if (key == null || l == null) { throw new IllegalArgumentException("addPropertyChangeListener got illegal arguments key=" + key); } Object o = changeListenerMap.get(key); if (o == null) { o = new HashSet(); changeListenerMap.put(key, o); } Set listenerSet = (HashSet)o; listenerSet.add(l); if (defaultValue != null) { // wants initial notification String value = get_(key); l.propertyChanged(new PropertyChangeEvent(key, value, (value==null)?defaultValue:value )); } return l; } /** * Listen on change or creation events of the given key * @param l If null all listeners are removed */ public final void removePropertyChangeListener(String key, I_PropertyChangeListener l) { if (key == null) { throw new IllegalArgumentException("removePropertyChangeListener got illegal arguments key=" + key); } Object o = changeListenerMap.get(key); if (o != null) { Set listenerSet = (Set)o; if (l != null) { listenerSet.remove(l); } else { listenerSet.clear(); } if ( listenerSet.size() < 1 ) { changeListenerMap.remove(key); } } } public String toXml() { return toXml((String)null); } /** * Dump all properties to xml representation. */ public String toXml(String extraOffset) { StringBuffer sb = new StringBuffer(5000); if (extraOffset == null) extraOffset = ""; String offset = "\n " + extraOffset; sb.append(offset).append("<Property>"); for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = (String)properties.get(key); // Avoid illegal characters in tag name: if (key.indexOf("[") != -1) continue; // Will be dumped later in <arrays> section key = org.xmlBlaster.util.ReplaceVariable.replaceAll(key, "/", "."); sb.append(offset).append(" <"); sb.append(key).append(">"); sb.append(org.xmlBlaster.util.ReplaceVariable.replaceAll(value, "<", "<")); sb.append("</").append(key).append(">"); } if (propMap != null) { Iterator it = propMap.keySet().iterator(); sb.append(offset).append(" <arrays>"); while (it.hasNext()) { String key = (String) it.next(); Map map = get(key, (Map)null); key = org.xmlBlaster.util.ReplaceVariable.replaceAll(key, "/", "."); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { String arg = (String) iter.next(); sb.append(offset).append(" <").append(key).append(" index='").append(arg).append("'>"); sb.append(org.xmlBlaster.util.ReplaceVariable.replaceAll((String)map.get(arg), "<", "<")); sb.append("</").append(key).append(">"); } } sb.append(offset).append(" </arrays>"); } sb.append(offset).append("</Property>"); return sb.toString(); }/*** For testing only* <p />* <pre>* java -Djava.compiler= org.xmlBlaster.util.property.Property -Persistence.Driver myDriver -isCool true -xml "<hello>world</hello>"* java -Djava.compiler= org.xmlBlaster.util.property.Property -dump true -uu "You are the user \${user.name}" -double "\${uu} using \${java.vm.name}"* java -Djava.compiler= org.xmlBlaster.util.property.Property -NameList Josua,David,Ken,Abel* java -Djava.compiler= org.xmlBlaster.util.property.Property -urlVariant true -url http://localhost/xy.properties* java -Djava.compiler= org.xmlBlaster.util.property.Property -hashVariant true* java -Djava.compiler= org.xmlBlaster.util.property.Property -dump true -val[A] aaaa -val[B] bbbb -val[C][1] cccc -val[C][2] c2c2* </pre>*/public static void main(String args[]) { try { boolean dump = Args.getArg(args, "-dump", false); if (dump) { Property props = new Property("jutils-test.properties", true, args, true); // initialize System.out.println(props.toXml()); } } catch (Exception e) { System.err.println(e.toString()); } try { boolean testClasspathProperties = Args.getArg(args, "-testClasspathProperties", false); if (testClasspathProperties) { Property props = new Property("jutils-test.properties", true, args, true); // initialize System.out.println("data=" + props.get("data", "ERROR")); props.saveProps(); } } catch (Exception e) { System.err.println(e.toString()); } try { boolean testSetArray = Args.getArg(args, "-testSetArray", false); if (testSetArray) { Property props = new Property(null, true, args, true); // initialize props.set("Array[a][b]", "arrayvalue"); System.out.println(props.toXml()); System.exit(0); } } catch (Exception e) { System.err.println(e.toString()); } try { boolean urlVariant = Args.getArg(args, "-urlVariant", false); if (urlVariant) { { System.out.println("*** Test 1"); Property props = new Property(null, true, (Applet) null, true); // initialize System.out.println("TestVariable=" + props.get("TestVariable", "ERROR")); System.out.println("java.home=" + props.get("java.home", "ERROR")); } { System.out.println("*** Test 2"); String url = Args.getArg(args, "-url", "http://localhost/xy.properties"); Property props = new Property(url, true, (Applet) null, true); // initialize System.out.println("TestVariable=" + props.get("TestVariable", "ERROR")); System.out.println("java.home=" + props.get("java.home", "ERROR")); } System.exit(0); } } catch (XmlBlasterException e) { //System.err.println(e.toXml(true)); System.err.println(e.toString()); System.exit(0); } try { boolean hashVariant = Args.getArg(args, "-hashVariant", false); if (hashVariant) { { System.out.println("*** Test 1"); Properties extra = new Properties(); extra.put("city", "Auckland"); extra.put("country", "NewZealand"); Property props = new Property(null, true, extra, true); // initialize System.out.println("city=" + props.get("city", "ERROR")); System.out.println("country=" + props.get("country", "ERROR")); System.out.println("TestVariable=" + props.get("TestVariable", "shouldBeUndef")); System.out.println("java.home=" + props.get("java.home", "ERROR")); } System.exit(0); } } catch (XmlBlasterException e) { //System.err.println(e.toXml(true)); System.err.println(e.toString()); System.exit(0); }} /** * The default constructor. Deeded for some IDEs to work properly. * Creation date: (07.11.2000 20:14:53) */ public Property() { properties = new Properties(); } /** * Saves the property to a file; this also will include the system properties! * @author M.Winkler, doubleslash NetBusiness GmbH, Friedrichshafen * @exception java.io.IOException Die Beschreibung der Ausnahmebedingung. */ public void saveProps() throws java.io.IOException { // check wether or not we can save FileInfo info = findGivenFile(propertyFileName); if (info.isLocalDisk()) saveProps(info.getFullPath()); else saveProps(propertyFileName); }/** * Saves the property to a file; this also will include the system properties! * @author M.Winkler, doubleslash NetBusiness GmbH, Friedrichshafen * @exception java.io.IOException Die Beschreibung der Ausnahmebedingung. */public void saveProps(String fileName) throws java.io.IOException { // check wether or not we can save File saveFile = new File(fileName); System.out.println("Property: Saving property to file '" + saveFile.getAbsolutePath() + "'"); // retrieve property Properties properties = getProperties(); // try to save to the original loading place OutputStream out = new FileOutputStream(saveFile); properties.store(out, "JUtils property file, including system properties"); out.close(); System.out.println("Property: Done.");} public class FileInfo { String path; // Without fileName String fileName; // file name without path String fullPath; // e.g. from URL InputStream in; // FileInfo(String fileName) { this.fileName = fileName; } public String getFullPath() { if (fullPath != null) return fullPath; if (path == null && fileName == null) return null; if (path == null) return fileName; if (fileName == null) return path; return FileLocator.concatPath(path, fileName); } public boolean isLocalDisk() { if (getFullPath() != null && getFullPath().indexOf("!") < 0) return true; return false; } /** * You need to call closeInputStream() when finished. */ public InputStream getInputStream() throws XmlBlasterException { try { if (in != null) return in; // e.g. from URL or Classloader if (getFullPath() != null) { if (getFullPath().indexOf("!") >= 0) { ClassLoader loader = Property.class.getClassLoader(); in = loader.getResourceAsStream(getFullPath()); } else { File file = new File(getFullPath()); in = new FileInputStream(file); } } return in; } catch (IOException e) { throw new XmlBlasterException(Global.instance(), ErrorCode.RESOURCE_CONFIGURATION, "Property.FileInfo", e.toString()); } } public void closeInputStream() { try { if (in != null) { in.close(); in = null; } } catch (IOException e) { } } } // class FileInfo} // class Property
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -