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

The following examples show how to use org.apache.commons.configuration2.ex.ConfigurationRuntimeException. 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: BaseConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a copy of this object. This implementation will create a deep
 * clone, i.e. the map that stores the properties is cloned, too. So changes
 * performed at the copy won't affect the original and vice versa.
 *
 * @return the copy
 * @since 1.3
 */
@Override
public Object clone()
{
    try
    {
        final BaseConfiguration copy = (BaseConfiguration) super.clone();
        cloneStore(copy);
        copy.cloneInterpolator(this);

        return copy;
    }
    catch (final CloneNotSupportedException cex)
    {
        // should not happen
        throw new ConfigurationRuntimeException(cex);
    }
}
 
Example #2
Source File: BeanHelper.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains the bean factory to use for creating the specified bean. This
 * method will check whether a factory is specified in the bean declaration.
 * If this is not the case, the default bean factory will be used.
 *
 * @param data the bean declaration
 * @return the bean factory to use
 * @throws ConfigurationRuntimeException if the factory cannot be determined
 */
private BeanFactory fetchBeanFactory(final BeanDeclaration data)
{
    final String factoryName = data.getBeanFactoryName();
    if (factoryName != null)
    {
        final BeanFactory factory = beanFactories.get(factoryName);
        if (factory == null)
        {
            throw new ConfigurationRuntimeException(
                    "Unknown bean factory: " + factoryName);
        }
        return factory;
    }
    return getDefaultBeanFactory();
}
 
Example #3
Source File: VFSFileHandlerReloadingDetector.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the file that is monitored by this strategy. Note that the return
 * value can be <b>null </b> under some circumstances.
 *
 * @return the monitored file
 */
protected FileObject getFileObject()
{
    if (!getFileHandler().isLocationDefined())
    {
        return null;
    }

    try
    {
        final FileSystemManager fsManager = VFS.getManager();
        final String uri = resolveFileURI();
        if (uri == null)
        {
            throw new ConfigurationRuntimeException("Unable to determine file to monitor");
        }
        return fsManager.resolveFile(uri);
    }
    catch (final FileSystemException fse)
    {
        final String msg = "Unable to monitor " + getFileHandler().getURL().toString();
        log.error(msg);
        throw new ConfigurationRuntimeException(msg, fse);
    }
}
 
Example #4
Source File: BeanHelper.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * The main method for creating and initializing beans from a configuration.
 * This method will return an initialized instance of the bean class
 * specified in the passed in bean declaration. If this declaration does not
 * contain the class of the bean, the passed in default class will be used.
 * From the bean declaration the factory to be used for creating the bean is
 * queried. The declaration may here return <b>null</b>, then a default
 * factory is used. This factory is then invoked to perform the create
 * operation.
 *
 * @param data the bean declaration
 * @param defaultClass the default class to use
 * @param param an additional parameter that will be passed to the bean
 * factory; some factories may support parameters and behave different
 * depending on the value passed in here
 * @return the new bean
 * @throws ConfigurationRuntimeException if an error occurs
 */
public Object createBean(final BeanDeclaration data, final Class<?> defaultClass,
        final Object param)
{
    if (data == null)
    {
        throw new IllegalArgumentException(
                "Bean declaration must not be null!");
    }

    final BeanFactory factory = fetchBeanFactory(data);
    final BeanCreationContext bcc =
            createBeanCreationContext(data, defaultClass, param, factory);
    try
    {
        return factory.createBean(bcc);
    }
    catch (final Exception ex)
    {
        throw new ConfigurationRuntimeException(ex);
    }
}
 
Example #5
Source File: BeanHelper.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Sets a property on the given bean using Common Beanutils.
 *
 * @param bean the bean
 * @param propName the name of the property
 * @param value the property's value
 * @throws ConfigurationRuntimeException if the property is not writeable or
 * an error occurred
 */
private static void initProperty(final Object bean, final String propName, final Object value)
{
    if (!isPropertyWriteable(bean, propName))
    {
        throw new ConfigurationRuntimeException("Property " + propName
                + " cannot be set on " + bean.getClass().getName());
    }

    try
    {
        BEAN_UTILS_BEAN.setProperty(bean, propName, value);
    }
    catch (final IllegalAccessException iaex)
    {
        throw new ConfigurationRuntimeException(iaex);
    }
    catch (final InvocationTargetException itex)
    {
        throw new ConfigurationRuntimeException(itex);
    }
}
 
Example #6
Source File: MapConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a copy of this object. The returned configuration will contain
 * the same properties as the original. Event listeners are not cloned.
 *
 * @return the copy
 * @since 1.3
 */
