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

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

Introduction

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

Prototype

public Iterator getKeys() 

Source Link

Document

Returns an Iterator with the keys contained in this configuration.

Usage

From source file:org.apache.whirr.karaf.itest.integration.WhirrLiveTestSupport.java

public void loadConfiguration(String name, String pid) throws ConfigurationException, IOException {
    if (configurationAdmin == null) {
        String message = "No configuration admin available. Make sure you have "
                + "properly looked it up before invoking this method";
        System.err.println(message);
        throw new IllegalStateException(message);
    }//from  w w  w .  j  a va 2  s . c  o m

    PropertiesConfiguration properties = new PropertiesConfiguration(
            getClass().getClassLoader().getResource(name));
    Configuration configuration = configurationAdmin.getConfiguration(pid);

    Dictionary dictionary = configuration.getProperties();
    if (dictionary == null) {
        dictionary = new Properties();
    }

    Iterator iterator = properties.getKeys();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String value = properties.getString(key);
        dictionary.put(key, value);
    }
    configuration.update(dictionary);
}

From source file:org.apache.wookie.feature.FeatureLoader.java

/**
 * Loads features based on the properties configuration supplied
 * @param config//  ww  w  .ja va  2 s. c  om
 */
@SuppressWarnings("unchecked")
public static void loadFeatures(PropertiesConfiguration config) {
    IPersistenceManager persistenceManager = PersistenceManagerFactory.getPersistenceManager();
    persistenceManager.begin();

    // Remove existing features
    for (IServerFeature sf : persistenceManager.findAll(IServerFeature.class)) {
        persistenceManager.delete(sf);
    }

    // Add features in properties configuration
    Iterator i = config.getKeys();
    while (i.hasNext()) {
        String klass = (String) i.next();
        String name = config.getString(klass);
        _logger.info("*** klass=" + klass);
        _logger.info("*** name=" + name);
        try {
            IServerFeature sf = createFeature(name, klass);
            // Only install it if there isn't an existing
            // feature with the same name
            if (persistenceManager.findServerFeatureByName(name) == null) {
                persistenceManager.save(sf);
                _logger.info("Installed feature:" + name);
            } else {
                _logger.error("Error installing feature: " + name + " was already installed");
            }

        } catch (Exception e) {
            _logger.error("Error installing feature:" + e.getMessage());
        }
    }

    try {
        persistenceManager.commit();
    } catch (PersistenceCommitException pce) {
        throw new RuntimeException("Feature loading exception: " + pce, pce);
    }
    PersistenceManagerFactory.closePersistenceManager();
}

From source file:org.dataconservancy.packaging.tool.model.PropertiesConfigurationParametersBuilder.java

@Override
public PackageGenerationParameters buildParameters(InputStream inputStream) throws ParametersBuildException {
    PackageGenerationParameters parameters = new PackageGenerationParameters();
    PropertiesConfiguration props = new PropertiesConfiguration();
    try {/*  w w w. j a  va2s  . c o  m*/
        props.load(new InputStreamReader(inputStream));
    } catch (ConfigurationException e) {
        throw new ParametersBuildException(e);
    }

    Iterator<String> keys = props.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        parameters.addParam(key, Arrays.asList(props.getStringArray(key)));

    }
    return parameters;
}

From source file:org.dataconservancy.packaging.tool.model.PropertiesPreferenceListBuilder.java

/**
 * {@inheritDoc}/*from w w w  .j  av  a 2  s .  co  m*/
 *
 * <p>
 * This implementation expects a property's name to include two elements about a preference. These two elements are
 * to be separated by a dot ('.'). Element preceding the dot is the preference's name. Element following the dot is
 * the preference's valueType. No other dots are to be included in the properties name.
 * </p>
 * <p>
 * This implementation expects references to format-specific preferences files to be held in properties for
 * preferences whose name ends with {@code "-PGP-ref"}.
 * </p>
 * If any format-specific preferences files are detected, Attempts to load them will be made. {@code
 * PreferencesBuildException} is thrown if one these attempts fails.
 * @param is The input stream representing the preferences
 * @return Fully populated {@code PackageGenerationPreferences} object
 * @throws PreferencesBuildException if the preferences can not be loaded or read.
 */
