Example usage for java.util Properties propertyNames

List of usage examples for java.util Properties propertyNames

Introduction

In this page you can find the example usage for java.util Properties propertyNames.

Prototype

public Enumeration<?> propertyNames() 

Source Link

Document

Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

Usage

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantDataManager.java

/**
 * There can be sensitive information like passwords in configuration file. If they are encrypted using secure
 * vault, this method will resolve them and replace with original values.
 *//*from  ww w . j av a2 s.  c o  m*/
private static void resolveSecrets(Properties properties) {

    SecretResolver secretResolver = SecretResolverFactory.create(properties);
    Enumeration propertyNames = properties.propertyNames();
    if (secretResolver != null && secretResolver.isInitialized()) {
        // Iterate through whole config file and find encrypted properties and resolve them
        while (propertyNames.hasMoreElements()) {
            String key = (String) propertyNames.nextElement();
            if (secretResolver.isTokenProtected(key)) {
                if (log.isDebugEnabled()) {
                    log.debug("Resolving and replacing secret for " + key);
                }
                // Resolving the secret password.
                String value = secretResolver.resolve(key);
                // Replaces the original encrypted property with resolved property
                properties.put(key, value);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No encryption done for value with key :" + key);
                }
            }
        }
    } else {
        log.warn("Secret Resolver is not present. Will not resolve encryptions in " + CONFIG_RELATIVE_PATH
                + " file");
    }
}

From source file:org.rdv.ConfigurationManager.java

/**
 * Inspect if the given DataPanel is detached from the DataPanelContainer
 * @param dataPanel to check//from  w  ww.  jav  a  2 s . c o  m
 * @param properties properties for the DataPanel
 * @return flag indicating detached
 */
private static boolean isPanelDetached(DataPanel dataPanel, Properties properties) {
    if (properties.size() == 0) {
        return false;
    }

    String key, value;
    for (Enumeration<?> keys = properties.propertyNames(); keys.hasMoreElements();) {
        key = (String) keys.nextElement();
        if (key == "attached") {
            value = properties.getProperty(key);
            if (value == "false")
                return true;
        }
    }

    return false;
}

From source file:com.dell.asm.asmcore.asmmanager.snmp.utils.SNMPTrapFrameworkUtils.java

/**
 * Creates the SNMP trap handler.//  w  w  w.java  2s. co  m
 * 
 * @return ISNMPTrapHandler
 * 
 * @throws SNMPTrapListenerException
 * 
 */
public static ISNMPTrapHandler createSNMPTrapHandler() throws SNMPTrapListenerException {

    ISNMPTrapHandler handler = null;
    SNMPTrapHandlerSpec handlerSpec = new SNMPTrapHandlerSpec();
    handlerSpec.setBrokerInstanceName(QMManager.DEFAULT_INSTANCE_NAME);
    handlerSpec.setDestinationName(SNMPTrapListnerConstants.DEST_NAME);
    handlerSpec.setDestinationType(DestinationType.TOPIC);

    try {
        // Load the properties file
        URL propFileURL = SNMPTrapFrameworkUtils.class.getClassLoader()
                .getResource(SNMPTrapConstants.SNMPTRAP_CONSTANT_PROPERTIES_FILE);

        // Read the properties file
        Properties props = getPropertiesFromFile(propFileURL);

        // Enumerate the properties
        Enumeration e = props.propertyNames();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = props.getProperty(key);
            String[] values = value.split(",");

            /**
             * Specific Trap Id - Every SNMP Trap has a specific id.
             */
            int genericTrapId = Integer.parseInt(values[0]);
            /**
             * Generic Trap Id - Every SNMP Trap has a generic id. This is generally constant for all the traps from a certain org.
             */
            int specificTrapId = Integer.parseInt(values[1]);
            /**
             * Enterprise Trap Id - Every SNMP Trap has an enterprise trap id. An enterprise id generally identifies all the traps from an
             * organization uniquely.
             */
            String enterpriseTrapId = values[2];

            logger.info(key + " = " + genericTrapId + "," + specificTrapId + "," + enterpriseTrapId);
            // Returns the value for OIds
            lookup.put(enterpriseTrapId, key);

            SNMPTrapDefinition def = new SNMPTrapDefinition();
            SNMPTrap trap = new SNMPTrap();
            trap.setGenericTrapId(genericTrapId);
            trap.setSpecificTrapId(specificTrapId);
            trap.setEnterpriseTrapId(enterpriseTrapId.trim());
            def.setFormatString("Message");
            def.setSnmpTrap(trap);
            def.setTrapDefinitionId("1");
            handlerSpec.getSupportedTraps().add(def);
        }

        handler = new SNMPTrapHandler(handlerSpec);

        logger.info("SNMP trap handler created successfully.");
    } catch (SecurityException e) {
        throw new SNMPTrapListenerException("Unable to create the SNMP trap handler. " + e.getMessage());
    } catch (IOException e) {
        throw new SNMPTrapListenerException("Unable to create the SNMP trap handler. " + e.getMessage());
    }
    return handler;
}

