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

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

Introduction

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

Prototype

boolean containsKey(String key);

Source Link

Document

Check if the configuration contains the specified key.

Usage

From source file:de.kopis.glacier.parsers.GlacierUploaderOptionParser.java

private ArgumentAcceptingOptionSpec<File> parseCredentials(final Configuration config) {
    ArgumentAcceptingOptionSpec<File> credentialsBuilder = acceptsAll(new ArrayList<String>() {
        {/*w ww .ja v a2s  .c  o  m*/
            add("credentials");
        }
    }, "path to your aws credentials file").withRequiredArg().ofType(File.class);

    if (config.containsKey("credentials")) {
        credentialsBuilder.defaultsTo(new File(config.getString("credentials")));
    } else {
        credentialsBuilder.defaultsTo(new File(System.getProperty("user.home") + "/aws.properties"));
    }
    return credentialsBuilder;
}

From source file:de.kopis.glacier.parsers.GlacierUploaderOptionParser.java

private ArgumentAcceptingOptionSpec<String> parseVault(final Configuration config) {
    ArgumentAcceptingOptionSpec<String> vaultBuilder = acceptsAll(new ArrayList<String>() {
        {//from  w ww.  ja  va2  s . c o  m
            add("vault");
            add("v");
        }
    }, "name of your vault").withRequiredArg().ofType(String.class);

    if (config.containsKey("vault")) {
        vaultBuilder.defaultsTo(config.getString("vault"));
    }
    return vaultBuilder;
}

From source file:ching.icecreaming.actions.FileLink.java

@Action(value = "file-link", results = { @Result(name = "success", type = "stream", params = { "inputName",
        "imageStream", "contentType", "${contentType}", "contentDisposition", "attachment;filename=${fileName}",
        "allowCaching", "false", "bufferSize", "1024" }), @Result(name = "error", location = "errors.jsp") })
public String execute() throws Exception {
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("mimeTypes.properties");
    File file1 = null, file2 = null;
    String string1 = null, fileExtension = null;
    fileExtension = FilenameUtils.getExtension(fileName);
    contentType = "application/octet-stream";
    if (!StringUtils.isBlank(fileExtension)) {
        if (propertiesConfiguration1.containsKey(fileExtension))
            contentType = propertiesConfiguration1.getString(fileExtension);
    } else {//w  w  w . j  a va  2 s.c o m
        contentType = "image/png";
    }
    try {
        if (StringUtils.isBlank(sessionId)) {
            sessionId = httpServletRequest.getSession().getId();
        }
        string1 = System.getProperty("java.io.tmpdir") + File.separator + sessionId;
        if (StringUtils.isBlank(fileExtension))
            string1 += File.separator + FilenameUtils.getPath(fileName);
        fileName = FilenameUtils.getName(fileName);
        if (StringUtils.equalsIgnoreCase(fileExtension, "html")) {
            file2 = new File(string1, FilenameUtils.getBaseName(fileName) + ".zip");
            if (file2.exists()) {
                file1 = file2;
                contentType = "application/zip";
                fileName = file2.getName();
            } else {
                file1 = new File(string1, fileName);
            }
        } else {
            file1 = new File(string1, fileName);
        }
        if (file1.exists()) {
            imageStream = new BufferedInputStream(FileUtils.openInputStream(file1));
        }
    } catch (IOException exception1) {
        addActionError(exception1.getMessage());
        return ERROR;
    }
    return SUCCESS;
}

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 2  s.com
 *
 *  <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:de.kopis.glacier.parsers.GlacierUploaderOptionParser.java

private ArgumentAcceptingOptionSpec<String> parseEndpoint(final Configuration config) {
    ArgumentAcceptingOptionSpec<String> endpointBuilder = acceptsAll(new ArrayList<String>() {
        {//  w  w w .  j  av a 2 s. c o m
            add("endpoint");
            add("e");
        }
    }, "URL or Region handle of the amazon AWS endpoint where your vault is").withRequiredArg()
            .ofType(String.class);

    if (config.containsKey("endpoint")) {
        endpointBuilder.defaultsTo(formatEndpointUrl(config.getString("endpoint")));
    }
    return endpointBuilder;
}

From source file:com.nesscomputing.migratory.mojo.database.AbstractDatabaseMojo.java

private boolean validateConfiguration(Configuration config) throws MojoExecutionException {
    boolean valid = true;
    for (String mustExist : MUST_EXIST) {
        final String propertyName = getPropertyName(mustExist);
        if (!config.containsKey(propertyName)) {
            LOG.error("The required property '%s' does not exist in the manifest.", propertyName);
            valid = false;/*from  w  ww .ja  v a 2s . c o m*/
        }
    }

    for (String mustNotBeEmpty : MUST_NOT_BE_EMPTY) {
        final String propertyName = getPropertyName(mustNotBeEmpty);
        if (StringUtils.isBlank(config.getString(propertyName, null))) {
            LOG.error("The property '%s' must not be empty.", propertyName);
            valid = false;
        }
    }

    final String defaultBase = config.getString(getPropertyName("default.base"), "");
    if (defaultBase.indexOf("%s") == -1 || defaultBase.indexOf("%s") != defaultBase.lastIndexOf("%s")) {
        LOG.error("The 'config.default.base' property must contain exactly one '%s' place holder!");
        valid = false;
    }

    return valid;
}

From source file:es.udc.gii.common.eaf.algorithm.operator.reproduction.CMASamplePopulationOperator.java

