Java Code Examples for org.apache.commons.configuration2.ex.ConfigurationException

The following examples show how to use org.apache.commons.configuration2.ex.ConfigurationException. 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
/**
 * Simulates the propertyLoaded() callback. If a builder was set, a
 * load() call on the layout is invoked.
 */
@Override
boolean propertyLoaded(final String key, final String value, Deque<URL> seenStack)
        throws ConfigurationException
{
    if (builder == null)
    {
        return super.propertyLoaded(key, value, seenStack);
    }
    if (PropertiesConfiguration.getInclude().equals(key))
    {
        getLayout().load(this, builder.getReader());
        return false;
    }
    return true;
}
 
Example 2
/**
 * Tests different access methods for properties.
 */
@Test
public void testUnmodifiableConfigurationOtherTypes()
        throws ConfigurationException
{
    final ImmutableConfiguration conf =
            ConfigurationUtils
                    .unmodifiableConfiguration(createTestConfig());
    assertEquals("Wrong byte", (byte) 10, conf.getByte("test.byte"));
    assertEquals("Wrong boolean", true, conf.getBoolean("test.boolean"));
    assertEquals("Wrong double", 10.25, conf.getDouble("test.double"), .05);
    assertEquals("Wrong float", 20.25f, conf.getFloat("test.float"), .05);
    assertEquals("Wrong int", 10, conf.getInt("test.integer"));
    assertEquals("Wrong long", 1000000L, conf.getLong("test.long"));
    assertEquals("Wrong short", (short) 1, conf.getShort("test.short"));
}
 
Example 3
/**
 * Tests whether this builder reacts on events fired by the reloading
 * controller.
 */
@Test
public void testReloadingControllerEvents() throws ConfigurationException
{
    final ReloadingDetector detector =
            EasyMock.createMock(ReloadingDetector.class);
    EasyMock.expect(detector.isReloadingRequired()).andReturn(Boolean.TRUE);
    final ReloadingFileBasedConfigurationBuilderTestImpl builder =
            new ReloadingFileBasedConfigurationBuilderTestImpl(detector);
    EasyMock.replay(detector);
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    builder.addEventListener(ConfigurationBuilderEvent.RESET, listener);
    builder.getConfiguration();
    builder.getReloadingController().checkForReloading(null);
    listener.nextEvent(ConfigurationBuilderEvent.RESET);
    listener.assertNoMoreEvents();
    EasyMock.verify(detector);
}
 
Example 4
/**
 * Tests whether a subnode configuration created from another subnode
 * configuration of a XMLConfiguration can trigger the auto save mechanism.
 */
@Test
public void testAutoSaveWithSubSubnodeConfig() throws ConfigurationException
{
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFileName(testProperties));
    conf = builder.getConfiguration();
    builder.getFileHandler().setFile(testSaveConf);
    builder.setAutoSave(true);
    final String newValue = "I am autosaved";
    final HierarchicalConfiguration<?> sub1 = conf.configurationAt("element2", true);
    final HierarchicalConfiguration<?> sub2 = sub1.configurationAt("subelement", true);
    sub2.setProperty("subsubelement", newValue);
    assertEquals("Change not visible to parent", newValue, conf
            .getString("element2.subelement.subsubelement"));
    final XMLConfiguration conf2 = new XMLConfiguration();
    load(conf2, testSaveConf.getAbsolutePath());
    assertEquals("Change was not saved", newValue, conf2
            .getString("element2.subelement.subsubelement"));
}
 
Example 5
/**
 * Tests whether the definition builder created by default supports
 * reloading.
 */
@Test
public void testReloadableDefinitionBuilder() throws ConfigurationException
{
    final File testFile =
            ConfigurationAssert
                    .getTestFile("testDigesterConfiguration.xml");
    final ReloadingCombinedConfigurationBuilder confBuilder =
            builder.configure(new FileBasedBuilderParametersImpl()
                    .setFile(testFile));
    assertSame("Wrong configured builder instance", builder, confBuilder);
    builder.getConfiguration();
    final CombinedReloadingController rc =
            (CombinedReloadingController) builder.getReloadingController();
    final Collection<ReloadingController> subControllers = rc.getSubControllers();
    assertEquals("Wrong number of sub controllers", 1,
            subControllers.size());
    final ReloadingController subctrl =
            ((ReloadingControllerSupport) builder.getDefinitionBuilder())
                    .getReloadingController();
    assertSame("Wrong sub controller", subctrl, subControllers.iterator()
            .next());
}
 