From source file:com.hazelcast.cli.CLI.java

private static void addHosts(Set<HostSettings> hosts) throws Exception {
    HashMap<String, String> hashMap = new HashMap();
    Set<String> set = new HashSet();
    Properties prop = new Properties();

    logger.info("Properties file is reading");
    InputStream is = CLI.class.getClassLoader().getResourceAsStream("cli.properties");
    prop.load(is);//from   ww  w . jav  a2  s  . c  o  m
    Enumeration it = prop.propertyNames();

    while (it.hasMoreElements()) {
        logger.trace("Properties file has more elements");
        String token = (String) it.nextElement();
        String key = token.split("\\.")[0];
        String value = token.split("\\.")[1];
        hashMap.put(token, prop.getProperty(token));
        set.add(key);
    }

    for (String key : set) {
        logger.trace("Key is reading from Properties File");
        String userName = hashMap.get(key + ".user");
        String hostIp = hashMap.get(key + ".ip");
        String remotePath = hashMap.get(key + ".remotePath");
        String identityPath = hashMap.get(key + ".identityPath");
        HostSettings host = new HostSettings(key, userName, hostIp, remotePath, identityPath);

        System.out.println("Connection settings set for " + host.userName + "@" + host.hostIp);
        String message = SshExecutor.exec(host.userName, host.hostIp, 22, "", false, host.identityPath, false);
        if ((message == null) || (!message.equals("exception"))) {
            logger.trace("Message is null or not exception");
            System.out.println("Host " + host.hostName + " is added.");
            hosts.add(host);
        } else {
            logger.trace("Could not connect to the hosts");
            System.out.println("Could not connect to the hosts.");
            System.out.println("Please try to add a hosts again.");
        }
    }

}

From source file:PropertiesHelper.java

/**
 * Adds new properties to an existing set of properties while
 * substituting variables. This function will allow value
 * substitutions based on other property values. Value substitutions
 * may not be nested. A value substitution will be ${property.key},
 * where the dollar-brace and close-brace are being stripped before
 * looking up the value to replace it with. Note that the ${..}
 * combination must be escaped from the shell.
 *
 * @param a is the initial set of known properties (besides System ones)
 * @param b is the set of properties to add to a
 * @return the combined set of properties from a and b.
 *///  w ww.j  a v  a2 s  .  c o  m
protected static Properties addProperties(Properties a, Properties b) {
    // initial
    Properties result = new Properties(a);
    Properties sys = System.getProperties();
    Pattern pattern = Pattern.compile("\\$\\{[-a-zA-Z0-9._]+\\}");

    for (Enumeration e = b.propertyNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        String value = b.getProperty(key);

        // unparse value ${prop.key} inside braces
        Matcher matcher = pattern.matcher(value);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            // extract name of properties from braces
            String newKey = value.substring(matcher.start() + 2, matcher.end() - 1);

            // try to find a matching value in result properties
            String newVal = result.getProperty(newKey);

            // if still not found, try system properties
            if (newVal == null) {
                newVal = sys.getProperty(newKey);
            }

            // replace braced string with the actual value or empty string
            matcher.appendReplacement(sb, newVal == null ? "" : newVal);
        }
        matcher.appendTail(sb);
        result.setProperty(key, sb.toString());
    }
    // final
    return result;
}