@Override
public void configure(Configuration conf) {

    super.configure(conf);
    if (conf.containsKey("LowerStandardDeviation")) {
        this.lowerStandardDeviation = parseDouble(conf.getString("LowerStandardDeviation").split(","));
    } else {/*from   ww w  .j  av  a2  s  .  c o  m*/
        this.lowerStandardDeviation = null;
        ConfWarning w = new ConfWarning("CMASamplePopulationOperator.LowerStandardDeviation", null);
        w.warn();
    }

    if (conf.containsKey("UpperStandardDeviation")) {
        this.upperStandardDeviation = parseDouble(conf.getString("UpperStandardDeviation").split(","));
    } else {
        this.upperStandardDeviation = null;
        ConfWarning w = new ConfWarning("CMASamplePopulationOperator.UpperStandardDeviation", null);
        w.warn();
    }

}

From source file:com.cisco.oss.foundation.logging.FoundationLoggerConfiguration.java

private boolean initRoot(org.apache.commons.configuration.Configuration log4jSubset) {

    boolean rootIsSet = false;

    if (log4jSubset.containsKey("rootLogger")) {
        rootIsSet = true;//from  ww w . j  a  v  a2  s .  c  o  m
        String val = log4jSubset.getString("rootLogger");
        if (StringUtils.isNotBlank(val)) {
            String[] rootParts = val.trim().split(",");
            for (String rootPart : rootParts) {

                String trimmedRootPart = rootPart.trim();
                if (Level.getLevel(rootPart.toUpperCase()) == null) {
                    getRootLogger().getAppenderRefs()
                            .add(AppenderRef.createAppenderRef(trimmedRootPart, Level.ALL, null));
                } else {
                    getRootLogger().setLevel(Level.getLevel(trimmedRootPart.toUpperCase()));
                }
            }
        }
    } else if (log4jSubset.containsKey("rootCategory")) {
        rootIsSet = true;
        String val = log4jSubset.getString("rootCategory");
        if (StringUtils.isNotBlank(val)) {
            String[] rootParts = val.trim().split(",");
            for (String rootPart : rootParts) {

                if (Level.getLevel(rootPart.toUpperCase()) == null) {
                    getRootLogger().getAppenderRefs()
                            .add(AppenderRef.createAppenderRef(rootPart, Level.ALL, null));
                } else {
                    getRootLogger().setLevel(Level.getLevel(rootPart.toUpperCase()));
                }
            }
        }

    }

    List<AppenderRef> appenderRefs = getRootLogger().getAppenderRefs();
    for (AppenderRef appenderRef : appenderRefs) {
        Appender appender = getAppender(appenderRef.getRef());
        getRootLogger().addAppender(appender, appenderRef.getLevel(), appenderRef.getFilter());
    }

    getRootLogger().start();

    return rootIsSet;

}

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

public BenchmarkConfiguration(Configuration appconfig) {
    if (appconfig == null) {
        throw new IllegalArgumentException("appconfig may not be null");
    }/*from   w  w  w . j  ava2  s .  com*/

    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.CMAEvolutionaryAlgorithm.java

@Override
public void configure(Configuration conf) {
    super.configure(conf);

    try {//from   w w w .j a v a  2s. co  m

        if (conf.containsKey("InitialX")) {

            double x = conf.getDouble("InitialX");
            this.xMean = new double[] { x };

        } else {
            this.xMean = new double[] { 0.0 };
            ConfWarning w = new ConfWarning("EvolutionaryAlgorithm.InitialX", 0.0);
            w.warn();

        }

        if (conf.containsKey("TypicalX")) {
            double x = conf.getDouble("TypicalX");
            this.typicalX = new double[] { x };
        } else {
            this.typicalX = null;
            ConfWarning w = new ConfWarning("EvolutionaryAlgorithm.TypicalX", 0.0);
            w.warn();

        }

        if (conf.containsKey("InitialStandardDeviation")) {

            this.startsigma = new double[] { conf.getDouble("InitialStandardDeviation") };

        } else {

            this.startsigma = new double[] { 1.0 };
            ConfWarning w = new ConfWarning("EvolutionaryAlgorithm.InitialStandardDeviation", 1.0);
            w.warn();

        }

        if (conf.containsKey("Mu")) {

            this.mu = conf.getInt("Mu");

        } else {

            this.mu = -1;
            ConfWarning w = new ConfWarning("EvolutionaryAlgorithm.Mu", this.mu);
            w.warn();

        }

        if (conf.containsKey("RecombinationType")) {

            this.recombinationType = (RecombinationType) Class
                    .forName(conf.getString("RecombinationType.Class")).newInstance();
            this.recombinationType.configure(conf.subset("RecombinationType"));
        } else {
            ConfWarning w = new ConfWarning("EvolutionaryAlgorithm.RecombinationType",
                    this.recombinationType.toString());
            w.warn();
        }

        if (conf.containsKey("Cs")) {
            this.cs = conf.getDouble("Cs");
        } else {
            this.cs = -1;
            ConfWarning w = new ConfWarning("CMAEvolutionaryAlgorithm.Cs", this.cs);
            w.warn();
        }

        if (conf.containsKey("Damps")) {
            this.damps = conf.getDouble("Damps");
        } else {

            this.damps = -1;
            ConfWarning w = new ConfWarning("CMAEvolutionaryAlgorithm.Damps", this.damps);
            w.warn();

        }

        if (conf.containsKey("DiagonalCovarianceMatrix")) {
            this.diagonalCovarianceMatrix = conf.getInt("DiagonalCovarianceMatrix");

        } else {
            this.diagonalCovarianceMatrix = -1;
            ConfWarning w = new ConfWarning("CMAEvolutionaryAlgorithm.DiagonalCovarianceMatrix",
                    this.diagonalCovarianceMatrix);
            w.warn();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}