last update: 11/10/2004 08:53:05

Getting started


Note

This document is a little outdated. 
We are working on new docs to help ypu getting started with jConfig. 
These docs are not done yet but you can find the current versions 
on the Scratchpad page

This guide should help get started with jConfig.
We will go through some steps that will demonstrate most of the features. First of all we will define a very simple configuration file called config.xml:
<?xml version="1.0" encoding="iso-8859-1" ?>
<properties>
  <variables>
    <variable name="my.path" value="/home/foo/data"/>
  </variables>
  <category name="general">
    <property name="upload_dir" value="${my.path}/data"/>
    <property name="NewsCounter" value="10"/>
    <property name="showNews" value="true"/>
    <property name="MyProp" value="Hello world"/>
  </category>
  <category name="JDBC">
    <property name="URL" value="jdbc:mysql://localhost/iportal"/>
    <property name="DRIVER" value="org.gjt.mm.mysql.Driver"/>
    <property name="PWD" value="pwd"/>
    <property name="USER" value="user"/>
  </category>
</properties>
Now we will write the "Hello world" application:
import org.jconfig.*;

public class ConfigDemo {

    private static final Configuration configuration = ConfigurationManager.getConfiguration();

    public static void main(String[] args) {
        String myProp = configuration.getProperty("MyProp");
        System.out.println("MyProp:"+myProp);
    }
}
In order to run all the demos make sure you have the config.xml from above, the jconfig.jar, crimson.jar and the jaxp.jar in your classpath. We have provided a shell scrip to compile the file:
./compile.sh ConfigDemo
There is a little shell script that sets the classpath correct and you can
use it to run the demo:
./run.sh ConfigDemo
This little demo will write out "Hello world". Actually not really surprisingly.
What happens behind the scenes is that the ConfigurationManager tries to find the file config.xml in the classpath and if it is found it will read in your configuration automatically. You do not have to load the configuration. When you call the
getConfiguration()
method then the ConfigurationManager returns the default configuration which in our case is the configuration inside our config.xml. When you use the
getProperty(String name)
or
getProperty(String name,String defaultValue)
methods then jConfig will return the property value from the default category. In order to get the property value from a specific category we use the
getProperty(String name,String defaultValue,String category). 
public static void main(String[] arg) {
    String myProp = configuration.getProperty("MyProp");
    System.out.println("MyProp:"+myProp);
    String jdbcUser = configuration.getProperty("USER",null,"JDBC");
    System.out.println("jdbcUser:"+jdbcUser);
    int newsCounter = configuration.getIntProperty("NewsCounter",-1);
    if ( newsCounter == 10 ) {
        System.out.println("We have found the correct value");
    }
    boolean showNews = configuration.getBooleanProperty("showNews",false);
    if ( showNews ) {
        System.out.println("We have to show the news");
    }
}
Run this demo with the same command as above.

Defining a configuration name

So far we have used a file called config.xml for our configuration and we have called
ConfigurationManager.getConfiguration()
to get our configuration.
The ConfigurationManager can handle many configurations which must have an unique name.
In order to get this configuration you have to call:
ConfigurationManager.getConfiguration("myapp");
The ConfigurationManager will now try to find a file called myapp_config.xml automatically.
This is the naming convention that is used. Simply add "_config.xml" to your configuration name
and you have the file name that the ConfigurationManager will search for.
If no file is found then it will try to read a file called config.xml. When there is no file then
it will create a new configuration. This configuration is generated with the given name.
Note: In order to see wether this is a new configuration or it was loaded you can call
(since v2.5):
Configuration config = ConfigurationManager.getConfiguration("myapp");
if ( config.isNew() ) {
  System.out.println("This config was NOT loaded. It was created");
}
The isNew flag is reset automatically when a configuration could be loaded.

Support for primitives


Since not all of your configuration data are Strings the configuration supports convinient
methods simple java types and String arrays. Here is an XML example that we will
use here:
<category name="example">
  <property name="intValue" value="1000"/>
  <property name="list" value="Mon,Tue,Wed,Thu,Fri"/>
  <property name="money" value="100.40"/>
</category>
Getting the int value means:
int myValue = config.getIntProperty("intValue",-1,"example");
You have to define a default value everytime when you use one of the convenience methods.
Since the configuration does not know which default value to return if the property is not found
you have to specify it.
In order to get the list you can do the following:
String[] myArray = config.getArray("list",new String[]{"Huhu"},"example");
System.out.println("day 3 is:"+myArray[2]);
The configuration support all java primitves. If we have forgotten one then let us know.

Inheritance


Our next demo will show the inheritance that jConfig supports. If you try to get the property from a category that does not contain this property then the Configuration will look for the property in the default category.
import org.jconfig.*;

public class InheritanceDemo {

    private static final Configuration configuration =
        ConfigurationManager.getConfiguration();

    public static void main(String[] args) {
        String myProp = configuration.getProperty("MyProp",null,"JDBC");
        System.out.println("MyProp:"+myProp);
    }
}

Variables

We have defined a variable in our configuration and now it is time to explain it. In order to ease the usage of often repeated phrases inside property values jConfig offers the possibility to define variables. These variables will be replaced with the defined values when you call getProperty(....). Here is a short example:
import org.jconfig.*;

public class VariableDemo {

    private static final Configuration configuration =
        ConfigurationManager.getConfiguration();

    public static void main(String[] args) {
        String uploadDir = configuration.getProperty("upload_dir");
        System.out.println("upload_dir:"+uploadDir);
    }
}
This will write out:

uploadDir:/home/foo/data/data

There is more about variables here: AdvancedVariables

PropertyListener


One of the new features is the PropertyListener that is raised every time the value of one of the properties is changed or a new property is added to a category. In order to receive this event you have to implement the PropertyListener interface:
import org.jconfig.*;
import org.jconfig.event.*;

public class PropertyListenerDemo implements PropertyListener {
    
    private static final Configuration configuration = ConfigurationManager.getConfiguration();
        
    public static void main(String[] args) {
        configuration.addPropertyListener(new PropertyListenerDemo());
        configuration.setProperty("Does not matter","hello world");
    }
    
    public void propertyChanged(PropertyListenerEvent e) {        
        System.out.println("property '"+e.getPropertyName()+"' in category '"+e.getCategoryName()+"' has changed");
    }    
}

Loading and saving


The last step is loading and saving a configuration file. There are some handlers that you can use for loading and saving your configuration files. You can find more about handlers here.
import org.jconfig.handler.*;
import org.jconfig.*;
import java.io.File;

public class LoadSaveDemo {

    private static final ConfigurationManager cm =
        ConfigurationManager.getInstance();

    public static void main(String[] args) {
        File file = new File("test.xml");
        XMLFileHandler handler = new XMLFileHandler();
        handler.setFile(file);
        try {
            System.out.println("trying to load file");
            cm.load(handler,"myConfig");
            System.out.println("file successfully processed");
            Configuration config = cm.getConfiguration("myConfig");
            config.setProperty("TEST","Added property");
            System.out.println("trying to save file");
            cm.save(handler,config); 
            System.out.println("file successfully saved");
            System.out.println("TEST:"+config.getProperty("TEST"));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
As of version v2.3 we have made saving easier. All you need is the call the
cm.save("myConfig");
The ConfigurationManager keeps the associated handler in memory and will call the save method of the handler. If you want to use a different handler then you need to call the
cm.save(handler,configname);
For example if you have used the URLHandler to load a configuration filr from an URL and want to save it to a local file to have a backup.