xmlBlaster 2.2.0 client API

org.xmlBlaster.util.property
Class Property

java.lang.Object
  extended by org.xmlBlaster.util.property.Property
All Implemented Interfaces:
java.lang.Cloneable

public class Property
extends java.lang.Object
implements java.lang.Cloneable

Handling properties for your project, e.g. your property file $HOME/cool.properties and command line properties.

Variable replacement

All environment variable (e.g. ${java.io.tmpdir}="/tmp", ${file.separator}="/") can be used in the properties file and are replaced on occurrence.
Further, you can use any of your own variables from the properties file or from the command line with curly braces: ${...}.
Example:
A user may specify the MOMS_NAME and use it later as a variable as follows:

   java -DMOMS_NAME=Joan ...

or in the properties file:
   MOMS_NAME=Joan
or on the command line:
   java org.MyApp  -MOMS_NAME Joan

and now use it like
   MOMS_RECIPY=Strawberry cake from ${MONS_NAME} is the best.
which results to
   MOMS_RECIPY=Strawberry cake from Joan is the best.
The maximum replacement (nesting) depth is 50.

A user may specify the PROJECT_HOME environment variable, the property file will be searched there as well.

NOTE: These are often helpful variables

user.dir and user.home are without a path separator at the end

The property file settings are the weakest, they are overwritten by system property settings and finally by command line arguments.

NOTE: If a variable like ${XYZ} is not resolved an exception is thrown, you can use the markup $_{XYZ} to avoid the exception in which case the $_{XYZ} remains as is.


Searching the property file

This class searches the given property file in typical directories (see findPath() method). It is searched for in the following order:

  1. Command line parameter '-propertyFile', e.g. "-propertyFile /tmp/xy.properties"
  2. Local directory user.dir
  3. In $PROJECT_HOME, e.g. "/opt/myproject"
  4. In user.home - $HOME
  5. In CLASSPATH - $CLASSPATH from your environment. You can stuff the property file into your project jar file
  6. In java.home/lib/ext directory, e.g. "/opt/jdk1.2.2/jre/lib/ext"
    You may use this path for Servlets, demons etc.
  7. In java.home directory, e.g. "/opt/jdk1.2.2/jre/lib"
    You may use this path for Servlets, demons etc.
  8. Fallback: "\jutils" on DOS-WIN$ or "/usr/local/jutils" on UNIX

Array support

We look for keys containing [] brackets and collect them into a map

  val[A]=AAA
  val[B]=BBB
 
Accessing the map with the array praefix (here it is "val")
   Map map = get("val", (Map)null);
 
returns a Map containing keys { "A", "B" } and values { "AAA", "BBB" }

Two dimensional arrays are supported as well:
   val[C][1]=cccc   -> map entry with key "C:1" and value "cccc"
 

Very simple array values

Values of properties may have a separator, example:

  names=Joe,Jack,Averell
 
Access the names split to an array:
  String[] arr = prop.get("array", new String[0], ",");
  //arr[0] contains "Joe", arr[1] contains "Jack" and arr[2] contains "Averell"
 

Listening on property changes

You can listen on added properties, changed properties or on removed properties, the following code snippet shows how to do it:

 I_PropertyChangeListener ll = prop.addPropertyChangeListener(theKey, new I_PropertyChangeListener() {
       public void propertyChanged(PropertyChangeEvent ev) {
          System.out.println("propertyChanged: " + ev.toString());
          // key = ev.getKey();
          // old = ev.getOldValue();
          // value = ev.getNewValue();
       }
    }
    );
 
Note that setting a property with an equal value is not triggering an event.

JDK 1.1 or higher only.

Author:
Marcel Ruff, Michael Winkler, doubleSlash Net-Business GmbH
See Also:
testsuite.TestProperty

Nested Class Summary
 class Property.FileInfo
           
 
Field Summary
static int DEFAULT_VERBOSE
           
static int MAX_NEST
           
 int verbose
          Set the verbosity when loading properties (outputs with System.out).
 
Constructor Summary
Property()
          The default constructor.
Property(java.lang.String propertyFileUrl, boolean scanSystemProperties, java.lang.Object applet, boolean replaceVariables)
          Construct a property container from supplied property file (URL) and Applet.
Property(java.lang.String fileName, boolean scanSystemProperties, java.util.Properties extraProps, boolean replaceVariables)
          Construct a property container from supplied property file and enumeration.
Property(java.lang.String fileName, boolean scanSystemProperties, java.lang.String[] args, boolean replaceVariables)
          Construct a property container from supplied property file and args array.