@Override
public Object clone()
{
    try
    {
        final MapConfiguration copy = (MapConfiguration) super.clone();
        // Safe because ConfigurationUtils returns a map of the same types.
        @SuppressWarnings("unchecked")
        final
        Map<String, Object> clonedMap = (Map<String, Object>) ConfigurationUtils.clone(map);
        copy.map = clonedMap;
        copy.cloneInterpolator(this);
        return copy;
    }
    catch (final CloneNotSupportedException cex)
    {
        // cannot happen
        throw new ConfigurationRuntimeException(cex);
    }
}
 
Example #7
Source File: BaseHierarchicalConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a sub configuration from the specified key which is independent
 * on this configuration. This means that the sub configuration operates on
 * a separate node model (although the nodes are initially shared).
 *
 * @param key the key of the sub configuration
 * @return the new sub configuration
 */
private BaseHierarchicalConfiguration createIndependentSubConfiguration(
        final String key)
{
    final List<ImmutableNode> targetNodes = fetchFilteredNodeResults(key);
    final int size = targetNodes.size();
    if (size != 1)
    {
        throw new ConfigurationRuntimeException(
                "Passed in key must select exactly one node (found %,d): %s", size, key);
    }
    final BaseHierarchicalConfiguration sub =
            new BaseHierarchicalConfiguration(new InMemoryNodeModel(
                    targetNodes.get(0)));
    initSubConfiguration(sub);
    return sub;
}
 
Example #8
Source File: NodeTracker.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code TrackedNodeData} object for a newly added observer for
 * the specified node selector.
 *
 * @param root the root node
 * @param selector the {@code NodeSelector}
 * @param resolver the {@code NodeKeyResolver}
 * @param handler the {@code NodeHandler}
 * @param trackData the current data for this selector
 * @return the updated {@code TrackedNodeData}
 * @throws ConfigurationRuntimeException if the selector does not select a
 *         single node
 */
private static TrackedNodeData trackDataForAddedObserver(
        final ImmutableNode root, final NodeSelector selector,
        final NodeKeyResolver<ImmutableNode> resolver,
        final NodeHandler<ImmutableNode> handler, final TrackedNodeData trackData)
{
    if (trackData != null)
    {
        return trackData.observerAdded();
    }
    final ImmutableNode target = selector.select(root, resolver, handler);
    if (target == null)
    {
        throw new ConfigurationRuntimeException(
                "Selector does not select unique node: " + selector);
    }
    return new TrackedNodeData(target);
}
 
Example #9
Source File: ConfigurationUtils.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Clones the given configuration object if this is possible. If the passed
 * in configuration object implements the {@code Cloneable}
 * interface, its {@code clone()} method will be invoked. Otherwise
 * an exception will be thrown.
 *
 * @param config the configuration object to be cloned (can be <b>null</b>)
 * @return the cloned configuration (<b>null</b> if the argument was
 * <b>null</b>, too)
 * @throws ConfigurationRuntimeException if cloning is not supported for
 * this object
 * @since 1.3
 */
public static Configuration cloneConfiguration(final Configuration config)
        throws ConfigurationRuntimeException
{
    if (config == null)
    {
        return null;
    }
    try
    {
        return (Configuration) clone(config);
    }
    catch (final CloneNotSupportedException cnex)
    {
        throw new ConfigurationRuntimeException(cnex);
    }
}
 
Example #10
Source File: TestDefaultBeanFactory.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the case that no matching constructor is found.
 */
@Test
public void testFindMatchingConstructorNoMatch()
{
    final BeanDeclarationTestImpl decl = new BeanDeclarationTestImpl();
    final Collection<ConstructorArg> args = new ArrayList<>();
    args.add(ConstructorArg.forValue(TEST_STRING, getClass().getName()));
    decl.setConstructorArgs(args);
    try
    {
        DefaultBeanFactory.findMatchingConstructor(BeanCreationTestCtorBean.class, decl);
        fail("No exception thrown!");
    }
    catch (final ConfigurationRuntimeException crex)
    {
        final String msg = crex.getMessage();
        assertTrue("Bean class not found:" + msg,
                msg.indexOf(BeanCreationTestCtorBean.class.getName()) > 0);
        assertTrue("Parameter value not found: " + msg,
                msg.indexOf(TEST_STRING) > 0);
        assertTrue("Parameter type not found: " + msg,
                msg.indexOf("(" + getClass().getName() + ')') > 0);
    }
}
 
Example #11
Source File: TestInMemoryNodeModelTrackedNodes.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether tracking of a node can be stopped.
 */
@Test
public void testUntrackNode()
{
    model.trackNode(selector, createResolver());
    model.untrackNode(selector);
    try
    {
        model.getTrackedNode(selector);
        fail("Could get untracked node!");
    }
    catch (final ConfigurationRuntimeException crex)
    {
        // expected
    }
}
 
