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:atg.test.AtgDustCase.java

/**
 * Prepares a test against an existing database.
 * /* www  . j  a  v a  2  s.  co  m*/
 * @param repositoryPath
 *            The the repository to be tested, specified as nucleus
 *            component path.
 * @param connectionProperties
 *            A {@link Properties} instance with the following values (in
 *            this example the properties are geared towards an mysql
 *            database):
 * 
 *            <pre>
 * final Properties properties = new Properties();
 * properties.put(&quot;driver&quot;, &quot;com.mysql.jdbc.Driver&quot;);
 * properties.put(&quot;url&quot;, &quot;jdbc:mysql://localhost:3306/someDb&quot;);
 * properties.put(&quot;user&quot;, &quot;someUserName&quot;);
 * properties.put(&quot;password&quot;, &quot;somePassword&quot;);
 * </pre>
 * 
 * 
 * @param dropTables
 *            If <code>true</code> then existing tables will be dropped and
 *            re-created, if set to <code>false</code> the existing tables
 *            will be used.
 * 
 * @param createTables
 *            if set to <code>true</code> all non existing tables needed for
 *            the current test run will be created, if set to
 *            <code>false</code> this class expects all needed tables for
 *            this test run to be already created
 * 
 * @param definitionFiles
 *            One or more needed repository definition files.
 * @throws IOException
 *             The moment we have some properties/configuration related
 *             error
 * @throws SQLException
 *             Whenever there is a database related error
 * 
 */
protected final void prepareRepository(final String repositoryPath, final Properties connectionProperties,
        final boolean dropTables, final boolean createTables, final String... definitionFiles)
        throws SQLException, IOException {

    final Map<String, String> connectionSettings = new HashMap<String, String>();

    for (final Iterator<Entry<Object, Object>> it = connectionProperties.entrySet().iterator(); it.hasNext();) {
        final Entry<Object, Object> entry = it.next();
        connectionSettings.put((String) entry.getKey(), (String) entry.getValue());

    }
    final RepositoryConfiguration repositoryConfiguration = new RepositoryConfiguration();

    repositoryConfiguration.setDebug(isDebug);
    repositoryConfiguration.createPropertiesByConfigurationLocation(configurationLocation);
    repositoryConfiguration.createFakeXADataSource(configurationLocation, connectionSettings);

    repositoryConfiguration.createRepositoryConfiguration(configurationLocation, repositoryPath, dropTables,
            createTables, definitionFiles);

    repositoryManager.initializeMinimalRepositoryConfiguration(configurationLocation, repositoryPath,
            connectionSettings, dropTables, isDebug, definitionFiles);
}

From source file:com.iorga.webappwatcher.RequestLogFilter.java

@SuppressWarnings("unchecked")
@Override//from  w w  w .  j a  va2 s .c  o  m
public void init(final FilterConfig filterConfig) throws ServletException {
    // Initializing context
    final CpuCriticalUsageWatcher cpuCriticalUsageWatcher = new CpuCriticalUsageWatcher();
    parametersContext.put(CpuCriticalUsageWatcher.class, cpuCriticalUsageWatcher);
    final WriteAllRequestsWatcher writeAllRequestsWatcher = new WriteAllRequestsWatcher();
    parametersContext.put(WriteAllRequestsWatcher.class, writeAllRequestsWatcher);
    final RequestDurationWatcher requestDurationWatcher = new RequestDurationWatcher();
    parametersContext.put(RequestDurationWatcher.class, requestDurationWatcher);
    final RetentionLogWritingWatcher retentionLogWritingWatcher = createRetentionLogWritingWatcher();
    parametersContext.put(RetentionLogWritingWatcher.class, retentionLogWritingWatcher);
    final EventLogManager eventLogManager = EventLogManager.getInstance();
    parametersContext.put(EventLogManager.class, eventLogManager);
    systemEventLogger = new SystemEventLogger();
    parametersContext.put(SystemEventLogger.class, systemEventLogger);
    parametersContext.put(RequestLogFilter.class, this);
    // by default, watch the CPU peaks, the request duration & write all requests to the log
    eventLogManager.setEventLogWatchers(Sets.newHashSet(cpuCriticalUsageWatcher, requestDurationWatcher,
            writeAllRequestsWatcher, retentionLogWritingWatcher));

    // Reading web.xml filterConfig init-params
    for (final String parameterName : (List<String>) Collections.list(filterConfig.getInitParameterNames())) {
        final String value = filterConfig.getInitParameter(parameterName);
        setParameter(parameterName, value);
    }
    // Reading "webappwatcher.properties" parameters
    try {
        final Properties properties = new Properties();
        final InputStream propertiesStream = getClass().getClassLoader()
                .getResourceAsStream("webappwatcher.properties");
        if (propertiesStream != null) {
            properties.load(propertiesStream);
            for (final Entry<Object, Object> property : properties.entrySet()) {
                setParameter((String) property.getKey(), (String) property.getValue());
            }
        }
    } catch (final IOException e) {
        throw new ServletException("Problem while reading webappwatcher.properties file", e);
    }

    startServices();
}

From source file:org.apache.camel.builder.xml.XPathBuilder.java

public XPathFactory getXPathFactory() throws XPathFactoryConfigurationException {
    if (xpathFactory == null) {
        if (objectModelUri != null) {
            LOG.info("Using objectModelUri " + objectModelUri + " when creating XPathFactory");
            xpathFactory = XPathFactory.newInstance(objectModelUri);
            return xpathFactory;
        }//  www .  j a v  a  2  s . co m

        // read system property and see if there is a factory set
        Properties properties = System.getProperties();
        for (Map.Entry prop : properties.entrySet()) {
            String key = (String) prop.getKey();
            if (key.startsWith(XPathFactory.DEFAULT_PROPERTY_NAME)) {
                String uri = ObjectHelper.after(key, ":");
                if (uri != null) {
                    LOG.info("Using system property " + key + " with value: " + prop.getValue()
                            + " when creating XPathFactory");
                    xpathFactory = XPathFactory.newInstance(uri);
                    return xpathFactory;
                }
            }
        }

        if (xpathFactory == null) {
            LOG.debug("Creating default XPathFactory");
            xpathFactory = XPathFactory.newInstance();
        }
    }
    return xpathFactory;
}

From source file:com.vaushell.superpipes.tools.scribe.fb.FacebookClient.java

private List<FB_Post> readFeedImpl(final String url, final Properties properties)
        throws IOException, FacebookException {
    if (url == null || properties == null) {
        throw new IllegalArgumentException();
    }/*w  ww  . j a  v  a  2  s.c o m*/

    final OAuthRequest request = new OAuthRequest(Verb.GET, url);
    for (final Entry<Object, Object> entry : properties.entrySet()) {
        request.addQuerystringParameter((String) entry.getKey(), (String) entry.getValue());
    }

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node);

    final List<FB_Post> posts = new ArrayList<>();

    final JsonNode nDatas = node.get("data");
    if (nDatas != null) {
        for (final JsonNode nData : nDatas) {
            posts.add(convertJsonToPost(nData));
        }
    }

    return posts;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.support.uima.AnalysisEngineFactory.java

/**
 * Create an AnalysisEngine from a .properties file.
 * /*from w  ww .  j  a  v a 2s . c  o  m*/
 * @param aSettingsFile
 *            filename of the file which specifies the options for the AE
 * @param aAdditionalParameters
 *            additional parameters for the AE
 * @return an AnalysisEngine with the specified parameters
 */
public static AnalysisEngine createAnalysisEngine(String aSettingsFile, Object... aAdditionalParameters)
        throws ResourceInitializationException {
    Properties options = new Properties();
    InputStream is = null;
    try {
        File settingsFile = new File(getSettingsPath(), aSettingsFile);
        // first look in the settings directory for the specified file
        if (settingsFile.exists()) {
            is = new FileInputStream(settingsFile);
            log.info("Loading AnalysisEngine from " + settingsFile.getAbsolutePath());
        }
        // if the file cannot be found, use the default file from the classpath
        else {
            is = ResourceUtils.resolveLocation("classpath:" + aSettingsFile).openStream();
            log.info("Loading AnalysisEngine from classpath:" + aSettingsFile);
        }
        options.load(is);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    // find class
    String classname;
    try {
        classname = (String) options.remove("classname");
    } catch (NullPointerException e) {
        throw new IllegalArgumentException(
                "The properties file needs a property [classname] whose value has to be the qualified pathname of the analysis engine class that should be used.");
    }

    // check for additional parameters
    if (aAdditionalParameters.length % 2 == 1) {
        throw new IllegalArgumentException("Illegal number of additional parameters ["
                + aAdditionalParameters.length + "], has to be an even amount.");
    }

    // create list of parameters
    List<Object> params = new ArrayList<Object>();
    for (Entry<Object, Object> param : options.entrySet()) {
        params.add(param.getKey());
        params.add(convert(param.getValue()));
    }
    for (Object adParam : aAdditionalParameters) {
        params.add(convert(adParam));
    }

    // create class
    Class<? extends AnalysisComponent> aeClass;
    try {
        aeClass = Class.forName(classname).asSubclass(AnalysisComponent.class);
    } catch (ClassNotFoundException e) {
        throw new ResourceInitializationException(e);
    }

    log.info("Creating AnalysisEngine [" + classname + "] with following options: "
            + StringUtils.join(params, ","));

    return createPrimitive(aeClass, params.toArray());
}

From source file:com.cloudera.sqoop.metastore.hsqldb.HsqldbJobStorage.java

private void setV0Properties(String jobName, String propClass, Properties properties) throws SQLException {
    LOG.debug("Job: " + jobName + "; Setting bulk properties for class " + propClass);

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = entry.getKey().toString();
        String val = entry.getValue().toString();
        setV0Property(jobName, propClass, key, val);
    }/*from w w w .  jav  a  2 s  .c o m*/
}

From source file:com.esri.geoportal.commons.pdf.PdfUtils.java

/**
 * Generates the list of "PARAMETER" entries in the WKT.
 * /*from w w w. ja v a  2  s .co  m*/
 * @param projectionDictionary the GeoPDF projection dictionary
 * 
 * @returns string of WKT parameters
 */
private static String generateWKTParameters(COSDictionary projectionDictionary) throws IOException {
    // Set up the projection parameters
    Properties parameters = new Properties();

    COSDictionaryMap<String, Object> dictionaryMap = COSDictionaryMap
            .convertBasicTypesToMap(projectionDictionary);

    if (projectionDictionary.containsKey("CentralMeridian")) {
        parameters.put("Central_Meridian", (String) dictionaryMap.get("CentralMeridian"));
    }
    if (projectionDictionary.containsKey("OriginLatitude")) {
        parameters.put("Latitude_Of_Origin", (String) dictionaryMap.get("OriginLatitude"));
    }
    if (projectionDictionary.containsKey("StandardParallelOne")) {
        parameters.put("Standard_Parallel_1", (String) dictionaryMap.get("StandardParallelOne"));
    }
    if (projectionDictionary.containsKey("StandardParallelTwo")) {
        parameters.put("Standard_Parallel_2", (String) dictionaryMap.get("StandardParallelTwo"));
    }
    if (projectionDictionary.containsKey("FalseEasting")) {
        parameters.put("False_Easting", (String) dictionaryMap.get("FalseEasting"));
    }
    if (projectionDictionary.containsKey("FalseNorthing")) {
        parameters.put("False_Northing", (String) dictionaryMap.get("FalseNorthing"));
    }
    if (projectionDictionary.containsKey("ScaleFactor")) {
        parameters.put("Scale_Factor", (String) dictionaryMap.get("ScaleFactor"));
    }

    return parameters.entrySet().stream()
            .map(entry -> "PARAMETER[\"" + entry.getKey() + "\", " + entry.getValue() + "]")
            .collect(Collectors.joining(","));
}

From source file:org.apache.ddlutils.TestSummaryCreatorTask.java

/**
 * Adds the data from the test jdbc propertis file to the document.
 * /*w ww.  j  a  v a  2  s .c o m*/
 * @param element            The element to add the relevant database properties to
 * @param jdbcPropertiesFile The path of the properties file
 */
protected void addTargetDatabaseInfo(Element element, String jdbcPropertiesFile)
        throws IOException, BuildException {
    if (jdbcPropertiesFile == null) {
        return;
    }

    Properties props = readProperties(jdbcPropertiesFile);
    Connection conn = null;
    DatabaseMetaData metaData = null;

    try {
        String dataSourceClass = props.getProperty(
                TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class",
                BasicDataSource.class.getName());
        DataSource dataSource = (DataSource) Class.forName(dataSourceClass).newInstance();

        for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String propName = (String) entry.getKey();

            if (propName.startsWith(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX)
                    && !propName.equals(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class")) {
                BeanUtils.setProperty(dataSource,
                        propName.substring(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX.length()),
                        entry.getValue());
            }
        }

        String platformName = props.getProperty(TestAgainstLiveDatabaseBase.DDLUTILS_PLATFORM_PROPERTY);

        if (platformName == null) {
            platformName = new PlatformUtils().determineDatabaseType(dataSource);
            if (platformName == null) {
                throw new BuildException(
                        "Could not determine platform from datasource, please specify it in the jdbc.properties via the ddlutils.platform property");
            }
        }

        element.addAttribute("platform", platformName);
        element.addAttribute("dataSourceClass", dataSourceClass);

        conn = dataSource.getConnection();
        metaData = conn.getMetaData();

        try {
            element.addAttribute("dbProductName", metaData.getDatabaseProductName());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("dbProductVersion", metaData.getDatabaseProductVersion());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            int databaseMajorVersion = metaData.getDatabaseMajorVersion();
            int databaseMinorVersion = metaData.getDatabaseMinorVersion();

            element.addAttribute("dbVersion", databaseMajorVersion + "." + databaseMinorVersion);
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("driverName", metaData.getDriverName());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("driverVersion", metaData.getDriverVersion());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            int jdbcMajorVersion = metaData.getJDBCMajorVersion();
            int jdbcMinorVersion = metaData.getJDBCMinorVersion();

            element.addAttribute("jdbcVersion", jdbcMajorVersion + "." + jdbcMinorVersion);
        } catch (Throwable ex) {
            // we ignore it
        }
    } catch (Exception ex) {
        throw new BuildException(ex);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                // we ignore it
            }
        }
    }
}