From source file:org.wso2.carbon.identity.event.EventManagementUtils.java

/**
 * Returns a set of properties which has keys starting with the given prefix
 *
 * @param prefix     prefix of the property key
 * @param properties Set of properties which needs be filtered for the given prefix
 * @return A set of properties which has keys starting with given prefix
 *//*from  w w  w.java 2 s .c  o m*/
public static Properties getPropertiesWithPrefix(String prefix, Properties properties) {

    if (StringUtils.isEmpty(prefix) || properties == null) {
        throw new IllegalArgumentException(
                "Prefix and properties should not be null to extract properties with " + "certain prefix");
    }

    Properties subProperties = new Properties();
    Enumeration propertyNames = properties.propertyNames();

    while (propertyNames.hasMoreElements()) {
        String key = (String) propertyNames.nextElement();
        if (key.startsWith(prefix)) {
            // Remove from original properties to hold property schema. ie need to get the set of properties which
            // remains after consuming all required specific properties
            subProperties.setProperty(key, (String) properties.remove(key));
        }
    }
    return subProperties;
}

From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java

/**
 * Sign a JAD file outputting the modified JAD to a different file.
 *
 * @param jadFile/*from   w  w w.jav  a  2  s .  com*/
 *            JAD file
 * @param outputJadFile
 *            Output JAD file
 * @param jarFile
 *            JAR file
 * @param privateKey
 *            Private RSA key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param certificateNumber
 *            Certificate number
 * @throws IOException
 *             If an I/O problem occurs while signing the MIDlet
 * @throws CryptoException
 *             If a crypto problem occurs while signing the MIDlet
 */
public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey,
        X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException {
    Properties jadProperties = readJadFile(jadFile);

    Properties newJadProperties = new Properties();

    // Copy over existing attrs (excepting digest and any certificates at
    // provided number)
    for (Enumeration enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) {
        String propName = (String) enumPropNames.nextElement();

        // Ignore digest attr
        if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) {
            continue;
        }

        // Ignore certificates at provided number
        if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) {
            continue;
        }

        newJadProperties.put(propName, jadProperties.getProperty(propName));
    }

    // Get certificate attrs
    for (int i = 0; i < certificateChain.length; i++) {
        X509Certificate certificate = certificateChain[i];
        String base64Cert = null;
        try {
            base64Cert = new String(Base64.encode(certificate.getEncoded()));
        } catch (CertificateEncodingException ex) {
            throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex);
        }

        String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber,
                (i + 1));
        newJadProperties.put(midletCertificateAttr, base64Cert);
    }

    // Get signed Base 64 SHA-1 digest of JAR file as attr
    byte[] signedJarDigest = signJarDigest(jarFile, privateKey);
    String base64SignedJarDigest = new String(Base64.encode(signedJarDigest));
    newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest);

    // Sort properties alphabetically
    TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>();

    for (Enumeration names = newJadProperties.propertyNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        String value = newJadProperties.getProperty(name);

        sortedJadProperties.put(name, value);
    }

    // Write out new JAD properties to JAD file
    FileWriter fw = null;

    try {
        fw = new FileWriter(outputJadFile);

        for (Iterator itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted.hasNext();) {
            Map.Entry property = (Map.Entry) itrSorted.next();

            fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue()));
            fw.write(CRLF);
        }
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:org.apache.struts.scripting.ScriptAction.java

/**
 *  Loads and initializes the filters./*from  w  w  w.ja  va  2 s .c om*/
 *
 *@param  props  The properties defining the filters
 *@return        An array of the loaded filters
 */
