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

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

Introduction

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

Prototype

public boolean containsKey(String key) 

Source Link

Document

Checks if the specified key is contained in this configuration.

Usage

From source file:com.servioticy.queueclient.QueueClient.java

private static QueueClient createInstance(String configPath) throws QueueClientException {
    QueueClient instance;//w  w w  .j a  va2s.  c  o m
    File f = new File(configPath);
    if (!f.exists()) {
        if (Thread.currentThread().getContextClassLoader().getResource(configPath) == null) {
            return createInstance(configPath, "kestrel", "localhost:22133", "services");
        }
    }

    String type;
    HierarchicalConfiguration config;

    try {
        config = new XMLConfiguration(configPath);

        config.setExpressionEngine(new XPathExpressionEngine());

        if (!config.containsKey("defaultQueue/queueType")) {
            String errMsg = "No default queue. Fix your configuration file.";
            logger.error(errMsg);
            throw new QueueClientException(errMsg);
        }
        type = config.getString("defaultQueue/queueType");
        instance = createInstance(configPath, type,
                config.getString("defaultQueue/baseAddress", "localhost:22133"),
                config.getString("defaultQueue/relativeAddress", "services"));
    } catch (ConfigurationException e) {
        String errMsg = "'" + configPath + "' configuration file is malformed (" + e.getMessage() + ").";
        logger.error(errMsg);
        throw new QueueClientException(errMsg);
    }

    return instance;
}

From source file:jsprit.core.algorithm.io.InsertionFactory.java

@SuppressWarnings("deprecation")
public static InsertionStrategy createInsertion(VehicleRoutingProblem vrp, HierarchicalConfiguration config,
        VehicleFleetManager vehicleFleetManager, StateManager stateManager,
        List<PrioritizedVRAListener> algorithmListeners, ExecutorService executorService, int nuOfThreads,
        ConstraintManager constraintManager, boolean addDefaultCostCalculators) {

    if (config.containsKey("[@name]")) {
        String insertionName = config.getString("[@name]");
        if (!insertionName.equals("bestInsertion") && !insertionName.equals("regretInsertion")) {
            throw new IllegalStateException(
                    insertionName + " is not supported. use either \"bestInsertion\" or \"regretInsertion\"");
        }//from   w w  w. ja  v a  2 s  . com

        InsertionBuilder iBuilder = new InsertionBuilder(vrp, vehicleFleetManager, stateManager,
                constraintManager);

        if (executorService != null) {
            iBuilder.setConcurrentMode(executorService, nuOfThreads);
        }

        if (config.containsKey("level")) {
            String level = config.getString("level");
            if (level.equals("local")) {
                iBuilder.setLocalLevel(addDefaultCostCalculators);
            } else if (level.equals("route")) {
                int forwardLooking = 0;
                int memory = 1;
                String forward = config.getString("level[@forwardLooking]");
                String mem = config.getString("level[@memory]");
                if (forward != null)
                    forwardLooking = Integer.parseInt(forward);
                else
                    log.warn(
                            "parameter route[@forwardLooking] is missing. by default it is 0 which equals to local level");
                if (mem != null)
                    memory = Integer.parseInt(mem);
                else
                    log.warn("parameter route[@memory] is missing. by default it is 1");
                iBuilder.setRouteLevel(forwardLooking, memory, addDefaultCostCalculators);
            } else
                throw new IllegalStateException(
                        "level " + level + " is not known. currently it only knows \"local\" or \"route\"");
        } else
            iBuilder.setLocalLevel(addDefaultCostCalculators);

        if (config.containsKey("considerFixedCosts") || config.containsKey("considerFixedCost")) {
            if (addDefaultCostCalculators) {
                String val = config.getString("considerFixedCosts");
                if (val == null)
                    val = config.getString("considerFixedCost");
                if (val.equals("true")) {
                    double fixedCostWeight = 0.5;
                    String weight = config.getString("considerFixedCosts[@weight]");
                    if (weight == null)
                        weight = config.getString("considerFixedCost[@weight]");
                    if (weight != null)
                        fixedCostWeight = Double.parseDouble(weight);
                    else
                        throw new IllegalStateException(
                                "fixedCostsParameter 'weight' must be set, e.g. <considerFixedCosts weight=1.0>true</considerFixedCosts>.\n"
                                        + "this has to be changed in algorithm-config-xml-file.");
                    iBuilder.considerFixedCosts(fixedCostWeight);
                } else if (val.equals("false")) {

                } else
                    throw new IllegalStateException(
                            "considerFixedCosts must either be true or false, i.e. <considerFixedCosts weight=1.0>true</considerFixedCosts> or \n<considerFixedCosts weight=1.0>false</considerFixedCosts>. "
                                    + "if latter, you can also omit the tag. this has to be changed in algorithm-config-xml-file");
            }
        }
        String timeSliceString = config.getString("experimental[@timeSlice]");
        String neighbors = config.getString("experimental[@neighboringSlices]");
        if (timeSliceString != null && neighbors != null) {
            iBuilder.experimentalTimeScheduler(Double.parseDouble(timeSliceString),
                    Integer.parseInt(neighbors));
        }
        String allowVehicleSwitch = config.getString("allowVehicleSwitch");
        if (allowVehicleSwitch != null) {
            iBuilder.setAllowVehicleSwitch(Boolean.parseBoolean(allowVehicleSwitch));
        }

        if (insertionName.equals("regretInsertion")) {
            iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.REGRET);

            String fastRegret = config.getString("fastRegret");
            if (fastRegret != null) {
                iBuilder.setFastRegret(Boolean.parseBoolean(fastRegret));
            }
        }
        return iBuilder.build();
    } else
        throw new IllegalStateException("cannot create insertionStrategy, since it has no name.");
}

