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:net.sf.zekr.common.config.ApplicationConfig.java

@SuppressWarnings("unchecked")
private void initSearchInfo() {
    try {/*from   w  ww. java 2  s .  co m*/
        logger.info("Load search info...");

        File usi = new File(ApplicationPath.USER_SEARCH_INFO);
        if (!usi.exists()) {
            logger.info("User search info does not exist at " + ApplicationPath.USER_SEARCH_INFO);
            logger.info(
                    "Will make user search info with default values at " + ApplicationPath.MAIN_SEARCH_INFO);
            String searchInfoFile = ApplicationPath.MAIN_SEARCH_INFO;
            try {
                logger.info("Save user search info file to " + ApplicationPath.USER_CONFIG);
                FileUtils.copyFile(new File(searchInfoFile), usi);

                logger.debug("Load " + searchInfoFile);
                FileInputStream fis = new FileInputStream(searchInfoFile);
                searchProps = ConfigUtils.loadConfig(fis, "UTF-8");
            } catch (Exception e) {
                logger.error("Error loading search info file " + searchInfoFile);
                logger.implicitLog(e);
            }
        } else {
            String searchInfoFile = ApplicationPath.USER_SEARCH_INFO;
            try {
                String ver = null;
                boolean error = false;
                try {
                    FileInputStream fis = new FileInputStream(searchInfoFile);
                    searchProps = ConfigUtils.loadConfig(fis, "UTF-8", ApplicationPath.CONFIG_DIR);
                    ver = searchProps.getString("search.version");
                } catch (Exception e) {
                    logger.error(String.format(
                            "Error loading user search info file %s."
                                    + " Will replace it with original search info file %s.",
                            searchInfoFile, ApplicationPath.MAIN_SEARCH_INFO), e);
                    error = true;
                }
                if (!GlobalConfig.ZEKR_VERSION.equals(ver) || error) {
                    searchInfoFile = ApplicationPath.USER_CONFIG;
                    searchProps = ConfigUtils.loadConfig(new FileInputStream(searchInfoFile), "UTF-8");
                    String newName = String.format("%s_%s", res.getString("config.searchInfo.file"),
                            String.format(ver == null ? "old" : ver));
                    logger.info(String.format(
                            "Migrate search info from version %s to %s. Will rename old file to %s.", ver,
                            GlobalConfig.ZEKR_VERSION, newName));
                    FileUtils.copyFile(usi, new File(usi.getParent(), newName));
                    FileUtils.copyFile(new File(ApplicationPath.MAIN_SEARCH_INFO), usi);
                }
            } catch (Exception e) {
                logger.error("Error loading search info file " + searchInfoFile);
                logger.implicitLog(e);
            }
        }

        searchInfo = new SearchInfo();
        Configuration stopWordConf = searchProps.subset("search.stopword");
        List<String> defaultStopWord = searchProps.getList("search.stopword");
        Configuration replacePatternConf = searchProps.subset("search.pattern.replace");
        List<String> defaultReplacePattern = searchProps.getList("search.pattern.replace");
        Configuration punctuationConf = searchProps.subset("search.pattern.punct");
        String defaultPunctuation = searchProps.getString("search.pattern.punct");
        Configuration diacriticsConf = searchProps.subset("search.pattern.diacr");
        String defaultDiacritics = searchProps.getString("search.pattern.diacr");
        Configuration letterConf = searchProps.subset("search.pattern.letter");

        searchInfo.setDefaultStopWord(defaultStopWord);
        for (Iterator<String> iterator = stopWordConf.getKeys(); iterator.hasNext();) {
            String langCode = iterator.next();
            if (langCode.length() <= 0) {
                continue;
            }
            logger.debug("\tAdd stop words for: " + langCode);
            searchInfo.addStopWord(langCode, stopWordConf.getList(langCode));
        }

        searchInfo.setDefaultReplacePattern(defaultReplacePattern);
        for (Iterator<String> iterator = replacePatternConf.getKeys(); iterator.hasNext();) {
            String langCode = iterator.next();
            if (langCode.length() <= 0) {
                continue;
            }
            logger.debug("\tAdd replace patterns for: " + langCode);
            searchInfo.addReplacePattern(langCode, replacePatternConf.getList(langCode));
        }

        if (defaultPunctuation != null) {
            searchInfo.setDefaultPunctuation(Pattern.compile(defaultPunctuation));
        }
        for (Iterator<String> iterator = punctuationConf.getKeys(); iterator.hasNext();) {
            String langCode = iterator.next();
            if (langCode.length() <= 0) {
                continue;
            }
            logger.debug("\tAdd punctuation pattern for: " + langCode);
            searchInfo.setPunctuation(langCode, Pattern.compile(punctuationConf.getString(langCode)));
        }

        if (defaultDiacritics != null) {
            searchInfo.setDefaultDiacritic(Pattern.compile(defaultDiacritics));
        }
        for (Iterator<String> iterator = diacriticsConf.getKeys(); iterator.hasNext();) {
            String langCode = iterator.next();
            if (langCode.length() <= 0) {
                continue;
            }
            logger.debug("\tAdd diacritics pattern for: " + langCode);
            searchInfo.setDiacritic(langCode, Pattern.compile(diacriticsConf.getString(langCode)));
        }

        for (Iterator<String> iterator = letterConf.getKeys(); iterator.hasNext();) {
            String langCode = iterator.next();
            if (langCode.length() <= 0) {
                continue;
            }
            logger.debug("\tAdd letters range pattern for: " + langCode);
            searchInfo.setLetter(langCode, Pattern.compile(letterConf.getString(langCode)));
        }
    } catch (Exception ex) {
        logger.error("Search info not initialized correctly because of the next error."
                + " Zekr, however, will be launched.");
        logger.implicitLog(ex);
    }
}

