Example usage for org.apache.commons.configuration SubnodeConfiguration getKeys

List of usage examples for org.apache.commons.configuration SubnodeConfiguration getKeys

Introduction

In this page you can find the example usage for org.apache.commons.configuration SubnodeConfiguration getKeys.

Prototype

public Iterator getKeys() 

Source Link

Document

Returns an iterator with all keys defined in this configuration.

Usage

From source file:de.clusteval.framework.repository.config.RepositoryConfig.java

/**
 * This method parses a repository configuration from the file at the given
 * absolute path./*from  w  w w.  ja v  a 2  s.com*/
 * 
 * <p>
 * A repository configuration contains several sections and possible
 * options:
 * <ul>
 * <li><b>[mysql]</b></li>
 * <ul>
 * <li><b>host</b>: The ip address of the mysql host server.</li>
 * <li><b>database</b>: The mysql database name.</li>
 * <li><b>user</b>: The username used to connect to the database.</li>
 * <li><b>password</b>: The mysql password used to connect to the database.
 * The password is prompted from the console and not parsed from the file.</li>
 * </ul>
 * <li><b>[threading]</b></li>
 * <li><b>NameOfTheThreadSleepTime</b>: Sleeping time of the thread
 * 'NameOfTheThread'. This option can be used to control the frequency, with
 * which the threads check for changes on the filesystem.</li> </ul>
 * 
 * @param absConfigPath
 *            The absolute path of the repository configuration file.
 * @return The parsed repository configuration.
 * @throws RepositoryConfigNotFoundException
 * @throws RepositoryConfigurationException
 */
public static RepositoryConfig parseFromFile(final File absConfigPath)
        throws RepositoryConfigNotFoundException, RepositoryConfigurationException {
    if (!absConfigPath.exists())
        throw new RepositoryConfigNotFoundException(
                "Repository config \"" + absConfigPath + "\" does not exist!");

    Logger log = LoggerFactory.getLogger(RepositoryConfig.class);

    log.debug("Parsing repository config \"" + absConfigPath + "\"");

    try {

        HierarchicalINIConfiguration props = new HierarchicalINIConfiguration(absConfigPath);
        props.setThrowExceptionOnMissing(true);

        boolean usesMysql = false;
        MysqlConfig mysqlConfig = null;

        if (props.getSections().contains("mysql")
                && !ClustevalBackendServer.getBackendServerConfiguration().getNoDatabase()) {
            usesMysql = true;
            String mysqlUsername, mysqlDatabase, mysqlHost;
            SubnodeConfiguration mysql = props.getSection("mysql");
            mysqlUsername = mysql.getString("user");

            mysqlDatabase = mysql.getString("database");
            mysqlHost = mysql.getString("host");
            mysqlConfig = new MysqlConfig(usesMysql, mysqlUsername, mysqlDatabase, mysqlHost);
        } else
            mysqlConfig = new MysqlConfig(usesMysql, "", "", "");

        Map<String, Long> threadingSleepTimes = new HashMap<String, Long>();

        if (props.getSections().contains("threading")) {
            SubnodeConfiguration threading = props.getSection("threading");
            Iterator<String> it = threading.getKeys();
            while (it.hasNext()) {
                String key = it.next();
                if (key.endsWith("SleepTime")) {
                    String subKey = key.substring(0, key.indexOf("SleepTime"));
                    try {
                        threadingSleepTimes.put(subKey, threading.getLong(key));
                    } catch (Exception e) {
                        // in case anything goes wrong, we just ignore this
                        // option
                        e.printStackTrace();
                    }
                }
            }
        }

        return new RepositoryConfig(mysqlConfig, threadingSleepTimes);
    } catch (ConfigurationException e) {
        throw new RepositoryConfigurationException(e.getMessage());
    } catch (NoSuchElementException e) {
        throw new RepositoryConfigurationException(e.getMessage());
    }
}

From source file:de.clusteval.program.ProgramParameter.java

/**
 * Parses a program parameter from a section of a configuration file.
 * //w w w  .j a v a2s  .c  o  m
 * <p>
 * This method only delegates depending on the type of the program parameter
 * to the methods
 * {@link DoubleProgramParameter#parseFromStrings(ProgramConfig, String, String, String, String, String)},
 * {@link IntegerProgramParameter#parseFromStrings(ProgramConfig, String, String, String, String, String)}
 * and
 * {@link StringProgramParameter#parseFromStrings(ProgramConfig, String, String, String, String, String)}.
 * 
 * @param programConfig
 *            The program configuration in which the program parameter has
 *            been defined.
 * @param name
 *            The name of the program parameter.
 * @param config
 *            The section of the configuration, which contains the
 *            information about this parameter.
 * @return The parsed program parameter.
 * @throws RegisterException
 * @throws UnknownParameterType
 */