protected static BSFManagerFilter[] loadFilters(Properties props) {
    ArrayList list = new ArrayList();
    for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
        String prop = (String) e.nextElement();
        if (prop.startsWith(FILTERS_BASE) && prop.endsWith("class")) {
            String type = prop.substring(FILTERS_BASE.length(), prop.indexOf(".", FILTERS_BASE.length()));
            String claz = props.getProperty(prop);
            try {
                Class cls = Class.forName(claz);
                BSFManagerFilter f = (BSFManagerFilter) cls.newInstance();
                f.init(type, props);
                list.add(f);
                if (LOG.isInfoEnabled()) {
                    LOG.info("Loaded " + type + " filter: " + claz);
                }
            } catch (Exception ex) {
                LOG.error("Unable to load " + type + " filter: " + claz);
            }
        }
    }
    BSFManagerFilter[] filters = new BSFManagerFilter[list.size()];
    filters = (BSFManagerFilter[]) list.toArray(filters);
    return filters;
}

From source file:org.kse.crypto.signing.MidletSigner.java

/**
 * Sign a JAD file outputting the modified JAD to a different file.
 *
 * @param jadFile/*from  w  ww  .j  av  a2s. c o m*/
 *            JAD file
 * @param outputJadFile
 *            Output JAD file
 * @param jarFile
 *            JAR file
 * @param privateKey
 *            Private RSA key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param certificateNumber
 *            Certificate number
 * @throws IOException
 *             If an I/O problem occurs while signing the MIDlet
 * @throws CryptoException
 *             If a crypto problem occurs while signing the MIDlet
 */
public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey,
        X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException {
    Properties jadProperties = readJadFile(jadFile);

    Properties newJadProperties = new Properties();

    // Copy over existing attrs (excepting digest and any certificates at
    // provided number)
    for (Enumeration<?> enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) {
        String propName = (String) enumPropNames.nextElement();

        // Ignore digest attr
        if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) {
            continue;
        }

        // Ignore certificates at provided number
        if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) {
            continue;
        }

        newJadProperties.put(propName, jadProperties.getProperty(propName));
    }

    // Get certificate attrs
    for (int i = 0; i < certificateChain.length; i++) {
        X509Certificate certificate = certificateChain[i];
        String base64Cert = null;
        try {
            base64Cert = new String(Base64.encode(certificate.getEncoded()));
        } catch (CertificateEncodingException ex) {
            throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex);
        }

        String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber,
                (i + 1));
        newJadProperties.put(midletCertificateAttr, base64Cert);
    }

    // Get signed Base 64 SHA-1 digest of JAR file as attr
    byte[] signedJarDigest = signJarDigest(jarFile, privateKey);
    String base64SignedJarDigest = new String(Base64.encode(signedJarDigest));
    newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest);

    // Sort properties alphabetically
    TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>();

    for (Enumeration<?> names = newJadProperties.propertyNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        String value = newJadProperties.getProperty(name);

        sortedJadProperties.put(name, value);
    }

    // Write out new JAD properties to JAD file
    FileWriter fw = null;

    try {
        fw = new FileWriter(outputJadFile);

        for (Iterator<Entry<String, String>> itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted
                .hasNext();) {
            Entry<String, String> property = itrSorted.next();

            fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue()));
            fw.write(CRLF);
        }
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:org.nuxeo.theme.editor.Utils.java

public static List<FieldProperty> getPropertiesOf(final Element element) {
    List<FieldProperty> fieldProperties = new ArrayList<FieldProperty>();
    if (element == null) {
        return fieldProperties;
    }/*  w  w  w.j  a  v a 2 s  . com*/
    Properties properties = new Properties();
    try {
        properties = FieldIO.dumpFieldsToProperties(element);
    } catch (ThemeIOException e) {
        log.error("Failed to obtain properties of element: " + element.computeXPath(), e);
        return fieldProperties;
    }
    if (properties == null) {
        return fieldProperties;
    }
    Class<? extends Element> c = element.getClass();
    Enumeration<?> names = properties.propertyNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        String value = properties.getProperty(name);
        FieldInfo fieldInfo = FieldIO.getFieldInfo(c, name);
        if (fieldInfo == null) {
            continue;
        }
        fieldProperties.add(new FieldProperty(name, value.trim(), fieldInfo));
    }
    return fieldProperties;
}