From source file:com.github.mrstampy.gameboot.messages.context.GameBootContextLoader.java

private void createError(String c, Properties p, Map<Integer, ResponseContext> map) {
    try {//from ww w. j  a v  a2s .c  o  m
        String keyPart = c.substring(0, c.length() - CODE.length());

        int code = Integer.parseInt(p.getProperty(c));
        String function = p.getProperty(keyPart + FUNCTION);
        String description = p.getProperty(keyPart + DESCRIPTION);

        log.trace("Creating error code {}, function {}, description '{}'", code, function, description);

        map.put(code, new ResponseContext(code, function, description));
    } catch (Exception e) {
        log.error("***********************************");
        log.error("Malformed error properties for code {}", c);
        log.error("***********************************");
        p.entrySet().forEach(f -> log.warn("{} = {}", f.getKey(), f.getValue()));
    }
}

From source file:org.jenkins.tools.test.PluginCompatTester.java

public PluginCompatReport testPlugins() throws PlexusContainerException, IOException, MavenEmbedderException {
    // Providing XSL Stylesheet along xml report file
    if (config.reportFile != null) {
        if (config.isProvideXslReport()) {
            File xslFilePath = PluginCompatReport.getXslFilepath(config.reportFile);
            FileUtils.copyStreamToFile(new RawInputStreamFacade(getXslTransformerResource().getInputStream()),
                    xslFilePath);/*from   w  w  w  .  j a  v  a  2 s  .com*/
        }
    }

    DataImporter dataImporter = null;
    if (config.getGaeBaseUrl() != null && config.getGaeSecurityToken() != null) {
        dataImporter = new DataImporter(config.getGaeBaseUrl(), config.getGaeSecurityToken());
    }

    HashMap<String, String> pluginGroupIds = new HashMap<String, String>(); // Used to track real plugin groupIds from WARs
    UpdateSite.Data data = config.getWar() == null ? extractUpdateCenterData()
            : scanWAR(config.getWar(), pluginGroupIds);
    PluginCompatReport report = PluginCompatReport.fromXml(config.reportFile);

    SortedSet<MavenCoordinates> testedCores = config.getWar() == null
            ? generateCoreCoordinatesToTest(data, report)
            : coreVersionFromWAR(data);

    MavenRunner.Config mconfig = new MavenRunner.Config();
    mconfig.userSettingsFile = config.getM2SettingsFile();
    // TODO REMOVE
    mconfig.userProperties.put("failIfNoTests", "false");
    mconfig.userProperties.put("argLine", "-XX:MaxPermSize=128m");
    String mavenPropertiesFilePath = this.config.getMavenPropertiesFile();
    if (StringUtils.isNotBlank(mavenPropertiesFilePath)) {
        File file = new File(mavenPropertiesFilePath);
        if (file.exists()) {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                Properties properties = new Properties();
                properties.load(fileInputStream);
                for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                    mconfig.userProperties.put((String) entry.getKey(), (String) entry.getValue());
                }
            } finally {
                IOUtils.closeQuietly(fileInputStream);
            }
        } else {
            System.out.println("File " + mavenPropertiesFilePath + " not exists");
        }
    }

    SCMManagerFactory.getInstance().start();
    for (MavenCoordinates coreCoordinates : testedCores) {
        System.out.println("Starting plugin tests on core coordinates : " + coreCoordinates.toString());
        for (Plugin plugin : data.plugins.values()) {
            if (config.getIncludePlugins() == null
                    || config.getIncludePlugins().contains(plugin.name.toLowerCase())) {
                PluginInfos pluginInfos = new PluginInfos(plugin.name, plugin.version, plugin.url);

                if (config.getExcludePlugins() != null
                        && config.getExcludePlugins().contains(plugin.name.toLowerCase())) {
                    System.out.println("Plugin " + plugin.name + " is in excluded plugins => test skipped !");
                    continue;
                }

                String errorMessage = null;
                TestStatus status = null;

                MavenCoordinates actualCoreCoordinates = coreCoordinates;
                PluginRemoting remote = new PluginRemoting(plugin.url);
                PomData pomData;
                try {
                    pomData = remote.retrievePomData();
                    System.out.println("detected parent POM " + pomData.parent.toGAV());
                    if ((pomData.parent.groupId.equals(PluginCompatTesterConfig.DEFAULT_PARENT_GROUP)
                            && pomData.parent.artifactId
                                    .equals(PluginCompatTesterConfig.DEFAULT_PARENT_ARTIFACT)
                            || pomData.parent.groupId.equals("org.jvnet.hudson.plugins"))
                            && coreCoordinates.version.matches("1[.][0-9]+[.][0-9]+")
                            && new VersionNumber(coreCoordinates.version)
                                    .compareTo(new VersionNumber("1.485")) < 0) { // TODO unless 1.480.3+
                        System.out.println("Cannot test against " + coreCoordinates.version
                                + " due to lack of deployed POM for " + coreCoordinates.toGAV());
                        actualCoreCoordinates = new MavenCoordinates(coreCoordinates.groupId,
                                coreCoordinates.artifactId,
                                coreCoordinates.version.replaceFirst("[.][0-9]+$", ""));
                    }
                } catch (Throwable t) {
                    status = TestStatus.INTERNAL_ERROR;
                    errorMessage = t.getMessage();
                    pomData = null;
                }

                if (!config.isSkipTestCache() && report.isCompatTestResultAlreadyInCache(pluginInfos,
                        actualCoreCoordinates, config.getTestCacheTimeout(), config.getCacheThresholStatus())) {
                    System.out.println(
                            "Cache activated for plugin " + pluginInfos.pluginName + " => test skipped !");
                    continue; // Don't do anything : we are in the cached interval ! :-)
                }

                List<String> warningMessages = new ArrayList<String>();
                if (errorMessage == null) {
                    try {
                        TestExecutionResult result = testPluginAgainst(actualCoreCoordinates, plugin, mconfig,
                                pomData, data.plugins, pluginGroupIds);
                        // If no PomExecutionException, everything went well...
                        status = TestStatus.SUCCESS;
                        warningMessages.addAll(result.pomWarningMessages);
                    } catch (PomExecutionException e) {
                        if (!e.succeededPluginArtifactIds.contains("maven-compiler-plugin")) {
                            status = TestStatus.COMPILATION_ERROR;
                        } else if (!e.succeededPluginArtifactIds.contains("maven-surefire-plugin")) {
                            status = TestStatus.TEST_FAILURES;
                        } else { // Can this really happen ???
                            status = TestStatus.SUCCESS;
                        }
                        errorMessage = e.getErrorMessage();
                        warningMessages.addAll(e.getPomWarningMessages());
                    } catch (Error e) {
                        // Rethrow the error ... something is getting wrong !
                        throw e;
                    } catch (Throwable t) {
                        status = TestStatus.INTERNAL_ERROR;
                        errorMessage = t.getMessage();
                    }
                }

                File buildLogFile = createBuildLogFile(config.reportFile, plugin.name, plugin.version,
                        actualCoreCoordinates);
                String buildLogFilePath = "";
                if (buildLogFile.exists()) {
                    buildLogFilePath = createBuildLogFilePathFor(pluginInfos.pluginName,
                            pluginInfos.pluginVersion, actualCoreCoordinates);
                }
                PluginCompatResult result = new PluginCompatResult(actualCoreCoordinates, status, errorMessage,
                        warningMessages, buildLogFilePath);
                report.add(pluginInfos, result);

                // Adding result to GAE
                if (dataImporter != null) {
                    dataImporter.importPluginCompatResult(result, pluginInfos,
                            config.reportFile.getParentFile());
                    // TODO: import log files
                }

                if (config.reportFile != null) {
                    if (!config.reportFile.exists()) {
                        FileUtils.fileWrite(config.reportFile.getAbsolutePath(), "");
                    }
                    report.save(config.reportFile);
                }
            } else {
                System.out.println("Plugin " + plugin.name + " not in included plugins => test skipped !");
            }
        }
    }

    // Generating HTML report if needed
    if (config.reportFile != null) {
        if (config.isGenerateHtmlReport()) {
            generateHtmlReportFile();
        }
    }

    return report;
}