Example usage for org.apache.commons.configuration CompositeConfiguration getString

List of usage examples for org.apache.commons.configuration CompositeConfiguration getString

Introduction

In this page you can find the example usage for org.apache.commons.configuration CompositeConfiguration getString.

Prototype

public String getString(String key) 

Source Link

Usage

From source file:net.elsched.utils.SettingsBinder.java

/**
 * Bind configuration parameters into Guice Module.
 * /*from   w w  w .  j a v  a 2s.com*/
 * @return a Guice module configured with setting support.
 * @throws ConfigurationException
 *             on configuration error
 */
public static Module bindSettings(String propertiesFileKey, Class<?>... settingsArg)
        throws ConfigurationException {
    final CompositeConfiguration config = new CompositeConfiguration();
    config.addConfiguration(new SystemConfiguration());
    String propertyFile = config.getString(propertiesFileKey);

    if (propertyFile != null) {
        config.addConfiguration(new PropertiesConfiguration(propertyFile));
    }

    List<Field> fields = new ArrayList<Field>();
    for (Class<?> settings : settingsArg) {
        fields.addAll(Arrays.asList(settings.getDeclaredFields()));
    }

    // Reflect on settings class and absorb settings
    final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>();
    for (Field field : fields) {
        if (!field.isAnnotationPresent(Setting.class)) {
            continue;
        }

        // Validate target type
        SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType());
        if (typeHelper == null || !typeHelper.check(field.getGenericType())) {
            throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types");
        }

        Setting setting = field.getAnnotation(Setting.class);
        settings.put(setting, field);
    }

    // Now validate them
    List<String> missingProperties = new ArrayList<String>();
    for (Setting setting : settings.keySet()) {
        if (setting.defaultValue().isEmpty()) {
            if (!config.containsKey(setting.name())) {
                missingProperties.add(setting.name());
            }
        }
    }
    if (missingProperties.size() > 0) {
        StringBuilder error = new StringBuilder();
        error.append("The following required properties are missing from the server configuration: ");
        error.append(Joiner.on(", ").join(missingProperties));
    }

    // bundle everything up in an injectable guice module
    return new AbstractModule() {

        @Override
        protected void configure() {
            // We must iterate the settings a third time when binding.
            // Note: do not collapse these loops as that will damage
            // early error detection. The runtime is still O(n) in setting
            // count.
            for (Map.Entry<Setting, Field> entry : settings.entrySet()) {
                Class<?> type = entry.getValue().getType();
                Setting setting = entry.getKey();

                if (int.class.equals(type)) {
                    Integer defaultValue = null;
                    if (!setting.defaultValue().isEmpty()) {
                        defaultValue = Integer.parseInt(setting.defaultValue());
                    }
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getInteger(setting.name(), defaultValue));
                } else if (boolean.class.equals(type)) {
                    Boolean defaultValue = null;
                    if (!setting.defaultValue().isEmpty()) {
                        defaultValue = Boolean.parseBoolean(setting.defaultValue());
                    }
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getBoolean(setting.name(), defaultValue));
                } else if (String.class.equals(type)) {
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getString(setting.name(), setting.defaultValue()));
                } else {
                    String[] value = config.getStringArray(setting.name());
                    if (value.length == 0 && !setting.defaultValue().isEmpty()) {
                        value = setting.defaultValue().split(",");
                    }
                    bind(new TypeLiteral<List<String>>() {
                    }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value));
                }
            }
        }
    };
}

From source file:mpaf.ice.IceModel.java

public IceModel(CompositeConfiguration config) {
    this.config = config;
    secret = config.getString("ice.secret");
    serverIp = config.getString("ice.hosts.remote");
    clientIp = config.getString("ice.hosts.local");
    icePort = config.getString("ice.port");
}

From source file:com.dattack.naming.loader.factory.DataSourceFactory.java

