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.apache.servicemix.platform.testing.support.SmxPlatform.java

/**
 * Loads Felix config.properties.//from w w w. j a  v  a  2  s .com
 *
 * <strong>Note</strong> the current implementation uses Felix's Main class
 * to resolve placeholders as opposed to loading the properties manually
 * (through JDK's Properties class or Spring's PropertiesFactoryBean).
 *
 * @return
 */
// TODO: this method should be removed once Felix 1.0.2 is released
private Properties getFelixConfiguration() {
    String location = "/".concat(ClassUtils.classPackageAsResourcePath(getClass())).concat("/")
            .concat(FELIX_CONF_FILE);
    URL url = getClass().getResource(location);
    if (url == null)
        throw new RuntimeException("cannot find felix configuration properties file:" + location);

    // used with Main
    System.getProperties().setProperty(FELIX_CONFIG_PROPERTY, url.toExternalForm());

    // load config.properties (use Felix's Main for resolving placeholders)
    Properties props = new Properties();
    InputStream is = null;
    try {
        is = url.openConnection().getInputStream();
        props.load(is);
        is.close();
    } catch (FileNotFoundException ex) {
        // Ignore file not found.
    } catch (Exception ex) {
        System.err.println("Main: Error loading system properties from " + url);
        System.err.println("Main: " + ex);
        try {
            if (is != null)
                is.close();
        } catch (IOException ex2) {
            // Nothing we can do.
        }
        return null;
    }
    // Perform variable substitution for system properties.
    for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        props.setProperty(name, substVars(props.getProperty(name), name, null, props));
    }
    return props;
}

From source file:org.dspace.installer_edm.InstallerEDMBase.java

/**
 * carga de dspace.cfg los elementos dc que estn controlados como autoridades, i.e., tienen la propiedad authority.controlled
 *//*from  ww w .  j  av  a2s  .  c  om*/
protected void loadAuthDspaceCfg() {
    elementsAuthDspaceCfg = new HashSet<String>();
    Properties properties = new Properties();
    InputStream is = null;
    try {
        String name = ConfigurationManager.getProperty("dspace.dir") + "/config/dspace.cfg";
        File file = new File(name);
        if (file.exists() && file.canRead()) {
            is = file.toURI().toURL().openStream();
            properties.load(is);
            for (Enumeration pe = properties.propertyNames(); pe.hasMoreElements();) {
                String key = (String) pe.nextElement();
                if (key.startsWith("authority.controlled.")) {
                    String field = key.substring("authority.controlled.".length());
                    int dot = field.indexOf(46);
                    if (dot < 0)
                        continue;
                    String schema = field.substring(0, dot);
                    String element = field.substring(dot + 1);
                    String qualifier = null;
                    dot = element.indexOf(46);
                    if (dot >= 0) {
                        qualifier = element.substring(dot + 1);
                        element = element.substring(0, dot);
                    }
                    StringBuilder fkeySB = new StringBuilder(element);
                    if (qualifier != null)
                        fkeySB.append(".").append(qualifier);
                    String fkey = fkeySB.toString();
                    if (ConfigurationManager.getBooleanProperty(key, true))
                        elementsAuthDspaceCfg.add(fkey);
                }
            }
        }
    } catch (IOException e) {
        showException(e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                showException(e);
            }
        }
    }
}

From source file:org.apache.stratos.rest.endpoint.util.converter.ObjectConverter.java

private static List<org.apache.stratos.common.beans.PropertyBean> convertJavaUtilPropertiesToPropertyBeans(
        java.util.Properties properties) {

    List<org.apache.stratos.common.beans.PropertyBean> propertyBeans = null;
    if (properties != null && !properties.isEmpty()) {
        Enumeration<?> e = properties.propertyNames();
        propertyBeans = new ArrayList<org.apache.stratos.common.beans.PropertyBean>();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = properties.getProperty(key);
            org.apache.stratos.common.beans.PropertyBean propertyBean = new org.apache.stratos.common.beans.PropertyBean();
            propertyBean.setName(key);/*from ww w .  j av  a2s.  c  o  m*/
            propertyBean.setValue(value);
            propertyBeans.add(propertyBean);
        }
    }
    return propertyBeans;
}

From source file:shelper.ifmock.HttpMock.java

/**
 * Override this to customize the server.<p>
 *
 * (By default, this delegates to serveFile() and allows directory listing.)
 *
 * @param uri   Percent-decoded URI without parameters, for example "/index.cgi"
 * @param method   "GET", "POST" etc.//from   w ww  . ja v a2 s .c om
 * @param parms   Parsed, percent decoded parameters from URI and, in case of POST, data.
 * @param header   Header entries, percent decoded
 * @return HTTP response, see class Response for details
 */
