Java Code Examples for org.apache.commons.configuration2.io.FileHandler

The following examples show how to use org.apache.commons.configuration2.io.FileHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: james-project   Source File: FileConfigurationProvider.java    License: Apache License 2.0 6 votes vote down vote up
public static XMLConfiguration getConfig(InputStream configStream) throws ConfigurationException {
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
        .configure(new Parameters()
            .xml()
            .setListDelimiterHandler(new DisabledListDelimiterHandler()));
    XMLConfiguration xmlConfiguration = builder.getConfiguration();
    FileHandler fileHandler = new FileHandler(xmlConfiguration);
    fileHandler.load(configStream);
    try {
        configStream.close();
    } catch (IOException ignored) {
        // Ignored
    }

    return xmlConfiguration;
}
 
Example 2
/**
 * Tests whether a windows path can be saved correctly. This test is related
 * to CONFIGURATION-428.
 */
@Test
public void testSaveWindowsPath() throws ConfigurationException
{
    conf.clear();
    conf.setListDelimiterHandler(new DisabledListDelimiterHandler());
    conf.addProperty("path", "C:\\Temp");
    final StringWriter writer = new StringWriter();
    new FileHandler(conf).save(writer);
    final String content = writer.toString();
    assertThat("Path not found: ", content,
            containsString("<path>C:\\Temp</path>"));
    saveTestConfig();
    final XMLConfiguration conf2 = new XMLConfiguration();
    load(conf2, testSaveConf.getAbsolutePath());
    assertEquals("Wrong windows path", "C:\\Temp",
            conf2.getString("path"));
}
 
Example 3
/**
 * Tests whether a custom reloading detector factory can be installed.
 */
@Test
public void testCreateReloadingDetectoryCustomFactory()
        throws ConfigurationException
{
    final ReloadingDetector detector =
            EasyMock.createMock(ReloadingDetector.class);
    final ReloadingDetectorFactory factory =
            EasyMock.createMock(ReloadingDetectorFactory.class);
    final FileHandler handler = new FileHandler();
    final FileBasedBuilderParametersImpl params =
            new FileBasedBuilderParametersImpl();
    EasyMock.expect(factory.createReloadingDetector(handler, params))
            .andReturn(detector);
    EasyMock.replay(detector, factory);
    params.setReloadingDetectorFactory(factory);
    final ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder =
            new ReloadingFileBasedConfigurationBuilder<>(
                    PropertiesConfiguration.class);
    assertSame("Wrong detector", detector,
            builder.createReloadingDetector(handler, params));
    EasyMock.verify(factory);
}
 
Example 4
@Override
public ReloadingDetector createReloadingDetector(final FileHandler handler,
        final FileBasedBuilderParametersImpl params)
        throws ConfigurationException
{
    final Long refreshDelay = params.getReloadingRefreshDelay();

    final FileHandlerReloadingDetector fileHandlerReloadingDetector =
            refreshDelay != null ? new FileHandlerReloadingDetector(
            handler, refreshDelay) : new FileHandlerReloadingDetector(
            handler);

    fileHandlerReloadingDetector.refresh();

    return fileHandlerReloadingDetector;
}
 
Example 5
/**
 * Tests whether a reloading detector is created correctly.
 */
@Test
public void testCreateReloadingDetector() throws ConfigurationException
{
    final FileHandler handler = new FileHandler();
    final FileBasedBuilderParametersImpl params =
            new FileBasedBuilderParametersImpl();
    final Long refreshDelay = 10000L;
    params.setReloadingRefreshDelay(refreshDelay);
    final FileHandlerReloadingDetector detector =
            (FileHandlerReloadingDetector) factory.createReloadingDetector(
                    handler, params);
    assertSame("Wrong file handler", handler, detector.getFileHandler());
    assertEquals("Wrong refresh delay", refreshDelay.longValue(),
            detector.getRefreshDelay());
}
 