Example #12
Source File: PropertiesConfigurationLayout.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a copy of this object.
 *
 * @return the copy
 */
@Override
public PropertyLayoutData clone()
{
    try
    {
        final PropertyLayoutData copy = (PropertyLayoutData) super.clone();
        if (comment != null)
        {
            // must copy string buffer, too
            copy.comment = new StringBuffer(getComment());
        }
        return copy;
    }
    catch (final CloneNotSupportedException cnex)
    {
        // This cannot happen!
        throw new ConfigurationRuntimeException(cnex);
    }
}
 
Example #13
Source File: TestVFSFileHandlerReloadingDetector.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a URI which cannot be resolved.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testLastModificationDateUnresolvableURI()
{
    final VFSFileHandlerReloadingDetector strategy =
            new VFSFileHandlerReloadingDetector()
            {
                @Override
                protected String resolveFileURI()
                {
                    return null;
                }
            };
    strategy.getFileHandler().setFileSystem(new VFSFileSystem());
    strategy.getFileHandler().setFileName("test.xml");
    strategy.getLastModificationDate();
}
 
Example #14
Source File: DatabaseConfigurationTestHelper.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code DataSource} managed by this class. The data
 * source is created on first access.
 *
 * @return the {@code DataSource}
 */
public DataSource getDatasource()
{
    if (datasource == null)
    {
        try
        {
            datasource = setUpDataSource();
        }
        catch (final Exception ex)
        {
            throw new ConfigurationRuntimeException(
                    "Could not create data source", ex);
        }
    }
    return datasource;
}
 
Example #15
Source File: TestConfigurationUtils.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether runtime exceptions can be enabled.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testEnableRuntimeExceptions()
{
    final PropertiesConfiguration config = new PropertiesConfiguration()
    {
        @Override
        protected void addPropertyDirect(final String key, final Object value)
        {
            // always simulate an exception
            fireError(ConfigurationErrorEvent.WRITE,
                    ConfigurationEvent.ADD_PROPERTY, key, value,
                    new RuntimeException("A faked exception!"));
        }
    };
    config.clearErrorListeners();
    ConfigurationUtils.enableRuntimeExceptions(config);
    config.addProperty("test", "testValue");
}
 
Example #16
Source File: TestBasicConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether a check for the correct bean class is made.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testGetResultDeclarationInvalidBeanClass()
        throws ConfigurationException
{
    final BasicConfigurationBuilder<PropertiesConfiguration> builder =
            new BasicConfigurationBuilder<PropertiesConfiguration>(
                    PropertiesConfiguration.class, createTestParameters())
            {
                @Override
                protected BeanDeclaration createResultDeclaration(
                        final Map<String, Object> params)
                {
                    return new XMLBeanDeclaration(
                            new BaseHierarchicalConfiguration(), "bean",
                            true, Object.class.getName());
                }
            };
    builder.getConfiguration();
}
 
Example #17
Source File: CopyObjectDefaultHandler.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc} This implementation uses
 * {@code PropertyUtils.copyProperties()} to copy all defined properties
 * from the source object onto the passed in parameters object. Both the map
 * with properties (obtained via the {@code getParameters()} method of the
 * source parameters object) and other properties of the source object are
 * copied.
 *
 * @throws ConfigurationRuntimeException if an exception occurs
 * @see BuilderParameters#getParameters()
 */
@Override
public void initializeDefaults(final Object parameters)
{
    try
    {
        BeanHelper.copyProperties(parameters, getSource()
                .getParameters());
        BeanHelper.copyProperties(parameters, getSource());
    }
    catch (final Exception e)
    {
        // Handle all reflection-related exceptions the same way
        throw new ConfigurationRuntimeException(e);
    }
}
 
Example #18
Source File: TestXMLBeanDeclaration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests constructing a bean declaration from a key with multiple values.
 * This should cause an exception because keys must be unique.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testInitFromMultiValueKey()
{
    final BaseHierarchicalConfiguration config = new BaseHierarchicalConfiguration();
    config.addProperty(KEY, "myFirstKey");
    config.addProperty(KEY, "mySecondKey");
    new XMLBeanDeclaration(config, KEY);
}
 
Example #19
Source File: TestConfigurationUtils.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether errors are handled correctly by cloneIfPossible().
 */
@Test
public void testCloneIfPossibleError()
{
    final XMLBuilderParametersImpl params = new XMLBuilderParametersImpl()
    {
        @Override
        public XMLBuilderParametersImpl clone()
        {
            throw new ConfigurationRuntimeException();
        }
    };
    assertSame("Wrong result", params,
            ConfigurationUtils.cloneIfPossible(params));
}
 