From source file:com.graphhopper.jsprit.core.algorithm.io.InsertionFactory.java

@SuppressWarnings("deprecation")
public static InsertionStrategy createInsertion(VehicleRoutingProblem vrp, HierarchicalConfiguration config,
        VehicleFleetManager vehicleFleetManager, StateManager stateManager,
        List<VehicleRoutingAlgorithmListeners.PrioritizedVRAListener> algorithmListeners,
        ExecutorService executorService, int nuOfThreads, ConstraintManager constraintManager,
        boolean addDefaultCostCalculators) {

    if (config.containsKey("[@name]")) {
        String insertionName = config.getString("[@name]");
        if (!insertionName.equals("bestInsertion") && !insertionName.equals("regretInsertion")) {
            throw new IllegalStateException(
                    insertionName + " is not supported. use either \"bestInsertion\" or \"regretInsertion\"");
        }//from w w w  . ja v a  2s. c om

        InsertionBuilder iBuilder = new InsertionBuilder(vrp, vehicleFleetManager, stateManager,
                constraintManager);

        if (executorService != null) {
            iBuilder.setConcurrentMode(executorService, nuOfThreads);
        }

        if (config.containsKey("level")) {
            String level = config.getString("level");
            if (level.equals("local")) {
                iBuilder.setLocalLevel(addDefaultCostCalculators);
            } else if (level.equals("route")) {
                int forwardLooking = 0;
                int memory = 1;
                String forward = config.getString("level[@forwardLooking]");
                String mem = config.getString("level[@memory]");
                if (forward != null)
                    forwardLooking = Integer.parseInt(forward);
                else
                    log.warn(
                            "parameter route[@forwardLooking] is missing. by default it is 0 which equals to local level");
                if (mem != null)
                    memory = Integer.parseInt(mem);
                else
                    log.warn("parameter route[@memory] is missing. by default it is 1");
                iBuilder.setRouteLevel(forwardLooking, memory, addDefaultCostCalculators);
            } else
                throw new IllegalStateException(
                        "level " + level + " is not known. currently it only knows \"local\" or \"route\"");
        } else
            iBuilder.setLocalLevel(addDefaultCostCalculators);

        if (config.containsKey("considerFixedCosts") || config.containsKey("considerFixedCost")) {
            if (addDefaultCostCalculators) {
                String val = config.getString("considerFixedCosts");
                if (val == null)
                    val = config.getString("considerFixedCost");
                if (val.equals("true")) {
                    double fixedCostWeight = 0.5;
                    String weight = config.getString("considerFixedCosts[@weight]");
                    if (weight == null)
                        weight = config.getString("considerFixedCost[@weight]");
                    if (weight != null)
                        fixedCostWeight = Double.parseDouble(weight);
                    else
                        throw new IllegalStateException(
                                "fixedCostsParameter 'weight' must be set, e.g. <considerFixedCosts weight=1.0>true</considerFixedCosts>.\n"
                                        + "this has to be changed in algorithm-config-xml-file.");
                    iBuilder.considerFixedCosts(fixedCostWeight);
                } else if (val.equals("false")) {

                } else
                    throw new IllegalStateException(
                            "considerFixedCosts must either be true or false, i.e. <considerFixedCosts weight=1.0>true</considerFixedCosts> or \n<considerFixedCosts weight=1.0>false</considerFixedCosts>. "
                                    + "if latter, you can also omit the tag. this has to be changed in algorithm-config-xml-file");
            }
        }
        String allowVehicleSwitch = config.getString("allowVehicleSwitch");
        if (allowVehicleSwitch != null) {
            iBuilder.setAllowVehicleSwitch(Boolean.parseBoolean(allowVehicleSwitch));
        }

        if (insertionName.equals("regretInsertion")) {
            iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.REGRET);

            String fastRegret = config.getString("fastRegret");
            if (fastRegret != null) {
                iBuilder.setFastRegret(Boolean.parseBoolean(fastRegret));
            }
        }
        return iBuilder.build();
    } else
        throw new IllegalStateException("cannot create insertionStrategy, since it has no name.");
}