Example 6
@Test
public void testSave() throws Exception
{
    final FileHandler handler = new FileHandler(config);
    handler.setFileName(TEST_FILE3);
    handler.load();
    final File saveFile = folder.newFile(TEST_SAVENAME);
    handler.save(saveFile);

    config = new XMLConfiguration();
    final FileHandler handler2 = new FileHandler(config);
    handler2.load(saveFile.toURI().toURL());
    assertEquals("value", config.getProperty("element"));
    assertEquals("I'm complex!", config.getProperty("element2.subelement.subsubelement"));
    assertEquals(8, config.getInt("test.short"));
    assertEquals("one", config.getString("list(0).item(0)[@name]"));
    assertEquals("two", config.getString("list(0).item(1)"));
    assertEquals("six", config.getString("list(1).sublist.item(1)"));
}
 
Example 7
/**
 * Tests whether the name of the root element is copied when a configuration
 * is created using the copy constructor.
 */
@Test
public void testCopyRootName() throws ConfigurationException
{
    final String rootName = "rootElement";
    final String xml = "<" + rootName + "><test>true</test></" + rootName
            + ">";
    conf.clear();
    new FileHandler(conf).load(new StringReader(xml));
    XMLConfiguration copy = new XMLConfiguration(conf);
    assertEquals("Wrong name of root element", rootName, copy
            .getRootElementName());
    new FileHandler(copy).save(testSaveConf);
    copy = new XMLConfiguration();
    load(copy, testSaveConf.getAbsolutePath());
    assertEquals("Wrong name of root element after save", rootName, copy
            .getRootElementName());
}
 
Example 8
/**
 * Tests whether a properties configuration can be successfully cloned. It
 * is especially checked whether the layout object is taken into account.
 */
@Test
public void testClone() throws ConfigurationException
{
    final PropertiesConfiguration copy = (PropertiesConfiguration) conf.clone();
    assertNotSame("Copy has same layout object", conf.getLayout(),
            copy.getLayout());
    assertEquals("Wrong number of event listeners for original", 1, conf
            .getEventListeners(ConfigurationEvent.ANY).size());
    assertEquals("Wrong number of event listeners for clone", 1, copy
            .getEventListeners(ConfigurationEvent.ANY).size());
    assertSame("Wrong event listener for original", conf.getLayout(), conf
            .getEventListeners(ConfigurationEvent.ANY).iterator().next());
    assertSame("Wrong event listener for clone", copy.getLayout(), copy
            .getEventListeners(ConfigurationEvent.ANY).iterator().next());
    final StringWriter outConf = new StringWriter();
    new FileHandler(conf).save(outConf);
    final StringWriter outCopy = new StringWriter();
    new FileHandler(copy).save(outCopy);
    assertEquals("Output from copy is different", outConf.toString(), outCopy.toString());
}
 
Example 9
/**
 * Tests the escaping of quotation marks in a properties value. This test is
 * related to CONFIGURATION-516.
 */
@Test
public void testEscapeQuote() throws ConfigurationException
{
    conf.clear();
    final String text = "\"Hello World!\"";
    conf.setProperty(PROP_NAME, text);
    final StringWriter out = new StringWriter();
    new FileHandler(conf).save(out);
    assertTrue("Value was escaped: " + out,
            out.toString().contains(text));
    saveTestConfig();
    final PropertiesConfiguration c2 = new PropertiesConfiguration();
    load(c2, testSavePropertiesFile.getAbsolutePath());
    assertEquals("Wrong value", text, c2.getString(PROP_NAME));
}
 
Example 10
/**
 * Tests whether a correct reloading detector is created if no custom factory
 * was set.
 */
@Test
public void testCreateReloadingDetectorDefaultFactory() throws ConfigurationException
{
    final ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder =
            new ReloadingFileBasedConfigurationBuilder<>(
                    PropertiesConfiguration.class);
    final FileHandler handler = new FileHandler();
    final FileBasedBuilderParametersImpl params = new FileBasedBuilderParametersImpl();
    final long refreshDelay = 60000L;
    params.setReloadingRefreshDelay(refreshDelay);
    final FileHandlerReloadingDetector detector =
            (FileHandlerReloadingDetector) builder.createReloadingDetector(
                    handler, params);
    assertSame("Wrong file handler", handler, detector.getFileHandler());
    assertEquals("Wrong refresh delay", refreshDelay,
            detector.getRefreshDelay());
}
 
