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

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

Introduction

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

Prototype

public String getString(String key) 

Source Link

Usage

From source file:com.seanmadden.fast.ldap.main.Main.java

/**
 * The Main Event./*from   www .  j ava 2s .c o m*/
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    BasicConfigurator.configure();
    log.debug("System initializing");
    try {
        Logger.getRootLogger().addAppender(
                new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log"));
    } catch (IOException e1) {
        log.error("Unable to open the log file..?");
    }

    /*
     * Initialize the configuration engine.
     */
    XMLConfiguration config = new XMLConfiguration();
    config.setListDelimiter('|');

    /*
     * Initialize the Command-Line parsing engine.
     */
    CommandLineParser parser = new PosixParser();
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg()
            .withDescription("The configuration file to load").withArgName("config.xml").create("c"));

    opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use")
            .withArgName("Default").create("p"));

    opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with")
            .withArgName("password").create("P"));

    opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d'));

    opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v'));

    File configurationFile = new File("config.xml");

    try {
        // Parse the command-line options
        CommandLine cmds = parser.parse(opts, args);

        if (!cmds.hasOption('p')) {
            Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR));
        }

        Logger.getRootLogger().setLevel(Level.ERROR);
        if (cmds.hasOption('v')) {
            Logger.getRootLogger().setLevel(Level.INFO);
        }
        if (cmds.hasOption('d')) {
            Logger.getRootLogger().setLevel(Level.DEBUG);
        }

        log.debug("Enabling configuration file parsing");
        // The user has given us a file to parse.
        if (cmds.hasOption("c")) {
            configurationFile = new File(cmds.getOptionValue("c"));
        }
        log.debug("Config file: " + configurationFile);

        // Load the configuration file
        if (configurationFile.exists()) {
            config.load(configurationFile);
        } else {
            log.error("Cannot find config file");
        }

        /*
         * Convert the profiles into memory
         */
        Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>();
        List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile");
        for (Object p : profList) {
            SubnodeConfiguration profile = (SubnodeConfiguration) p;
            String name = profile.getString("[@name]");
            String auth = profile.getString("LdapAuthString");
            String server = profile.getString("LdapServerString");
            String group = profile.getString("LdapGroupsLocation");
            ConnectionProfile prof = new ConnectionProfile(name, server, auth, group);
            profs.add(prof);
        }
        ConnectionProfile prof = null;
        if (!cmds.hasOption('p')) {
            /*
             * Deploy the profile selector, to select a profile
             */
            ProfileSelector profSel = new ProfileSelector(profs);
            prof = profSel.getSelection();
            if (prof == null) {
                return;
            }
            /*
             * Empty the profiles and load a clean copy - then save it back
             * to the file
             */
            config.clearTree("Profiles");
            for (ConnectionProfile p : profSel.getProfiles()) {
                config.addProperty("Profiles.Profile(-1)[@name]", p.getName());
                config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString());
                config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString());
                config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString());
            }
            config.save(configurationFile);
        } else {
            for (ConnectionProfile p : profs) {
                if (p.getName().equals(cmds.getOptionValue('p'))) {
                    prof = p;
                    break;
                }
            }
        }

        log.info("User selected " + prof);

        String password = "";
        if (cmds.hasOption('P')) {
            password = cmds.getOptionValue('P');
        } else {
            password = PasswordPrompter.promptForPassword("Password?");
        }

        if (password.equals("")) {
            return;
        }

        LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(),
                prof.getLdapGroupsString(), password);

        /*
         * Gather options information from the configuration engine for the
         * specified report.
         */
        Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>();
        List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report");
        for (Object p : repConfig) {
            SubnodeConfiguration repNode = (SubnodeConfiguration) p;

            // TODO Do something with the report profile.
            // Allowing the user to deploy "profiles" is a nice feature
            // String profile = repNode.getString("[@profile]");

            String reportName = repNode.getString("[@report]");
            Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>();
            reportDataStructure.put(reportName, reportOptions);
            // Loop through the options and add each to the table.
            for (Object o : repNode.configurationsAt("option")) {
                SubnodeConfiguration option = (SubnodeConfiguration) o;
                String name = option.getString("[@name]");
                String type = option.getString("[@type]");
                String value = option.getString("[@value]");

                ReportOption ro = new ReportOption();
                ro.setName(name);

                if (type.toLowerCase().equals("boolean")) {
                    ro.setBoolValue(Boolean.parseBoolean(value));
                } else if (type.toLowerCase().equals("integer")) {
                    ro.setIntValue(Integer.valueOf(value));
                } else {
                    // Assume a string type here then.
                    ro.setStrValue(value);
                }
                reportOptions.put(name, ro);
                log.debug(ro);
            }
        }
        System.out.println(reportDataStructure);

        /*
         * At this point, we now need to deploy the reports window to have
         * the user pick a report and select some happy options to allow
         * that report to work. Let's go.
         */
        /*
         * Deploy the Reports selector, to select a report
         */
        Reports.getInstance().setLdapConnection(ldap);
        ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure);
        Report report = reports.getSelection();
        if (report == null) {
            return;
        }
        /*
         * Empty the profiles and load a clean copy - then save it back to
         * the file
         */
        config.clearTree("Reports");
        for (Report r : Reports.getInstance().getAllReports()) {
            config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName());
            config.addProperty("Reports.Report[@name]", "Standard");
            for (ReportOption ro : r.getOptions().values()) {
                config.addProperty("Reports.Report.option(-1)[@name]", ro.getName());
                config.addProperty("Reports.Report.option[@type]", ro.getType());
                config.addProperty("Reports.Report.option[@value]", ro.getStrValue());
            }
        }
        config.save(configurationFile);
        ProgressBar bar = new ProgressBar();
        bar.start();
        report.execute();
        ASCIIFormatter format = new ASCIIFormatter();
        ReportResult res = report.getResult();
        format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt"));
        bar.stop();

        JOptionPane.showMessageDialog(null,
                "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success",
                JOptionPane.INFORMATION_MESSAGE);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FAST Ldap Searcher", opts);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        log.fatal("OH EM GEES!  Configuration errors.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

