Example usage for java.util Properties keySet

List of usage examples for java.util Properties keySet

Introduction

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

Prototype

@Override
    public Set<Object> keySet() 

Source Link

Usage

From source file:org.opennms.core.test.MockLogAppender.java

/**
 * <p>setupLogging</p>/*from  ww w . java  2 s.c o  m*/
 *
 * @param toConsole a boolean.
 * @param level a {@link java.lang.String} object.
 * @param config a {@link java.util.Properties} object.
 */
public static void setupLogging(final boolean toConsole, String level, final Properties config) {
    s_defaultLevel = level;
    resetLogLevel();
    resetEvents();

    setProperty(MockLogger.DEFAULT_LOG_LEVEL_KEY, level);
    setProperty(MockLogger.LOG_KEY_PREFIX + "com.mchange", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "com.mchange.v2", "WARN");
    setProperty(MockLogger.LOG_KEY_PREFIX + "httpclient", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.apache.aries.blueprint.container", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.apache.bsf", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.apache.http", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.apache.commons.httpclient.HttpMethodBase", "ERROR");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.exolab.castor", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.gwtwidgets", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.hibernate", "INFO");
    // One of these is probably unused...
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.hibernate.sql", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.hibernate.SQL", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.hibernate.cfg.AnnotationBinder", "ERROR");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.hibernate.cfg.annotations.EntityBinder", "ERROR");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.quartz", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.snmp4j", "ERROR");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.snmp4j.agent", "ERROR");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.springframework", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.springframework.beans.factory.support", "WARN");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.springframework.context.support", "WARN");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.springframework.jdbc.datasource", "WARN");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.springframework.test.context.support", "WARN");
    setProperty(MockLogger.LOG_KEY_PREFIX + "org.springframework.security", "INFO");
    setProperty(MockLogger.LOG_KEY_PREFIX + "com.mchange.v2", "WARN");
    setProperty(MockLogger.LOG_KEY_PREFIX + "snaq.db", "INFO");

    for (final Object oKey : config.keySet()) {
        final String key = ((String) oKey).replaceAll("^log4j.logger.", MockLogger.LOG_KEY_PREFIX);
        setProperty(key, config.getProperty((String) oKey));
    }
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }/*  w  ww . ja va 2  s.  co  m*/
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

From source file:org.opencastproject.capture.impl.CaptureAgentImpl.java

/**
 * {@inheritDoc}//from   ww w.jav a2 s.  c o m
 * 
 * @see org.opencastproject.capture.api.CaptureAgent#getDefaultAgentPropertiesAsString()
 */
@Deprecated
public String getDefaultAgentPropertiesAsString() {
    Properties p = configService.getAllProperties();
    StringBuffer result = new StringBuffer();
    String[] lines = new String[p.size()];
    int i = 0;
    for (Object k : p.keySet()) {
        String key = (String) k;
        lines[i++] = key + "=" + p.getProperty(key) + "\n";
    }
    Arrays.sort(lines);
    for (String s : lines) {
        result.append(s);
    }

    return result.toString();
}

From source file:org.apache.struts.util.PropertyMessageResources.java

/**
 * Load the messages associated with the specified Locale key.  For this
 * implementation, the <code>config</code> property should contain a fully
 * qualified package and resource name, separated by periods, of a series
 * of property resources to be loaded from the class loader that created
 * this PropertyMessageResources instance.  This is exactly the same name
 * format you would use when utilizing the <code>java.util.PropertyResourceBundle</code>
 * class./*from  w  ww.ja v a  2 s .c  o m*/
 *
 * @param localeKey Locale key for the messages to be retrieved
 */