Example 11
@Before
public void setUp() throws Exception
{
    cc = new CompositeConfiguration();
    final ListDelimiterHandler listHandler = new LegacyListDelimiterHandler(',');
    conf1 = new PropertiesConfiguration();
    conf1.setListDelimiterHandler(listHandler);
    final FileHandler handler1 = new FileHandler(conf1);
    handler1.setFileName(testProperties);
    handler1.load();
    conf2 = new PropertiesConfiguration();
    conf2.setListDelimiterHandler(listHandler);
    final FileHandler handler2 = new FileHandler(conf2);
    handler2.setFileName(testProperties2);
    handler2.load();
    xmlConf = new XMLConfiguration();
    final FileHandler handler3 = new FileHandler(xmlConf);
    handler3.load(new File(testPropertiesXML));

    cc.setThrowExceptionOnMissing(true);
}
 
Example 12
@Test
public void testIncludeIncludeLoadCyclicalReferenceFail() throws Exception
{
    final PropertiesConfiguration pc = new PropertiesConfiguration();
    final FileHandler handler = new FileHandler(pc);
    handler.setBasePath(testBasePath);
    handler.setFileName("include-include-cyclical-reference.properties");
    try {
        handler.load();
        Assert.fail("Expected " + Configuration.class.getCanonicalName());
    } catch (ConfigurationException e) {
        // expected
        // e.printStackTrace();
    }
    assertNull(pc.getString("keyA"));
}
 
Example 13
/**
 * Tests whether configuration properties with a namespace can be handled.
 */
@Test
public void testPropertiesWithNamespace() throws ConfigurationException
{
    final String xml =
            "<Config>\n"
                    + "<dsig:Transforms xmlns:dsig=\"http://www.w3.org/2000/09/xmldsig#\">\n"
                    + "  <dsig:Transform Algorithm=\"http://www.w3.org/TR/1999/REC-xpath-19991116\">\n"
                    + "    <dsig:XPath xmlns:ietf=\"http://www.ietf.org\" xmlns:pl=\"http://test.test\">self::pl:policy1</dsig:XPath>\n"
                    + "  </dsig:Transform>\n"
                    + "  <dsig:Transform Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/>\n"
                    + "</dsig:Transforms>" + "</Config>";
    final FileHandler handler = new FileHandler(config);
    handler.load(new StringReader(xml));

    for (final Iterator<String> it = config.getKeys(); it.hasNext();)
    {
        final String key = it.next();
        assertNotNull("No value for " + key, config.getString(key));
    }
}
 
Example 14
/**
 * Tests whether the encoding is written when saving a configuration.
 */
@Test
public void testSaveWithEncoding() throws ConfigurationException
{
    final String encoding = "UTF-8";
    final FileHandler handler = new FileHandler(config);
    handler.setEncoding(encoding);
    final StringWriter writer = new StringWriter();
    handler.save(writer);
    assertTrue(
            "Encoding not found",
            writer.toString()
                    .indexOf(
                            "<?xml version=\"1.0\" encoding=\"" + encoding
                                    + "\"?>") >= 0);
}
 
Example 15
Source Project: standalone-app   Source File: Helios.java    License: Apache License 2.0 5 votes vote down vote up
private static Configuration loadConfiguration() throws IOException, ConfigurationException {
    Configurations configurations = new Configurations();
    File file = Constants.SETTINGS_FILE_XML;
    if (!file.exists()) {
        XMLConfiguration tempConfiguration = new XMLConfiguration();
        new FileHandler(tempConfiguration).save(file);
    }
    FileBasedConfigurationBuilder<XMLConfiguration> builder = configurations.xmlBuilder(file);
    builder.setAutoSave(true);
    return builder.getConfiguration();
}
 
