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:energy.usef.time.Config.java

/***
 * Reads the configuration properties which consist of application specific properties which overrule default properties.
 *
 * @throws IOException/*  w  w w. j  a  v  a2 s .  com*/
 */
public void readProperties() throws IOException {
    properties.clear();
    String filename = getConfigurationFolder() + CONFIG_LOCAL_FILE_NAME;
    Properties defaults = readDefaultProperties();
    if (isFileExists(filename)) {
        properties = readPropertiesFromFile(filename);

        // merge default properties if the property does not exist.
        for (Map.Entry<Object, Object> entry : defaults.entrySet()) {
            String key = (String) entry.getKey();
            if (properties.getProperty(key) == null) {
                LOGGER.debug("Default property is added: {}", key);
                properties.put(key, entry.getValue());
            }
        }

    } else {
        LOGGER.warn("Could not find properties file: {}. Using the default properties.", filename);
        properties = defaults;
    }

    List<String> propertiesList = properties.entrySet().stream()
            .map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.toList());
    Collections.sort(propertiesList);

    LOGGER.info("\nProperties:\n" + StringUtils.join(propertiesList.toArray(), "\n"));
}

From source file:com.headstrong.fusion.launcher.Fusion.java

/**
 * Load properties from the given input stream.
 * //  w  w  w.ja va2  s.c  o m
 * @precondition props!=null ins!=null
 * @postcondition props!=null
 * @param props
 *            The <code>Properties</code> into which the loaded properties
 *            are loaded
 * @param ins
 *            The <code>InputStream</code> from where the properties are
 *            to be loaded
 */

private void load(Map<String, String> props, InputStream ins) throws IOException {
    try {
        Properties tmp = new Properties();
        tmp.load(ins);

        for (Map.Entry<Object, Object> entry : tmp.entrySet()) {
            props.put((String) entry.getKey(), (String) entry.getValue());
        }
    } finally {
        try {
            ins.close();
        } catch (IOException ioe2) {
            logger.log(Logger.LOG_ERROR, "Error closing resource" + ioe2);
        }
    }
}

From source file:org.apache.falcon.oozie.OozieEntityBuilder.java

protected Configuration getHiveCredentialsAsConf(Cluster cluster) {
    Properties hiveCredentials = getHiveCredentials(cluster);

    Configuration hiveConf = new Configuration(false);
    for (Entry<Object, Object> entry : hiveCredentials.entrySet()) {
        hiveConf.set((String) entry.getKey(), (String) entry.getValue());
    }/*from w  w  w  .  j a  v  a2s.  c o m*/

    return hiveConf;
}

From source file:org.apache.jetspeed.services.resources.JetspeedResourceService.java

