Example usage for org.apache.commons.configuration Configuration subset

List of usage examples for org.apache.commons.configuration Configuration subset

Introduction

In this page you can find the example usage for org.apache.commons.configuration Configuration subset.

Prototype

Configuration subset(String prefix);

Source Link

Document

Return a decorator Configuration containing every key from the current Configuration that starts with the specified prefix.

Usage

From source file:keel.Algorithms.Neural_Networks.NNEP_Common.problem.ProblemEvaluator.java

/**
  * <p>/*from   w w  w. j  av a  2 s .  c o m*/
 * Configuration parameters for NeuralNetEvaluator are:
 * 
 * <ul>
 * <li>
 * <code>train-data: complex</code></p> 
 * Train data set used in individuals evaluation.
 * <ul>
 *       <li>
 *       <code>train-data[@file-name] String </code>
 *       File name of train data
 *       </li>
 * </ul> 
 * </li>
 * <li>
 * <code>test-data: complex</code></p> 
 * Test data set used in individuals evaluation.
 * <ul>
 *       <li>
 *       <code>test-data[@file-name] String </code>
 *       File name of test data
 *       </li>
 * </ul> 
 * </li>
 * <li>
 * <code>[@normalize-data]: boolean (default = false)</code></p>
 * If this parameter is set to <code>true</true> data sets values are
 * normalizated after reading their contents
 * </li>
 * <li>
 * <code>[input-interval] (complex)</code></p>
 *  Input interval of normalization.
 * </li>
 * <li>
 * <code>[output-interval] (complex)</code></p>
 *  Output interval of normalization.
 * </li>
 * </ul>
  * <p>
  * @param settings Configuration object from which the properties are read
 */
public void configure(Configuration settings) {

    // Set trainData
    unscaledTrainData = new DoubleTransposedDataSet();
    unscaledTrainData.configure(settings.subset("train-data"));

    // Set testData
    unscaledTestData = new DoubleTransposedDataSet();
    unscaledTestData.configure(settings.subset("test-data"));

    // Set normalizer
    normalizer = new Normalizer();

    // Set dataNormalized
    dataNormalized = settings.getBoolean("[@normalize-data]", false);

    // Set dataNormalized
    logTransformation = settings.getBoolean("[@log-input-data]", false);

    if (dataNormalized) {
        // Normalization Input Interval
        Interval interval = new Interval();
        // Configure interval
        interval.configure(settings.subset("input-interval"));
        // Set interval
        setInputInterval(interval);
        // Normalization Output Interval
        interval = new Interval();
        // Configure range
        interval.configure(settings.subset("output-interval"));
        // Set interval
        setOutputInterval(interval);
    }
}

From source file:eu.socialsensor.main.BenchmarkConfiguration.java

