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:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Write various info on the system we're using into the given file. This
 * info will later get put into metadata for the crawl.
 *
 * @param outputFile//from   w  ww. j a  v  a 2  s.  c  o m
 *            A file to write to.
 * @param builder
 *            The ProcessBuilder being used to start the Heritrix process
 */
@SuppressWarnings("unchecked")
private void writeSystemInfo(File outputFile, ProcessBuilder builder) {
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(new FileWriter(outputFile));
        writer.println("The Heritrix process is started in the following"
                + " environment\n (note that some entries will be" + " changed by the starting JVM):");
        Map<String, String> env = builder.environment();
        List<String> keyList = new ArrayList<String>(env.keySet());
        Collections.sort(keyList);
        for (String key : keyList) {
            writer.println(key + "=" + env.get(key));
        }
        writer.println("Process properties:");
        Properties properties = System.getProperties();
        keyList = new ArrayList<String>((Set) properties.keySet());
        Collections.sort(keyList);
        for (String key : keyList) {
            writer.println(key + "=" + properties.get(key));
        }
    } catch (IOException e) {
        log.warn("Error writing basic properties to output file.", e);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:com.photon.phresco.impl.ConfigManagerImpl.java

private void createProperties(Element configNode, Properties properties) {
    Set<Object> keySet = properties.keySet();
    for (Object key : keySet) {
        String value = (String) properties.get(key);
        Element propNode = document.createElement(key.toString());
        propNode.setTextContent(value);/*from   ww  w  .ja va2  s  . c o m*/
        configNode.appendChild(propNode);
    }
}

From source file:org.apache.openaz.xacml.std.pap.StdPDPPolicy.java

public StdPDPPolicy(String id, boolean isRoot, URI location, Properties properties) throws IOException {
    this(id, isRoot);
    this.location = location;
    ///*w ww .  ja v  a  2 s. com*/
    // Read the policy data
    //
    this.readPolicyData();
    //
    // See if there's a name
    //
    for (Object key : properties.keySet()) {
        if (key.toString().equals(id + ".name")) {
            this.name = properties.getProperty(key.toString());
            break;
        }
    }
}

From source file:com.xpn.xwiki.store.DBCPConnectionProvider.java

public void configure(Properties props) throws HibernateException {
    try {/*from  w w w .  ja va2 s  .com*/
        LOGGER.debug("Configure DBCPConnectionProvider");

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);
        String jdbcUrl = props.getProperty(Environment.URL);
        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password. Only put username and password if they're not null. This allows
        // external authentication support (OS authenticated). It'll thus work if the hibernate
        // config does not specify a username and/or password.
        String username = props.getProperty(Environment.USER);
        if (username != null) {
            dbcpProperties.put("username", username);
        }
        String password = props.getProperty(Environment.PASS);
        if (password != null) {
            dbcpProperties.put("password", password);
        }

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set)
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderFactory.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }

        // Some debug info
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            LOGGER.debug(sw.toString());
        }

        // Let the factory create the pool
        ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(dbcpProperties);

        // The BasicDataSource has lazy initialization
        // borrowing a connection will start the DataSource
        // and make sure it is configured correctly.
        Connection conn = ds.getConnection();
        conn.close();

        // Log pool statistics before continuing.
        logStatistics();
    } catch (Exception e) {
        String message = "Could not create a DBCP pool. "
                + "There is an error in the hibernate configuration file, please review it.";
        LOGGER.error(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                // ignore
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    LOGGER.debug("Configure DBCPConnectionProvider complete");
}

From source file:org.alloy.metal.xml.merge.MergeContext.java

private void setHandlers(Properties props)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    MutableList<MergeHandler> tempHandlers = _Lists.list();
    String[] keys = props.keySet().toArray(new String[props.keySet().size()]);
    for (String key : keys) {
        if (key.startsWith("handler.")) {
            MergeHandler temp = (MergeHandler) Class.forName(props.getProperty(key)).newInstance();
            String name = key.substring(8, key.length());
            temp.setName(name);//from   ww w .  java2s.c om

            String priority = props.getProperty("priority." + name);
            if (priority != null) {
                temp.setPriority(Integer.parseInt(priority));
            }

            String xpath = props.getProperty("xpath." + name);
            if (xpath != null) {
                temp.setXPath(xpath);
            }

            String matcherType = props.getProperty("matcherType." + name);
            if (matcherType != null) {
                temp.setMatcherType(MergeMatcherType.valueOf(matcherType));
            }

            tempHandlers.add(temp);
        }
    }

    List<MergeHandler> finalHandlers = Lists.newArrayList();
    for (MergeHandler temp : tempHandlers) {
        if (temp.getName().contains(".")) {
            String parentName = temp.getName().substring(0, temp.getName().lastIndexOf("."));

            MergeHandler parent = tempHandlers.filter((handler) -> handler.getName().equals(parentName))
                    .singleStrict();

            parent.getChildren().add(temp);
        } else {
            finalHandlers.add(temp);
        }
    }

    this.handlers = finalHandlers;
}

From source file:org.apache.drill.exec.store.hive.HiveScan.java