public synchronized void init(ServletConfig config) throws InitializationException {
    String propsDir = null;/*from   ww w. j ava2s . com*/
    String appName = config.getServletName();
    String deployFilename = appName + ".properties";
    String torqueFilename = appName + "_torque.properties";
    super.init(config);

    // Display product information
    //System.out.println("Jetspeed Services: Starting servlet: [" + appName +"]");
    String version = getString(JetspeedResources.JETSPEED_VERSION_KEY);
    String name = getString(JetspeedResources.JETSPEED_NAME_KEY);
    if (version != null && name != null) {
        System.out.println("");
        System.out.println("Starting " + name + "/" + version);
        System.out.println("");
    }

    try {
        propsDir = System.getProperty("jetspeed.conf.dir", null);
        if (null == propsDir) {
            // no deploy-time directory defined to find properties, return
            return;
        }

        String torqueProps = makeFileNamePath(propsDir, torqueFilename);
        String deployProps = makeFileNamePath(propsDir, deployFilename);

        System.out.println("torque props = " + torqueProps);
        System.out.println("deploy props = " + deployProps);

        File deployFile = new File(deployProps);
        if (deployFile.exists()) {
            FileInputStream is = new FileInputStream(deployProps);
            Properties props = new Properties();
            props.load(is);

            Iterator it = props.entrySet().iterator();
            while (it.hasNext()) {
                Entry entry = (Entry) it.next();
                //if (entry.getValue() != null && ((String)entry.getValue()).length() > 0)
                this.setProperty((String) entry.getKey(), (String) entry.getValue());
                System.out.println("setting key/value: " + entry.getKey() + ":" + entry.getValue());
            }
        } else {
            String msg = "Failed to find Deploy properties: " + deployProps;
            System.err.println(msg);
        }

        File torqueFile = new File(torqueProps);
        if (torqueFile.exists()) {
            this.setProperty("component.torque.config", torqueProps);

            FileInputStream tis = new FileInputStream(torqueProps);
            Properties tprops = new Properties();
            tprops.load(tis);

            System.out.println("Connecting to: " + tprops.getProperty("database.default.url"));
            System.out.println("Database Username: " + tprops.getProperty("database.default.username"));
        }
    } catch (IOException e) {
        StringBuffer msg = new StringBuffer("Error reading properties for appName: ");
        msg.append(appName);
        msg.append(", props Dir: " + propsDir);
        System.err.println("Exception in loading properties: " + propsDir);
        e.printStackTrace();
    }
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private ImmutableResult createResult(Verifier.Scope scope, Verifier.Result.Status status, Properties response) {
    ImmutableResult.Builder builder = ImmutableResult.builder().scope(scope).status(status);
    if (response != null) {
        LinkedHashMap<String, ImmutableError.Builder> errors = new LinkedHashMap<>();
        for (Map.Entry<Object, Object> entry : response.entrySet()) {
            String key = (String) entry.getKey();
            if (key.startsWith("error.")) {
                String errorId = key.substring("error.".length()).replaceFirst("\\..*", "");
                ImmutableError.Builder error = errors.getOrDefault(errorId, ImmutableError.builder());
                String value = (String) entry.getValue();
                if (key.endsWith(".code")) {
                    error.code(value);//from  w w w  .  j av  a 2 s .  c  om
                }
                if (key.endsWith(".description")) {
                    error.description(value);
                }
                errors.put(errorId, error);
            }
        }
        builder.addAllErrors(
                errors.values().stream().map(ImmutableError.Builder::build).collect(Collectors.toList()));
    }
    return builder.build();
}

From source file:anhttpclient.impl.MultiThreadWebBrowser.java

/**
 * {@inheritDoc}/*from   w  w w .  ja v a 2  s. c  o m*/
 */
public void setDefaultHeaders(Properties defaultHeaders) {
    synchronized (this.defaultHeaders) {
        this.defaultHeaders.clear();
        for (Map.Entry<Object, Object> entryObject : defaultHeaders.entrySet()) {
            String headerName = String.valueOf(entryObject.getKey());
            String headerValue = String.valueOf(entryObject.getValue());
            this.defaultHeaders.put(headerName, headerValue);
        }

        for (WebBrowser webBrowser : webBrowsersList.values()) {
            webBrowser.setDefaultHeaders(defaultHeaders);
        }
    }
}

From source file:och.service.props.impl.FileProps.java

private void saveToFile(Properties newProps) {

    log.info("save props to " + file.getAbsolutePath());

    Properties newState = modifyProps(newProps);

    StringBuilder sb = new StringBuilder();
    sb.append("#Props from app");
    for (Entry<Object, Object> entry : newProps.entrySet()) {
        sb.append("\n" + entry.getKey() + "=" + entry.getValue());
    }// w  ww. j a  v  a2  s. co  m

    try {
        replaceFileUTF8(file, sb.toString());
    } catch (Exception e) {
        log.error("can't saveToFile", e);
        return;
    }

    this.curModified = file.lastModified();
    this.state = newState;
}

From source file:io.fabric8.agent.download.DownloadManagerTest.java

/**
 * Prepares DownloadManager to test//from   w  w  w  .jav a2s.c  om
 *
 * @param remoteRepo
 * @param settingsFile
 * @param props
 * @return
 * @throws IOException
 */
private DownloadManager createDownloadManager(String remoteRepo, String settingsFile, Properties props)
        throws IOException {
    File mavenSettings = new File(karafHome, settingsFile);
    Hashtable<String, String> properties = new Hashtable<>();
    if (props != null) {
        for (Map.Entry<Object, Object> entry : props.entrySet()) {
            properties.put(entry.getKey().toString(), entry.getValue().toString());
        }
    }
    properties.put("org.ops4j.pax.url.mvn.localRepository", systemRepoUri);
    properties.put("org.ops4j.pax.url.mvn.repositories", remoteRepo);
    properties.put("org.ops4j.pax.url.mvn.defaultRepositories", systemRepoUri);
    properties.put("org.ops4j.pax.url.mvn.settings", mavenSettings.toURI().toString());

    MavenResolver resolver = MavenResolvers.createMavenResolver(properties, "org.ops4j.pax.url.mvn");
    return DownloadManagers.createDownloadManager(resolver, Executors.newSingleThreadScheduledExecutor());
}

From source file:org.jets3t.service.utils.signedurl.GatekeeperClientUtils.java

/**
 * Request permission from the Gatekeeper for a particular operation.
 *
 * @param operationType/*  ww  w. ja  v  a 2  s  .  c  o  m*/
 * @param bucketName
 * @param objects
 * @param applicationPropertiesMap
 * @throws HttpException
 * @throws Exception
 */
public GatekeeperMessage requestActionThroughGatekeeper(String operationType, String bucketName,
        S3Object[] objects, Map applicationPropertiesMap) throws HttpException, Exception {
    /*
     *  Build Gatekeeper request.
     */
    GatekeeperMessage gatekeeperMessage = new GatekeeperMessage();
    gatekeeperMessage.addApplicationProperties(applicationPropertiesMap);
    gatekeeperMessage.addApplicationProperty(GatekeeperMessage.PROPERTY_CLIENT_VERSION_ID,
            userAgentDescription);

    // If a prior failure has occurred, add information about this failure.
    if (priorFailureException != null) {
        gatekeeperMessage.addApplicationProperty(GatekeeperMessage.PROPERTY_PRIOR_FAILURE_MESSAGE,
                priorFailureException.getMessage());
        // Now reset the prior failure variable.
        priorFailureException = null;
    }

    // Add all S3 objects as candiates for PUT signing.
    for (int i = 0; i < objects.length; i++) {
        SignatureRequest signatureRequest = new SignatureRequest(operationType, objects[i].getKey());
        signatureRequest.setObjectMetadata(objects[i].getMetadataMap());
        signatureRequest.setBucketName(bucketName);

        gatekeeperMessage.addSignatureRequest(signatureRequest);
    }

    /*
     *  Build HttpClient POST message.
     */

    // Add all properties/parameters to credentials POST request.
    HttpPost postMethod = new HttpPost(gatekeeperUrl);
    Properties properties = gatekeeperMessage.encodeToProperties();
    Iterator<Map.Entry<Object, Object>> propsIter = properties.entrySet().iterator();
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(properties.size());
    while (propsIter.hasNext()) {
        Map.Entry<Object, Object> entry = propsIter.next();
        String fieldName = (String) entry.getKey();
        String fieldValue = (String) entry.getValue();
        parameters.add(new BasicNameValuePair(fieldName, fieldValue));
    }
    postMethod.setEntity(new UrlEncodedFormEntity(parameters));

    // Create Http Client if necessary, and include User Agent information.
    if (httpClientGatekeeper == null) {
        httpClientGatekeeper = initHttpConnection();
    }

    // Try to detect any necessary proxy configurations.
    try {
        HttpHost proxyHost = PluginProxyUtil.detectProxy(new URL(gatekeeperUrl));
        if (proxyHost != null) {
            httpClientGatekeeper.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("No proxy detected");
        }
    }

    // Perform Gateway request.
    if (log.isDebugEnabled()) {
        log.debug("Contacting Gatekeeper at: " + gatekeeperUrl);
    }
    HttpResponse response = null;
    try {
        response = httpClientGatekeeper.execute(postMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        String contentType = response.getFirstHeader("Content-Type").getValue();
        if (responseCode == 200) {
            InputStream responseInputStream = null;

            Header encodingHeader = response.getFirstHeader("Content-Encoding");
            if (encodingHeader != null && "gzip".equalsIgnoreCase(encodingHeader.getValue())) {
                if (log.isDebugEnabled()) {
                    log.debug("Inflating gzip-encoded response");
                }
                responseInputStream = new GZIPInputStream(response.getEntity().getContent());
            } else {
                responseInputStream = response.getEntity().getContent();
            }

            if (responseInputStream == null) {
                throw new IOException("No response input stream available from Gatekeeper");
            }

            Properties responseProperties = new Properties();
            try {
                responseProperties.load(responseInputStream);
            } finally {
                responseInputStream.close();
            }

            GatekeeperMessage gatekeeperResponseMessage = GatekeeperMessage
                    .decodeFromProperties(responseProperties);

            // Check for Gatekeeper Error Code in response.
            String gatekeeperErrorCode = gatekeeperResponseMessage.getApplicationProperties()
                    .getProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE);
            if (gatekeeperErrorCode != null) {
                if (log.isWarnEnabled()) {
                    log.warn("Received Gatekeeper error code: " + gatekeeperErrorCode);
                }
            }

            return gatekeeperResponseMessage;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("The Gatekeeper did not permit a request. Response code: " + responseCode
                        + ", Response content type: " + contentType);
            }
            throw new IOException("The Gatekeeper did not permit your request");
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new Exception("Gatekeeper did not respond", e);
    } finally {
        try {
            EntityUtils.consume(response.getEntity());
        } catch (Exception ee) {
            // ignore
        }
    }
}

From source file:org.apache.hama.zookeeper.QuorumPeer.java

private static void writeMyID(Properties properties) throws IOException {
    long myId = -1;

    Configuration conf = new HamaConfiguration();
    String myAddress = DNS.getDefaultHost(conf.get("hama.zookeeper.dns.interface", "default"),
            conf.get("hama.zookeeper.dns.nameserver", "default"));

    List<String> ips = new ArrayList<String>();

    // Add what could be the best (configured) match
    ips.add(myAddress.contains(".") ? myAddress : StringUtils.simpleHostname(myAddress));

    // For all nics get all hostnames and IPs
    Enumeration<?> nics = NetworkInterface.getNetworkInterfaces();
    while (nics.hasMoreElements()) {
        Enumeration<?> rawAdrs = ((NetworkInterface) nics.nextElement()).getInetAddresses();
        while (rawAdrs.hasMoreElements()) {
            InetAddress inet = (InetAddress) rawAdrs.nextElement();
            ips.add(StringUtils.simpleHostname(inet.getHostName()));
            ips.add(inet.getHostAddress());
        }/*from  w ww . ja v  a  2  s. c  om*/
    }

    for (Entry<Object, Object> entry : properties.entrySet()) {
        String key = entry.getKey().toString().trim();
        String value = entry.getValue().toString().trim();

        if (key.startsWith("server.")) {
            int dot = key.indexOf('.');
            long id = Long.parseLong(key.substring(dot + 1));
            String[] parts = value.split(":");
            String address = parts[0];
            if (addressIsLocalHost(address) || ips.contains(address)) {
                myId = id;
                break;
            }
        }
    }

    if (myId == -1) {
        throw new IOException(
                "Could not find my address: " + myAddress + " in list of ZooKeeper quorum servers");
    }

    String dataDirStr = properties.get("dataDir").toString().trim();
    File dataDir = new File(dataDirStr);
    if (!dataDir.isDirectory()) {
        if (!dataDir.mkdirs()) {
            throw new IOException("Unable to create data dir " + dataDir);
        }
    }

    File myIdFile = new File(dataDir, "myid");
    PrintWriter w = new PrintWriter(myIdFile);
    w.println(myId);
    w.close();
}