Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java CompositeConfiguration usage
# Properties definining the GUI
colors.background = #FFFFFF
colors.foreground = #000080
window.width = 500
window.height = 300
version = old
# Properties definining the GUI
# this should show up
colors.new = #ABCDERF
# this will be overridden by in-memory config
version = bversion
# this will be overridden too
window.width = 1000
apply plugin: 'java'
dependencies {
implementation "commons-configuration:commons-configuration:1.6"
}
repositories {
mavenCentral()
}
task runFinalJar(type: JavaExec) {
group = "Run"
classpath = files('build/libs/conf-test.jar')
classpath += sourceSets.main.runtimeClasspath
main = 'test.PropMain'
}
runFinalJar.dependsOn('build')
package test;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.BaseConfiguration;
import java.util.Iterator;
class PropMain {
private static CompositeConfiguration globalConfig = new CompositeConfiguration();
private static PropertiesConfiguration configa;
public static void main(String[] args) throws Exception {
readSaved();
applyVersionIfNew();
saveIfChanged();
readb();
printGlobal();
}
private static void applyVersionIfNew() {
if (!globalConfig.getString("version").equals("3.3.4.2")) {
System.out.printf("Changing GlobalConfig version to 3.3.4.2 from %s\n", globalConfig.getString("version"));
globalConfig.setProperty("version", "3.3.4.2");
}
}
private static void readSaved() throws Exception {
configa = new PropertiesConfiguration("a.properties");
globalConfig.addConfiguration(configa);
}
private static void readb() throws Exception {
PropertiesConfiguration configb = new PropertiesConfiguration("b.properties");
globalConfig.addConfiguration(configb);
}
private static void saveIfChanged() throws Exception {
Configuration changes = globalConfig.getInMemoryConfiguration();
Iterator<String> iter = changes.getKeys();
if (iter.hasNext()) {
System.out.printf("****Update a.properties\n");
while (iter.hasNext()) {
String key = iter.next();
Object value = changes.getProperty(key);
configa.setProperty(key, value);
}
configa.save();
}
}
private static void printGlobal() {
Iterator<String> keysg = globalConfig.getKeys();
while(keysg.hasNext()) {
String key = keysg.next();
String prop = globalConfig.getString(key);
System.out.printf("Key %s Value %s\n", key, prop);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.