public Response serve(String uri, String method, Properties header, Properties parms, String rawbodystr,
        Properties files) {
    System.out.println(method + " '" + uri + "' ");
    System.out.println("rawbody is :" + rawbodystr);
    Enumeration e = header.propertyNames();
    while (e.hasMoreElements()) {
        String value = (String) e.nextElement();
        System.out.println("  HDR: '" + value + "' = '" + header.getProperty(value) + "'");
    }
    e = parms.propertyNames();
    while (e.hasMoreElements()) {
        String value = (String) e.nextElement();
        System.out.println("  PRM: '" + value + "' = '" + parms.getProperty(value) + "'");
    }
    e = files.propertyNames();
    while (e.hasMoreElements()) {
        String value = (String) e.nextElement();
        System.out.println("  UPLOADED: '" + value + "' = '" + files.getProperty(value) + "'");
    }

    return serveFile(uri, header, myRootDir, true);
}

From source file:com.wallabystreet.kinjo.common.transport.ws.ServiceDescriptor.java

/**
 * Loads the configuration of the described service, assuming that the file
 * is stored in the service package's folder with the file name
 * <i>properties.xml</i>. It is expected that the file corresponds to the
 * <a href="http://java.sun.com/dtd/properties.dtd">Java Property File DTD<a/>.
 * //from   w  w w.ja  v  a 2  s  . co m
 * @return The configuration of this service as a
 *         <code>java.util.Properties</code> instance.
 * @throws MalformedServiceException,
 *             IIF the property file is missing or invalid.
 * 
 * @see java.util.Properties
 */
private Properties loadProperties() throws MalformedServiceException {
    // constant for the property file name
    final String PROPERTIES_FILENAME = "properties.xml";

    Properties p = new Properties();
    try {
        p.loadFromXML(
                ClassLoader.getSystemResourceAsStream(this.pkg.replace('.', '/') + "/" + PROPERTIES_FILENAME));

        /*
         * due to the stoopid implementation of
         * Properties#loadFromXML(InputStream), leading and trailing
         * whitespace of values is preserved; we have to fix this to prevent
         * ClassLoader#getSystemResource(String) and
         * ClassLoader#getSystemResourceAsStream(String) from wreckage.
         */
        Enumeration e = p.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object o = p.getProperty(key);
            if (o instanceof String) {
                String value = (String) o;
                p.setProperty(key, value.trim());
            }
        }

        /* return the demoronized result */
        return p;
    } catch (InvalidPropertiesFormatException e) {
        String msg = "invalid configuration file: " + this.pkg.replace('.', '/') + "/" + PROPERTIES_FILENAME;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    } catch (IOException e) {
        String msg = "could not open configuration file: " + this.pkg.replace('.', '/') + "/"
                + PROPERTIES_FILENAME;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    }
}

From source file:org.apache.directory.fortress.core.ldap.LdapDataProvider.java

/**
 * Given a collection of {@link java.util.Properties}, convert to raw data name-value format and load into ldap modification set in preparation for ldap add.
 *
 * @param props    contains {@link java.util.Properties} targeted for adding to ldap.
 * @param entry    contains ldap entry to push attrs into.
 * @param attrName contains the name of the ldap attribute to be added.
 * @param separator contains the char value used to separate name and value in ldap raw format.
 * @throws LdapException If we weren't able to add the properies into the entry
 *///from   ww w .  jav  a 2 s  .c  o m
protected void loadProperties(Properties props, Entry entry, String attrName, char separator)
        throws LdapException {
    if ((props != null) && (props.size() > 0)) {
        Attribute attr = null;

        for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
            // This LDAP attr is stored as a name-value pair separated by a ':'.
            String key = (String) e.nextElement();
            String val = props.getProperty(key);
            String prop = key + separator + val;

            if (attr == null) {
                attr = new DefaultAttribute(attrName);
            } else {
                attr.add(prop);
            }
        }

        if (attr != null) {
            entry.add(attr);
        }
    }
}

From source file:org.apereo.portal.security.InitialSecurityContextFactory.java

/**
 * This method parses the {@link Properties} file to find the configuration
 * for the specified context. The factory is loaded and the configuration is
 * named then the {@link Properties} are parsed to find all context configuration
 * properties and sub-contexts for this context. For each sub-context this method
 * is called recursively.//from  w  w  w  .  ja va  2s.c om
 * 
 * @param fullContextName The fully qualified name of the context to configure.
 * @param securtiyProperties The {@link Properties} to use for configuration.
 * @return A fully configured {@link ContextConfiguration} object.
 * @throws PortalSecurityException If no context with the specified named exists or the factory cannot be created.
 */