protected synchronized void loadLocale(String localeKey) {
    if (log.isTraceEnabled()) {
        log.trace("loadLocale(" + localeKey + ")");
    }

    // Have we already attempted to load messages for this locale?
    if (locales.get(localeKey) != null) {
        return;
    }

    locales.put(localeKey, localeKey);

    // Set up to load the property resource for this locale key, if we can
    String name = config.replace('.', '/');

    if (localeKey.length() > 0) {
        name += ("_" + localeKey);
    }

    name += ".properties";

    InputStream is = null;
    Properties props = new Properties();

    // Load the specified property resource
    if (log.isTraceEnabled()) {
        log.trace("  Loading resource '" + name + "'");
    }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    if (classLoader == null) {
        classLoader = this.getClass().getClassLoader();
    }

    is = classLoader.getResourceAsStream(name);

    if (is != null) {
        try {
            props.load(is);
        } catch (IOException e) {
            log.error("loadLocale()", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("loadLocale()", e);
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("  Loading resource completed");
        }
    } else {
        if (log.isWarnEnabled()) {
            log.warn("  Resource " + name + " Not Found.");
        }
    }

    // Copy the corresponding values into our cache
    if (props.size() < 1) {
        return;
    }

    synchronized (messages) {
        Iterator names = props.keySet().iterator();

        while (names.hasNext()) {
            String key = (String) names.next();

            if (log.isTraceEnabled()) {
                log.trace("  Saving message key '" + messageKey(localeKey, key));
            }

            messages.put(messageKey(localeKey, key), props.getProperty(key));
        }
    }
}

From source file:br.edu.ufcg.lsd.commune.context.PropertiesFileParser.java

public Map<Object, Object> parseContext() {
    Properties properties = new Properties();

    /** Get an abstraction for the properties file */
    File propertiesFile = new File(fileName);

    if (!propertiesFile.exists()) {
        return getDefaultProperties(propertiesFile);
    }//ww w. j  av  a 2s. co m

    /* load the properties file, if it exists */
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(propertiesFile);
    } catch (FileNotFoundException e) {
        throw new CommuneRuntimeException("Context couldn't be loaded. " + fileName
                + " does not exist. Please check this file. Exception: " + e.getMessage());
    }
    try {
        properties.load(fileInputStream);
    } catch (IOException e) {
        throw new CommuneRuntimeException("Context couldn't be loaded. " + fileName
                + " is corrupted. Please check this file. Exception: " + e.getMessage());
    } catch (IllegalArgumentException iae) {
        throw new CommuneRuntimeException("Context couldn't be loaded. " + fileName
                + " isn't a properties file. Please use correct file format.");
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            throw new CommuneRuntimeException("Context couldn't be loaded. " + fileName
                    + " is corrupeed. Please check this file. Exception: " + e.getMessage());
        }
    }

    Map<Object, Object> responseMap = new LinkedHashMap<Object, Object>();

    for (Object key : properties.keySet()) {
        if (!properties.get(key).toString().trim().equals("")) {
            responseMap.put(key, properties.get(key));
        }
    }

    return responseMap;
}

From source file:com.quinsoft.zeidon.jmx.JmxObjectEngineMonitor.java

@Override
public Properties getRuntimeProperties() {
    Properties properties = new Properties();

    // Add activate information.
    for (String key : eventInfo.keySet()) {
        EventInfo info = eventInfo.get(key);
        synchronized (info) // To keep other threads from changing times and counts.
        {//  w  w w . java 2s. co  m
            if (info.activates > 0) {
                properties.put(String.format("%s activates", key), info.activates);
                double average = info.totalActivateTime / 1000.0 / info.activates;
                properties.put(String.format("%s activate average", key), String.format("%1.4f", average));
                if (info.activateErrors > 0)
                    properties.put(String.format("%s activate errors", key), info.activateErrors);
            }

            if (info.commits > 0) {
                properties.put(String.format("%s commits\n", key), info.commits);
                double average = info.totalCommitTime / 1000.0 / info.commits;
                properties.put(String.format("%s commit average", key), String.format("%1.4f", average));
                if (info.commitErrors > 0)
                    properties.put(String.format("%s commit errors", key), info.commitErrors);
            }
        }
    }

    ZeidonLogger logger = oe.getSystemTask().log();
    for (Object key : properties.keySet()) {
        Object value = properties.get(key);
        logger.info("%s %s", key, value);
    }

    return properties;
}

From source file:org.apache.archiva.metadata.repository.file.FileMetadataRepository.java