Example 6
/**
 * Tests setting an attribute on the root element.
 */
@Test
public void testSetRootAttribute() throws ConfigurationException
{
    conf.setProperty("[@test]", "true");
    assertEquals("Root attribute not set", "true", conf
            .getString("[@test]"));
    saveTestConfig();
    XMLConfiguration checkConf = checkSavedConfig();
    assertTrue("Attribute not found after save", checkConf
            .containsKey("[@test]"));
    checkConf.setProperty("[@test]", "newValue");
    conf = checkConf;
    saveTestConfig();
    checkConf = checkSavedConfig();
    assertEquals("Attribute not modified after save", "newValue", checkConf
            .getString("[@test]"));
}
 
Example 7
/**
 * Determines the name of the class to be used for a new builder instance.
 * This implementation selects between the normal and the reloading builder
 * class, based on the passed in {@code ConfigurationDeclaration}. If a
 * reloading builder is desired, but this provider has no reloading support,
 * an exception is thrown.
 *
 * @param decl the current {@code ConfigurationDeclaration}
 * @return the name of the builder class
 * @throws ConfigurationException if the builder class cannot be determined
 */
protected String determineBuilderClass(final ConfigurationDeclaration decl)
        throws ConfigurationException
{
    if (decl.isReload())
    {
        if (getReloadingBuilderClass() == null)
        {
            throw new ConfigurationException(
                    "No support for reloading for builder class "
                            + getBuilderClass());
        }
        return getReloadingBuilderClass();
    }
    return getBuilderClass();
}
 
Example 8
/**
 * Tests whether variable substitution works across multiple child
 * configurations and also in the definition configuration.
 */
@Test
public void testInterpolationOverMultipleSources()
        throws ConfigurationException
{
    final File testFile =
            ConfigurationAssert.getTestFile("testInterpolationBuilder.xml");
    builder.configure(createParameters().setFile(testFile));
    final CombinedConfiguration combConfig = builder.getConfiguration();
    assertEquals("Wrong value", "abc-product",
            combConfig.getString("products.product.desc"));
    final XMLConfiguration xmlConfig =
            (XMLConfiguration) combConfig.getConfiguration("test");
    assertEquals("Wrong value from XML config", "abc-product",
            xmlConfig.getString("products/product/desc"));
    final HierarchicalConfiguration<ImmutableNode> subConfig =
            xmlConfig
                    .configurationAt("products/product[@name='abc']", true);
    assertEquals("Wrong value from sub config", "abc-product",
            subConfig.getString("desc"));
}
 
Example 9
/**
 * Tests whether an expression engine can be used which ignores case.
 */
@Test
public void testExpressionEngineIgnoringCase()
        throws ConfigurationException
{
    final DefaultExpressionEngine engine =
            new DefaultExpressionEngine(
                    DefaultExpressionEngineSymbols.DEFAULT_SYMBOLS,
                    NodeNameMatchers.EQUALS_IGNORE_CASE);
    final INIConfiguration config = new INIConfiguration();
    config.setExpressionEngine(engine);
    load(config, INI_DATA);

    checkContent(config);
    assertEquals("Wrong result (1)", "foo",
            config.getString("Section1.var1"));
    assertEquals("Wrong result (2)", "foo",
            config.getString("section1.Var1"));
    assertEquals("Wrong result (1)", "foo",
            config.getString("SECTION1.VAR1"));
}
 
Example 10
/**
 * Tests concurrent access to the global section.
 */
@Test
public void testGetSectionGloabalMultiThreaded()
        throws ConfigurationException, InterruptedException
{
    final INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
    config.setSynchronizer(new ReadWriteSynchronizer());
    final int threadCount = 10;
    final GlobalSectionTestThread[] threads = new GlobalSectionTestThread[threadCount];
    for (int i = 0; i < threadCount; i++)
    {
        threads[i] = new GlobalSectionTestThread(config);
        threads[i].start();
    }
    for (int i = 0; i < threadCount; i++)
    {
        threads[i].join();
        assertFalse("Exception occurred", threads[i].error);
    }
}
 
Example 11
/**
 * Tests whether a configuration is loaded from file if a location is
 * provided.
 */
@Test
public void testGetConfigurationLoadFromFile()
        throws ConfigurationException
{
    final File file = createTestFile(1);
    final FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    PropertiesConfiguration.class)
                    .configure(new FileBasedBuilderParametersImpl()
                            .setFile(file));
    final PropertiesConfiguration config = builder.getConfiguration();
    assertEquals("Not read from file", 1, config.getInt(PROP));
    assertSame("FileHandler not initialized", config, builder
            .getFileHandler().getContent());
}
 