Property(java.lang.String fileName, boolean scanSystemProperties, java.lang.String[] args, boolean replaceVariables, boolean output)
          Construct a property container from supplied property file and args array.
Property(java.lang.String fileName, boolean scanSystemProperties, java.lang.String projectname, boolean replaceVariables)
          Construct a property container from supplied property file and enumeration.
 
Method Summary
 void addArgs2Props(java.util.Properties argsProps)
          The same as addArgs2Props(String[] args) but passing the args in a Properties hashtable.
 void addArgs2Props(java.lang.String[] args)
          Add key/values, for example from startup command line args to the property variable.
 I_PropertyChangeListener addPropertyChangeListener(java.lang.String key, I_PropertyChangeListener l)
          Listen on change or creation events of the given key.
 I_PropertyChangeListener addPropertyChangeListener(java.lang.String key, java.lang.String defaultValue, I_PropertyChangeListener l)
          Listen on change or creation events of the given key
static java.util.Properties argsToProps(java.lang.String[] args)
          Scan args, correct and check them and return the result in a Properties hash table
 java.lang.Object clone()
          We do a deep copy for all properties and listeners
 Property.FileInfo findArgsFile(java.util.Properties argsProps)
          Find properties file.
 Property.FileInfo findFile(java.lang.String fileName, java.util.Properties argsProps)
          Find properties file.
 Property.FileInfo findGivenFile(java.lang.String fileName)
          Find properties file which was given with the constructor.
 Property.FileInfo findPath(java.lang.String fileName)
          Look for properties file.
 boolean get(java.lang.String key, boolean defaultVal)
          Try to find the given key.
 double get(java.lang.String key, double defaultVal)
          Try to find the given key.
 float get(java.lang.String key, float defaultVal)
          Try to find the given key.
 int get(java.lang.String key, int defaultVal)
          Try to find the given key.
 long get(java.lang.String key, long defaultVal)
          Try to find the given key.
 java.util.Map get(java.lang.String key, java.util.Map defaultVal)
          Try to find the given key.
 java.lang.String get(java.lang.String key, java.lang.String defaultVal)
          Try to find the given key.
 java.lang.String[] get(java.lang.String key, java.lang.String[] defaultVal, java.lang.String separator)
          Try to find the given key.
 java.util.Properties getProperties()
          Get the internal handle.
 java.util.Map getPropertiesForContextNode(ContextNode parentCtx, java.lang.String shortKey, java.lang.String keyForDefault)
          Returns a map containing all properties of the specified context.
 java.util.Map getPropertiesStartingWith(java.lang.String prefix)
          Returns the subset of properties found in the properties starting with the specified prefix.
 java.util.Properties loadProps(Property.FileInfo info, java.util.Properties argsProps)
          Use this method only the first time to initialize everything.
static void main(java.lang.String[] args)
          For testing only

 boolean propertyExists(java.lang.String key)
          Try to find the given key.
static java.lang.String[] propsToArgs(java.util.Map props)
          Convert a properties hashtable to a String array with leading "-" in front of the keys
 java.lang.String removeProperty(java.lang.String key)
          Remove the given property.
 void removePropertyChangeListener(java.lang.String key, I_PropertyChangeListener l)
          Listen on change or creation events of the given key
 java.lang.String replaceVariableNoException(java.lang.String key, java.lang.String value)
          Replace dynamic variables, e.g.
 java.lang.String replaceVariableWithException(java.lang.String key, java.lang.String value)
          Replace dynamic variables, e.g.
 void saveProps()
          Saves the property to a file; this also will include the system properties!
 void saveProps(java.lang.String fileName)
          Saves the property to a file; this also will include the system properties!
 java.lang.String set(java.lang.String key, java.lang.String value)
          Set or overwrite a property, note that currently no variable replacement is implemented for the passed value.
 void setApplet(java.lang.Object applet)
           
static boolean toBool(java.lang.String token)
          Parse a string to boolean.
 java.lang.String toXml()
           
 java.lang.String toXml(java.lang.String extraOffset)
          Dump all properties to xml representation.
 boolean wantsHelp()
          If set to true user wants you to display a usage text.
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MAX_NEST

public static final int MAX_NEST
See Also:
Constant Field Values

DEFAULT_VERBOSE

public static final int DEFAULT_VERBOSE
See Also:
Constant Field Values

verbose

public int verbose
Set the verbosity when loading properties (outputs with System.out).

0=nothing, 1=info, 2=trace, configure with

 java -Dproperty.verbose 2

 java MyApp -property.verbose 2
 