public BenchmarkConfiguration(Configuration appconfig) {
    if (appconfig == null) {
        throw new IllegalArgumentException("appconfig may not be null");
    }//  w w w.  j  av a  2  s  .co m

    Configuration eu = appconfig.subset("eu");
    Configuration socialsensor = eu.subset("socialsensor");

    //metrics
    final Configuration metrics = socialsensor.subset(GraphDatabaseConfiguration.METRICS_NS.getName());

    final Configuration graphite = metrics.subset(GRAPHITE);
    this.graphiteHostname = graphite.getString(GRAPHITE_HOSTNAME, null);
    this.graphiteReportingInterval = graphite.getLong(GraphDatabaseConfiguration.GRAPHITE_INTERVAL.getName(),
            1000 /*default 1sec*/);

    final Configuration csv = metrics.subset(CSV);
    this.csvReportingInterval = metrics.getLong(CSV_INTERVAL, 1000 /*ms*/);
    this.csvDir = csv.containsKey(CSV_DIR)
            ? new File(csv.getString(CSV_DIR, System.getProperty("user.dir") /*default*/))
            : null;

    Configuration dynamodb = socialsensor.subset("dynamodb");
    this.dynamodbWorkerThreads = dynamodb.getInt("workers", 25);
    Configuration credentials = dynamodb.subset(CREDENTIALS);
    this.dynamodbPrecreateTables = dynamodb.getBoolean("precreate-tables", Boolean.FALSE);
    this.dynamodbTps = Math.max(1, dynamodb.getLong(TPS, 750 /*default*/));
    this.dynamodbConsistentRead = dynamodb.containsKey(CONSISTENT_READ) ? dynamodb.getBoolean(CONSISTENT_READ)
            : false;
    this.dynamodbDataModel = dynamodb.containsKey("data-model")
            ? BackendDataModel.valueOf(dynamodb.getString("data-model"))
            : null;
    this.dynamodbCredentialsFqClassName = credentials.containsKey(CLASS_NAME)
            ? credentials.getString(CLASS_NAME)
            : null;
    this.dynamodbCredentialsCtorArguments = credentials.containsKey(CONSTRUCTOR_ARGS)
            ? credentials.getString(CONSTRUCTOR_ARGS)
            : null;
    this.dynamodbEndpoint = dynamodb.containsKey(ENDPOINT) ? dynamodb.getString(ENDPOINT) : null;
    this.dynamodbTablePrefix = dynamodb.containsKey(TABLE_PREFIX) ? dynamodb.getString(TABLE_PREFIX)
            : Constants.DYNAMODB_TABLE_PREFIX.getDefaultValue();

    Configuration orient = socialsensor.subset("orient");
    orientLightweightEdges = orient.containsKey(LIGHTWEIGHT_EDGES) ? orient.getBoolean(LIGHTWEIGHT_EDGES)
            : null;

    Configuration sparksee = socialsensor.subset("sparksee");
    sparkseeLicenseKey = sparksee.containsKey(LICENSE_KEY) ? sparksee.getString(LICENSE_KEY) : null;

    Configuration titan = socialsensor.subset(TITAN); //TODO(amcp) move dynamodb ns into titan
    bufferSize = titan.getInt(BUFFER_SIZE, GraphDatabaseConfiguration.BUFFER_SIZE.getDefaultValue());
    blocksize = titan.getInt(IDS_BLOCKSIZE, GraphDatabaseConfiguration.IDS_BLOCK_SIZE.getDefaultValue());
    pageSize = titan.getInt(PAGE_SIZE, GraphDatabaseConfiguration.PAGE_SIZE.getDefaultValue());

    // database storage directory
    if (!socialsensor.containsKey(DATABASE_STORAGE_DIRECTORY)) {
        throw new IllegalArgumentException("configuration must specify database-storage-directory");
    }
    dbStorageDirectory = new File(socialsensor.getString(DATABASE_STORAGE_DIRECTORY));
    dataset = validateReadableFile(socialsensor.getString(DATASET), DATASET);

    // load the dataset
    DatasetFactory.getInstance().getDataset(dataset);

    if (!socialsensor.containsKey(PERMUTE_BENCHMARKS)) {
        throw new IllegalArgumentException("configuration must set permute-benchmarks to true or false");
    }
    permuteBenchmarks = socialsensor.getBoolean(PERMUTE_BENCHMARKS);

    List<?> benchmarkList = socialsensor.getList("benchmarks");
    benchmarkTypes = new ArrayList<BenchmarkType>();
    for (Object str : benchmarkList) {
        benchmarkTypes.add(BenchmarkType.valueOf(str.toString()));
    }

    selectedDatabases = new TreeSet<GraphDatabaseType>();
    for (Object database : socialsensor.getList("databases")) {
        if (!GraphDatabaseType.STRING_REP_MAP.keySet().contains(database.toString())) {
            throw new IllegalArgumentException(
                    String.format("selected database %s not supported", database.toString()));
        }
        selectedDatabases.add(GraphDatabaseType.STRING_REP_MAP.get(database));
    }
    scenarios = permuteBenchmarks ? Ints.checkedCast(CombinatoricsUtils.factorial(selectedDatabases.size()))
            : 1;

    resultsPath = new File(System.getProperty("user.dir"), socialsensor.getString("results-path"));
    if (!resultsPath.exists() && !resultsPath.mkdirs()) {
        throw new IllegalArgumentException("unable to create results directory");
    }
    if (!resultsPath.canWrite()) {
        throw new IllegalArgumentException("unable to write to results directory");
    }

    randomNodes = socialsensor.getInteger(RANDOM_NODES, new Integer(100));

    if (this.benchmarkTypes.contains(BenchmarkType.CLUSTERING)) {
        if (!socialsensor.containsKey(NODES_COUNT)) {
            throw new IllegalArgumentException("the CW benchmark requires nodes-count integer in config");
        }
        nodesCount = socialsensor.getInt(NODES_COUNT);

        if (!socialsensor.containsKey(RANDOMIZE_CLUSTERING)) {
            throw new IllegalArgumentException("the CW benchmark requires randomize-clustering bool in config");
        }
        randomizedClustering = socialsensor.getBoolean(RANDOMIZE_CLUSTERING);

        if (!socialsensor.containsKey(ACTUAL_COMMUNITIES)) {
            throw new IllegalArgumentException("the CW benchmark requires a file with actual communities");
        }
        actualCommunities = validateReadableFile(socialsensor.getString(ACTUAL_COMMUNITIES),
                ACTUAL_COMMUNITIES);

        final boolean notGenerating = socialsensor.containsKey(CACHE_VALUES);
        if (notGenerating) {
            List<?> objects = socialsensor.getList(CACHE_VALUES);
            cacheValues = new ArrayList<Integer>(objects.size());
            cacheValuesCount = null;
            cacheIncrementFactor = null;
            for (Object o : objects) {
                cacheValues.add(Integer.valueOf(o.toString()));
            }
        } else if (socialsensor.containsKey(CACHE_VALUES_COUNT)
                && socialsensor.containsKey(CACHE_INCREMENT_FACTOR)) {
            cacheValues = null;
            // generate the cache values with parameters
            if (!socialsensor.containsKey(CACHE_VALUES_COUNT)) {
                throw new IllegalArgumentException(
                        "the CW benchmark requires cache-values-count int in config when cache-values not specified");
            }
            cacheValuesCount = socialsensor.getInt(CACHE_VALUES_COUNT);

            if (!socialsensor.containsKey(CACHE_INCREMENT_FACTOR)) {
                throw new IllegalArgumentException(
                        "the CW benchmark requires cache-increment-factor int in config when cache-values not specified");
            }
            cacheIncrementFactor = socialsensor.getDouble(CACHE_INCREMENT_FACTOR);
        } else {
            throw new IllegalArgumentException(
                    "when doing CW benchmark, must provide cache-values or parameters to generate them");
        }
    } else {
        randomizedClustering = null;
        nodesCount = null;
        cacheValuesCount = null;
        cacheIncrementFactor = null;
        cacheValues = null;
        actualCommunities = null;
    }
}