@Override
public void removeArtifact(String repoId, String namespace, String project, String version, String id)
        throws MetadataRepositoryException {
    try {/*from   w w  w  .  j  a va  2  s.c  o m*/
        File directory = new File(getDirectory(repoId), namespace + "/" + project + "/" + version);

        Properties properties = readOrCreateProperties(directory, PROJECT_VERSION_METADATA_KEY);

        properties.remove("artifact:updated:" + id);
        properties.remove("artifact:whenGathered:" + id);
        properties.remove("artifact:size:" + id);
        properties.remove("artifact:md5:" + id);
        properties.remove("artifact:sha1:" + id);
        properties.remove("artifact:version:" + id);
        properties.remove("artifact:facetIds:" + id);

        String prefix = "artifact:facet:" + id + ":";
        for (Object key : new ArrayList(properties.keySet())) {
            String property = (String) key;
            if (property.startsWith(prefix)) {
                properties.remove(property);
            }
        }

        FileUtils.deleteDirectory(directory);
        //writeProperties( properties, directory, PROJECT_VERSION_METADATA_KEY );
    } catch (IOException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java

@Override
public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
    result.addParam("mailMessage subject", mailMessage.getSubject());

    SystemConfigurationType systemConfiguration = NotificationsUtil
            .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null
            || systemConfiguration.getNotificationConfiguration().getMail() == null) {
        String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);//from   w w  w  .  j  a  va  2  s  . c  o  m
        result.recordWarning(msg);
        return;
    }

    MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
    String redirectToFile = mailConfigurationType.getRedirectToFile();
    if (redirectToFile != null) {
        try {
            TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
            result.recordSuccess();
        } catch (IOException e) {
            LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
            result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
        }
        return;
    }

    if (mailConfigurationType.getServer().isEmpty()) {
        String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    long start = System.currentTimeMillis();

    String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom()
            : "nobody@nowhere.org";

    for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {

        OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
        final String host = mailServerConfigurationType.getHost();
        resultForServer.addContext("server", host);
        resultForServer.addContext("port", mailServerConfigurationType.getPort());

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        if (mailServerConfigurationType.getPort() != null) {
            properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
        }
        MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType
                .getTransportSecurity();

        boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
        switch (mailTransportSecurityType) {
        case STARTTLS_ENABLED:
            starttlsEnable = true;
            break;
        case STARTTLS_REQUIRED:
            starttlsEnable = true;
            starttlsRequired = true;
            break;
        case SSL:
            sslEnabled = true;
            break;
        }
        properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
        properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
        properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
        if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
            properties.put("mail.debug", "true");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Using mail properties: ");
            for (Object key : properties.keySet()) {
                if (key instanceof String && ((String) key).startsWith("mail.")) {
                    LOGGER.debug(" - " + key + " = " + properties.get(key));
                }
            }
        }

        task.recordState("Sending notification mail via " + host);

        Session session = Session.getInstance(properties);

        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
            String contentType = mailMessage.getContentType();
            if (StringUtils.isEmpty(contentType)) {
                contentType = "text/plain; charset=UTF-8";
            }
            mimeMessage.setContent(mailMessage.getBody(), contentType);
            javax.mail.Transport t = session.getTransport("smtp");
            if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                String password = null;
                if (passwordProtected != null) {
                    try {
                        password = protector.decryptString(passwordProtected);
                    } catch (EncryptionException e) {
                        String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host
                                + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                        LoggingUtils.logException(LOGGER, msg, e);
                        resultForServer.recordFatalError(msg, e);
                        continue;
                    }
                }
                t.connect(mailServerConfigurationType.getUsername(), password);
            } else {
                t.connect();
            }
            t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
            resultForServer.recordSuccess();
            result.recordSuccess();
            long duration = System.currentTimeMillis() - start;
            task.recordState(
                    "Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
            task.recordNotificationOperation(NAME, true, duration);
            return;
        } catch (MessagingException e) {
            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host
                    + ", trying another mail server, if there is any";
            LoggingUtils.logException(LOGGER, msg, e);
            resultForServer.recordFatalError(msg, e);
            task.recordState("Error sending notification mail via " + host);
        }
    }
    LOGGER.warn(
            "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
    result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}

From source file:io.fabric8.maven.plugin.AbstractDeployMojo.java

/**
 * Before applying the given template lets allow template parameters to be overridden via the maven
 * properties - or optionally - via the command line if in interactive mode.
 *//* w  ww. j a  v a  2 s.c om*/
protected void overrideTemplateParameters(Template template) {
    List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters();
    MavenProject project = getProject();
    if (parameters != null && project != null) {
        Properties properties = getProjectAndFabric8Properties(project);
        boolean missingProperty = false;
        for (io.fabric8.openshift.api.model.Parameter parameter : parameters) {
            String parameterName = parameter.getName();
            String name = "fabric8.apply." + parameterName;
            String propertyValue = properties.getProperty(name);
            if (propertyValue != null) {
                getLog().info("Overriding template parameter " + name + " with value: " + propertyValue);
                parameter.setValue(propertyValue);
            } else {
                missingProperty = true;
                getLog().info("No property defined for template parameter: " + name);
            }
        }
        if (missingProperty) {
            getLog().debug("Current properties " + new TreeSet<>(properties.keySet()));
        }
    }
}

From source file:edu.ku.brc.specify.utilapps.RegisterApp.java

/**
 * @param entries//  ww  w  .j ava  2 s.com
 * @return
 */
private Vector<String> getKeyWordsList(final Collection<RegProcEntry> entries) {
    Properties props = new Properties();
    Hashtable<String, Boolean> statKeywords = new Hashtable<String, Boolean>();
    for (RegProcEntry entry : entries) {
        props.clear();
        props.putAll(entry.getProps());

        String os = props.getProperty("os_name");
        String ver = props.getProperty("os_version");
        props.put("platform", os + " " + ver);

        for (Object keywordObj : props.keySet()) {
            statKeywords.put(keywordObj.toString(), true);
        }
    }

    String[] trackKeys = rp.getTrackKeys();

    for (String keyword : new Vector<String>(statKeywords.keySet())) {
        if (keyword.startsWith("Usage") || keyword.startsWith("num_") || keyword.endsWith("_portal")
                || keyword.endsWith("_number") || keyword.endsWith("_website") || keyword.endsWith("id")
                || keyword.endsWith("os_name") || keyword.endsWith("os_version")) {
            statKeywords.remove(keyword);

        } else {
            for (String key : trackKeys) {
                if (keyword.startsWith(key)) {
                    statKeywords.remove(keyword);
                }
            }
        }
    }

    statKeywords.remove("date");
    //statKeywords.remove("time");
    statKeywords.put("by_date", true);
    statKeywords.put("by_month", true);
    statKeywords.put("by_year", true);

    return new Vector<String>(statKeywords.keySet());
}