Example 16
@Test
public void testSave() throws Exception
{
    // load the configuration
    final XMLPropertiesConfiguration conf = load(TEST_PROPERTIES_FILE);

    // update the configuration
    conf.addProperty("key4", "value4");
    conf.clearProperty("key2");
    conf.setHeader("Description of the new property list");

    // save the configuration
    final File saveFile = folder.newFile("test2.properties.xml");
    final FileHandler saveHandler = new FileHandler(conf);
    saveHandler.save(saveFile);

    // reload the configuration
    final XMLPropertiesConfiguration conf2 = load(saveFile.getAbsolutePath());

    // test the configuration
    assertEquals("header", "Description of the new property list", conf2.getHeader());

    assertFalse("The configuration is empty", conf2.isEmpty());
    assertEquals("'key1' property", "value1", conf2.getProperty("key1"));
    assertEquals("'key3' property", "value3", conf2.getProperty("key3"));
    assertEquals("'key4' property", "value4", conf2.getProperty("key4"));
}
 
Example 17
Source Project: james-project   Source File: ConfigurationProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load the xmlConfiguration from the given resource.
 * 
 * @param r
 * @return
 * @throws ConfigurationException
 * @throws IOException
 */
private XMLConfiguration getConfig(Resource r) throws ConfigurationException, IOException {
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
        .configure(new Parameters()
            .xml()
            .setListDelimiterHandler(new DisabledListDelimiterHandler()));
    XMLConfiguration xmlConfiguration = builder.getConfiguration();
    FileHandler fileHandler = new FileHandler(xmlConfiguration);
    fileHandler.load(r.getInputStream());

    return xmlConfiguration;
}
 
Example 18
Source Project: studio   Source File: ConfigUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static HierarchicalConfiguration<ImmutableNode> readXmlConfiguration(InputStream input)
        throws ConfigurationException {
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(XMLConfiguration.class);
    XMLConfiguration config = builder.configure(params.xml()).getConfiguration();
    FileHandler fileHandler = new FileHandler(config);

    fileHandler.setEncoding("UTF-8");
    fileHandler.load(input);

    return config;
}
 
Example 19
@Before
public void setUp() throws Exception
{
    // any concrete class will do
    final PropertiesConfiguration c = new PropertiesConfiguration();
    new FileHandler(c).load(ConfigurationAssert
            .getTestFile("test.properties"));
    sync = new SynchronizerTestImpl();
    c.setSynchronizer(sync);
    config = c;
}
 
Example 20
/**
 * Tests removing the text of the root element.
 */
@Test
public void testClearTextRootElement() throws ConfigurationException
{
    final String xml = "<e a=\"v\">text</e>";
    conf.clear();
    final StringReader in = new StringReader(xml);
    final FileHandler handler = new FileHandler(conf);
    handler.load(in);
    assertEquals("Wrong text of root", "text", conf.getString(""));

    conf.clearProperty("");
    saveTestConfig();
    checkSavedConfig();
}
 
Example 21
@Test
public void testSaveWithRootAttributes() throws ConfigurationException
{
    conf.setProperty("[@xmlns:ex]", "http://example.com/");
    assertEquals("Root attribute not set", "http://example.com/", conf
            .getString("[@xmlns:ex]"));
    final FileHandler handler = new FileHandler(conf);

    final StringWriter out = new StringWriter();
    handler.save(out);
    assertThat("Encoding was not written to file", out.toString(),
            containsString("testconfig xmlns:ex=\"http://example.com/\""));
}
 
Example 22
@Override
protected AbstractConfiguration createConfiguration()
{
    try
    {
        final XMLPropertyListConfiguration c = new XMLPropertyListConfiguration();
        new FileHandler(c).load(TEST_FILE);
        return c;
    }
    catch (final ConfigurationException cex)
    {
        throw new ConfigurationRuntimeException(cex);
    }
}
 