private static ContextConfiguration loadContextConfigurationChain(final String fullContextName,
        final Properties securtiyProperties) throws PortalSecurityException {
    //Load the context factory name
    final String factoryName = securtiyProperties.getProperty(fullContextName);
    if (factoryName == null) {
        final PortalSecurityException ep = new PortalSecurityException(
                "No such security context " + fullContextName);
        log.error(ep.getMessage(), ep);
        throw (ep);
    }

    //The contextConfig this method will return
    final ContextConfiguration contextConfig = new ContextConfiguration();

    final int lastDotIndex = fullContextName.lastIndexOf(".");
    String localContextName = fullContextName;
    if (lastDotIndex >= 0) {
        try {
            localContextName = fullContextName.substring(lastDotIndex + 1);
        } catch (IndexOutOfBoundsException ioobe) {
            final PortalSecurityException pse = new PortalSecurityException(
                    "Invalid context name " + fullContextName, ioobe);
            log.error(pse.getMessage(), pse);
            throw pse;
        }
    }

    //Create the context factory
    try {
        final ISecurityContextFactory factory = (ISecurityContextFactory) Class.forName(factoryName)
                .newInstance();
        contextConfig.contextFactory = factory;
        contextConfig.contextName = localContextName;
    } catch (Exception e) {
        final PortalSecurityException ep = new PortalSecurityException("Failed to instantiate " + factoryName);
        log.error("Failed to instantiate " + factoryName, e);
        throw (ep);
    }

    //Just move this string concatination out of the loop to save cycles
    final String contextConfigPropertyPrefix = CONTEXT_PROPERTY_PREFIX + "." + fullContextName;

    //Read sub context names & properties for this context
    final Collection subContexts = new Vector();
    for (final Enumeration ctxnames = securtiyProperties.propertyNames(); ctxnames.hasMoreElements();) {
        final String securityPropName = (String) ctxnames.nextElement();

        if (securityPropName.startsWith(fullContextName) && securityPropName.length() > fullContextName.length()
                && securityPropName.indexOf(".", fullContextName.length() + 1) < 0) {

            //call getContextConfiguration(name) on each
            final ContextConfiguration subContextConfig = loadContextConfigurationChain(securityPropName,
                    securtiyProperties);
            //add context to list for this context
            subContexts.add(subContextConfig);
        }
        //Context configuration properties as securityContextProperty. entries
        // Format is:
        //  securityContextProperty.<SecurityContextName>.<PropertyName>
        //  <PropertyName> cannot contain .
        else if (securityPropName.startsWith(contextConfigPropertyPrefix)
                && securityPropName.length() > contextConfigPropertyPrefix.length()
                && securityPropName.indexOf(".", contextConfigPropertyPrefix.length() + 1) < 0) {

            final String propValue = securtiyProperties.getProperty(securityPropName);
            final String propName = securityPropName.substring(contextConfigPropertyPrefix.length() + 1);

            contextConfig.contextProperties.setProperty(propName, propValue);
        }
    }

    //Set the sub contexts into this context
    contextConfig.subConfigs = (ContextConfiguration[]) subContexts
            .toArray(new ContextConfiguration[subContexts.size()]);

    return contextConfig;
}

From source file:org.apache.easyant.core.EasyAntMain.java

/**
 * Start Ant//  ww w.  ja v a2  s.  c  om
 *
 * @param args                     command line args
 * @param additionalUserProperties properties to set beyond those that may be specified on the args list
 * @param coreLoader               - not used
 * @since Ant 1.6
 */
public void startAnt(String[] args, Properties additionalUserProperties, ClassLoader coreLoader) {
    easyAntConfiguration.setCoreLoader(coreLoader);
    configureOptions();
    CommandLineParser parser = new GnuParser();
    CommandLine line;
    try {
        line = parser.parse(options, args);
        processArgs(line);
    } catch (ParseException exc) {
        if (easyAntConfiguration.getMsgOutputLevel() >= Project.MSG_VERBOSE) {
            exc.printStackTrace();
        }
        handleLogfile();
        printMessage(exc);
        exit(1);
        return;
    }

    if (additionalUserProperties != null) {
        Enumeration<?> properties = additionalUserProperties.propertyNames();
        while (properties.hasMoreElements()) {
            String key = (String) properties.nextElement();
            String property = additionalUserProperties.getProperty(key);
            easyAntConfiguration.getDefinedProps().put(key, property);
        }
    }

    // expect the worst
    int exitCode = 1;
    try {
        try {
            runBuild(line);
            exitCode = 0;
        } catch (ExitStatusException ese) {
            exitCode = ese.getStatus();
            if (exitCode != 0) {
                throw ese;
            }
        }
    } catch (BuildException be) {
        // do nothing they have been already logged by our logger
    } catch (Throwable exc) {
        exc.printStackTrace();
        printMessage(exc);
    } finally {
        handleLogfile();
    }
    exit(exitCode);
}