From source file:es.udc.gii.common.eaf.algorithm.parallel.migration.MigrationOperator.java

/** Configures this operator.<p>
 *
 *  Configuration example:/* w w w .  j av a  2s .c o m*/
 *
 *  <pre>
 *  &lt;Operator&gt;
 *      &lt;Class&gt;...parallel.migration.MigrationOperator&lt;/Class&gt;
 *
 *      &lt;MigrationFrequency&gt;2&lt;/MigrationFrequency&gt;
 *
 *      &lt;CullingStrategy&gt;
 *          &lt;Class&gt;...&lt;/Class&gt;
 *          ...
 *      &lt;/CullingStrategy&gt;
 *
 *      &lt;SelectionStrategy&gt;
 *          &lt;Class&gt;...&lt;/Class&gt;
 *          ...
 *      &lt;/SelectionStrategy&gt;
 *
 *      &lt;AcceptancePolicy&gt;
 *          &lt;Class&gt;...&lt;/Class&gt;
 *          ...
 *      &lt;/AcceptancePolicy&gt;
 *
 *      &lt;Topology&gt;
 *          &lt;Class&gt;...&lt;/Class&gt;
 *          ...
 *      &lt;/Topology&gt;
 *
 *      &lt;Synchronized/&gt;
 *  &lt;/Operator&gt;
 *  </pre>
 *
 * <p>Migration will be performed every 2 generations and, before receiving,
 * all nodes are synchronized. If no synchronization is needed, simply remove
 * the {@code <Synchronized/>} tag.
 *
 * @param conf Configuration.
 */