From source file:nl.tudelft.graphalytics.domain.NestedConfiguration.java

/**
 * Parses an external configuration and wraps its keys and values in a NestedConfiguration object.
 *
 * @param configuration the external configuration to read
 * @param sourceName    the name to give this "source" of properties
 * @return the parsed NestedConfiguration
 */// ww w .j av a 2s  .c o  m
public static NestedConfiguration fromExternalConfiguration(Configuration configuration, String sourceName) {
    Map<String, String> properties = new HashMap<>();
    for (Iterator<String> propertyKeys = configuration.getKeys(); propertyKeys.hasNext();) {
        String propertyKey = propertyKeys.next();
        properties.put(propertyKey, configuration.getString(propertyKey));
    }
    return new NestedConfiguration(properties, sourceName, null);
}

From source file:org.acmsl.queryj.ConfigurationQueryJCommandImpl.java

/**
 * Retrieves all keys.//w  w w  .  j  av a  2s . c om
 * @param configuration the {@link Configuration}.
 * @return such keys.
 */
@NotNull
protected Iterable<String> getKeys(@NotNull final Configuration configuration) {
    return new Iterable<String>() {
        /**
         * {@inheritDoc}
         */
        @Override
        public Iterator<String> iterator() {
            return configuration.getKeys();
        }
    };
}

From source file:org.acmsl.queryj.ConfigurationQueryJCommandImpl.java

/**
 * Returns a JSON representation of given {@link Configuration}.
 * @param conf the instance to represent.
 * @return the JSON string.//from   www  .  j av  a2  s  .co  m
 */