From source file:fr.cmoatoto.multishare.receiver.NanoHTTPDReceiver.java

/**
 * Override this to customize the server.
 * <p>/*from   w ww  .j a v a 2 s  .  c  o  m*/
 * 
 * (By default, this delegates to serveFile() and allows directory listing.)
 * 
 * @param uri
 *            Percent-decoded URI without parameters, for example "/index.cgi"
 * @param method
 *            "GET", "POST" etc.
 * @param parms
 *            Parsed, percent decoded parameters from URI and, in case of POST, data.
 * @param header
 *            Header entries, percent decoded
 * @param inetAddress
 * @return HTTP response, see class Response for details
 */
public Response serve(String uri, String method, Properties header, Properties parms, Properties files,
        InetAddress inetAddress) {
    myOut.println(method + " '" + uri + "' " + inetAddress.toString());

    Enumeration e = header.propertyNames();
    String element = null;
    myOut.println("URI: " + uri);
    String value = null;
    String mimeType = null;
    String extension = null;

    while (e.hasMoreElements()) {
        element = (String) e.nextElement();
        myOut.println("  HDR: '" + element + "' = '" + header.getProperty(element) + "'");
    }
    e = parms.propertyNames();
    while (e.hasMoreElements()) {
        element = (String) e.nextElement();

        myOut.println("  PRM: '" + element + "' = '" + parms.getProperty(element) + "'");
        if (element.equals("value")) {
            value = parms.getProperty(element);
            if (value.contains("http://remote_host:")) {
                value = value.replace("/remote_host", inetAddress.toString());
                myOut.println("  PRM REPLACED BY: '" + element + "' = '" + value + "'");
            }
        } else if (element.equals("mime")) {
            mimeType = parms.getProperty(element);
        } else if (element.equals("extension")) {
            extension = parms.getProperty(element);
        }

        if (value != null && mimeType != null) {
            if ("keyboard/key".equals(mimeType)) {
                try {
                    RemotedKeyboard.sendKeyEvent(mContext, Integer.parseInt(value));
                } catch (NumberFormatException e2) {
                    myOut.println(Log.getStackTraceString(e2));
                }
            } else {
                HttpServiceReceiver.show(mContext, value, mimeType, extension);
            }
        }
    }
    e = files.propertyNames();
    while (e.hasMoreElements()) {
        element = (String) e.nextElement();
        myOut.println("  UPLOADED: '" + value + "' = '" + files.getProperty(value) + "'");
    }

    final StringBuilder buf = new StringBuilder();
    for (Entry<Object, Object> kv : header.entrySet())
        buf.append(kv.getKey() + " : " + kv.getValue() + "\n");

    return new NanoHTTPDReceiver.Response(HTTP_OK, mimeType, uri);
}

From source file:org.apache.stratos.messaging.broker.publish.TopicPublisher.java

private void doPublish(String message, Properties headers) throws Exception, JMSException {
    if (!initialized) {
        // Initialize a topic connection to the message broker
        connector.init(getName());//from ww  w .  j  a v a  2 s.  c  om
        initialized = true;
        if (log.isDebugEnabled()) {
            log.debug(String.format("Topic publisher connector initialized: [topic] %s", getName()));
        }
    }

    try {
        // Create a new session
        topicSession = createSession(connector);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Topic publisher session created: [topic] %s", getName()));
        }
        // Create a publisher from session
        topicPublisher = createPublisher(topicSession);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Topic publisher created: [topic] %s", getName()));
        }

        // Create text message
        TextMessage textMessage = topicSession.createTextMessage(message);

        if (headers != null) {
            // Add header properties
            @SuppressWarnings("rawtypes")
            Enumeration e = headers.propertyNames();

            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                textMessage.setStringProperty(key, headers.getProperty(key));
            }
        }

        topicPublisher.publish(textMessage);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Message published: [topic] %s [header] %s [body] %s", getName(),
                    (headers != null) ? headers.toString() : "null", message));
        }
    } finally {
        if (topicPublisher != null) {
            topicPublisher.close();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Topic publisher closed: [topic] %s", getName()));
            }
        }
        if (topicSession != null) {
            topicSession.close();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Topic publisher session closed: [topic] %s", getName()));
            }
        }
    }
}