@Override
public PackageGenerationPreferences buildPackageGenerationPreferences(InputStream is)
        throws PreferencesBuildException {
    PackageGenerationPreferences preferences = new PackageGenerationPreferences();
    PropertiesConfiguration props = new PropertiesConfiguration();
    try {
        props.load(new InputStreamReader(is));
    } catch (ConfigurationException e) {
        throw new PreferencesBuildException(e);
    }

    Iterator<String> keyIter = props.getKeys();
    while (keyIter.hasNext()) {
        String key = keyIter.next();
        String[] propertyKeyTokens = key.split("\\.");
        String parameterName = propertyKeyTokens[0];
        String parameterValueType = propertyKeyTokens[1];

        preferences.setPreference(
                new Preference(parameterName, parameterValueType, Arrays.asList(props.getStringArray(key))));
    }

    //Retrieves list of properties which hold references to format-specific preferences files.
    List<String> formatSpecificFileRefs = preferences.getReferencesToFormatSpecificPreferences();

    //If properties which hold references for format-specific preferences files exist,
    //Loop through these references and load the files' content into format-specific preferences.
    if (formatSpecificFileRefs != null && !formatSpecificFileRefs.isEmpty()) {
        Map<String, Preference> formatSpecificPrefsMap = new HashMap<>();
        String formatId = null;
        //Look up preferences
        for (String refKey : formatSpecificFileRefs) {
            //retrieve file's path and name from general preferences:
            String fileName = preferences.getPreference(refKey).getValues().get(0);
            //Create a file object from the provide fileName
            //TODO: should this be passed URI to a file instead of file path? How to load a file from anywhere
            //in the files system?
            File file = new File(fileName);

            props = new PropertiesConfiguration();

            try {
                props.load(new FileReader(file));
            } catch (ConfigurationException | FileNotFoundException e) {
                //TODO: Should builder just log this failure and move on? instead of throwing exception?
                throw new PreferencesBuildException(
                        "Attempt to load package generation preferences for a specific"
                                + "packaging format failed. " + e);
            }

            keyIter = props.getKeys();
            while (keyIter.hasNext()) {
                String key = keyIter.next();
                String[] propertyKeyTokens = key.split("\\.");
                String parameterName = propertyKeyTokens[0];
                String parameterValueType = propertyKeyTokens[1];

                formatSpecificPrefsMap.put(parameterName, new Preference(parameterName, parameterValueType,
                        Arrays.asList(props.getStringArray(key))));

                if (parameterName.equals("package-format")) {
                    formatId = formatSpecificPrefsMap.get(parameterName).getValues().get(0);
                }
            }
            if (formatId != null && !formatId.isEmpty()) {
                preferences.setPreferences(formatId, formatSpecificPrefsMap);
            }
        }
    } //else no further lookup will be performed.

    return preferences;
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Import namespace prefixes. This is kind of a quick hack. TODO: during the import, the prefixes
 * should be extracted using JAXB and stored in the NamespacesResource
 * //from   www  . j  a  v  a2s.co  m
 * @param rootPath the root path of the extracted CSAR
 */
private void importNamespacePrefixes(Path rootPath) {
    Path properties = rootPath.resolve(CSARExporter.PATH_TO_NAMESPACES_PROPERTIES);
    if (Files.exists(properties)) {
        PropertiesConfiguration pconf;
        try {
            pconf = new PropertiesConfiguration(properties.toFile());
        } catch (ConfigurationException e) {
            CSARImporter.logger.debug(e.getMessage(), e);
            return;
        }
        Iterator<String> namespaces = pconf.getKeys();
        while (namespaces.hasNext()) {
            boolean addToStorage = false;
            String namespace = namespaces.next();
            if (NamespacesResource.INSTANCE.getIsPrefixKnownForNamespace(namespace)) {
                String storedPrefix = NamespacesResource.getPrefix(namespace);
                // QUICK HACK to check whether the prefix is a generated one
                // We assume we know the internal generation routine
                Matcher m = CSARImporter.GENERATED_PREFIX_PATTERN.matcher(storedPrefix);
                if (m.matches()) {
                    // the stored prefix is a generated one
                    // replace it by the one stored in the exported properties
                    addToStorage = true;
                }
            } else {
                addToStorage = true;
            }
            if (addToStorage) {
                String prefix = pconf.getString(namespace);
                NamespacesResource.INSTANCE.addNamespace(namespace, prefix);
            }
        }
    }
}

From source file:org.janusgraph.core.JanusGraphFactory.java

/**
 * Load a properties file containing a JanusGraph graph configuration.
 * <p/>//from w w w  .  java 2  s  .c  o  m
 * <ol>
 * <li>Load the file contents into a {@link org.apache.commons.configuration.PropertiesConfiguration}</li>
 * <li>For each key that points to a configuration object that is either a directory
 * or local file, check
 * whether the associated value is a non-null, non-absolute path. If so,
 * then prepend the absolute path of the parent directory of the provided configuration {@code file}.
 * This has the effect of making non-absolute backend
 * paths relative to the config file's directory rather than the JVM's
 * working directory.
 * <li>Return the {@link ReadConfiguration} for the prepared configuration file</li>
 * </ol>
 * <p/>
 *
 * @param file A properties file to load
 * @return A configuration derived from {@code file}
 */
@SuppressWarnings("unchecked")
private static ReadConfiguration getLocalConfiguration(File file) {
    Preconditions.checkArgument(file != null && file.exists() && file.isFile() && file.canRead(),
            "Need to specify a readable configuration file, but was given: %s", file.toString());

    try {
        PropertiesConfiguration configuration = new PropertiesConfiguration(file);

        final File tmpParent = file.getParentFile();
        final File configParent;

        if (null == tmpParent) {
            /*
             * null usually means we were given a JanusGraph config file path
             * string like "foo.properties" that refers to the current
             * working directory of the process.
             */
            configParent = new File(System.getProperty("user.dir"));
        } else {
            configParent = tmpParent;
        }

        Preconditions.checkNotNull(configParent);
        Preconditions.checkArgument(configParent.isDirectory());

        // TODO this mangling logic is a relic from the hardcoded string days; it should be deleted and rewritten as a setting on ConfigOption
        final Pattern p = Pattern.compile("(" + Pattern.quote(STORAGE_NS.getName()) + "\\..*" + "("
                + Pattern.quote(STORAGE_DIRECTORY.getName()) + "|" + Pattern.quote(STORAGE_CONF_FILE.getName())
                + ")" + "|" + Pattern.quote(INDEX_NS.getName()) + "\\..*" + "("
                + Pattern.quote(INDEX_DIRECTORY.getName()) + "|" + Pattern.quote(INDEX_CONF_FILE.getName())
                + ")" + ")");

        final Iterator<String> keysToMangle = Iterators.filter(configuration.getKeys(),
                new Predicate<String>() {
                    @Override
                    public boolean apply(String key) {
                        if (null == key)
                            return false;
                        return p.matcher(key).matches();
                    }
                });

        while (keysToMangle.hasNext()) {
            String k = keysToMangle.next();
            Preconditions.checkNotNull(k);
            String s = configuration.getString(k);
            Preconditions.checkArgument(StringUtils.isNotBlank(s),
                    "Invalid Configuration: key %s has null empty value", k);
            configuration.setProperty(k, getAbsolutePath(configParent, s));
        }
        return new CommonsConfiguration(configuration);
    } catch (ConfigurationException e) {
        throw new IllegalArgumentException("Could not load configuration at: " + file, e);
    }
}

From source file:org.janusgraph.util.system.ConfigurationLint.java

public static Status validate(String filename) throws IOException {
    Properties p = new Properties();
    FileInputStream fis = new FileInputStream(filename);
    p.load(fis);/*from w w  w . ja va2 s .co m*/
    fis.close();

    final PropertiesConfiguration apc;
    try {
        apc = new PropertiesConfiguration(filename);
    } catch (ConfigurationException e) {
        throw new IOException(e);
    }

    //        new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS,
    //                , BasicConfiguration.Restriction.NONE);

    Iterator<String> iter = apc.getKeys();

    int totalKeys = 0;
    int keysVerified = 0;

    while (iter.hasNext()) {
        totalKeys++;
        String key = iter.next();
        String value = apc.getString(key);
        try {
            ConfigElement.PathIdentifier pid = ConfigElement.parse(GraphDatabaseConfiguration.ROOT_NS, key);
            // ConfigElement shouldn't return null; failure here probably relates to janusgraph-core, not the file
            Preconditions.checkState(null != pid);
            Preconditions.checkState(null != pid.element);
            if (!pid.element.isOption()) {
                log.warn("Config key {} is a namespace (only options can be keys)", key);
                continue;
            }
            final ConfigOption<?> opt;
            try {
                opt = (ConfigOption<?>) pid.element;
            } catch (RuntimeException re) {
                // This shouldn't happen given the preceding check, but catch it anyway
                log.warn("Config key {} maps to the element {}, but it could not be cast to an option", key,
                        pid.element, re);
                continue;
            }
            try {
                Object o = new CommonsConfiguration(apc).get(key, opt.getDatatype());
                opt.verify(o);
                keysVerified++;
            } catch (RuntimeException re) {
                log.warn("Config key {} is recognized, but its value {} could not be validated", key,
                        value /*, re*/);
                log.debug("Validation exception on {}={} follows", key, value, re);
            }
        } catch (RuntimeException re) {
            log.warn("Unknown config key {}", key);
        }
    }

    return new Status(totalKeys, totalKeys - keysVerified);
}

From source file:org.kontalk.util.Tr.java

public static void init() {
    // get language
    String lang = Locale.getDefault().getLanguage();
    if (lang.equals(DEFAULT_LANG)) {
        return;//  ww w. ja v  a2 s . co m
    }

    LOGGER.info("Setting language: " + lang);

    // load string keys file
    String path = Kontalk.RES_PATH + I18N_DIR + STRING_FILE + PROP_EXT;
    PropertiesConfiguration stringKeys;
    try {
        stringKeys = new PropertiesConfiguration(ClassLoader.getSystemResource(path));
    } catch (ConfigurationException ex) {
        LOGGER.log(Level.WARNING, "can't load string key file", ex);
        return;
    }

    // load translation file
    path = Kontalk.RES_PATH + I18N_DIR + STRING_FILE + "_" + lang + PROP_EXT;
    URL url = ClassLoader.getSystemResource(path);
    if (url == null) {
        LOGGER.info("can't find translation file: " + path);
        return;
    }
    PropertiesConfiguration tr = new PropertiesConfiguration();
    tr.setEncoding("UTF-8");
    try {
        tr.load(url);
    } catch (ConfigurationException ex) {
        LOGGER.log(Level.WARNING, "can't load translation file", ex);
        return;
    }

    TR_MAP = new HashMap<>();
    Iterator<String> it = tr.getKeys();
    while (it.hasNext()) {
        String k = it.next();
        if (!stringKeys.containsKey(k)) {
            LOGGER.warning("key in translation but not in key file: " + k);
            continue;
        }
        TR_MAP.put(stringKeys.getString(k), tr.getString(k));
    }
}

From source file:org.manalith.ircbot.plugin.missedmessage.MissedMessageRunner.java

public String addMsg(String sender, String receiver, String msg) {
    StringBuilder result = new StringBuilder();

    boolean savedMsg = false;
    int msglen = msg.length();

    try {//ww w. j a  va 2  s.c  om
        PropertiesConfiguration prop = new PropertiesConfiguration(
                getResourcePath() + MissedMessageRunner.filename);

        Iterator<String> userlist = prop.getKeys();
        if (userlist != null) {
            while (userlist.hasNext()) {
                String key = userlist.next();
                if (key.equals(receiver)) {
                    if (prop.getString(receiver).length() != 0) {
                        result.append(StringUtils.split(receiver, '.')[1]);
                        String str = prop.getString(receiver);

                        result.append("? ?   ( ");
                        int availableSpace = 3 - str.split("\\:\\:").length;
                        if (availableSpace != 0) {
                            if (msglen <= 150) {

                                prop.setProperty(receiver, str + "::" + "[:" + sender + "] " + msg);
                                result.append(availableSpace - 1);
                                result.append(" / 3 )");
                            } else {
                                result.delete(0, result.length());
                                result.append(" ? 150? .");
                            }
                        } else {
                            result.append(availableSpace);
                            result.append(" / 3 ) : ???    ");
                        }
                    } else // if key has no value
                    {
                        if (msglen <= 150) {
                            prop.setProperty(receiver, "[:" + sender + "] " + msg);
                            result.append(StringUtils.split(receiver, '.')[1]);
                            result.append("? ?   ( 2 / 3 )");
                        } else {
                            result.delete(0, result.length());
                            result.append(" ? 150? .");
                        }
                    }
                    savedMsg = true;
                    prop.save();
                    break;
                }
            }

            if (!savedMsg) {
                result.append(receiver.split("\\.")[1]
                        + "? ? ??     ?? .");
            }
        }
    } catch (ConfigurationException ce) {
        return ce.getMessage();
    }

    return result.toString();
}

From source file:org.manalith.ircbot.plugin.missedmessage.MissedMessageRunner.java

public boolean isMatchedNickinList(String newRecv) {
    boolean result = false;

    try {//from   ww  w. j a  va2 s . c om
        PropertiesConfiguration prop = new PropertiesConfiguration(
                getResourcePath() + MissedMessageRunner.filename);

        Iterator<String> userlist = prop.getKeys();
        if (userlist != null) {
            while (userlist.hasNext()) {
                String u = userlist.next();
                // if user found from userlist, just break this routine
                if (u.equals(newRecv)) {
                    result = true;
                    break;
                }
            }
        }
    } catch (ConfigurationException ce) {
        // Ignore.
    }

    return result;
}