Example #20
Source File: TestCompositeConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests cloning if one of the contained configurations does not support
 * this operation. This should cause an exception.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testCloneNotSupported()
{
    cc.addConfiguration(new NonCloneableConfiguration());
    cc.clone();
}
 
Example #21
Source File: TestXMLListHandling.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to save the configuration with a different list delimiter handler
 * which does not support escaping of lists. This should fail with a
 * meaningful exception message.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testIncompatibleListDelimiterOnSaving()
        throws ConfigurationException
{
    config.setListDelimiterHandler(DisabledListDelimiterHandler.INSTANCE);
    saveToString();
}
 
Example #22
Source File: TestConfigurationUtils.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests cloning a configuration that does not support this operation. This
 * should cause an exception.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testCloneConfigurationNotSupported()
{
    final Configuration myNonCloneableConfig = new NonCloneableConfiguration();
    ConfigurationUtils.cloneConfiguration(myNonCloneableConfig);
}
 
Example #23
Source File: TestCombinedConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests adding a configuration with a name when this name already exists.
 * This should cause an exception.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testAddConfigurationWithNameTwice()
{
    config.addConfiguration(setUpTestConfiguration(), TEST_NAME);
    config.addConfiguration(setUpTestConfiguration(), TEST_NAME,
            "prefix");
}
 
Example #24
Source File: TestInMemoryNodeModelTrackedNodes.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests trackChildNodeWithCreation() if the passed in key selects multiple
 * nodes.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testTrackChildNodeWithCreationMultipleResults()
{
    final List<ImmutableNode> nodes =
            Arrays.asList(
                    NodeStructureHelper.nodeForKey(root, "tables/table(0)"),
                    NodeStructureHelper.nodeForKey(root, "tables/table(1)"));
    checkTrackChildNodeWithCreationInvalidKey(nodes);
}
 
Example #25
Source File: TestInMemoryNodeModelTrackedNodes.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to call trackNode() with a key that selects multiple results.
 */
@Test(expected = ConfigurationRuntimeException.class)
public void testTrackNodeKeyMultipleResults()
{
    model.trackNode(new NodeSelector("tables.table.fields.field.name"),
            createResolver());
}
 
Example #26
Source File: TestPropertyListConfigurationEvents.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractConfiguration createConfiguration()
{
    try
    {
        final PropertyListConfiguration c = new PropertyListConfiguration();
        new FileHandler(c).load(TEST_FILE);
        return c;
    }
    catch (final ConfigurationException cex)
    {
        throw new ConfigurationRuntimeException(cex);
    }
}
 
Example #27
Source File: TestXMLPropertyListConfigurationEvents.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: ConfigurationAssert.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for converting a file to a URL.
 *
 * @param file the file
 * @return the corresponding URL
 * @throws ConfigurationRuntimeException if the URL cannot be constructed
 */
private static URL urlFromFile(final File file)
{
    try
    {
        return file.toURI().toURL();
    }
    catch (final MalformedURLException mex)
    {
        throw new ConfigurationRuntimeException(mex);
    }
}
 
Example #29
Source File: TestCombinedConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether requested locks are freed correctly if an exception occurs
 * while constructing the root node.
 */
@Test
public void testLockHandlingWithExceptionWhenConstructingRootNode()
{
    final SynchronizerTestImpl sync = setUpSynchronizerTest();
    final RuntimeException testEx =
            new ConfigurationRuntimeException("Test exception");
    final BaseHierarchicalConfiguration childEx =
            new BaseHierarchicalConfiguration()
            {
                @Override
                public NodeModel<ImmutableNode> getModel() {
                    throw testEx;
                }
            };
    config.addConfiguration(childEx);
    try
    {
        config.lock(LockMode.READ);
        fail("Exception not detected!");
    }
    catch (final Exception ex)
    {
        assertEquals("Unexpected exception", testEx, ex);
    }
    // 1 x add configuration, then obtain read lock and create root node
    sync.verify(Methods.BEGIN_WRITE, Methods.END_WRITE, Methods.BEGIN_READ,
            Methods.END_READ, Methods.BEGIN_WRITE, Methods.END_WRITE);
}
 
Example #30
Source File: CamelMailetContainerModule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
HierarchicalConfiguration<ImmutableNode> getProcessorConfiguration() throws ConfigurationException {
    HierarchicalConfiguration<ImmutableNode> mailetContainerConfiguration = configurationProvider.getConfiguration("mailetcontainer");
    try {
        return mailetContainerConfiguration.configurationAt("processors");
    } catch (ConfigurationRuntimeException e) {
        LOGGER.warn("Could not load configuration for Processors. Fallback to default.");
        return defaultProcessorsConfigurationSupplier.getDefaultConfiguration();
    }
}