Constructor Detail

Property

public Property(java.lang.String fileName,
                boolean scanSystemProperties,
                java.lang.String[] args,
                boolean replaceVariables)
         throws XmlBlasterException
Construct a property container from supplied property file and args array.

Parameters:
fileName - The property file name, e.g. "project.properties"
scanSystemProperties - Scan System.getProperties() as well, you can add variable to JVM like: java -DmyName=Joe ...
args - A String array with properties, usually from command line, e.g. java myApp -logging FINE -name Joe
replaceVariables - true: replace occurrences of ${key} with the value of key
Throws:
XmlBlasterException

Property

public Property(java.lang.String fileName,
                boolean scanSystemProperties,
                java.util.Properties extraProps,
                boolean replaceVariables)
         throws XmlBlasterException
Construct a property container from supplied property file and enumeration.

Usually used by servlets (ServletConfig conf):

    Properties extraProps = new Properties();
    Enumeration e = conf.getInitParameterNames();
    while (e.hasMoreElements()) {
       String name = (String)e.nextElement();
       extraProps.put(name, conf.getInitParameter(name));
    }
 

Parameters:
fileName - The property file name, e.g. "project.properties"
scanSystemProperties - Scan System.getProperties() as well, you can add variable to JVM like: java -DmyName=Joe ...
args - A String array with properties, usually from command line, e.g. java myApp -trace true -name Joe
replaceVariables - true: replace occurrences of ${key} with the value of key
Throws:
XmlBlasterException

Property

public Property(java.lang.String fileName,
                boolean scanSystemProperties,
                java.lang.String projectname,
                boolean replaceVariables)
         throws XmlBlasterException
Construct a property container from supplied property file and enumeration.

Usually used by servlets (ServletConfig conf):

    Properties extraProps = new Properties();
    Enumeration e = conf.getInitParameterNames();
    while (e.hasMoreElements()) {
       String name = (String)e.nextElement();
       extraProps.put(name, conf.getInitParameter(name));
    }
 

Parameters:
fileName - The property file name, e.g. "project.properties"
scanSystemProperties - Scan System.getProperties() as well, you can add variable to JVM like: java -DmyName=Joe ...
name - of project which is to be extracted from user.home/projects.properties
replaceVariables - true: replace occurrences of ${key} with the value of key
Throws:
XmlBlasterException

Property

public Property(java.lang.String fileName,
                boolean scanSystemProperties,
                java.lang.String[] args,
                boolean replaceVariables,
                boolean output)
         throws XmlBlasterException
Construct a property container from supplied property file and args array.

Parameters:
fileName - The property file name, e.g. "project.properties"
scanSystemProperties - Scan System.getProperties() as well, you can add variable to JVM like: java -DmyName=Joe ...
args - A String array with properties, usually from command line, e.g. java myApp -trace true -name Joe
replaceVariables - true: replace occurrences of ${key} with the value of key
output - false: no info output to System.out is printed. Only successfull operation.
Throws:
XmlBlasterException

Property

public Property(java.lang.String propertyFileUrl,
                boolean scanSystemProperties,
                java.lang.Object applet,
                boolean replaceVariables)
         throws XmlBlasterException
Construct a property container from supplied property file (URL) and Applet.

NOTE: Applet HTML PARAM values may not contain variables ${...}, they are currently not replaced.

Parameters:
propertyFileUrl - applet.getCodeBase()+"xy.properties" e.g. "http://myHost.com:80/xy.properties"
scanSystemProperties - Scan System.getProperties() as well, you can add variable to JVM like: java -DmyName=Joe ...
NOTE: If you set this to true, you need a signed applet!
applet - Not yet supported. How to access all applet parameters???
replaceVariables - true: replace occurrences of ${key} with the value of key
Throws:
XmlBlasterException

Property

public Property()
The default constructor. Deeded for some IDEs to work properly. Creation date: (07.11.2000 20:14:53)

Method Detail

getPropertiesStartingWith

public java.util.Map getPropertiesStartingWith(java.lang.String prefix)
Returns the subset of properties found in the properties starting with the specified prefix.

Parameters:
prefix - The prefix to use. If null is passed, then all properties are returned
Returns:
the subset of properties found. The keys are stripped from their prefix. The returned keys are returned in alphabetical order.

getPropertiesForContextNode

public java.util.Map getPropertiesForContextNode(ContextNode parentCtx,
                                                 java.lang.String shortKey,
                                                 java.lang.String keyForDefault)