public static ProgramParameter<?> parseFromConfiguration(final ProgramConfig programConfig, final String name,
        final SubnodeConfiguration config) throws RegisterException, UnknownParameterType {
    Map<String, String> paramValues = new HashMap<String, String>();
    paramValues.put("name", name);

    Iterator<String> itSubParams = config.getKeys();
    while (itSubParams.hasNext()) {
        final String subParam = itSubParams.next();
        final String value = config.getString(subParam);

        paramValues.put(subParam, value);
    }
    ParameterType type = ProgramParameter.parseTypeFromString(paramValues.get("type"));

    String na = paramValues.get("name");
    String description = paramValues.get("desc");
    String def = paramValues.get("def");

    // 23.05.2014: added support for options for float and integer
    // parameters. if options are given, we set minValue and maxValue to the
    // empty string.
    ProgramParameter<?> param = null;
    String[] options = config.getStringArray("options");
    String minValue = paramValues.get("minValue");
    String maxValue = paramValues.get("maxValue");
    if (config.containsKey("options")) {
        minValue = "";
        maxValue = "";
    }
    if (type.equals(ParameterType.FLOAT)) {
        param = DoubleProgramParameter.parseFromStrings(programConfig, na, description, minValue, maxValue,
                options, def);
    } else if (type.equals(ParameterType.INTEGER)) {
        param = IntegerProgramParameter.parseFromStrings(programConfig, na, description, minValue, maxValue,
                options, def);
    } else if (type.equals(ParameterType.STRING)) {
        param = StringProgramParameter.parseFromStrings(programConfig, na, description, options, def);
    }
    return param;
}

From source file:com.baasbox.db.DbHelper.java

public static void populateConfiguration() throws IOException, ConfigurationException {
    BaasBoxLogger.info("Load initial configuration...");
    InputStream is;//  w  ww. j  a  v a 2 s  .  c  o m
    if (Play.application().isProd())
        is = Play.application().resourceAsStream(CONFIGURATION_FILE_NAME);
    else
        is = new FileInputStream(Play.application().getFile("conf/" + CONFIGURATION_FILE_NAME));
    HierarchicalINIConfiguration c = new HierarchicalINIConfiguration();
    c.setEncoding("UTF-8");
    c.load(is);
    CharSequence doubleDot = "..";
    CharSequence dot = ".";

    Set<String> sections = c.getSections();
    for (String section : sections) {
        Class en = PropertiesConfigurationHelper.CONFIGURATION_SECTIONS.get(section);
        if (en == null) {
            BaasBoxLogger.warn(section + " is not a valid configuration section, it will be skipped!");
            continue;
        }
        SubnodeConfiguration subConf = c.getSection(section);
        Iterator<String> it = subConf.getKeys();
        while (it.hasNext()) {
            String key = (it.next());
            Object value = subConf.getString(key);
            key = key.replace(doubleDot, dot);//bug on the Apache library: if the key contain a dot, it will be doubled!
            try {
                BaasBoxLogger.info("Setting " + value + " to " + key);
                PropertiesConfigurationHelper.setByKey(en, key, value);
            } catch (Exception e) {
                BaasBoxLogger.warn("Error loading initial configuration: Section " + section + ", key: " + key
                        + ", value: " + value, e);
            }
        }
    }
    is.close();
    BaasBoxLogger.info("...done");
}

From source file:com.bist.elasticsearch.jetty.security.AuthorizationConfigurationLoader.java

protected void loadIndiceAuthZ(QueryConstraints queryConstraints, String section,
        SubnodeConfiguration subnodeConfiguration) {
    Iterator<String> iterator = subnodeConfiguration.getKeys();
    while (iterator.hasNext()) {
        String key = iterator.next();
        String regex;//from   w w  w  . jav a  2  s . c o m
        if (section.startsWith("_")) // special like _all _plugin etc
            regex = "^" + section + "$";
        else
            regex = "^" + section + "-\\d{4}\\.\\d{2}\\.\\d{2}$";
        if (key.equals("users")) {
            for (String userName : subnodeConfiguration.getString(key).split(",")) {
                queryConstraints.addUserIndiceQuery(userName, regex);

            }
        } else {
            String groupName = subnodeConfiguration.getString(key);
            queryConstraints.addGroupIndiceQuery(groupName, regex);
        }
    }
}

From source file:de.uni_rostock.goodod.owl.normalization.BasicNormalizerFactory.java

protected void populateMap() {
    if (null == config) {
        return;/*www  .  j  a v  a 2s.  com*/
    }
    SubnodeConfiguration mapCfg = config.configurationAt("importMap");
    @SuppressWarnings("unchecked")
    Iterator<String> iter = mapCfg.getKeys();
    while (iter.hasNext()) {
        String key = iter.next();
        String oldImport = key.replace("..", ".");
        String newImport = mapCfg.getString(key);
        importMap.put(IRI.create(oldImport), IRI.create(newImport));
    }

}

From source file:it.jnrpe.server.IniJNRPEConfiguration.java