/**
 * This method parses a repository configuration from the file at the given
 * absolute path.//  w  w w .j a va  2 s .c  om
 * 
 * <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:ee.ria.xroad.signer.tokenmanager.module.ModuleConf.java

private static void parseSection(String uid, SubnodeConfiguration section) {
    boolean enabled = section.getBoolean(ENABLED_PARAM, true);

    if (SOFTKEY_TYPE.equalsIgnoreCase(uid)) {
        if (!enabled) {
            MODULES.remove(SoftwareModuleType.TYPE);
        }//from  w  w w.  j  a va2  s  . co m

        return;
    }

    if (!enabled) {
        return;
    }

    String library = section.getString("library");

    if (StringUtils.isBlank(library)) {
        log.error("No pkcs#11 library specified for module ({}), skipping...", uid);

        return;
    }

    boolean verifyPin = getBoolean(section, SIGN_VERIFY_PIN_PARAM, false);
    boolean batchSigning = getBoolean(section, BATCH_SIGNING_ENABLED_PARAM, true);
    boolean readOnly = getBoolean(section, READ_ONLY_PARAM, false);
    String tokenIdFormat = section.getString(TOKEN_ID_FORMAT_PARAM);

    if (StringUtils.isBlank(tokenIdFormat)) {
        tokenIdFormat = DEFAULT_TOKEN_ID_FORMAT;
    }

    String signMechanismName = section.getString(SIGN_MECHANISM_PARAM);

    if (StringUtils.isBlank(signMechanismName)) {
        signMechanismName = DEFAULT_SIGN_MECHANISM_NAME;
    }

    Long signMechanism = getSupportedSignMechanismCode(signMechanismName);

    if (signMechanism == null) {
        log.error("Not supported sign mechanism ({}) specified for module ({}), skipping...", signMechanismName,
                uid);

        return;
    }

    PubKeyAttributes pubKeyAttributes = loadPubKeyAttributes(section);
    PrivKeyAttributes privKeyAttributes = loadPrivKeyAttributes(section);

    log.trace(
            "Read module configuration (UID = {}, library = {}, tokenIdFormat = {}"
                    + ", pinVerificationPerSigning = {}, batchSigning = {}, signMechanism = {}"
                    + ", pubKeyAttributes = {}, privKeyAttributes = {})",
            uid, library, tokenIdFormat, verifyPin, batchSigning, signMechanismName, pubKeyAttributes,
            privKeyAttributes);

    if (MODULES.containsKey(uid)) {
        log.warn("Module information already defined for {}, skipping...", uid);

        return;
    }

    MODULES.put(uid, new HardwareModuleType(uid, library, tokenIdFormat, verifyPin, batchSigning, readOnly,
            signMechanismName, privKeyAttributes, pubKeyAttributes));
}

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

/**
 * Parses a program parameter from a section of a configuration file.
 * //from ww w  .j a  va 2s. com
 * <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.oltpbenchmark.multitenancy.MuTeBench.java

private static List<String> get_weights(String plugin, SubnodeConfiguration work) {

    List<String> weight_strings = new LinkedList<String>();
    @SuppressWarnings("unchecked")
    List<SubnodeConfiguration> weights = work.configurationsAt("weights");
    boolean weights_started = false;

    for (SubnodeConfiguration weight : weights) {

        // stop if second attributed node encountered
        if (weights_started && weight.getRootNode().getAttributeCount() > 0) {
            break;
        }//from   w w w  .  j a  va2 s  .c  o m
        // start adding node values, if node with attribute equal to current
        // plugin encountered
        if (weight.getRootNode().getAttributeCount() > 0
                && weight.getRootNode().getAttribute(0).getValue().equals(plugin)) {
            weights_started = true;
        }
        if (weights_started) {
            weight_strings.add(weight.getString(""));
        }

    }
    return weight_strings;
}

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

public static void populateConfiguration() throws IOException, ConfigurationException {
    BaasBoxLogger.info("Load initial configuration...");
    InputStream is;//from  w  w  w.  ja v a 2s . 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.hipstogram.context.config.sections.KafkaSection.java

public KafkaSection(SubnodeConfiguration kafka) {
    this.port = kafka.getInt("port");
    this.host = kafka.getString("host");
}

From source file:com.hipstogram.storm.context.config.sections.KafkaSection.java

public KafkaSection(SubnodeConfiguration kafka) {
    this.port = kafka.getInt("port");
    this.host = kafka.getString("host");
    this.topic = kafka.getString("topic");
}

From source file:com.hipstogram.context.config.sections.CassandraSection.java

public CassandraSection(SubnodeConfiguration cassandra) {
    this.port = cassandra.getInt("port");
    this.host = cassandra.getString("host");
}

From source file:com.hipstogram.context.config.sections.MongoDBSection.java

public MongoDBSection(SubnodeConfiguration cassandra) {
    this.port = cassandra.getInt("port");
    this.host = cassandra.getString("host");
}