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

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

Introduction

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

Prototype

Iterator getKeys();

Source Link

Document

Get the list of the keys contained in the configuration.

Usage

From source file:com.netflix.config.AbstractPollingScheduler.java

/**
 * Apply the polled result to the configuration.
 * If the polled result is full result from source, each property in the result is either added to set 
 * to the configuration, and any property that is in the configuration but not in the result is deleted if ignoreDeletesFromSource
 * is false. If the polled result is incremental, properties added and changed in the partial result 
 * are set with the configuration, and deleted properties are deleted form configuration if ignoreDeletesFromSource
 * is false.//from w  ww.  java  2 s .  co  m
 * 
 * @param result Polled result from source
 */
protected void populateProperties(final PollResult result, final Configuration config) {
    if (result == null || !result.hasChanges()) {
        return;
    }
    if (!result.isIncremental()) {
        Map<String, Object> props = result.getComplete();
        if (props == null) {
            return;
        }
        for (Entry<String, Object> entry : props.entrySet()) {
            propertyUpdater.addOrChangeProperty(entry.getKey(), entry.getValue(), config);
        }
        HashSet<String> existingKeys = new HashSet<String>();
        for (Iterator<String> i = config.getKeys(); i.hasNext();) {
            existingKeys.add(i.next());
        }
        if (!ignoreDeletesFromSource) {
            for (String key : existingKeys) {
                if (!props.containsKey(key)) {
                    propertyUpdater.deleteProperty(key, config);
                }
            }
        }
    } else {
        Map<String, Object> props = result.getAdded();
        if (props != null) {
            for (Entry<String, Object> entry : props.entrySet()) {
                propertyUpdater.addOrChangeProperty(entry.getKey(), entry.getValue(), config);
            }
        }
        props = result.getChanged();
        if (props != null) {
            for (Entry<String, Object> entry : props.entrySet()) {
                propertyUpdater.addOrChangeProperty(entry.getKey(), entry.getValue(), config);
            }
        }
        if (!ignoreDeletesFromSource) {
            props = result.getDeleted();
            if (props != null) {
                for (String name : props.keySet()) {
                    propertyUpdater.deleteProperty(name, config);
                }
            }
        }
    }
}

From source file:com.netflix.config.ConcurrentCompositeConfiguration.java

/**
 * Get all the keys contained by sub configurations.
 * // w w w .ja v  a 2s  .  c  o m
 * @throws ConcurrentModificationException if concurrent modification happens on any sub configuration
 * when it is iterated to get all the keys
 * 
 */
public Iterator<String> getKeys() throws ConcurrentModificationException {
    Set<String> keys = new LinkedHashSet<String>();
    for (Iterator<String> it = overrideProperties.getKeys(); it.hasNext();) {
        keys.add(it.next());
    }
    for (Configuration config : configList) {
        for (Iterator<String> it = config.getKeys(); it.hasNext();) {
            try {
                keys.add(it.next());
            } catch (ConcurrentModificationException e) {
                logger.error("unexpected exception when iterating the keys for configuration " + config
                        + " with name " + getNameForConfiguration(config));
                throw e;
            }
        }
    }

    return keys.iterator();
}

From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java