@Override
public DataSource getObjectInstance(final Properties properties, final Collection<File> extraClasspath)
        throws NamingException {

    final CompositeConfiguration configuration = new CompositeConfiguration();
    configuration.addConfiguration(new SystemConfiguration());
    configuration.addConfiguration(new EnvironmentConfiguration());
    configuration.addConfiguration(new MapConfiguration(properties));

    final String driver = configuration.getString(DRIVER_KEY);
    if (driver == null) {
        throw new ConfigurationException(String.format("Missing property '%s'", DRIVER_KEY));
    }//from   w ww .ja va 2  s .c o  m

    final String url = configuration.getString(URL_KEY);
    if (url == null) {
        throw new ConfigurationException(String.format("Missing property '%s'", URL_KEY));
    }

    final String user = configuration.getString(USERNAME_KEY);
    final String password = configuration.getString(PASSWORD_KEY);

    DataSource dataSource = null;
    try {
        final Properties props = ConfigurationConverter.getProperties(configuration);
        dataSource = BasicDataSourceFactory.createDataSource(props);
    } catch (final Exception e) { // NOPMD by cvarela on 8/02/16 22:28
        // we will use a DataSource without a connection pool
        LOGGER.info(e.getMessage());
        dataSource = new SimpleDataSource(driver, url, user, password);
    }

    return new DataSourceClasspathDecorator(dataSource, extraClasspath);
}

From source file:de.chdev.artools.loga.lang.KeywordLoader.java

private List<Configuration> getAllConfigurations() {
    List<Configuration> localConfigurationList = new ArrayList<Configuration>();
    try {/*from   w  w  w  .j  a  v a 2 s.c o m*/
        // File path = new File("./config");

        // File[] listFiles = path.listFiles();

        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.startsWith("keywords")) {
                    return true;
                } else {
                    return false;
                }
            }

        };

        /* TESTCODE */
        // Bundle location = Activator.getDefault().getBundle();
        // Enumeration entryPaths =
        // Activator.getDefault().getBundle().getEntryPaths("/");
        URL configEntry = Activator.getDefault().getBundle().getEntry("config");
        URL configPath = FileLocator.resolve(configEntry);
        File path = new File(configPath.getFile());
        // String[] list2 = resFile.list();
        // File file = new ConfigurationScope().getLocation().toFile();
        // String[] list = file.list();
        // IProject project = root.getProject();
        // IFolder files = project.getFolder("");
        // IResource[] members = files.members();
        /* TESTCODE END */

        String[] fileNames = path.list(filter);
        supportedLanguages.clear();

        for (String fileName : fileNames) {
            File fileObj = new File(path, fileName);
            CompositeConfiguration configuration = new CompositeConfiguration();

            PropertiesConfiguration keywords = new PropertiesConfiguration(fileObj);
            configuration.addConfiguration(keywords);
            configuration.addProperty("filename", fileName);
            localConfigurationList.add(configuration);
            supportedLanguages.add(configuration.getString("language.name"));
            nameConfigMap.put(configuration.getString("language.name"), configuration);
        }

        // for (String fileName : fileNames) {
        // CompositeConfiguration configuration = new
        // CompositeConfiguration();
        //
        // PropertiesConfiguration keywords = new PropertiesConfiguration(
        // "config/" + fileName);
        // configuration.addConfiguration(keywords);
        // configuration.addProperty("filename", fileName);
        // localConfigurationList.add(configuration);
        // }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return localConfigurationList;
}

From source file:com.blazebit.jbake.mojo.BuildMojo.java

protected CompositeConfiguration createConfiguration() throws ConfigurationException {
    final CompositeConfiguration config = new CompositeConfiguration();

    if (properties != null) {
        config.addConfiguration(new MapConfiguration(properties));
    }//  ww w  .ja  v  a  2  s  .c o  m
    config.addConfiguration(new MapConfiguration(project.getProperties()));
    config.addConfiguration(ConfigUtil.load(inputDirectory));

    if (getLog().isDebugEnabled()) {
        getLog().debug("Configuration:");

        Iterator<String> iter = config.getKeys();
        while (iter.hasNext()) {
            String key = iter.next();
            getLog().debug(key + ": " + config.getString(key));
        }
    }

    return config;
}

From source file:ffx.potential.parsers.ForceFieldFilter.java

/**
 * <p>//from w ww  .j  a va2s  .  com
 * Constructor for ForceFieldFilter.</p>
 *
 * @param properties a
 * {@link org.apache.commons.configuration.CompositeConfiguration} object.
 */
public ForceFieldFilter(CompositeConfiguration properties) {
    this.properties = properties;
    if (properties.containsKey("parameters")) {
        String fileName = properties.getString("parameters");
        if (properties.containsKey("propertyFile")) {
            String propertyName = properties.getString("propertyFile");
            File propertyFile = new File(propertyName);
            forceFieldFile = parseParameterLocation(fileName, propertyFile);
        } else {
            forceFieldFile = parseParameterLocation(fileName, null);
        }
    } else {
        forceFieldFile = null;
    }
    forceField = new ForceField(properties, forceFieldFile);
}

