Kohei Nozaki's blog 

Using DatabaseConfiguration of Commons Configuration


Posted on Sunday Feb 22, 2015 at 10:50PM in Technology


Commons Configuration is a very useful library which manages configurations of an application. it supported various data stores including RDBMS. I’ve done some test against RDBMS so leave this posting as a note. test was done against Commons Configuration 1.10. the project which used in test is can be obtained from my GitHub repository.

app_config Table

Assume now we have following data in a table named app_config.

Table 1. app_config Table
name value

anyJob.someProp1

abc

anyJob.someProp2

def

someJob.list

1,2,3,4,5

someJob.someProp

${anyJob.someProp1}

Create Configuration instance

First, we need to create a DatabaseConfiguration instance with following procedure:

Configuration config = new DatabaseConfiguration(dataSource, "app_config", "name", "value");

Obtain all of configuration

We can obtain all of configurations as follows:

// Obtain all of keys
for (Iterator<String> keys = config.getKeys(); keys.hasNext(); ) {
	String key = keys.next();
	Object value = config.getProperty(key);
	System.out.println(key + "=" + value);
}

It produces:

anyJob.someProp1=abc
anyJob.someProp2=gef
someJob.list=[1, 2, 3, 4, 5]
someJob.someProp=${anyJob.someProp1}

Obtain keys with particular prefix

Sometimes we’d like to filter using prefixes. this time we get keys prefixed with someJob.

// Obtain keys with particular prefix
for (Iterator<String> keys = config.getKeys("someJob"); keys.hasNext(); ) {
	String key = keys.next();
	Object value = config.getProperty(key);
	System.out.println(key + "=" + value);
}

It produces:

someJob.list=[1, 2, 3, 4, 5]
someJob.someProp=${anyJob.someProp1}

Obtain list

We can obtain comma-separated values as List as follows:

// Obtain list
System.out.println(config.getList("someJob.list")); // [1, 2, 3, 4, 5]
System.out.println(config.getString("someJob.list")); // 1

It produces:

[1, 2, 3, 4, 5]
1

Note that invocation of getString() returns only the first value.

Obtain referencing value

The value ${anyJob.someProp1} in the key someJob.someProp resolved as abc with getString() method as follows:

// Referencing a value of other key
System.out.println(config.getString("someJob.someProp")); // abc

It produces:

abc

Update

The library reflects a update of database immediately even after instantiation of DatabaseConfiguration. consider following procedure was executed after instantiation of the configuration instance.

// update value of a row
try (Connection cn = dataSource.getConnection()) {
	try (Statement st = cn.createStatement()) {
		st.executeUpdate("update app_config set value='hij' where name='anyJob.someProp1'");
	}
}

// check updated value
System.out.println(config.getString("anyJob.someProp1")); // hij
System.out.println(config.getString("someJob.someProp")); // hij

It produces:

hij
hij



No one has commented yet.

Leave a Comment

HTML Syntax: NOT allowed