private InternalServerProxyMetadata loadServersMetadataConfiguration() {

    Configuration subset = ConfigurationFactory.getConfiguration().subset(getApiName());
    final Iterator<String> keysIterator = subset.getKeys();

    // read default values
    int readTimeout = subset.getInt("http." + LoadBalancerConstants.READ_TIME_OUT,
            LoadBalancerConstants.DEFAULT_READ_TIMEOUT);
    int connectTimeout = subset.getInt("http." + LoadBalancerConstants.CONNECT_TIME_OUT,
            LoadBalancerConstants.DEFAULT_CONNECT_TIMEOUT);
    long waitingTime = subset.getLong("http." + LoadBalancerConstants.WAITING_TIME,
            LoadBalancerConstants.DEFAULT_WAITING_TIME);
    int numberOfAttempts = subset.getInt("http." + LoadBalancerConstants.NUMBER_OF_ATTEMPTS,
            LoadBalancerConstants.DEFAULT_NUMBER_OF_ATTEMPTS);
    long retryDelay = subset.getLong("http." + LoadBalancerConstants.RETRY_DELAY,
            LoadBalancerConstants.DEFAULT_RETRY_DELAY);

    long idleTimeout = subset.getLong("http." + LoadBalancerConstants.IDLE_TIME_OUT,
            LoadBalancerConstants.DEFAULT_IDLE_TIMEOUT);
    int maxConnectionsPerAddress = subset.getInt("http." + LoadBalancerConstants.MAX_CONNECTIONS_PER_ADDRESS,
            LoadBalancerConstants.DEFAULT_MAX_CONNECTIONS_PER_ADDRESS);
    int maxConnectionsTotal = subset.getInt("http." + LoadBalancerConstants.MAX_CONNECTIONS_TOTAL,
            LoadBalancerConstants.DEFAULT_MAX_CONNECTIONS_TOTAL);
    int maxQueueSizePerAddress = subset.getInt("http." + LoadBalancerConstants.MAX_QUEUE_PER_ADDRESS,
            LoadBalancerConstants.DEFAULT_MAX_QUEUE_PER_ADDRESS);
    boolean followRedirects = subset.getBoolean("http." + LoadBalancerConstants.FOLLOW_REDIRECTS, false);
    boolean disableCookies = subset.getBoolean("http." + LoadBalancerConstants.DISABLE_COOKIES, false);
    boolean autoCloseable = subset.getBoolean("http." + LoadBalancerConstants.AUTO_CLOSEABLE, true);
    boolean autoEncodeUri = subset.getBoolean("http." + LoadBalancerConstants.AUTO_ENCODE_URI, true);
    boolean staleConnectionCheckEnabled = subset
            .getBoolean("http." + LoadBalancerConstants.IS_STALE_CONN_CHECK_ENABLED, false);
    boolean serviceDirectoryEnabled = subset
            .getBoolean("http." + LoadBalancerConstants.SERVICE_DIRECTORY_IS_ENABLED, false);
    String serviceName = subset.getString("http." + LoadBalancerConstants.SERVICE_DIRECTORY_SERVICE_NAME,
            "UNKNOWN");

    String keyStorePath = subset.getString("http." + LoadBalancerConstants.KEYSTORE_PATH, "");
    String keyStorePassword = subset.getString("http." + LoadBalancerConstants.KEYSTORE_PASSWORD, "");
    String trustStorePath = subset.getString("http." + LoadBalancerConstants.TRUSTSTORE_PATH, "");
    String trustStorePassword = subset.getString("http." + LoadBalancerConstants.TRUSTSTORE_PASSWORD, "");
    startEurekaClient = subset.getBoolean("http.startEurekaClient", true);

    final List<String> keys = new ArrayList<String>();

    while (keysIterator.hasNext()) {
        String key = keysIterator.next();
        keys.add(key);//from  ww  w  . j  a va2  s . co  m
    }

    Collections.sort(keys);

    List<Pair<String, Integer>> hostAndPortPairs = new CopyOnWriteArrayList<Pair<String, Integer>>();

    for (String key : keys) {

        if (key.contains(LoadBalancerConstants.HOST)) {

            String host = subset.getString(key);

            // trim the host name
            if (org.apache.commons.lang.StringUtils.isNotEmpty(host)) {
                host = host.trim();
            }
            final String portKey = key.replace(LoadBalancerConstants.HOST, LoadBalancerConstants.PORT);
            if (subset.containsKey(portKey)) {
                int port = subset.getInt(portKey);
                // save host and port for future creation of server list
                hostAndPortPairs.add(Pair.of(host, port));
            }
        }

    }

    InternalServerProxyMetadata metadata = new InternalServerProxyMetadata(readTimeout, connectTimeout,
            idleTimeout, maxConnectionsPerAddress, maxConnectionsTotal, maxQueueSizePerAddress, waitingTime,
            numberOfAttempts, retryDelay, hostAndPortPairs, keyStorePath, keyStorePassword, trustStorePath,
            trustStorePassword, followRedirects, autoCloseable, staleConnectionCheckEnabled, disableCookies,
            serviceDirectoryEnabled, serviceName, autoEncodeUri);
    //        metadata.getHostAndPortPairs().addAll(hostAndPortPairs);
    //        metadata.setReadTimeout(readTimeout);
    //        metadata.setConnectTimeout(connectTimeout);
    //        metadata.setNumberOfRetries(numberOfAttempts);
    //        metadata.setRetryDelay(retryDelay);
    //        metadata.setWaitingTime(waitingTime);

    return metadata;

}