From source file:com.graphhopper.jsprit.core.algorithm.io.VehicleRoutingAlgorithms.java

private static String getName(HierarchicalConfiguration strategyConfig) {
    if (strategyConfig.containsKey("[@name]")) {
        return strategyConfig.getString("[@name]");
    }/* w ww. java  2s.  c  om*/
    return "";
}

From source file:com.vmware.qe.framework.datadriven.impl.filter.DataFilterBasedOnProperty.java

/**
 * filters test based on given filterKey/filterValue. If the any of the filter key/value pairs
 * found from data object, then returns true.
 * //from   w w  w  . j  a  v  a 2 s .c o  m
 * @param data test data
 * @return true if test is selected after applying filter, false otherwise
 */
private boolean checkAgainstFilterProperties(HierarchicalConfiguration data,
        HierarchicalConfiguration context) {
    boolean included = true;
    String filterKeys[] = null;
    String filterValues[] = null;
    if (context.containsKey(ARG_FILTER_KEY) && !context.getString(ARG_FILTER_KEY).trim().equals("")) {
        filterKeys = context.getStringArray(ARG_FILTER_KEY);
        filterValues = context.getStringArray(ARG_FILTER_VALUE);
    } else if (DDConfig.getSingleton().getData().containsKey(ARG_FILTER_KEY)
            && !DDConfig.getSingleton().getData().getString(ARG_FILTER_KEY).trim().equals("")) {
        filterKeys = DDConfig.getSingleton().getData().getStringArray(ARG_FILTER_KEY);
        filterValues = DDConfig.getSingleton().getData().getStringArray(ARG_FILTER_VALUE);
    }
    if (filterKeys != null && filterValues != null) {
        included = false;
        for (int index = 0; index < filterKeys.length; index++) {
            String filterKey = filterKeys[index];
            String filterValue = null;
            if (index >= filterValues.length) {
                filterValue = "";
            } else {
                filterValue = filterValues[index];
            }
            if (data.containsKey(filterKey) && data.getString(filterKey, "").equals(filterValue)) {
                included = true;
                break;
            }
        }
    }
    return included;
}

From source file:com.github.steveash.typedconfig.resolver.type.simple.BooleanValueResolverFactory.java

private ValueResolver makeJustCheckKeyExistsResolver(final String configKeyToLookup,
        final HierarchicalConfiguration config) {
    return new ValueResolver() {
        @Override/*from   w w  w. j  av  a  2 s  . c o  m*/
        public Boolean resolve() {
            if (config.containsKey(configKeyToLookup))
                return true;

            // it may be a subconfiguration
            try {
                config.configurationAt(configKeyToLookup);
                return true; // throws exception otherwise
            } catch (RuntimeException e) {
                return false;
            }
        }

        @Override
        public Boolean convertDefaultValue(String defaultValue) {
            throw new IllegalStateException("Cant use a default value with the 'check exists' option");
        }

        @Override
        public String configurationKeyToLookup() {
            return configKeyToLookup;
        }
    };
}