From source file:br.eti.kinoshita.testlinkjavaapi.TestLinkAPI.java

/**
 * Creates XML-RPC client configuration.
 * //from  w w  w.  java2 s . co  m
 * By default enabled for extensions is always true. 
 * 
 * @param url Application URL.
 * @param appConfig Application composite configuration.
 * @return XML-RPC client configuration.
 */
private XmlRpcClientConfigImpl createXmlRpcClientConfiguration(URL url, CompositeConfiguration appConfig) {
    final XmlRpcClientConfigImpl xmlRpcClientConfig = new XmlRpcClientConfigImpl();

    xmlRpcClientConfig.setServerURL(url);
    xmlRpcClientConfig.setEnabledForExtensions(true);

    xmlRpcClientConfig.setBasicEncoding(appConfig.getString(XMLRPC_BASIC_ENCODING));
    xmlRpcClientConfig.setBasicPassword(appConfig.getString(XMLRPC_BASIC_PASSWORD));
    xmlRpcClientConfig.setBasicUserName(appConfig.getString(XMLRPC_BASIC_USERNAME));

    try {
        xmlRpcClientConfig.setConnectionTimeout(appConfig.getInt(XMLRPC_CONNECTION_TIMEOUT));
    } catch (ConversionException ce) {
        this.debug(ce);
    } catch (NoSuchElementException nsee) {
        this.debug(nsee);
    }

    try {
        xmlRpcClientConfig.setContentLengthOptional(appConfig.getBoolean(XMLRPC_CONTENT_LENGTH_OPTIONAL));
    } catch (ConversionException ce) {
        this.debug(ce);
    } catch (NoSuchElementException nsee) {
        this.debug(nsee);
    }

    try {
        xmlRpcClientConfig.setEnabledForExceptions(appConfig.getBoolean(XMLRPC_ENABLED_FOR_EXCEPTIONS));
    } catch (ConversionException ce) {
        this.debug(ce);
    } catch (NoSuchElementException nsee) {
        this.debug(nsee);
    }

    xmlRpcClientConfig.setEncoding(appConfig.getString(XMLRPC_ENCODING));

    try {
        xmlRpcClientConfig.setGzipCompressing(appConfig.getBoolean(XMLRPC_GZIP_COMPRESSION));
    } catch (ConversionException ce) {
        this.debug(ce);
    } catch (NoSuchElementException nsee) {
        this.debug(nsee);
    }

    try {
        xmlRpcClientConfig.setGzipRequesting(appConfig.getBoolean(XMLRPC_GZIP_REQUESTING));
    } catch (ConversionException ce) {
        this.debug(ce);
    } catch (NoSuchElementException nsee) {
        this.debug(nsee);
    }

    try {
        xmlRpcClientConfig.setReplyTimeout(appConfig.getInt(XMLRPC_REPLY_TIMEOUT));
    } catch (ConversionException ce) {
        this.debug(ce);
    } catch (NoSuchElementException nsee) {
        this.debug(nsee);
    }

    xmlRpcClientConfig.setUserAgent(appConfig.getString(XMLRPC_USER_AGENT));

    return xmlRpcClientConfig;
}

From source file:org.apache.accumulo.core.conf.SiteConfiguration.java