From source file:com.intel.mtwilson.MyConfiguration.java

private void logConfiguration(String source, Configuration config) {
    log.debug("Loaded configuration keys from {}: {}", source, StringUtils.join(config.getKeys(), ", "));
    // we log the source of each configuration key;  CompositeConfiguration has a method called getSource() but it throws IllegalArgumentException if more than one child configuration has the key, which is wrong because get*() functions return from the first configuration to have it, and so getSource() should also return the first configuration that has the key... but it doesn't. so we keep track ourselves.
    Iterator<String> it = config.getKeys();
    while (it.hasNext()) {
        String key = it.next();/*www .j ava  2 s.  c o m*/
        if (!keySourceMap.containsKey(key)) {
            keySourceMap.put(key, source);
        }
    }
}

From source file:com.netflix.client.config.DefaultClientConfigImpl.java

/**
 * Load properties for a given client. It first loads the default values for all properties,
 * and any properties already defined with Archaius ConfigurationManager.
 *///from w ww. j  ava2 s  .  c  o  m
@Override
public void loadProperties(String restClientName) {
    enableDynamicProperties = true;
    setClientName(restClientName);
    loadDefaultValues();
    Configuration props = ConfigurationManager.getConfigInstance().subset(restClientName);
    for (Iterator<String> keys = props.getKeys(); keys.hasNext();) {
        String key = keys.next();
        String prop = key;
        try {
            if (prop.startsWith(getNameSpace())) {
                prop = prop.substring(getNameSpace().length() + 1);
            }
            setPropertyInternal(prop, getStringValue(props, key));
        } catch (Exception ex) {
            throw new RuntimeException(String.format("Property %s is invalid", prop));
        }
    }
}

From source file:ffx.autoparm.ForceFieldFilter_2.java

private void parse(CompositeConfiguration properties) {
    try {//from   w  ww .  j  a va2  s.c om
        int numConfigs = properties.getNumberOfConfigurations();
        /**
         * Loop over the configurations starting with lowest precedence.
         * This way higher precedence entries will overwrite lower
         * precedence entries within the ForceField instance.
         */
        for (int n = numConfigs - 1; n >= 0; n--) {
            Configuration config = properties.getConfiguration(n);
            Iterator i = config.getKeys();
            while (i.hasNext()) {
                String key = (String) i.next();
                ForceFieldType type = null;
                try {
                    type = ForceFieldType.valueOf(key.toUpperCase());
                } catch (Exception e) {
                    continue;
                }
                String list[] = config.getStringArray(key);
                for (String s : list) {
                    // Add back the key to the input line.
                    s = key + " " + s;
                    String tokens[] = s.trim().split(" +");
                    String input = s;
                    switch (type) {
                    case ATOM:
                        parseAtom(input, tokens);
                        break;
                    case ANGLE:
                        parseAngle(input, tokens);
                        break;
                    case BIOTYPE:
                        parseBioType(input, tokens);
                        break;
                    case BOND:
                        parseBond(input, tokens);
                        break;
                    case CHARGE:
                        parseCharge(input, tokens);
                        break;
                    case MULTIPOLE:
                        parseMultipole(input, tokens);
                        break;
                    case OPBEND:
                        parseOPBend(input, tokens);
                        break;
                    case STRBND:
                        parseStrBnd(input, tokens);
                        break;
                    case PITORS:
                        parsePiTorsion(input, tokens);
                        break;
                    case TORSION:
                        parseTorsion(input, tokens);
                        break;
                    case TORTORS:
                        parseTorsionTorsion(input, tokens);
                        break;
                    case UREYBRAD:
                        parseUreyBradley(input, tokens);
                        break;
                    case VDW:
                        parseVDW(input, tokens);
                        break;
                    case POLARIZE:
                        parsePolarize(input, tokens);
                        break;
                    default:
                        logger.warning("ForceField type recognized, but not stored:" + type);
                    }
                }
            }
        }
        //forceField.checkPolarizationTypes();
    } catch (Exception e) {
        String message = "Exception parsing force field.";
        logger.log(Level.WARNING, message, e);
    }
}