@SuppressWarnings("unused")
@NotNull
protected String confToString(@NotNull final Configuration conf) {
    @NotNull
    final StringBuilder result = new StringBuilder();

    @NotNull
    final Iterator<String> t_itKey = conf.getKeys();

    while (t_itKey.hasNext()) {
        @NotNull
        final String t_strKey = t_itKey.next();
        result.append(", \"");
        result.append(t_strKey);
        result.append("\": \"");
        result.append(conf.getProperty(t_strKey));
        result.append('"');
    }

    return result.toString();
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

/**
 * Returns a string with information about many of the ambra.* properties
 * in a Configuration.  Intended to be informational-only, not exhaustive.
 *///from   w  w  w  .j ava  2  s  . c  o m
private String dumpConfig(Configuration config) {
    StringBuilder result = new StringBuilder();
    Iterator iter = config.getKeys();
    while (iter.hasNext()) {
        String key = (String) iter.next();

        // Don't display the virtual journal stuff; it's long and not particularly useful.
        if (key.startsWith("ambra.") && !key.startsWith("ambra.virtualJournals.")) {
            Object value = config.getProperty(key);

            // Attempt to dereference other properties referred to by "${foo}" notation.
            if (value instanceof String) {
                String valueStr = (String) value;
                if (valueStr.startsWith("${")) {
                    String refKey = valueStr.substring(2, valueStr.length() - 1);
                    Object refValue = config.getProperty(refKey);
                    if (refValue != null) {
                        value = String.format("%s -> %s", valueStr, refValue);
                    }
                }
            }
            result.append(key).append(": ").append(value).append('\n');
        }
    }
    return result.toString();
}

From source file:org.apache.accumulo.core.client.impl.ClientContext.java

/**
 * A utility method for converting client configuration to a standard configuration object for use internally.
 *
 * @param config//w w  w.  j  a v a  2  s  .  c om
 *          the original {@link ClientConfiguration}
 * @return the client configuration presented in the form of an {@link AccumuloConfiguration}
 */
public static AccumuloConfiguration convertClientConfig(final Configuration config) {

    final AccumuloConfiguration defaults = DefaultConfiguration.getInstance();

    return new AccumuloConfiguration() {
        @Override
        public String get(Property property) {
            final String key = property.getKey();

            // Attempt to load sensitive properties from a CredentialProvider, if configured
            if (property.isSensitive()) {
                org.apache.hadoop.conf.Configuration hadoopConf = getHadoopConfiguration();
                if (null != hadoopConf) {
                    try {
                        char[] value = CredentialProviderFactoryShim.getValueFromCredentialProvider(hadoopConf,
                                key);
                        if (null != value) {
                            log.trace("Loaded sensitive value for {} from CredentialProvider", key);
                            return new String(value);
                        } else {
                            log.trace(
                                    "Tried to load sensitive value for {} from CredentialProvider, but none was found",
                                    key);
                        }
                    } catch (IOException e) {
                        log.warn(
                                "Failed to extract sensitive property ({}) from Hadoop CredentialProvider, falling back to base AccumuloConfiguration",
                                key, e);
                    }
                }
            }

            if (config.containsKey(key))
                return config.getString(key);
            else {
                // Reconstitute the server kerberos property from the client config
                if (Property.GENERAL_KERBEROS_PRINCIPAL == property) {
                    if (config.containsKey(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey())) {
                        // Avoid providing a realm since we don't know what it is...
                        return config.getString(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey()) + "/_HOST@"
                                + SaslConnectionParams.getDefaultRealm();
                    }
                }
                return defaults.get(property);
            }
        }

        @Override
        public void getProperties(Map<String, String> props, Predicate<String> filter) {
            defaults.getProperties(props, filter);

            Iterator<?> keyIter = config.getKeys();
            while (keyIter.hasNext()) {
                String key = keyIter.next().toString();
                if (filter.test(key))
                    props.put(key, config.getString(key));
            }

            // Two client props that don't exist on the server config. Client doesn't need to know about the Kerberos instance from the principle, but servers do
            // Automatically reconstruct the server property when converting a client config.
            if (props.containsKey(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey())) {
                final String serverPrimary = props.remove(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey());
                if (filter.test(Property.GENERAL_KERBEROS_PRINCIPAL.getKey())) {
                    // Use the _HOST expansion. It should be unnecessary in "client land".
                    props.put(Property.GENERAL_KERBEROS_PRINCIPAL.getKey(),
                            serverPrimary + "/_HOST@" + SaslConnectionParams.getDefaultRealm());
                }
            }

            // Attempt to load sensitive properties from a CredentialProvider, if configured
            org.apache.hadoop.conf.Configuration hadoopConf = getHadoopConfiguration();
            if (null != hadoopConf) {
                try {
                    for (String key : CredentialProviderFactoryShim.getKeys(hadoopConf)) {
                        if (!Property.isValidPropertyKey(key) || !Property.isSensitive(key)) {
                            continue;
                        }

                        if (filter.test(key)) {
                            char[] value = CredentialProviderFactoryShim
                                    .getValueFromCredentialProvider(hadoopConf, key);
                            if (null != value) {
                                props.put(key, new String(value));
                            }
                        }
                    }
                } catch (IOException e) {
                    log.warn(
                            "Failed to extract sensitive properties from Hadoop CredentialProvider, falling back to accumulo-site.xml",
                            e);
                }
            }
        }

        private org.apache.hadoop.conf.Configuration getHadoopConfiguration() {
            String credProviderPaths = config
                    .getString(Property.GENERAL_SECURITY_CREDENTIAL_PROVIDER_PATHS.getKey());
            if (null != credProviderPaths && !credProviderPaths.isEmpty()) {
                org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration();
                hadoopConf.set(CredentialProviderFactoryShim.CREDENTIAL_PROVIDER_PATH, credProviderPaths);
                return hadoopConf;
            }

            log.trace("Did not find credential provider configuration in ClientConfiguration");

            return null;
        }
    };

}

From source file:org.apache.accumulo.core.client.impl.ServerConfigurationUtil.java

public static AccumuloConfiguration convertClientConfig(final AccumuloConfiguration base,
        final Configuration config) {

    return new AccumuloConfiguration() {
        @Override/*  w w w. j  av a 2 s  .c  o  m*/
        public String get(Property property) {
            if (config.containsKey(property.getKey()))
                return config.getString(property.getKey());
            else
                return base.get(property);
        }

        @Override
        public void getProperties(Map<String, String> props, PropertyFilter filter) {

            base.getProperties(props, filter);

            @SuppressWarnings("unchecked")
            Iterator<String> keyIter = config.getKeys();
            while (keyIter.hasNext()) {
                String key = keyIter.next();
                if (filter.accept(key))
                    props.put(key, config.getString(key));
            }
        }
    };

}

From source file:org.apache.atlas.ApplicationProperties.java

private static void logConfiguration(Configuration configuration) {
    if (LOG.isDebugEnabled()) {
        Iterator<String> keys = configuration.getKeys();
        LOG.debug("Configuration loaded:");
        while (keys.hasNext()) {
            String key = keys.next();
            LOG.debug("{} = {}", key, configuration.getProperty(key));
        }//from  w w  w  .ja  v a 2s.  c  om
    }
}

From source file:org.apache.atlas.repository.audit.HBaseBasedAuditRepository.java

/**
 * Converts atlas' application properties to hadoop conf
 * @return/*from  w w  w.ja  v  a 2s.com*/
 * @throws AtlasException
 * @param atlasConf
 */
public static org.apache.hadoop.conf.Configuration getHBaseConfiguration(Configuration atlasConf)
        throws AtlasException {
    Configuration subsetAtlasConf = ApplicationProperties.getSubsetConfiguration(atlasConf, CONFIG_PREFIX);
    org.apache.hadoop.conf.Configuration hbaseConf = HBaseConfiguration.create();
    Iterator<String> keys = subsetAtlasConf.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        hbaseConf.set(key, subsetAtlasConf.getString(key));
    }
    return hbaseConf;
}

From source file:org.apache.bookkeeper.common.conf.ComponentConfiguration.java

protected void loadConf(Configuration loadedConf) {
    loadedConf.getKeys().forEachRemaining(fullKey -> {
        if (fullKey.startsWith(componentPrefix)) {
            String componentKey = fullKey.substring(componentPrefix.length());
            setProperty(componentKey, loadedConf.getProperty(fullKey));
        }/*from   w  w w.  j ava2  s. com*/
    });
}