@Override
public void load(final File confFile) throws ConfigurationException {
    // Parse an ini file
    ServerSection serverConf = getServerSection();
    CommandsSection commandSection = getCommandSection();
    try {/* w w  w. j ava 2  s .c om*/
        HierarchicalINIConfiguration confParser = new HierarchicalINIConfiguration(confFile);

        List<Object> vBindAddresses = confParser.getList("server.bind-address");
        if (vBindAddresses != null) {
            for (Object address : vBindAddresses) {
                serverConf.addBindAddress((String) address);
            }
        }

        // Defaults accept params
        String sAcceptParams = confParser.getString("server.accept-params", "true");
        serverConf.setAcceptParams(
                "true".equalsIgnoreCase(sAcceptParams) || "yes".equalsIgnoreCase(sAcceptParams));
        serverConf.setPluginPath(confParser.getString("server.plugin-path", "."));

        serverConf.setBackLogSize(confParser.getInt("server.backlog-size", ServerSection.DEFAULT_BACKLOG));

        // TODO : move this to publicly accessible constants
        serverConf.setReadTimeout(confParser.getInteger("server.read-timeout", 10));
        // TODO : move this to publicly accessible constants
        serverConf.setWriteTimeout(confParser.getInteger("server.write-timeout", 60));

        List<Object> vAllowedAddresses = confParser.getList("server.allow-address");
        if (vAllowedAddresses != null) {
            for (Object address : vAllowedAddresses) {
                serverConf.addAllowedAddress((String) address);
            }
        }

        SubnodeConfiguration sc = confParser.getSection("commands");

        if (sc != null) {
            for (Iterator<String> it = sc.getKeys(); it.hasNext();) {
                String sCommandName = it.next();

                String sCommandLine = org.apache.commons.lang.StringUtils.join(sc.getStringArray(sCommandName),
                        ",");
                // first element of the command line is the plugin name

                String[] vElements = StringUtils.split(sCommandLine, false);
                String sPluginName = vElements[0];

                // Rebuilding the commandline
                StringBuilder cmdLine = new StringBuilder();

                for (int i = 1; i < vElements.length; i++) {
                    cmdLine.append(quoteAndEscape(vElements[i])).append(' ');
                }

                commandSection.addCommand(sCommandName, sPluginName, cmdLine.toString());
            }
        }
    } catch (org.apache.commons.configuration.ConfigurationException e) {
        throw new ConfigurationException(e);
    }

}

From source file:eu.itesla_project.dymola.DymolaAdaptersMatParamsWriter.java

public DymolaAdaptersMatParamsWriter(HierarchicalINIConfiguration configuration) {
    if (configuration == null) {
        throw new RuntimeException("null config");
    }// w  w  w . j  a  v a  2  s. c  o m
    this.configuration = configuration;
    //this below will simply log parameters ..
    for (String section : configuration.getSections()) {
        SubnodeConfiguration node = configuration.getSection(section);
        List<String> paramsSummary = StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(node.getKeys(), Spliterator.ORDERED), false)
                .map(p -> p + "=" + node.getString(p)).collect(Collectors.<String>toList());
        LOGGER.info("index {}: {}", section, paramsSummary);
    }
}

From source file:iddb.web.security.SecurityConfig.java

private SecurityConfig() {
    try {/*from w  w w  . ja v a  2 s.  c  o m*/
        HierarchicalINIConfiguration configFile = new HierarchicalINIConfiguration(
                this.getClass().getClassLoader().getResource("security.properties"));
        for (Object section : configFile.getSections()) {
            SubnodeConfiguration node = configFile.getSection((String) section);
            Map<String, String> map = new LinkedHashMap<String, String>();
            for (@SuppressWarnings("unchecked")
            Iterator<Object> it = node.getKeys(); it.hasNext();) {
                String key = it.next().toString();
                if (log.isTraceEnabled()) {
                    log.trace("Loading '{}' with value '{}' on section '{}'",
                            new String[] { key, node.getString(key), section.toString() });
                }
                map.put(key, node.getString(key));
            }
            config.put(section.toString(), map);
        }
    } catch (ConfigurationException e) {
        log.error(e.getMessage());
    }
}

From source file:ee.ria.xroad.common.SystemPropertiesLoader.java

private void loadSection(String sectionName, SubnodeConfiguration sec) {
    sec.getKeys().forEachRemaining(key -> setProperty(prefix + sectionName + "." + key, sec.getString(key)));
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests whether getSection() can deal with duplicate sections.
 *///from  w w  w. j  av  a2  s . c  o  m
@Test
public void testGetSectionDuplicate() {
    HierarchicalINIConfiguration config = new HierarchicalINIConfiguration();
    config.addProperty("section.var1", "value1");
    config.addProperty("section(-1).var2", "value2");
    SubnodeConfiguration section = config.getSection("section");
    Iterator<String> keys = section.getKeys();
    assertEquals("Wrong key", "var1", keys.next());
    assertFalse("Too many keys", keys.hasNext());
}