From source file:edu.kit.dama.rest.client.DataManagerPropertiesHelper.java

/**
 * Test access to webDAV server./*from  www  .ja v  a 2  s . c  om*/
 * <b>Attention:<b><br/>
 * This method should only chosen if the credentials are not fixed. The chosen
 * authentication is slow but allows you to test several credentials.
 *
 * @param pAuthenticationClass Class used for authentication.
 * @return success
 */
private boolean genericWebDavAccess(String pAuthenticationClass) {
    boolean returnValue = false;
    StagingServiceRESTClient ssrc = new StagingServiceRESTClient(restServerUrl + REST_STAGING_PATH, context);
    try {
        StagingAccessPointConfigurationWrapper allAccessPoints = ssrc
                .getAllAccessPoints(properties.getAccessPoint(), properties.getUserGroup(), context);
        String webDavUrl = ssrc.getAccessPointById(allAccessPoints.getEntities().get(0).getId(), context)
                .getEntities().get(0).getRemoteBaseUrl();
        // Method to overwrite the Webdav configuration class with a custom configuration class
        for (String protocol : new String[] { "http", "https" }) {
            Configuration configuration = ProtocolSettings.getSingleton().getConfiguration(protocol);
            configuration.setProperty("authClass", pAuthenticationClass);
            Iterator iter = configuration.getKeys();
            while (iter.hasNext()) {
                String key = (String) iter.next();
                String value = configuration.getString(key);
                configuration.clearProperty(key);
                configuration.addProperty(protocol + "." + key, value);
            }
            ProtocolSettings.getSingleton().overwriteConfiguration(configuration);
        }
        LOGGER.debug(
                "Overwriting the default configuration with the specific configuration of generic ingest client.");
        AbstractFile af = new AbstractFile(new URL(webDavUrl + "/USERS"));
        af.list();
        AbstractFile createDirectory = af.createDirectory(UUID.randomUUID().toString());
        if (createDirectory.exists()) {
            createDirectory.delete();
            returnValue = true;
        }
    } catch (MalformedURLException | AdalapiException e) {
        LOGGER.error(invalidWebDavSettings, e);
    }
    return returnValue;

}

From source file:com.w20e.socrates.process.RunnerFactoryImpl.java

/**
 * Create a context for the given id./*from  ww w. jav  a  2s  . c om*/
 * 
 * @param url
 *            runner config id
 * @throws UnsupportedMediumException
 *             in case the medium isn't supported.
 */
public RunnerContextImpl createContext(final URI url, final Map<String, String> options)
        throws UnsupportedMediumException {

    try {

        Configuration cfg = ConfigurationResource.getInstance().getConfiguration(url.toURL());

        if (cfg == null) {
            return null;
        }

        URI modelId = new URI((String) cfg.getProperty("model.id"));

        LOGGER.fine("Creating model for " + modelId);
        Model model = ModelResource.getInstance().getModel(modelId, cfg);

        LOGGER.finer("Done. Now creating instance");
        Instance inst = ModelResource.getInstance().createInstance(modelId, cfg);

        RenderConfig rCfg = ModelResource.getInstance().getRenderConfig(modelId, cfg);

        LOGGER.finer("Created. Let's create a new context");
        RunnerContextImpl ctx = new RunnerContextImpl(null, getFormatter(url, cfg, options),
                createStateManager(cfg, rCfg, model, inst), model, inst, rCfg);

        // Allow arbitrary properties to be set on the context.
        String key;

        for (final Iterator<?> i = cfg.getKeys(); i.hasNext();) {

            key = (String) i.next();

            if (key.startsWith("context")) {

                ctx.setProperty(key, cfg.getProperty(key));
            }
        }

        return ctx;

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Couldn't create context", e);
        throw new UnsupportedMediumException(e.getMessage());
    }
}