Example 12
/**
 * Tests the reloadingPerformed() implementation of the detector associated
 * with the reloading controller.
 */
@Test
public void testReloadingDetectorReloadingPerformed()
        throws ConfigurationException
{
    final ReloadingDetector detector =
            EasyMock.createMock(ReloadingDetector.class);
    detector.reloadingPerformed();
    EasyMock.replay(detector);
    final ReloadingFileBasedConfigurationBuilderTestImpl builder =
            new ReloadingFileBasedConfigurationBuilderTestImpl(detector);
    builder.getConfiguration();
    final ReloadingDetector ctrlDetector =
            builder.getReloadingController().getDetector();
    ctrlDetector.reloadingPerformed();
    EasyMock.verify(detector);
}
 
Example 13
/**
 * Tests if the content of the layout object is correctly written.
 */
@Test
public void testSave() throws ConfigurationException
{
    config.addProperty(TEST_KEY, TEST_VALUE);
    layout.setComment(TEST_KEY, TEST_COMMENT);
    config.addProperty(TEST_KEY, TEST_VALUE + "2");
    config.addProperty("AnotherProperty", "AnotherValue");
    config.addProperty("AnotherProperty", "3rdValue");
    layout.setComment("AnotherProperty", "AnotherComment");
    layout.setBlancLinesBefore("AnotherProperty", 2);
    layout.setSingleLine("AnotherProperty", true);
    layout.setHeaderComment("A header comment" + CRNORM + "for my properties");
    checkLayoutString("# A header comment" + CR + "# for my properties"
            + CR + CR + "# " + TEST_COMMENT + CR + TEST_KEY + " = "
            + TEST_VALUE + CR + TEST_KEY + " = " + TEST_VALUE + "2" + CR
            + CR + CR + "# AnotherComment" + CR
            + "AnotherProperty = AnotherValue,3rdValue" + CR);
}
 
Example 14
/**
 * Tests whether an empty CLOB is correctly handled by
 * extractPropertyValue().
 */
@Test
public void testExtractPropertyValueCLOBEmpty()
        throws ConfigurationException, SQLException
{
    final ResultSet rs = EasyMock.createMock(ResultSet.class);
    final Clob clob = EasyMock.createMock(Clob.class);
    EasyMock.expect(rs.getObject(DatabaseConfigurationTestHelper.COL_VALUE))
            .andReturn(clob);
    EasyMock.expect(clob.length()).andReturn(0L);
    EasyMock.replay(rs, clob);
    final DatabaseConfiguration config = helper.setUpConfig();
    assertEquals("Wrong extracted value", "",
            config.extractPropertyValue(rs));
    EasyMock.verify(rs, clob);
}
 
Example 15
/**
 * Returns a mock builder which always returns the specified configuration.
 *
 * @param conf the builder's result configuration
 * @return the mock builder
 */
private ConfigurationBuilder<BaseHierarchicalConfiguration> createBuilderMock(
        final BaseHierarchicalConfiguration conf)
{
    @SuppressWarnings("unchecked")
    final
    ConfigurationBuilder<BaseHierarchicalConfiguration> builder =
            EasyMock.createMock(ConfigurationBuilder.class);
    try
    {
        EasyMock.expect(builder.getConfiguration()).andReturn(conf)
                .anyTimes();
    }
    catch (final ConfigurationException e)
    {
        // Cannot happen
        fail("Unexpected exception: " + e);
    }
    return builder;
}
 
Example 16
/**
 * Tests whether a result created event is correctly generated.
 */
@Test
public void testResultCreatedEvent() throws ConfigurationException
{
    final BasicConfigurationBuilder<PropertiesConfiguration> builder =
            new BasicConfigurationBuilder<>(
                    PropertiesConfiguration.class);
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    builder.addEventListener(ConfigurationBuilderEvent.ANY, listener);

    final PropertiesConfiguration configuration = builder.getConfiguration();
    listener.nextEvent(ConfigurationBuilderEvent.CONFIGURATION_REQUEST);
    final ConfigurationBuilderResultCreatedEvent event =
            listener.nextEvent(ConfigurationBuilderResultCreatedEvent.RESULT_CREATED);
    assertSame("Wrong builder", builder, event.getSource());
    assertSame("Wrong configuration", configuration,
            event.getConfiguration());
}
 