From source file:com.sonicle.webtop.core.app.DataSourcesConfig.java

protected HikariConfig parseDataSource(HierarchicalConfiguration dsEl) throws ParseException {
    HikariConfig config = createHikariConfig();

    if (dsEl.containsKey("[@dataSourceClassName]")) { // Jdbc 4 configs
        config.setDataSourceClassName(dsEl.getString("[@dataSourceClassName]"));
        config.addDataSourceProperty("serverName", dsEl.getString("[@serverName]"));
        if (dsEl.containsKey("[@port]"))
            config.addDataSourceProperty("port", dsEl.getInt("[@port]"));
        config.addDataSourceProperty("databaseName", dsEl.getString("[@databaseName]"));

    } else if (dsEl.containsKey("[@driverClassName]")) { // Jdbc 3 configs
        config.setDriverClassName(dsEl.getString("[@driverClassName]"));
        config.setJdbcUrl(dsEl.getString("[@jdbcUrl]"));
    }//from ww w  .ja va  2  s.  co  m

    if (dsEl.containsKey("[@username]"))
        config.setUsername(dsEl.getString("[@username]"));
    if (dsEl.containsKey("[@password]"))
        config.setPassword(dsEl.getString("[@password]"));

    if (!dsEl.isEmpty()) {
        List<HierarchicalConfiguration> elProps = dsEl.configurationsAt("property");
        Properties props = new Properties();
        for (HierarchicalConfiguration elProp : elProps) {
            if (elProp.containsKey("[@name]") && elProp.containsKey("[@value]")) {
                final String name = elProp.getString("[@name]");
                final String value = elProp.getString("[@value]");
                if (!StringUtils.isBlank(name)) {
                    props.setProperty(name, value);
                    logger.trace("property: {} -> {}", name, value);
                }
            }
        }
        PropertyElf.setTargetFromProperties(config, props);
    }

    // Common configs...
    /*
    if(dsEl.containsKey("[@autoCommit]")) config.setAutoCommit(dsEl.getBoolean("[@autoCommit]"));
    if(dsEl.containsKey("[@connectionTimeout]")) config.setConnectionTimeout(dsEl.getLong("[@connectionTimeout]"));
    if(dsEl.containsKey("[@idleTimeout]")) config.setIdleTimeout(dsEl.getLong("[@idleTimeout]"));
    if(dsEl.containsKey("[@maxLifetime]")) config.setMaxLifetime(dsEl.getLong("[@maxLifetime]"));
    if(dsEl.containsKey("[@minimumIdle]")) config.setMinimumIdle(dsEl.getInt("[@minimumIdle]"));
    if(dsEl.containsKey("[@maximumPoolSize]")) config.setMaximumPoolSize(dsEl.getInt("[@maximumPoolSize]"));
    */

    return config;
}

From source file:com.eyeq.pivot4j.ui.property.PropertySupport.java

/**
 * @see com.eyeq.pivot4j.state.Configurable#restoreSettings(org.apache.commons.configuration.HierarchicalConfiguration)
 *///from   w  w w  . ja v  a 2  s.com
@Override
public void restoreSettings(HierarchicalConfiguration configuration) {
    this.properties.clear();

    try {
        List<HierarchicalConfiguration> configurations = configuration.configurationsAt("property");

        for (HierarchicalConfiguration propertyConfig : configurations) {
            boolean conditional = propertyConfig.containsKey("conditions");

            Property property;

            // TODO Need more robust method to determine property types.
            if (conditional) {
                property = new ConditionalProperty(conditionFactory);
            } else {
                property = new SimpleProperty();
            }

            property.restoreSettings(propertyConfig);

            this.properties.put(property.getName(), property);
        }
    } catch (IllegalArgumentException e) {
    }
}

From source file:com.servioticy.dispatcher.DispatcherContext.java