Example 23
Source Project: commons-configuration   Source File: TestExprLookup.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loads the test configuration.
 *
 * @return the test configuration
 * @throws ConfigurationException if an error occurs
 */
private static XMLConfiguration loadConfig() throws ConfigurationException
{
    final XMLConfiguration config = new XMLConfiguration();
    final FileHandler handler = new FileHandler(config);
    handler.load(TEST_FILE);
    return config;
}
 
Example 24
@Before
public void setUp() throws Exception
{
    final PropertiesConfiguration c = new PropertiesConfiguration();
    final FileHandler handler = new FileHandler(c);
    handler.setFileName(testProperties);
    handler.load();
    conf = c;
    nonStringTestHolder.setConfiguration(conf);
}
 
Example 25
/**
 * {@inheritDoc} This implementation also creates a copy of the
 * {@code FileHandler}.
 */
@Override
public FileBasedBuilderParametersImpl clone()
{
    final FileBasedBuilderParametersImpl copy =
            (FileBasedBuilderParametersImpl) super.clone();
    copy.fileHandler =
            new FileHandler(fileHandler.getContent(), fileHandler);
    return copy;
}
 
Example 26
Source Project: commons-configuration   Source File: AutoSaveListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates the {@code FileHandler}. This method is called by the builder
 * when a new configuration instance was created which is associated with a
 * new file handler. It updates the internal file handler reference and
 * performs necessary listener registrations.
 *
 * @param fh the new {@code FileHandler} (can be <b>null</b>)
 */
public synchronized void updateFileHandler(final FileHandler fh)
{
    if (handler != null)
    {
        handler.removeFileHandlerListener(this);
    }

    if (fh != null)
    {
        fh.addFileHandlerListener(this);
    }
    handler = fh;
}
 
Example 27
/**
 * Initializes the new current {@code FileHandler}. When a new result object
 * is created, a new {@code FileHandler} is created, too, and associated
 * with the result object. This new handler is passed to this method. If a
 * location is defined, the result object is loaded from this location.
 * Note: This method is called from a synchronized block.
 *
 * @param handler the new current {@code FileHandler}
 * @throws ConfigurationException if an error occurs
 */
protected void initFileHandler(final FileHandler handler)
        throws ConfigurationException
{
    initEncoding(handler);
    if (handler.isLocationDefined())
    {
        handler.locate();
        handler.load();
    }
}
 
Example 28
/**
 * Tests whether a non existing file is handled correctly.
 */
@Test
public void testLastModificationDateNonExisting()
{
    final File file = ConfigurationAssert.getOutFile("NonExistingFile.xml");
    final FileHandler handler = new FileHandler();
    handler.setFileSystem(new VFSFileSystem());
    handler.setFile(file);
    final VFSFileHandlerReloadingDetector strategy =
            new VFSFileHandlerReloadingDetector(handler);
    assertEquals("Got a modification date", 0,
            strategy.getLastModificationDate());
}
 
Example 29
/**
 * Tests a write operation if the wrapped configuration does not implement
 * FileBased.
 */
@Test(expected = ConfigurationException.class)
public void testSaveNotFileBased() throws ConfigurationException
{
    final HierarchicalConfiguration<ImmutableNode> hc = new BaseHierarchicalConfiguration();
    final PatternSubtreeConfigurationWrapper config =
            new PatternSubtreeConfigurationWrapper(hc, PATTERN);
    new FileHandler(config).save(new StringWriter());
}
 
Example 30
/**
 * {@inheritDoc} This implementation also takes care that a new
 * {@code ReloadingDetector} for the new current {@code FileHandler} is
 * created. Also, the reloading controller's reloading state has to be
 * reset; after the creation of a new result object changes in the
 * underlying configuration source have to be monitored again.
 */
@Override
protected void initFileHandler(final FileHandler handler)
        throws ConfigurationException
{
    super.initFileHandler(handler);

    resultReloadingDetector =
            createReloadingDetector(handler,
                    FileBasedBuilderParametersImpl.fromParameters(
                            getParameters(), true));
}