Skip to content

Instantly share code, notes, and snippets.

@paulwellnerbou
Last active February 1, 2018 09:25
Show Gist options
  • Save paulwellnerbou/dfed371d67e2f19a699b248ebf5c62d7 to your computer and use it in GitHub Desktop.
Save paulwellnerbou/dfed371d67e2f19a699b248ebf5c62d7 to your computer and use it in GitHub Desktop.
Unit test demonstrating behaviour of apache commons configuration
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.event.Event;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class ReloadablePropertiesTest {
private final String propertyFilePath = "/tmp/test.properties";
private ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder;
@Before
public void setUp() throws FileNotFoundException {
try (PrintWriter out = new PrintWriter(propertyFilePath)) {
out.println("test=99");
}
File propertiesFile = new File(propertyFilePath);
builder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(new Parameters().fileBased().setFile(propertiesFile));
builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST,
new EventListener() {
@Override
public void onEvent(final Event event) {
builder.getReloadingController().checkForReloading(null);
}
});
}
@Test
public void test() throws InterruptedException, FileNotFoundException, ConfigurationException {
builder.getConfiguration().getInt("test");
Assert.assertEquals(99, builder.getConfiguration().getInt("test"));
Thread.sleep(6_000);
try (PrintWriter out = new PrintWriter(propertyFilePath)) {
out.println("test=100");
}
Thread.sleep(1_000);
Assert.assertEquals(100, builder.getConfiguration().getInt("test"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment