Example usage for java.util Properties entrySet

List of usage examples for java.util Properties entrySet

Introduction

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

Prototype

@Override
    public Set<Map.Entry<Object, Object>> entrySet() 

Source Link

Usage

From source file:org.opencastproject.scheduler.remote.SchedulerServiceRemoteImpl.java

@Override
public void updateCaptureAgentMetadata(Properties configuration, Tuple<Long, DublinCoreCatalog>... events)
        throws NotFoundException, SchedulerException {
    logger.debug("Start updating {} events with following capture agent metadata: {}", events.length,
            configuration);//from   w  w  w.j  a v  a 2  s .c  o m
    for (Tuple<Long, DublinCoreCatalog> event : events) {
        final long eventId = event.getA();
        final DublinCoreCatalog eventCatalog = event.getB();

        logger.debug("Start updating event {} with capture agent metadata", eventId);

        String propertiesString = "";
        for (Entry<Object, Object> entry : configuration.entrySet())
            propertiesString += (String) entry.getKey() + "=" + (String) entry.getValue() + "\n";

        HttpPut put = new HttpPut("/" + eventId);

        try {
            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("dublincore", eventCatalog.toXmlString()));
            params.add(new BasicNameValuePair("agentproperties", propertiesString));

            put.setEntity(new UrlEncodedFormEntity(params));
        } catch (Exception e) {
            throw new SchedulerException(
                    "Unable to assemble a remote scheduler request for adding an event " + eventCatalog, e);
        }

        HttpResponse response = getResponse(put, SC_OK, SC_NOT_FOUND);
        try {
            if (response != null) {
                if (SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                    logger.warn("Event {} was not found by the scheduler service", eventId);
                } else if (SC_OK == response.getStatusLine().getStatusCode()) {
                    logger.info("Event {} successfully updated with capture agent metadata.", eventId);
                } else {
                    throw new SchedulerException("Unexpected status code " + response.getStatusLine());
                }
                return;
            }
        } catch (Exception e) {
            throw new SchedulerException(
                    "Unable to update event " + eventId + " to the scheduler service: " + e);
        } finally {
            closeConnection(response);
        }
        throw new SchedulerException("Unable to update  event " + eventId);
    }
}

From source file:com.myee.tarot.core.config.RuntimePropertyPlaceholderConfigurer.java

public void afterPropertiesSet() throws IOException {
    // If no environment override has been specified, used the default environments
    if (environments == null || environments.size() == 0) {
        environments = defaultEnvironments;
    }/*www  .  j  av  a 2  s . c  om*/

    // Prepend the default property locations to the specified property locations (if any)
    Set<Resource> combinedLocations = new LinkedHashSet<Resource>();
    if (!CollectionUtils.isEmpty(overridableProperyLocations)) {
        combinedLocations.addAll(overridableProperyLocations);
    }

    if (!CollectionUtils.isEmpty(propertyLocations)) {
        combinedLocations.addAll(propertyLocations);
    }
    propertyLocations = combinedLocations;

    if (!environments.contains(defaultEnvironment)) {
        throw new AssertionError(
                "Default environment '" + defaultEnvironment + "' not listed in environment list");
    }

    if (keyResolver == null) {
        keyResolver = new RuntimePropertyEnvironmentKeyResolver();
    }

    String environment = determineEnvironment();
    ArrayList<Resource> allLocations = new ArrayList<Resource>();

    /* Process configuration in the following order (later files override earlier files
     * common-shared.properties
     * [environment]-shared.properties
     * common.properties
     * [environment].properties
     * -Dproperty-override-shared specified value, if any
     * -Dproperty-override specified value, if any  */
    Set<Set<Resource>> testLocations = new LinkedHashSet<Set<Resource>>();
    testLocations.add(propertyLocations);
    testLocations.add(defaultPropertyLocations);

    for (Resource resource : createBroadleafResource()) {
        if (resource.exists()) {
            allLocations.add(resource);
        }
    }

    for (Set<Resource> locations : testLocations) {
        for (Resource resource : createSharedCommonResource(locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createSharedPropertiesResource(environment, locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createCommonResource(locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createPropertiesResource(environment, locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }
    }

    Resource sharedPropertyOverride = createSharedOverrideResource();
    if (sharedPropertyOverride != null) {
        allLocations.add(sharedPropertyOverride);
    }

    Resource propertyOverride = createOverrideResource();
    if (propertyOverride != null) {
        allLocations.add(propertyOverride);
    }

    Properties props = new Properties();
    for (Resource resource : allLocations) {
        if (resource.exists()) {
            // We will log source-control managed properties with trace and overrides with info
            if (((resource.equals(sharedPropertyOverride) || resource.equals(propertyOverride)))
                    || LOG.isTraceEnabled()) {
                props = new Properties(props);
                props.load(resource.getInputStream());
                for (Entry<Object, Object> entry : props.entrySet()) {
                    //                        if (resource.equals(sharedPropertyOverride) || resource.equals(propertyOverride)) {
                    //                            logger.support("Read " + entry.getKey() + " from " + resource.getFilename());
                    //                        } else {
                    LOG.trace("Read " + entry.getKey() + " from " + resource.getFilename());
                    //                        }
                }
            }
        } else {
            LOG.debug("Unable to locate resource: " + resource.getFilename());
        }
    }

    setLocations(allLocations.toArray(new Resource[] {}));
}

From source file:org.apache.airavata.gfac.hadoop.handler.HadoopDeploymentHandler.java

private void clusterPropertiesToHadoopSiteXml(Properties props, File hadoopSiteXml)
        throws ParserConfigurationException, TransformerException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

    Document hadoopSiteXmlDoc = documentBuilder.newDocument();

    hadoopSiteXmlDoc.setXmlVersion("1.0");
    hadoopSiteXmlDoc.setXmlStandalone(true);
    hadoopSiteXmlDoc.createProcessingInstruction("xml-stylesheet",
            "type=\"text/xsl\" href=\"configuration.xsl\"");

    Element configEle = hadoopSiteXmlDoc.createElement("configuration");

    hadoopSiteXmlDoc.appendChild(configEle);

    for (Map.Entry<Object, Object> entry : props.entrySet()) {
        addPropertyToConfiguration(entry, configEle, hadoopSiteXmlDoc);
    }//from w ww.  j  a v a  2 s  .c  o m

    saveDomToFile(hadoopSiteXmlDoc, hadoopSiteXml);
}

From source file:org.apache.ode.dao.jpa.BPELDAOConnectionFactoryImpl.java

@SuppressWarnings("unchecked")
public void init(Properties properties) {
    HashMap<String, Object> propMap = new HashMap<String, Object>();

    //        propMap.put("openjpa.Log", "DefaultLevel=TRACE");
    propMap.put("openjpa.Log", "commons");
    //        propMap.put("openjpa.jdbc.DBDictionary", "org.apache.openjpa.jdbc.sql.DerbyDictionary");

    propMap.put("openjpa.ManagedRuntime", new JpaTxMgrProvider(_tm));
    propMap.put("openjpa.ConnectionFactory", _ds);
    propMap.put("openjpa.ConnectionFactoryMode", "managed");
    //        propMap.put("openjpa.FlushBeforeQueries", "false");
    propMap.put("openjpa.FetchBatchSize", 1000);
    //propMap.put("openjpa.jdbc.TransactionIsolation", "read-committed");

    if (_dbdictionary != null)
        propMap.put("openjpa.jdbc.DBDictionary", _dbdictionary);

    if (properties != null)
        for (Map.Entry me : properties.entrySet())
            propMap.put((String) me.getKey(), me.getValue());

    _emf = Persistence.createEntityManagerFactory("ode-dao", propMap);
}

From source file:kr.motd.maven.exec.ExecMojo.java

private Map<String, String> handleSystemEnvVariables() throws MojoExecutionException {

    validateEnvironmentVars();/*from  w  w w . j  a  v a  2s.c  om*/

    Map<String, String> enviro = new HashMap<String, String>();
    try {
        Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
        for (Map.Entry<?, ?> entry : systemEnvVars.entrySet()) {
            enviro.put((String) entry.getKey(), (String) entry.getValue());
        }
    } catch (IOException x) {
        getLog().error("Could not assign default system enviroment variables.", x);
    }

    if (environmentVariables != null) {
        enviro.putAll(environmentVariables);
    }

    if (this.environmentScript != null) {
        getLog().info("Pick up external environment script: " + this.environmentScript);
        Map<String, String> envVarsFromScript = this.createEnvs(this.environmentScript);
        if (envVarsFromScript != null) {
            enviro.putAll(envVarsFromScript);
        }
    }

    if (this.getLog().isDebugEnabled()) {
        Set<String> keys = new TreeSet<String>();
        keys.addAll(enviro.keySet());
        for (String key : keys) {
            this.getLog().debug("env: " + key + "=" + enviro.get(key));
        }
    }

    return enviro;
}

From source file:org.apache.bval.jsr.ConstraintDefaults.java

@SuppressWarnings("unchecked")
private Map<String, Class<? extends ConstraintValidator<?, ?>>[]> loadDefaultConstraints(String resource) {
    final Properties constraintProperties = new Properties();
    final ClassLoader classloader = getClassLoader();
    final InputStream stream = classloader.getResourceAsStream(resource);
    if (stream == null) {
        log.log(Level.WARNING, String.format("Cannot find %s", resource));
    } else {//from   ww  w . ja v a2 s  .co m
        try {
            constraintProperties.load(stream);
        } catch (IOException e) {
            log.log(Level.SEVERE, String.format("Cannot load %s", resource), e);
        } finally {
            try {
                stream.close();
            } catch (final IOException e) {
                // no-op
            }
        }
    }

    final Map<String, Class<? extends ConstraintValidator<?, ?>>[]> loadedConstraints = new HashMap<String, Class<? extends ConstraintValidator<?, ?>>[]>();

    for (final Map.Entry<Object, Object> entry : constraintProperties.entrySet()) {
        final List<Class<?>> classes = new LinkedList<Class<?>>();
        for (String className : StringUtils.split((String) entry.getValue(), ',')) {
            try {
                classes.add(Reflection.getClass(classloader, className.trim()));
            } catch (Exception e) {
                log.log(Level.SEVERE, String.format("Cannot find class %s", className), e);
            }
        }
        loadedConstraints.put((String) entry.getKey(), classes.toArray(new Class[classes.size()]));
    }
    return loadedConstraints;
}

From source file:com.bstek.dorado.web.loader.DoradoLoader.java

private void loadConfigureProperties(ConfigureStore configureStore, ResourceLoader resourceLoader,
        String configureLocation, boolean silence) throws IOException {
    // ??/*from w w  w. java 2 s . c o  m*/
    ConsoleUtils.outputLoadingInfo("Loading configure from [" + configureLocation + "]...");
    if (StringUtils.isNotEmpty(configureLocation)) {
        Resource resource = resourceLoader.getResource(configureLocation);
        if (!resource.exists()) {
            if (silence) {
                logger.warn("Can not found resource [" + configureLocation + "].");
                return;
            } else {
                throw new IOException("Can not found resource [" + configureLocation + "].");
            }
        }
        InputStream in = resource.getInputStream();
        Properties properties = new Properties();
        try {
            properties.load(in);
        } finally {
            in.close();
        }

        ExpressionHandler expressionHandler = new DefaultExpressionHandler() {
            @Override
            public JexlContext getJexlContext() {
                JexlContext elContext = new MapContext();
                elContext.set("env", System.getenv());
                return elContext;
            }
        };

        for (Map.Entry<?, ?> entry : properties.entrySet()) {
            String text = (String) entry.getValue();
            Object value = text;
            if (StringUtils.isNotEmpty(text)) {
                Expression expression = expressionHandler.compile(text);
                if (expression != null) {
                    value = expression.evaluate();
                }
            }
            configureStore.set((String) entry.getKey(), value);
        }
    }
}

From source file:com.spidertracks.datanucleus.convert.ByteConverterContext.java

/**
 * Initialize// ww w  .j a  v  a  2 s  . c  o  m
 * 
 * @param propertiesFilePath
 */
private void initialize(String propertiesFilePath) {
    converters = new HashMap<Class<?>, ByteConverter>();

    /**
     * Load our defaults
     */
    converters.put(Boolean.class, new BooleanConverter());
    converters.put(Character.class, new CharacterConverter());
    converters.put(Double.class, new DoubleConverter());
    converters.put(Float.class, new FloatConverter());
    converters.put(Integer.class, new IntegerConverter());
    converters.put(java.util.UUID.class, new LexicalUUIDConverter());
    converters.put(Long.class, new LongConverter());
    converters.put(Short.class, new ShortConverter());
    converters.put(String.class, new StringConverter());
    converters.put(com.eaio.uuid.UUID.class, new TimeUUIDConverter());
    converters.put(byte[].class, new ByteArrayConverter());

    // Load user defined props and override defaults if required
    if (propertiesFilePath != null) {

        InputStream propsFileSource = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath);

        if (propsFileSource == null) {
            throw new NucleusDataStoreException(
                    String.format("Could not load properties file %s from classpath", propertiesFilePath));
        }

        Properties converterProps = new Properties();
        try {
            converterProps.load(propsFileSource);
        } catch (IOException e) {
            throw new NucleusDataStoreException(
                    String.format("Could not load properties file %s from classpath", propertiesFilePath), e);
        }

        for (Entry<Object, Object> converterDef : converterProps.entrySet()) {
            String classKey = converterDef.getKey().toString();
            String converterClassName = converterDef.getValue().toString();

            try {
                ByteConverter instance = (ByteConverter) Class.forName(converterClassName).newInstance();

                converters.put(Class.forName(classKey), instance);

            } catch (Exception e) {
                throw new NucleusDataStoreException(String.format(
                        "Unable to instanciate converter for key class %s with converter class %s.  Please make a no arg constructor is present in the converter",
                        classKey, converterClassName), e);
            }

        }
    }

    // wire our our pointers to our primitive times after potential override
    this.boolConverter = converters.get(Boolean.class);
    this.charConverter = converters.get(Character.class);
    this.doubleConverter = converters.get(Double.class);
    this.floatConverter = converters.get(Float.class);
    this.intConverter = converters.get(Integer.class);
    this.longConverter = converters.get(Long.class);
    this.shortConverter = converters.get(Short.class);
    this.stringConverter = converters.get(String.class);

    this.serializerConverter = new SerializerWrapperConverter(serializer);

}

From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java

@VisibleForTesting
Pattern findClusterBootstrapJar(ExecutionMode executionMode, PipelineConfiguration pipelineConf,
        StageLibraryTask stageLibraryTask) throws IOException {
    StageConfiguration stageConf = PipelineConfigurationUtil.getSourceStageConf(pipelineConf);
    StageDefinition stageDefinition = stageLibraryTask.getStage(stageConf.getLibrary(),
            stageConf.getStageName(), false);
    ClassLoader stageClassLoader = stageDefinition.getStageClassLoader();
    Properties dataCollectorProps = readDataCollectorProperties(stageClassLoader);

    for (Map.Entry entry : dataCollectorProps.entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        getLog().debug("Datacollector library properties key : '{}', value: '{}'", key, value);
        if (key.equals(CLUSTER_BOOTSTRAP_JAR_REGEX + executionMode + "_" + stageDefinition.getClassName())) {
            getLog().info("Using bootstrap jar pattern: '{}'", value);
            return Pattern.compile(value + "-\\d+.*");
        }//  ww w  .  ja va 2  s  . co  m
    }
    Pattern defaultJarPattern;
    if (executionMode == ExecutionMode.CLUSTER_MESOS_STREAMING) {
        defaultJarPattern = CLUSTER_BOOTSTRAP_MESOS_JAR_PATTERN;
    } else if (executionMode == ExecutionMode.CLUSTER_YARN_STREAMING) {
        defaultJarPattern = CLUSTER_BOOTSTRAP_JAR_PATTERN;
    } else {
        defaultJarPattern = CLUSTER_BOOTSTRAP_API_JAR_PATTERN;
    }
    return defaultJarPattern;
}

From source file:org.apache.archiva.redback.rest.services.DefaultUtilServices.java

public String getI18nResources(String locale) throws RedbackServiceException {
    String cachedi18n = cachei18n.get(StringUtils.isEmpty(locale) ? "en" : StringUtils.lowerCase(locale));
    if (cachedi18n != null) {
        return cachedi18n;
    }/*from   ww w.j av a  2  s  .  c om*/

    Properties properties = new Properties();

    // load redback user api messages
    try {

        // load default first then requested locale
        loadResource(properties, "org/apache/archiva/redback/users/messages", null);
        loadResource(properties, "org/apache/archiva/redback/users/messages", locale);

    } catch (IOException e) {
        log.warn("skip error loading properties {}", "org/apache/archiva/redback/users/messages");
    }

    try {

        // load default first then requested locale
        loadResource(properties, "org/apache/archiva/redback/i18n/default", null);
        loadResource(properties, "org/apache/archiva/redback/i18n/default", locale);

    } catch (IOException e) {
        log.warn("skip error loading properties {}", "org/apache/archiva/redback/i18n/default");
    }

    StringBuilder output = new StringBuilder();

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        output.append((String) entry.getKey()).append('=').append((String) entry.getValue());
        output.append('\n');
    }

    cachei18n.put(StringUtils.isEmpty(locale) ? "en" : StringUtils.lowerCase(locale), output.toString());

    return output.toString();
}