public void loadConf(String path) {
    HierarchicalConfiguration config;

    try {/*from w  ww  . j  a  v a 2s. co  m*/
        if (path == null) {
            config = new XMLConfiguration(DispatcherContext.DEFAULT_CONFIG_PATH);
        } else {
            config = new XMLConfiguration(path);
        }
        config.setExpressionEngine(new XPathExpressionEngine());

        this.restBaseURL = config.getString("servioticyAPI", this.restBaseURL);

        ArrayList<String> updates = new ArrayList<String>();
        if (config.containsKey("spouts/updates/addresses/address[1]")) {
            for (int i = 1; config.containsKey("spouts/updates/addresses/address[" + i + "]"); i++) {
                updates.add(config.getString("spouts/updates/addresses/address[" + i + "]"));
            }
        } else {
            for (String address : this.updatesAddresses) {
                updates.add(address);
            }
        }
        this.updatesAddresses = (String[]) updates.toArray(new String[] {});
        this.updatesPort = config.getInt("spouts/updates/port", this.updatesPort);
        this.updatesQueue = config.getString("spouts/updates/name", this.updatesQueue);

        ArrayList<String> actions = new ArrayList<String>();
        if (config.containsKey("spouts/actions/addresses/address[1]")) {
            for (int i = 1; config.containsKey("spouts/actions/addresses/address[" + i + "]"); i++) {
                actions.add(config.getString("spouts/actions/addresses/address[" + i + "]"));
            }
        } else {
            for (String address : this.actionsAddresses) {
                actions.add(address);
            }
        }
        this.actionsAddresses = (String[]) actions.toArray(new String[] {});
        this.actionsPort = config.getInt("spouts/actions/port", this.actionsPort);
        this.actionsQueue = config.getString("spouts/actions/name", this.actionsQueue);

        this.benchmark = config.getBoolean("benchmark", this.benchmark);

        this.externalPubAddress = config.getString("publishers/external/address", this.externalPubAddress);
        this.externalPubPort = config.getInt("publishers/external/port", this.externalPubPort);
        this.externalPubUser = config.getString("publishers/external/username", this.externalPubUser);
        this.externalPubPassword = config.getString("publishers/external/password", this.externalPubPassword);
        this.externalPubClassName = config.getString("publishers/external/class", this.externalPubClassName);

        this.internalPubAddress = config.getString("publishers/internal/address", this.internalPubAddress);
        this.internalPubPort = config.getInt("publishers/internal/port", this.internalPubPort);
        this.internalPubUser = config.getString("publishers/internal/username", this.internalPubUser);
        this.internalPubPassword = config.getString("publishers/internal/password", this.internalPubPassword);
        this.internalPubClassName = config.getString("publishers/internal/class", this.internalPubClassName);

        this.actionsPubAddress = config.getString("publishers/actions/address", this.actionsPubAddress);
        this.actionsPubPort = config.getInt("publishers/actions/port", this.actionsPubPort);
        this.actionsPubUser = config.getString("publishers/actions/username", this.actionsPubUser);
        this.actionsPubPassword = config.getString("publishers/actions/password", this.actionsPubPassword);
        this.actionsPubClassName = config.getString("publishers/actions/class", this.actionsPubClassName);

        this.benchResultsDir = config.getString("benchResultsDir", this.benchResultsDir);

    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}

From source file:com.wrmsr.neurosis.util.Configs.java

public static Map<String, String> stripSubconfig(Map<String, String> properties, String prefix) {
    HierarchicalConfiguration hierarchicalProperties = toHierarchical(properties);
    Configuration subconfig;/*w  w w .j  a v  a 2s .  c  o  m*/
    try {
        subconfig = hierarchicalProperties.configurationAt(prefix);
    } catch (IllegalArgumentException e) {
        return ImmutableMap.of();
    }

    Map<String, String> subproperties = new ConfigurationMap(subconfig).entrySet().stream()
            .collect(ImmutableCollectors.toImmutableMap(e -> checkNotNull(e.getKey()).toString(),
                    e -> checkNotNull(e.getValue()).toString()));

    hierarchicalProperties.clearTree(prefix);
    for (String key : Sets.newHashSet(properties.keySet())) {
        if (!hierarchicalProperties.containsKey(key)) {
            properties.remove(key);
        }
    }

    return subproperties;
}