@Override
public void configure(Configuration conf) {
    try {

        MigrationTopology mt = null;

        if (conf.containsKey("Topology.Class")) {
            mt = (MigrationTopology) Class.forName(conf.getString("Topology.Class")).newInstance();
            mt.configure(conf.subset("Topology"));
        } else {
            (new ConfWarning("MigrationOperator.Topology.Class", "FullConnectedMigrationTopology")).warn();
            mt = new FullConnectedMigrationTopology();
        }

        setMigrationTopology(mt);

        if (mt.isConnected()) {
            int migFreq = 1;
            MigCullingStrategy mCS = null;
            MigSelectionStrategy mSS = null;
            MigAcceptancePolicy mAP = null;

            if (conf.containsKey("MigrationFrequency")) {
                migFreq = conf.getInt("MigrationFrequency");
            } else {
                (new ConfWarning("MigrationOperator.MigrationFrequency", migFreq)).warn();
            }

            setMigrationFrequecy(migFreq);

            if (conf.containsKey("CullingStrategy.Class")) {
                mCS = (MigCullingStrategy) Class.forName(conf.getString("CullingStrategy.Class")).newInstance();
                mCS.configure(conf.subset("CullingStrategy"));
            } else {
                mCS = new WorstCull();
                (new ConfWarning("MigrationOperator.CullingStrategy.Class", "WorstCull")).warn();
            }

            setMigCullingStrategy(mCS);

            if (conf.containsKey("SelectionStrategy.Class")) {
                mSS = (MigSelectionStrategy) Class.forName(conf.getString("SelectionStrategy.Class"))
                        .newInstance();
                mSS.configure(conf.subset("SelectionStrategy"));
            } else {
                (new ConfWarning("MigrationOperator.SelectionStrategy." + "Class", "BestMigration")).warn();
                mSS = new BestMigration();
            }

            setMigSelectionStrategy(mSS);

            if (conf.containsKey("AcceptancePolicy.Class")) {
                mAP = (MigAcceptancePolicy) Class.forName(conf.getString("AcceptancePolicy.Class"))
                        .newInstance();
                mAP.configure(conf.subset("AcceptancePolicy"));
            } else {
                (new ConfWarning("MigrationOperator.AcceptancePolicy." + "Class", "GenerationBasedAcceptance"))
                        .warn();
                mAP = new GenerationBasedAcceptance();
            }

            setMigAcceptancePolicy(mAP);

            setSynchronized(conf.containsKey("Synchronized"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:es.udc.gii.common.eaf.factory.XMLSimpleFactory.java

@Override
public List<LogTool> createLogs() {
    Configuration conf = EAFConfiguration.getInstance().subset("LogTool");

    List<LogTool> listLogs = new ArrayList<LogTool>();
    List logs = conf.getList("Log.Class");

    for (int i = 0; i < logs.size(); i++) {
        try {/*  ww w . ja v a  2  s  .co  m*/
            LogTool log = (LogTool) Class.forName((String) logs.get(i)).newInstance();
            log.configure(conf.subset("Log(" + i + ")"));
            listLogs.add(log);
        } catch (Exception ex) {
            throw new ConfigurationException("Wrong log tool configuration for " + (String) logs.get(i) + " ?"
                    + " \n Thrown exception: \n" + ex);
        }
    }

    return listLogs;
}

From source file:es.udc.gii.common.eaf.factory.XMLSimpleFactory.java

@Override
public StopTest createStopTest() {
    Configuration conf = EAFConfiguration.getInstance().subset("StopTests");
    List stptsts = conf.getList("StopTest.Class");

    if (stptsts.size() > 1) {
        CompositeStopTest compSt = new CompositeStopTest();

        for (int i = 0; i < stptsts.size(); i++) {
            try {
                StopTest st = (StopTest) Class.forName((String) stptsts.get(i)).newInstance();
                st.configure(conf.subset("StopTest(" + i + ")"));
                compSt.addStopTest(st);/*from w w w . j  ava2 s  .co  m*/
                //                    return compSt;
            } catch (Exception ex) {
                throw new ConfigurationException("Wrong stop test configuration for " + (String) stptsts.get(i)
                        + " ?" + " \n Thrown exception: \n" + ex);
            }
        }
        return compSt;
    } else if (stptsts.size() == 1) {
        try {
            StopTest st = (StopTest) Class.forName((String) stptsts.get(0)).newInstance();
            st.configure(conf.subset("StopTest"));
            return st;
        } catch (Exception ex) {
            throw new ConfigurationException("Wrong stop test configuration for " + (String) stptsts.get(0)
                    + " ?" + " \n Thrown exception: \n" + ex);
        }
    } else if (stptsts.isEmpty()) {
        return null;
    }

    throw new ConfigurationException("No stop test class specified.");

}

From source file:es.udc.gii.common.eaf.factory.XMLSimpleFactory.java

@Override
public OperatorChain<SelectionOperator> createSelectionChain() {

    OperatorChain<SelectionOperator> oChain = null;
    Configuration conf = EAFConfiguration.getInstance().subset("OperatorChains.SelectionChain");
    List ops = conf.getList("Operator.Class");

    if (ops.size() > 0) {
        oChain = new OperatorChain<SelectionOperator>();

        for (int i = 0; i < ops.size(); i++) {
            try {
                SelectionOperator op = (SelectionOperator) Class.forName((String) ops.get(i)).newInstance();

                op.configure(conf.subset("Operator(" + i + ")"));
                oChain.addOperators(op);
            } catch (Exception ex) {
                throw new ConfigurationException("Wrong selection operator configuration for "
                        + (String) ops.get(i) + " ?" + " \n Thrown exception: \n" + ex);
            }/*from   w  w  w  . ja va  2 s .  co  m*/

        }

    }

    return oChain;
}

From source file:com.appeligo.channelfeed.CaptureApp.java

private void configureLogging(Configuration config, PatternLayout pattern) {
    Logger.getRootLogger().setLevel(Level.WARN);
    String logEmail = config.getString("logEmail[@address]");
    if ((logEmail == null) || (logEmail.trim().length() == 0)) {
        logEmail = "root@localhost";
    }/*ww  w .j  a  va  2s  . com*/
    log.info("logEmail = " + logEmail);
    configureFatalLogging(pattern, logEmail);

    int loggerCount = config.getList("loggers.logger[@name]").size();

    for (int i = 0; i < loggerCount; i++) {
        Configuration logger = config.subset("loggers.logger(" + i + ")");
        String loggerName = logger.getString("[@name]");
        String loggerLevel = logger.getString("[@level]");
        log.info("Setting logger " + loggerName + " to level " + loggerLevel);
        Logger newlog = Logger.getLogger(loggerName);
        Level level = Level.toLevel(loggerLevel, null);
        if (level == null) {
            log.error("Invalid log level '" + loggerLevel + "' in: " + configFile);
        } else {
            newlog.setLevel(level);
        }
    }
}

From source file:es.udc.gii.common.eaf.factory.XMLSimpleFactory.java

@Override
public StopTest createRestartTest() {

    //01 - 07 - 2011: se aaden los test de reinicio, pueden existir o no.

    if (EAFConfiguration.getInstance().containsKey("RestartTests.RestartTest.Class")) {

        Configuration conf = EAFConfiguration.getInstance().subset("RestartTests");
        List rststs = conf.getList("RestartTest.Class");

        if (rststs.size() > 1) {
            CompositeStopTest compSt = new CompositeStopTest();

            for (int i = 0; i < rststs.size(); i++) {
                try {
                    StopTest st = (StopTest) Class.forName((String) rststs.get(i)).newInstance();
                    st.configure(conf.subset("RestartTest(" + i + ")"));
                    compSt.addStopTest(st);
                    //                    return compSt;
                } catch (Exception ex) {
                    throw new ConfigurationException("Wrong restart test configuration for "
                            + (String) rststs.get(i) + " ?" + " \n Thrown exception: \n" + ex);
                }//from  w w w.  j  av a2 s  .co  m
            }
            return compSt;
        } else if (rststs.size() == 1) {
            try {
                StopTest st = (StopTest) Class.forName((String) rststs.get(0)).newInstance();
                st.configure(conf.subset("RestartTest"));
                return st;
            } catch (Exception ex) {
                throw new ConfigurationException("Wrong restart test configuration for "
                        + (String) rststs.get(0) + " ?" + " \n Thrown exception: \n" + ex);
            }
        }
    }

    return null;
}

From source file:net.sf.jclal.classifier.WekaClassifier.java

/**
 *
 * @param configuration The configuration object for WekaClassifier.
 *The XML labels supported are://from   ww  w.  j a  va  2  s.  c om
 * <ul>
 * <li>
 * <b>classifier type= class</b>
 * <p>
 * Package: weka.classifiers</p>
 * <p>
 * Class: All</p>
 * </li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {

    String classifierError = "classifier type= ";
    try {

        // classifier classname
        String classifierClassname = configuration.getString("classifier[@type]");
        classifierError += classifierClassname;
        // classifier class
        Class<? extends Classifier> classifierClass = (Class<? extends Classifier>) Class
                .forName(classifierClassname);
        // classifier instance
        Classifier classifierTemp = classifierClass.newInstance();
        // Configure classifier (if necessary)
        if (classifierTemp instanceof IConfigure) {
            ((IConfigure) classifierTemp).configure(configuration.subset("classifier"));
        }
        // Add this classifier
        setClassifier(classifierTemp);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    } catch (InstantiationException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    }
}

From source file:es.udc.gii.common.eaf.algorithm.mga.MMGAAlgorithm.java

/**
 * Configures the algorithm./*www  . j  a va2  s .  c  om*/
 */
@Override
public void configure(Configuration conf) {
    try {
        super.configure(conf);

        if (conf.containsKey("ParetoFrontReplaceOperator.Class")) {
            setParetoFrontReplaceOperator((ParetoFrontReplaceOperator) Class
                    .forName(conf.getString("ParetoFrontReplaceOperator.Class")).newInstance());
        } else {
            (new ConfWarning("MMGAAlgorithm.ParetoFrontReplaceOperator", "ParetoFrontReplaceOperator")).warn();
            setParetoFrontReplaceOperator(new ParetoFrontReplaceOperator());
        }

        getParetoFrontReplaceOperator().configure(conf.subset("ParetoFrontReplaceOperator"));

        if (conf.containsKey("PopulationMemorySize")) {
            setPopulationMemorySize(conf.getInt("PopulationMemorySize"));
        } else {
            int memSize = getParetoFrontReplaceOperator().getMaximumParetoFrontSize() / 3;

            (new ConfWarning("MMGAAlgorithm.PopulationMemorySize", memSize)).warn();
            setPopulationMemorySize(memSize);
        }

        if (conf.containsKey("PopulationMemoryReplaceOperator.Class")) {
            setPopulationMemoryReplaceOperator((PopulationMemoryReplaceOperator) Class
                    .forName(conf.getString("PopulationMemoryReplaceOperator.Class")).newInstance());
        } else {
            (new ConfWarning("MMGAAlgorithm.PopulationMemoryReplaceOperator",
                    "PopulationMemoryReplaceOperator")).warn();
            setPopulationMemoryReplaceOperator(new PopulationMemoryReplaceOperator());
        }

        getPopulationMemoryReplaceOperator().setPopMemSize(getPopulationMemorySize());
        getPopulationMemoryReplaceOperator().configure(conf.subset("PopulationMemoryReplaceOperator"));

    } catch (Exception ex) {
        throw new ConfigurationException(this.getClass(), ex);
    }
}