@SuppressFBWarnings(value = "URLCONNECTION_SSRF_FD", justification = "location of props is specified by an admin")
private static ImmutableMap<String, String> createMap(URL accumuloPropsLocation,
        Map<String, String> overrides) {
    CompositeConfiguration config = new CompositeConfiguration();
    config.setThrowExceptionOnMissing(false);
    config.setDelimiterParsingDisabled(true);
    PropertiesConfiguration propsConfig = new PropertiesConfiguration();
    propsConfig.setDelimiterParsingDisabled(true);
    if (accumuloPropsLocation != null) {
        try {//from  w w  w . j  a  v  a  2 s . c o m
            propsConfig.load(accumuloPropsLocation.openStream());
        } catch (IOException | ConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }
    config.addConfiguration(propsConfig);

    // Add all properties in config file
    Map<String, String> result = new HashMap<>();
    config.getKeys().forEachRemaining(key -> result.put(key, config.getString(key)));

    // Add all overrides
    overrides.forEach(result::put);

    // Add sensitive properties from credential provider (if set)
    String credProvider = result.get(Property.GENERAL_SECURITY_CREDENTIAL_PROVIDER_PATHS.getKey());
    if (credProvider != null) {
        org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration();
        hadoopConf.set(CredentialProviderFactoryShim.CREDENTIAL_PROVIDER_PATH, credProvider);
        for (Property property : Property.values()) {
            if (property.isSensitive()) {
                char[] value = CredentialProviderFactoryShim.getValueFromCredentialProvider(hadoopConf,
                        property.getKey());
                if (value != null) {
                    result.put(property.getKey(), new String(value));
                }
            }
        }
    }
    return ImmutableMap.copyOf(result);
}

From source file:org.apereo.lap.services.ConfigurationService.java

@PostConstruct
public void init() throws IOException {
    logger.info("INIT started");
    logger.info("App Home: " + appHome().getAbsolutePath());

    CompositeConfiguration config = new CompositeConfiguration();
    // load internal config defaults first
    config.setProperty("app.name", "LAP");
    File dbDefaults = resourceLoader.getResource("classpath:db.properties").getFile();
    try {/*from www. j a v  a  2s.  com*/
        config.addConfiguration(new PropertiesConfiguration(dbDefaults));
    } catch (ConfigurationException e) {
        logger.error("Unable to load default db.properties file");
    }
    File appDefaults = resourceLoader.getResource("classpath:app.properties").getFile();
    try {
        config.addConfiguration(new PropertiesConfiguration(appDefaults));
        logger.info("Default app configuration loaded from: " + appDefaults.getAbsolutePath());
    } catch (ConfigurationException e) {
        logger.error("Unable to load default app.properties file");
    }

    // now try to load external config settings
    config.addConfiguration(new SystemConfiguration());
    File lapConfigProps = new File(appHome(), "lap.properties");
    if (lapConfigProps.exists() && lapConfigProps.canRead()) {
        try {
            config.addConfiguration(new PropertiesConfiguration(lapConfigProps));
        } catch (ConfigurationException e) {
            logger.warn("Unable to load lap.properties file");
        }
    } else {
        IOUtils.copy(
                SampleCSVInputHandlerService.class.getClassLoader()
                        .getResourceAsStream("config" + SLASH + "lap.properties"),
                new FileOutputStream(new File(appHome(), "lap.properties")));
        logger.info("No external LAP config found: " + lapConfigProps.getAbsolutePath()
                + ", copied default sample lap.properties");
    }
    this.config = config;

    // verify the existence of the various dirs
    pipelinesDirectory = verifyDir("dir.pipelines", "piplines");
    inputDirectory = verifyDir("dir.inputs", "inputs");
    outputDirectory = verifyDir("dir.outputs", "outputs");

    pipelineConfigs = new ConcurrentHashMap<>();
    // first load the internal ones (must be listed explicitly for now)
    Resource pipelineSample = resourceLoader.getResource("classpath:pipelines" + SLASH + "sample.xml");
    PipelineConfig plcfg = processPipelineConfigFile(pipelineSample.getFile());
    if (plcfg != null) {
        pipelineConfigs.put(plcfg.getType(), plcfg);
    }
    // then try to load the external ones
    File[] pipelineFiles = pipelinesDirectory.listFiles();
    if (pipelineFiles != null && pipelineFiles.length > 0) {
        for (final File fileEntry : pipelineFiles) {
            if (fileEntry.isFile()) {
                PipelineConfig filePLC = processPipelineConfigFile(pipelineSample.getFile());
                if (filePLC != null) {
                    pipelineConfigs.put(filePLC.getType(), filePLC);
                }
            }
        }
    }

    logger.info("INIT complete: " + config.getString("app.name") + ", home="
            + applicationHomeDirectory.getAbsolutePath());
}

From source file:org.debux.webmotion.server.ConfigurationTest.java

@Test
public void testComposite() throws ConfigurationException {
    PropertiesConfiguration local = new PropertiesConfiguration();
    local.load(new StringReader("name=value"));

    PropertiesConfiguration file = new PropertiesConfiguration();
    file.load(new StringReader("name=other"));

    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(file);//from w w w  . j  a va 2s.com
    composite.addConfiguration(local);

    AssertJUnit.assertEquals("other", composite.getString("name"));
}