Example 17
/**
 * Tests whether builder reset events are handled correctly.
 */
@Test
public void testBuilderListenerReset() throws ConfigurationException
{
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders =
            new ArrayList<>();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createBuilderWithAccessToManagedBuilders(managedBuilders);
    switchToConfig(1);
    builder.addEventListener(ConfigurationBuilderEvent.RESET, listener);
    final XMLConfiguration configuration = builder.getConfiguration();
    managedBuilders.iterator().next().resetResult();
    final ConfigurationBuilderEvent event =
            listener.nextEvent(ConfigurationBuilderEvent.RESET);
    assertSame("Wrong event source", builder, event.getSource());
    assertNotSame("Configuration not reset", configuration,
            builder.getConfiguration());
}
 
Example 18
Source Project: commons-configuration   Source File: FileHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Internal helper method for saving data to the given {@code File}.
 *
 * @param file the target file
 * @param locator the current {@code FileLocator}
 * @throws ConfigurationException if an error occurs during the save
 *         operation
 */
private void save(final File file, final FileLocator locator) throws ConfigurationException
{
    OutputStream out = null;

    try
    {
        out = FileLocatorUtils.obtainFileSystem(locator).getOutputStream(file);
        saveToStream(out, locator.getEncoding(), file.toURI().toURL());
    }
    catch (final MalformedURLException muex)
    {
        throw new ConfigurationException(muex);
    }
    finally
    {
        closeSilent(out);
    }
}
 
Example 19
/**
 * Internal helper method to wrap an exception in a
 * {@code ConfigurationException}.
 * @param e the exception to be wrapped
 * @throws ConfigurationException the resulting exception
 */
static void rethrowException(final Exception e) throws ConfigurationException
{
    if (e instanceof ClassCastException)
    {
        throw new ConfigurationException("Error parsing", e);
    }
    throw new ConfigurationException("Unable to load the configuration",
            e);
}
 
Example 20
@Singleton
@Provides
LocalFileBlobExportMechanism.Configuration localFileExportConfiguration(PropertiesProvider propertiesProvider) throws ConfigurationException {
    try {
        Configuration configuration = propertiesProvider.getConfigurations(ConfigurationComponent.NAMES);
        return LocalFileBlobExportMechanism.Configuration.from(configuration)
            .orElseGet(() -> {
                LOGGER.warn("Missing LocalFileBlobExportMechanism configuration, using default localFile blob exporting configuration");
                return LocalFileBlobExportMechanism.Configuration.DEFAULT_CONFIGURATION;
            });
    } catch (FileNotFoundException e) {
        LOGGER.warn("Could not find " + ConfigurationComponent.NAME + " configuration file, using default localFile blob exporting configuration");
        return LocalFileBlobExportMechanism.Configuration.DEFAULT_CONFIGURATION;
    }
}
 
Example 21
Source Project: commons-configuration   Source File: TestConfigurations.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a INI configuration can be loaded from a file.
 */
@Test
public void testINIFromFile() throws ConfigurationException
{
    final Configurations configs = new Configurations();
    final INIConfiguration config =
            configs.ini(ConfigurationAssert.getTestFile(TEST_INI));
    checkINI(config);
}
 
Example 22
Source Project: commons-configuration   Source File: TestConfigurations.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a builder for a XML configuration can be created for a
 * given file.
 */
@Test
public void testXMLBuilderFromFile() throws ConfigurationException
{
    final Configurations configs = new Configurations();
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            configs.xmlBuilder(ConfigurationAssert.getTestFile(TEST_XML));
    checkXML(builder.getConfiguration());
}
 
Example 23
Source Project: commons-configuration   Source File: TestConfigurations.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a properties configuration can be loaded from a URL.
 */
@Test
public void testPropertiesFromURL() throws ConfigurationException
{
    final Configurations configs = new Configurations();
    final PropertiesConfiguration config =
            configs.properties(ConfigurationAssert
                    .getTestURL(TEST_PROPERTIES));
    checkProperties(config);
}
 