From source file:ffx.potential.parsers.ForceFieldFilter.java

private void parse(CompositeConfiguration properties) {
    try {//  w  w  w.  ja  v a  2  s .c  om
        int numConfigs = properties.getNumberOfConfigurations();
        /**
         * Loop over the configurations starting with lowest precedence.
         * This way higher precedence entries will overwrite lower
         * precedence entries within the ForceField instance.
         */
        for (int n = numConfigs - 1; n >= 0; n--) {
            Configuration config = properties.getConfiguration(n);
            Iterator i = config.getKeys();
            while (i.hasNext()) {
                String key = (String) i.next();

                /**
                 * If the key is not recognized as a force field keyword,
                 * continue to the next key.
                 */
                if (!ForceField.isForceFieldKeyword(key)) {
                    continue;
                }

                String list[] = config.getStringArray(key);
                for (String s : list) {
                    // Add back the key to the input line.
                    s = key + " " + s;

                    // Split the line on the pound symbol to remove comments.
                    String input = s.split("#+")[0];
                    String tokens[] = input.trim().split(" +");

                    // Parse keywords.
                    if (parseKeyword(tokens)) {
                        continue;
                    }

                    // Parse force field types.
                    ForceFieldType type;
                    try {
                        type = ForceFieldType.valueOf(key.toUpperCase());
                    } catch (Exception e) {
                        break;
                    }

                    switch (type) {
                    case ATOM:
                        parseAtom(input, tokens);
                        break;
                    case ANGLE:
                        parseAngle(input, tokens);
                        break;
                    case BIOTYPE:
                        parseBioType(input, tokens);
                        break;
                    case BOND:
                        parseBond(input, tokens);
                        break;
                    case CHARGE:
                        parseCharge(input, tokens);
                        break;
                    case MULTIPOLE:
                        parseMultipole(input, tokens);
                        break;
                    case OPBEND:
                        parseOPBend(input, tokens);
                        break;
                    case STRBND:
                        parseStrBnd(input, tokens);
                        break;
                    case PITORS:
                        parsePiTorsion(input, tokens);
                        break;
                    case IMPTORS:
                        parseImproper(input, tokens);
                        break;
                    case TORSION:
                        parseTorsion(input, tokens);
                        break;
                    case TORTORS:
                        parseTorsionTorsion(input, tokens);
                        break;
                    case UREYBRAD:
                        parseUreyBradley(input, tokens);
                        break;
                    case VDW:
                        parseVDW(input, tokens);
                        break;
                    case POLARIZE:
                        parsePolarize(input, tokens);
                        break;
                    case ISOLVRAD:
                        parseISolvRad(input, tokens);
                        break;
                    case RELATIVESOLV:
                        parseRelativeSolvation(input, tokens);
                        break;
                    default:
                        logger.log(Level.WARNING, "ForceField type recognized, but not stored:{0}", type);
                    }
                }
            }
        }
        forceField.checkPolarizationTypes();
    } catch (Exception e) {
        String message = "Exception parsing force field.";
        logger.log(Level.WARNING, message, e);
    }
}

From source file:edu.jhuapl.tinkerpop.AccumuloGraphConfiguration.java

/**
 * Instantiate based on a configuration 
 * @param config/*www.j av a 2  s . c  o m*/
 */
public AccumuloGraphConfiguration(Configuration config) {
    this();
    Iterator<String> keys = config.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        conf.setProperty(key.replace("..", "."), config.getProperty(key));
    }
}