private void splitInput(final Properties properties, final StorageDescriptor sd, final Partition partition)
        throws ReflectiveOperationException, IOException {
    final JobConf job = new JobConf();
    for (final Object obj : properties.keySet()) {
        job.set((String) obj, (String) properties.get(obj));
    }//  w w w  .  ja  v  a  2s . co m
    for (final Map.Entry<String, String> entry : hiveReadEntry.hiveConfigOverride.entrySet()) {
        job.set(entry.getKey(), entry.getValue());
    }
    InputFormat<?, ?> format = (InputFormat<?, ?>) Class.forName(sd.getInputFormat()).getConstructor()
            .newInstance();
    job.setInputFormat(format.getClass());
    final Path path = new Path(sd.getLocation());
    final FileSystem fs = path.getFileSystem(job);

    if (fs.exists(path)) {
        FileInputFormat.addInputPath(job, path);
        format = job.getInputFormat();
        for (final InputSplit split : format.getSplits(job, 1)) {
            inputSplits.add(split);
            partitionMap.put(split, partition);
        }
    }
    final String numRowsProp = properties.getProperty("numRows");
    logger.trace("HiveScan num rows property = {}", numRowsProp);
    if (numRowsProp != null) {
        final long numRows = Long.valueOf(numRowsProp);
        // starting from hive-0.13, when no statistics are available, this property is set to -1
        // it's important to note that the value returned by hive may not be up to date
        if (numRows > 0) {
            rowCount += numRows;
        }
    }
}

From source file:com.fer.hr.olap.query.OlapQuery.java

public void setProperties(Properties props) {
    if (props != null) {
        this.properties.putAll(props);
        for (Object _key : props.keySet()) {
            String key = (String) _key;
            String value = props.getProperty((String) key);
            QueryProperty prop = QueryPropertyFactory.getProperty(key, value, this);
            prop.handle();//from w  ww .j  ava2  s  .  c  o m
        }
    }
}

From source file:com.jaspersoft.studio.custom.adapter.controls.DynamicControlComposite.java

/**
 * Return the castor mapping file definition of the data adapter 
 * //from  w w w .  j a v a2s.co m
 * @return the castor mapping path in the workspace of the data adapter or null if it can't be found
 */
protected String getXmlDefinitionLocation() {
    Properties props = new Properties();
    try {
        props.load(dataAdapterDescriptor.getClass().getResourceAsStream("/jasperreports_extension.properties"));
        for (Object property : props.keySet()) {
            if (property.toString().startsWith("net.sf.jasperreports.extension.castor.mapping")) {
                return props.getProperty(property.toString());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.aptd.simulation.TestCLanguageLabels.java

/**
 * test-case all resource strings//from  w  w  w. j av  a 2 s. c om
 *
 * @throws IOException throws on io errors
 */
@Test
public void testResourceString() throws IOException {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    final Set<String> l_ignoredlabel = new HashSet<>();

    // --- parse source and get label definition
    final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH))
            .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> {
                try {
                    final CJavaVistor l_parser = new CJavaVistor();
                    l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null);
                    return l_parser.labels().stream();
                } catch (final IOException l_excpetion) {
                    assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()),
                            false);
                    return Stream.empty();
                } catch (final ParseProblemException l_exception) {
                    // add label build by class path to the ignore list
                    l_ignoredlabel.add(i.toAbsolutePath().toString()
                            // remove path to class directory
                            .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath()
                                    .toString(), "")
                            // string starts with path separator
                            .substring(1)
                            // remove file extension
                            .replace(".java", "")
                            // replace separators with dots
                            .replace("/", CLASSSEPARATOR)
                            // convert to lower-case
                            .toLowerCase()
                            // remove package-root name
                            .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, ""));

                    System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i,
                            l_exception.getMessage()));
                    return Stream.empty();
                }
            }).collect(Collectors.toSet()));

    // --- check of any label is found
    assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty());

    // --- check label towards the property definition
    if (l_ignoredlabel.size() > 0)
        System.err.println(MessageFormat.format(
                "labels that starts with {0} are ignored, because parsing errors are occurred",
                l_ignoredlabel));

    LANGUAGEPROPERY.forEach((k, v) -> {
        try {
            final Properties l_property = new Properties();
            l_property.load(new FileInputStream(new File(v)));

            final Set<String> l_parseditems = new HashSet<>(l_label);
            final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString)
                    .collect(Collectors.toSet());

            // --- check if all property items are within the parsed labels
            l_parseditems.removeAll(l_propertyitems);
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}",
                    k, l_parseditems.size(), StringUtils.join(l_parseditems, ", ")), l_parseditems.isEmpty());

            // --- check if all parsed labels within the property item and remove ignored labels
            l_propertyitems.removeAll(l_label);
            final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream()
                    .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false))
                    .collect(Collectors.toSet());
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}",
                    k, l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")),
                    l_ignoredpropertyitems.isEmpty());
        } catch (final IOException l_exception) {
            assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false);
        }
    });
}

From source file:net.ymate.platform.configuration.provider.impl.JConfigProvider.java

public List<String> getList(String key) {
    List<String> valueList = new ArrayList<String>();
    String[] keys = StringUtils.split(key, IConfiguration.CFG_KEY_SEPERATE);
    int keysSize = keys.length;
    Properties properties = null;
    if (keysSize == 1) {
        properties = config.getProperties();
    } else if (keysSize == 2) {
        properties = config.getProperties(keys[0]);
    }/*from   w ww  .  j av  a 2  s .  c om*/
    if (properties != null && !properties.isEmpty()) {
        for (Object name : properties.keySet()) {
            if (name != null && name.toString().startsWith(keysSize == 1 ? keys[0] : keys[1])) { // key
                Object value = properties.get(name);
                valueList.add(value == null ? "" : value.toString());
            }
        }
    }
    return valueList;
}