Returns a map containing all properties of the specified context. /node/heron/logging, FINE, /node/heron/logging/org.xmlBlaster.engine.level, FINE Suppose you want to retrieve these values, then the parentCtx is /node/heron and the shortKey is logging. If you want to retrieve both values you have to pass keyForDefault which is not null (for example you will pass '__default'. Then you will get: __default = FINE org.xmlBlaster.engine.level = FINE two entries. If you pass keyForDefault = null you will only get the second value

Parameters:
ctx -
shortKey -
keyForDefault, - can be null in which case it will not return the default value.
Returns:

clone

public java.lang.Object clone()
We do a deep copy for all properties and listeners

Overrides:
clone in class java.lang.Object

getProperties

public final java.util.Properties getProperties()
Get the internal handle.

Returns:
The Properties handle.

setApplet

public void setApplet(java.lang.Object applet)

set

public final java.lang.String set(java.lang.String key,
                                  java.lang.String value)
                           throws XmlBlasterException
Set or overwrite a property, note that currently no variable replacement is implemented for the passed value.

Parameters:
key - The key for this property
value - The value for it
Returns:
The value, ${...} variables are replaced
Throws:
XmlBlasterException

get

public final java.lang.String get(java.lang.String key,
                                  java.lang.String defaultVal)
Try to find the given key.

Parameters:
key - the key to look for
defaultVal - the default value to return if key is not found
Returns:
The String value for the given key

get

public final java.lang.String[] get(java.lang.String key,
                                    java.lang.String[] defaultVal,
                                    java.lang.String separator)
Try to find the given key.

Example:
NameList=Josua,David,Ken,Abel
Will return each name separately in the array.

Parameters:
key - the key to look for
defaultVal - The default value to return if key is not found
separator - The separator, typically ","
Returns:
The String array for the given key, the elements are trimmed (no leading/following white spaces)

get

public final int get(java.lang.String key,
                     int defaultVal)
Try to find the given key.

Parameters:
key - the key to look for
defaultVal - the default value to return if key is not found
Returns:
The int value for the given key

get

public final long get(java.lang.String key,
                      long defaultVal)
Try to find the given key.

Parameters:
key - the key to look for
defaultVal - the default value to return if key is not found
Returns:
The long value for the given key

get

public final double get(java.lang.String key,
                        double defaultVal)
Try to find the given key.

Parameters:
key - the key to look for
defaultVal - the default value to return if key is not found
Returns:
The double value for the given key

get

public final float get(java.lang.String key,
                       float defaultVal)
Try to find the given key.

Parameters:
key - the key to look for
defaultVal - the default value to return if key is not found
Returns:
The float value for the given key

get

public final boolean get(java.lang.String key,
                         boolean defaultVal)
Try to find the given key.

See toBool() for a list of recognized strings.

Parameters:
key - the key to look for
defaultVal - the default value to return if key is not found
Returns:
The boolean value for the given key

get

public final java.util.Map get(java.lang.String key,
                               java.util.Map defaultVal)
Try to find the given key.

Example:

   Map map = get(key, (Map)null);
   if (map != null) {
      ...
   }
 

Parameters:
key - the key to look for
defaultVal - the default Map to return if key is not found
Returns:
The Map or null if not found

propertyExists

public final boolean propertyExists(java.lang.String key)
Try to find the given key.

Parameters:
key - the parameter key to look for
Returns:
true if the property exists

removeProperty

public final java.lang.String removeProperty(java.lang.String key)
Remove the given property.

This method does nothing if the key is not in the property hashtable.

Parameters:
key - the key to remove
Returns:
The removed value

wantsHelp

public final boolean wantsHelp()
If set to true user wants you to display a usage text.

Returns:
true if the option '--help' or '-help' or '-h' or '-?' was given.

loadProps

public final java.util.Properties loadProps(Property.FileInfo info,
                                            java.util.Properties argsProps)
                                     throws XmlBlasterException
Use this method only the first time to initialize everything.

Parameters:
argsProps - This key/value parameter array is added to the properties object (see addArgs2Props()).
Returns:
the initialized Properties
Throws:
XmlBlasterException

replaceVariableWithException

public final java.lang.String replaceVariableWithException(java.lang.String key,
                                                           java.lang.String value)
                                                    throws XmlBlasterException
Replace dynamic variables, e.g. ${XY} with their values.

The maximum replacement (nesting) depth is 50.

Parameters:
key - For logging only
Returns:
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

replaceVariableNoException

public final java.lang.String replaceVariableNoException(java.lang.String key,
                                                         java.lang.String value)
                                                  throws XmlBlasterException
Replace dynamic variables, e.g. $_{XY} with their values.

The maximum replacement (nesting) depth is 50.

Parameters:
key - For logging only
Returns:
The new value where all resolvable $_{} are replaced.
Throws:
XmlBlasterException - if matching "}" is missing

toBool

public static final boolean toBool(java.lang.String token)
                            throws XmlBlasterException
Parse a string to boolean.

Parameters:
token - for example "false"
Returns:
true for one of "true", "yes", "1", "ok"
false for "false", "0", "no"
Throws:
if - none of the above strings
XmlBlasterException

findPath

public final Property.FileInfo findPath(java.lang.String fileName)
Look for properties file.

The property file is searched in the specific order as described above

Parameters:
fileName - e.g. "cool.properties".
Returns:
the path to file or null if not found

findArgsFile

public final Property.FileInfo findArgsFile(java.util.Properties argsProps)
Find properties file.

Parameters:
args - Only "-propertyFile /tmp/xy.properties" is evaluated (if given)
Returns:
The property file name or null if not found of not given.

findGivenFile

public final Property.FileInfo findGivenFile(java.lang.String fileName)
Find properties file which was given with the constructor.

See findPath() for search - logic

Parameters:
fileName - e.g. "cool.properties"
args - Only "-propertyFile /tmp/xy.properties" is evaluated (if given) this has precedence over the given fileName!
Returns:
The path to file, e.g. "\jutils\"

findFile

public final Property.FileInfo findFile(java.lang.String fileName,
                                        java.util.Properties argsProps)
Find properties file.

See findPath() for search - logic

Parameters:
fileName - e.g. "cool.properties"
args - Only "-propertyFile /tmp/xy.properties" is evaluated (if given) this has precedence over the given fileName!
Returns:
The path to file or null

addArgs2Props

public void addArgs2Props(java.lang.String[] args)
                   throws XmlBlasterException
Add key/values, for example from startup command line args to the property variable.

Args parameters are stronger and overwrite the property file variables.

The arg key must have a leading - or -- (as usual on command line).
The leading - are stripped (to match the property variable) args must be a tuple (key / value pairs).

Throws:
XmlBlasterException

addArgs2Props

public void addArgs2Props(java.util.Properties argsProps)
                   throws XmlBlasterException
The same as addArgs2Props(String[] args) but passing the args in a Properties hashtable.

Throws:
XmlBlasterException

propsToArgs

public static java.lang.String[] propsToArgs(java.util.Map props)
Convert a properties hashtable to a String array with leading "-" in front of the keys


argsToProps

public static java.util.Properties argsToProps(java.lang.String[] args)
                                        throws XmlBlasterException
Scan args, correct and check them and return the result in a Properties hash table

Throws:
XmlBlasterException

addPropertyChangeListener

public final I_PropertyChangeListener addPropertyChangeListener(java.lang.String key,
                                                                I_PropertyChangeListener l)
Listen on change or creation events of the given key. Note that no initial event is sent.

Returns:
The listener you provided (nice if it is an anonymous class)

addPropertyChangeListener

public final I_PropertyChangeListener addPropertyChangeListener(java.lang.String key,
                                                                java.lang.String defaultValue,
                                                                I_PropertyChangeListener l)
Listen on change or creation events of the given key

Parameters:
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.
Returns:
The listener you provided (nice if it is an anonymous class)

removePropertyChangeListener

public final void removePropertyChangeListener(java.lang.String key,
                                               I_PropertyChangeListener l)
Listen on change or creation events of the given key

Parameters:
l - If null all listeners are removed

toXml

public java.lang.String toXml()

toXml

public java.lang.String toXml(java.lang.String extraOffset)
Dump all properties to xml representation.


main

public static void main(java.lang.String[] args)
For testing only

 java -Djava.compiler= org.xmlBlaster.util.property.Property -Persistence.Driver myDriver -isCool true -xml "world"
 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
 


saveProps

public void saveProps()
               throws java.io.IOException
Saves the property to a file; this also will include the system properties!

Throws:
java.io.IOException - Die Beschreibung der Ausnahmebedingung.

saveProps

public void saveProps(java.lang.String fileName)
               throws java.io.IOException
Saves the property to a file; this also will include the system properties!

Throws:
java.io.IOException - Die Beschreibung der Ausnahmebedingung.

xmlBlaster 2.2.0 client API

Copyright © 1999-2014 The xmlBlaster.org contributers.