Example 24
Source Project: commons-configuration   Source File: FileLocatorUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to locate the file referenced by the passed in {@code FileLocator}.
 * If this fails, an exception is thrown. This method works like
 * {@link #locate(FileLocator)}; however, in case of a failed location
 * attempt an exception is thrown.
 *
 * @param locator the {@code FileLocator} to be resolved
 * @return the URL pointing to the referenced file
 * @throws ConfigurationException if the file cannot be resolved
 */
public static URL locateOrThrow(final FileLocator locator)
        throws ConfigurationException
{
    final URL url = locate(locator);
    if (url == null)
    {
        throw new ConfigurationException("Could not locate: " + locator);
    }
    return url;
}
 
Example 25
/**
 * Tests whether the configuration deals correctly with list delimiters.
 */
@Test
public void testListDelimiterHandling() throws ConfigurationException
{
    final INIConfiguration config = new INIConfiguration();
    config.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
    config.addProperty("list", "a,b,c");
    config.addProperty("listesc", "3\\,1415");
    final String output = saveToString(config);
    final INIConfiguration config2 = setUpConfig(output);
    assertEquals("Wrong list size", 3, config2.getList("list").size());
    assertEquals("Wrong list element", "b", config2.getList("list").get(1));
    assertEquals("Wrong escaped list element", "3,1415",
            config2.getString("listesc"));
}
 
Example 26
Source Project: t-io   Source File: ConfigUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param filename1
 * @param filename2
 * @param encoding
 * @param listDelimiter
 * @return
 * @throws FileNotFoundException
 * @author: tanyaowu
 */
public static PropertiesConfiguration initConfig(String filename1, String filename2, String encoding, char listDelimiter) throws FileNotFoundException {
	Parameters _parameters = new Parameters();
	PropertiesBuilderParameters parameters = _parameters.properties();
	String filename = filename1;
	ClassLoader cl = ConfigUtils.class.getClassLoader();
	URL url = null;
	if (StrUtil.isNotBlank(filename1)) {
		url = (cl != null ? cl.getResource(filename1) : ClassLoader.getSystemResource(filename1));
	}

	if (url == null) {
		url = (cl != null ? cl.getResource(filename2) : ClassLoader.getSystemResource(filename2));
		if (url == null) {
			throw new FileNotFoundException(filename1);
		}
		filename = filename2;
	}

	parameters.setFileName(filename);
	parameters.setThrowExceptionOnMissing(false);
	parameters.setEncoding(encoding);
	parameters.setListDelimiterHandler(new DefaultListDelimiterHandler(listDelimiter));
	parameters.setReloadingDetectorFactory(new DefaultReloadingDetectorFactory());
	parameters.setIncludesAllowed(true);
	FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(parameters);

	try {
		PropertiesConfiguration config = builder.getConfiguration();
		return config;
	} catch (ConfigurationException e) {
		log.error(e.toString(), e);
		return null;
	}
}
 
Example 27
/**
 * Tests whether the node handler of a global section correctly filters
 * named children.
 */
@Test
public void testGlobalSectionNodeHandlerGetChildrenByName()
        throws ConfigurationException
{
    final INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
    final SubnodeConfiguration sub = config.getSection(null);
    final NodeHandler<ImmutableNode> handler = sub.getModel().getNodeHandler();
    assertTrue(
            "Sections not filtered",
            handler.getChildren(
                    sub.getModel().getNodeHandler().getRootNode(),
                    "section1").isEmpty());
}
 
Example 28
Source Project: commons-configuration   Source File: TestFileHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether data can be saved into a Writer.
 */
@Test
public void testSaveToWriter() throws ConfigurationException
{
    final FileBasedTestImpl content = new FileBasedTestImpl();
    final FileHandler handler = new FileHandler(content);
    final StringWriter out = new StringWriter();
    handler.save(out);
    assertEquals("Wrong content", CONTENT, out.toString());
}
 
Example 29
/**
 * Registers providers defined in the configuration.
 *
 * @param defConfig the definition configuration
 * @throws ConfigurationException if an error occurs
 */
private void registerConfiguredProviders(final HierarchicalConfiguration<?> defConfig)
        throws ConfigurationException
{
    final List<? extends HierarchicalConfiguration<?>> nodes =
            defConfig.configurationsAt(KEY_CONFIGURATION_PROVIDERS);
    for (final HierarchicalConfiguration<?> config : nodes)
    {
        final XMLBeanDeclaration decl = new XMLBeanDeclaration(config);
        final String key = config.getString(KEY_PROVIDER_KEY);
        currentParameters.registerProvider(key,
                (ConfigurationBuilderProvider) fetchBeanHelper().createBean(decl));
    }
}
 
Example 30
@Test
public void testClearMultiple() throws ConfigurationException
{
    final Configuration config = helper.setUpMultiConfig();
    config.clear();

    assertTrue("configuration is not cleared", config.isEmpty());
}