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

The following examples show how to use org.apache.commons.configuration2.ex.ConfigurationException. 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 File: TestReloadingFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: TestPropertiesConfigurationLayout.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: TestImmutableConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: TestReloadingFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: FileHandler.java    From commons-configuration with 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 #6
Source File: BaseConfigurationBuilderProvider.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: TestReloadingCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: TestBasicConfigurationBuilderEvents.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #11
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #12
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #13
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source File: TestBuilderConfigurationWrapperFactory.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #15
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: TestFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #17
Source File: TestDatabaseConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #18
Source File: TestPropertiesConfigurationLayout.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #19
Source File: GlobalOptions.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
public DSPropertiesConfiguration(URL url) throws ConfigurationException {
    this();
    try {
        GLOBAL_PROPERTIES.read(new URLReader(url));
    } catch (IOException ex) {
        logger.error("Can't read Global options", ex);
    }
}
 
Example #20
Source File: SimpleConfiguration.java    From fluo with Apache License 2.0 5 votes vote down vote up
/**
 * Loads configuration from File. Later loads have lower priority.
 * 
 * @param file File to load from
 * @since 1.2.0
 */
public void load(File file) {
  try (InputStream in = Files.newInputStream(file.toPath())) {
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.getLayout().load(config, checkProps(in));
    ((CompositeConfiguration) internalConfig).addConfiguration(config);
  } catch (ConfigurationException | IOException e) {
    throw new IllegalArgumentException(e);
  }
}
 
Example #21
Source File: TestOverrideCombiner.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if a list from the second structure is added if it is not defined
 * in the first structure.
 */
@Test
public void testListFromSecondStructure() throws ConfigurationException
{
    final BaseHierarchicalConfiguration config = createCombinedConfiguration();
    assertEquals("Wrong number of servers", 3, config
            .getMaxIndex("net.server.url"));
    assertEquals("Wrong server", "http://testsvr.com", config
            .getString("net.server.url(2)"));
}
 
Example #22
Source File: MailetPreconditionTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void filteringMailetCheckShouldThrowOnWrongMailet() {
    List<MatcherMailetPair> pairs = Lists.newArrayList(new MatcherMailetPair(new RecipientIsLocal(), new Null()));

    assertThatThrownBy(() -> JMAPModule.FILTERING_MAILET_CHECK.check(pairs))
        .isInstanceOf(ConfigurationException.class);
}
 
Example #23
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether property values are correctly escaped even if they are part
 * of a property with multiple values.
 */
@Test
public void testListDelimiterHandlingInList() throws ConfigurationException
{
    final String data =
            INI_DATA + "[sectest]" + LINE_SEPARATOR
                    + "list = 3\\,1415,pi,\\\\Test\\,5" + LINE_SEPARATOR;
    final INIConfiguration config = setUpConfig(data);
    final INIConfiguration config2 = setUpConfig(saveToString(config));
    final List<Object> list = config2.getList("sectest.list");
    assertEquals("Wrong number of values", 3, list.size());
    assertEquals("Wrong element 1", "3,1415", list.get(0));
    assertEquals("Wrong element 3", "\\Test,5", list.get(2));
}
 
Example #24
Source File: ElasticSearchConfigurationTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void validateHostsConfigurationOptionsShouldThrowWhenMonoHostWithoutPort() {
    assertThatThrownBy(() ->
        ElasticSearchConfiguration.validateHostsConfigurationOptions(
            Optional.of("localhost"),
            Optional.empty(),
            ImmutableList.of()))
        .isInstanceOf(ConfigurationException.class)
        .hasMessage(ElasticSearchConfiguration.ELASTICSEARCH_MASTER_HOST +
            " and " + ElasticSearchConfiguration.ELASTICSEARCH_PORT + " should be specified together");
}
 
Example #25
Source File: ExtensionModule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
ExtensionConfiguration extensionConfiguration(PropertiesProvider propertiesProvider) {
    try {
        Configuration configuration = propertiesProvider.getConfiguration("extensions");
        return ExtensionConfiguration.from(configuration);
    } catch (FileNotFoundException | ConfigurationException e) {
        LoggerFactory.getLogger(ExtensionModule.class).info("No extensions.properties configuration found. No additional Guice module will be used for instantiating extensions.");
        return ExtensionConfiguration.DEFAULT;
    }
}
 
Example #26
Source File: TestMergeCombiner.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether property values are correctly overridden.
 */
@Test
public void testOverrideValues() throws ConfigurationException
{
    final BaseHierarchicalConfiguration config = createCombinedConfiguration();
    assertEquals("Wrong user", "Admin", config
            .getString("base.services.security.login.user"));
    assertEquals("Wrong user type", "default", config
            .getString("base.services.security.login.user[@type]"));
    assertNull("Wrong password", config.getString("base.services.security.login.passwd"));
    assertEquals("Wrong password type", "secret", config
            .getString("base.services.security.login.passwd[@type]"));
}
 
Example #27
Source File: TestBasicConfigurationBuilder.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether the builder can create a correctly initialized
 * configuration object.
 */
@Test
public void testGetConfiguration() throws ConfigurationException
{
    final PropertiesConfiguration config =
            new BasicConfigurationBuilder<>(
                    PropertiesConfiguration.class).configure(
                    new BasicBuilderParameters().setListDelimiterHandler(
                            listHandler).setThrowExceptionOnMissing(true))
                    .getConfiguration();
    assertTrue("Wrong exception flag", config.isThrowExceptionOnMissing());
    assertEquals("Wrong list delimiter handler", listHandler,
            config.getListDelimiterHandler());
}
 
Example #28
Source File: TestBasicConfigurationBuilder.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests an exception during configuration initialization if the
 * allowFailOnInit flag is false.
 */
@Test(expected = ConfigurationException.class)
public void testInitializationErrorNotAllowed()
        throws ConfigurationException
{
    final BasicConfigurationBuilderInitFailImpl builder =
            new BasicConfigurationBuilderInitFailImpl(false);
    builder.getConfiguration();
}
 
Example #29
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a property whose value spans multiple lines with a comment.
 */
@Test
public void testLineContinuationComment() throws ConfigurationException
{
    final INIConfiguration config = setUpConfig(INI_DATA3);
    assertEquals("Wrong value", "one" + LINE_SEPARATOR + "two", config
            .getString("section5.multiComment"));
}
 
Example #30
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests an empty quoted value.
 */
@Test
public void testQuotedValueEmpty() throws ConfigurationException
{
    final INIConfiguration config = setUpConfig(INI_DATA2);
    assertEquals("Wrong value for empty property", "", config
            .getString("section4.var6"));
}