Example usage for java.util Properties putAll

List of usage examples for java.util Properties putAll

Introduction

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

Prototype

@Override
    public synchronized void putAll(Map<?, ?> t) 

Source Link

Usage

From source file:org.mitre.dsmiley.httpproxy.ProxyServletTest.java

protected void setUpServlet(Properties servletProps) {
    servletProps.putAll(servletProps);
    targetBaseUri = "http://localhost:" + localTestServer.getServiceAddress().getPort() + "/targetPath";
    servletProps.setProperty("targetUri", targetBaseUri);
    servletRunner.registerServlet(servletPath + "/*", servletName, servletProps);//also matches /proxyMe (no path info)
    sourceBaseUri = "http://localhost/proxyMe";//localhost:0 is hard-coded in ServletUnitHttpRequest
}

From source file:esg.gateway.service.ESGAccessLogServiceImpl.java

/**
   Initializes the service by setting up the database connection and result handling.
*///w  ww.j a  v a2s  . c om
public void init() {
    Properties props = new Properties();
    props.setProperty("db.protocol", "jdbc:postgresql:");
    props.setProperty("db.host", "localhost");
    props.setProperty("db.port", "5432");
    props.setProperty("db.database", "esgcet");
    props.setProperty("db.user", "dbsuper");
    props.setProperty("db.password", "changeme");
    try {
        props.putAll(new ESGFProperties());
    } catch (IOException ex) {
        log.error(ex);
    }

    queryRunner = new QueryRunner(DatabaseResource.init(props.getProperty("db.driver", "org.postgresql.Driver"))
            .setupDataSource(props).getDataSource());

    resultSetHandler = new ResultSetHandler<List<String[]>>() {
        public List<String[]> handle(ResultSet rs) throws SQLException {
            ArrayList<String[]> results = new ArrayList<String[]>();
            String[] record = null;
            assert (null != results);

            ResultSetMetaData meta = rs.getMetaData();
            int cols = meta.getColumnCount();
            log.trace("Number of fields: " + cols);

            log.trace("adding column data...");
            record = new String[cols];
            for (int i = 0; i < cols; i++) {
                try {
                    record[i] = meta.getColumnLabel(i + 1) + "|" + meta.getColumnType(i + 1);
                } catch (SQLException e) {
                    log.error(e);
                }
            }
            results.add(record);

            for (int i = 0; rs.next(); i++) {
                log.trace("Looking at record " + (i + 1));
                record = new String[cols];
                for (int j = 0; j < cols; j++) {
                    record[j] = rs.getString(j + 1);
                    log.trace("gathering result record column " + (j + 1) + " -> " + record[j]);
                }
                log.trace("adding record ");
                results.add(record);
                record = null; //gc courtesy
            }
            return results;
        }
    };
    log.trace("initialization complete");
}

From source file:org.codelibs.fess.job.CrawlJob.java

protected void executeCrawler() {
    final List<String> cmdList = new ArrayList<>();
    final String cpSeparator = SystemUtils.IS_OS_WINDOWS ? ";" : ":";
    final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
    final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
    final ProcessHelper processHelper = ComponentUtil.getProcessHelper();
    final FessConfig fessConfig = ComponentUtil.getFessConfig();

    cmdList.add(fessConfig.getJavaCommandPath());

    // -cp/* w  w  w.  j a  v a 2  s . c  o  m*/
    cmdList.add("-cp");
    final StringBuilder buf = new StringBuilder(100);
    ResourceUtil.getOverrideConfPath().ifPresent(p -> {
        buf.append(p);
        buf.append(cpSeparator);
    });
    final String confPath = System.getProperty(Constants.FESS_CONF_PATH);
    if (StringUtil.isNotBlank(confPath)) {
        buf.append(confPath);
        buf.append(cpSeparator);
    }
    // WEB-INF/env/crawler/resources
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("env");
    buf.append(File.separator);
    buf.append("crawler");
    buf.append(File.separator);
    buf.append("resources");
    buf.append(cpSeparator);
    // WEB-INF/classes
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("classes");
    // target/classes
    final String userDir = System.getProperty("user.dir");
    final File targetDir = new File(userDir, "target");
    final File targetClassesDir = new File(targetDir, "classes");
    if (targetClassesDir.isDirectory()) {
        buf.append(cpSeparator);
        buf.append(targetClassesDir.getAbsolutePath());
    }
    // WEB-INF/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/lib")),
            "WEB-INF" + File.separator + "lib" + File.separator);
    // WEB-INF/env/crawler/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/crawler/lib")), "WEB-INF"
            + File.separator + "env" + File.separator + "crawler" + File.separator + "lib" + File.separator);
    final File targetLibDir = new File(targetDir, "fess" + File.separator + "WEB-INF" + File.separator + "lib");
    if (targetLibDir.isDirectory()) {
        appendJarFile(cpSeparator, buf, targetLibDir, targetLibDir.getAbsolutePath() + File.separator);
    }
    cmdList.add(buf.toString());

    if (useLocalElasticsearch) {
        final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
        if (StringUtil.isNotBlank(httpAddress)) {
            cmdList.add("-D" + Constants.FESS_ES_HTTP_ADDRESS + "=" + httpAddress);
        }
    }

    final String systemLastaEnv = System.getProperty("lasta.env");
    if (StringUtil.isNotBlank(systemLastaEnv)) {
        if (systemLastaEnv.equals("web")) {
            cmdList.add("-Dlasta.env=crawler");
        } else {
            cmdList.add("-Dlasta.env=" + systemLastaEnv);
        }
    } else if (StringUtil.isNotBlank(lastaEnv)) {
        cmdList.add("-Dlasta.env=" + lastaEnv);
    }

    addSystemProperty(cmdList, Constants.FESS_CONF_PATH, null, null);
    cmdList.add("-Dfess.crawler.process=true");
    cmdList.add("-Dfess.log.path=" + (logFilePath != null ? logFilePath : systemHelper.getLogFilePath()));
    addSystemProperty(cmdList, "fess.log.name", "fess-crawler", "-crawler");
    if (logLevel == null) {
        addSystemProperty(cmdList, "fess.log.level", null, null);
    } else {
        cmdList.add("-Dfess.log.level=" + logLevel);
        if (logLevel.equalsIgnoreCase("debug")) {
            cmdList.add("-Dorg.apache.tika.service.error.warn=true");
        }
    }
    stream(fessConfig.getJvmCrawlerOptionsAsArray())
            .of(stream -> stream.filter(StringUtil::isNotBlank).forEach(value -> cmdList.add(value)));

    File ownTmpDir = null;
    final String tmpDir = System.getProperty("java.io.tmpdir");
    if (fessConfig.isUseOwnTmpDir() && StringUtil.isNotBlank(tmpDir)) {
        ownTmpDir = new File(tmpDir, "fessTmpDir_" + sessionId);
        if (ownTmpDir.mkdirs()) {
            cmdList.add("-Djava.io.tmpdir=" + ownTmpDir.getAbsolutePath());
            cmdList.add("-Dpdfbox.fontcache=" + ownTmpDir.getAbsolutePath());
        } else {
            ownTmpDir = null;
        }
    }

    cmdList.add(ComponentUtil.getThumbnailManager().getThumbnailPathOption());

    if (StringUtil.isNotBlank(jvmOptions)) {
        split(jvmOptions, " ").of(stream -> stream.filter(StringUtil::isNotBlank).forEach(s -> cmdList.add(s)));
    }

    cmdList.add(Crawler.class.getCanonicalName());

    cmdList.add("--sessionId");
    cmdList.add(sessionId);
    cmdList.add("--name");
    cmdList.add(namespace);

    if (webConfigIds != null && webConfigIds.length > 0) {
        cmdList.add("-w");
        cmdList.add(StringUtils.join(webConfigIds, ','));
    }
    if (fileConfigIds != null && fileConfigIds.length > 0) {
        cmdList.add("-f");
        cmdList.add(StringUtils.join(fileConfigIds, ','));
    }
    if (dataConfigIds != null && dataConfigIds.length > 0) {
        cmdList.add("-d");
        cmdList.add(StringUtils.join(dataConfigIds, ','));
    }
    if (documentExpires >= -1) {
        cmdList.add("-e");
        cmdList.add(Integer.toString(documentExpires));
    }

    File propFile = null;
    try {
        cmdList.add("-p");
        propFile = File.createTempFile("crawler_", ".properties");
        cmdList.add(propFile.getAbsolutePath());
        try (FileOutputStream out = new FileOutputStream(propFile)) {
            final Properties prop = new Properties();
            prop.putAll(ComponentUtil.getSystemProperties());
            prop.store(out, cmdList.toString());
        }

        final File baseDir = new File(servletContext.getRealPath("/WEB-INF")).getParentFile();

        if (logger.isInfoEnabled()) {
            logger.info("Crawler: \nDirectory=" + baseDir + "\nOptions=" + cmdList);
        }

        final JobProcess jobProcess = processHelper.startProcess(sessionId, cmdList, pb -> {
            pb.directory(baseDir);
            pb.redirectErrorStream(true);
        });

        final InputStreamThread it = jobProcess.getInputStreamThread();
        it.start();

        final Process currentProcess = jobProcess.getProcess();
        currentProcess.waitFor();
        it.join(5000);

        final int exitValue = currentProcess.exitValue();

        if (logger.isInfoEnabled()) {
            logger.info("Crawler: Exit Code=" + exitValue + " - Crawler Process Output:\n" + it.getOutput());
        }
        if (exitValue != 0) {
            throw new FessSystemException("Exit Code: " + exitValue + "\nOutput:\n" + it.getOutput());
        }
    } catch (final FessSystemException e) {
        throw e;
    } catch (final InterruptedException e) {
        logger.warn("Crawler Process interrupted.");
    } catch (final Exception e) {
        throw new FessSystemException("Crawler Process terminated.", e);
    } finally {
        try {
            processHelper.destroyProcess(sessionId);
        } finally {
            if (propFile != null && !propFile.delete()) {
                logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
            }
            deleteTempDir(ownTmpDir);
        }
    }
}

From source file:org.apache.flink.api.java.utils.ParameterTool.java

/**
 * Create a properties file with all the known parameters (call after the last get*() call).
 * Set the default value, if overwrite is true.
 *
 * @param pathToFile Location of the default properties file.
 * @param overwrite Boolean flag indicating whether or not to overwrite the file
 * @throws IOException If overwrite is not allowed and the file exists
 *//*ww  w .j  a v  a 2s  .  c o  m*/
public void createPropertiesFile(String pathToFile, boolean overwrite) throws IOException {
    File file = new File(pathToFile);
    if (file.exists()) {
        if (overwrite) {
            file.delete();
        } else {
            throw new RuntimeException("File " + pathToFile + " exists and overwriting is not allowed");
        }
    }
    Properties defaultProps = new Properties();
    defaultProps.putAll(this.defaultData);
    try (final OutputStream out = new FileOutputStream(file)) {
        defaultProps.store(out, "Default file created by Flink's ParameterUtil.createPropertiesFile()");
    }
}

From source file:org.owasp.webgoat.i18n.PluginMessages.java

@Override
@SneakyThrows/*from w w  w.ja v  a 2 s  . com*/
protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) {
    Properties properties = new Properties();
    long lastModified = System.currentTimeMillis();

    Enumeration<URL> resources = Thread.currentThread().getContextClassLoader()
            .getResources(filename + PROPERTIES_SUFFIX);
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        String sourcePath = resource.toURI().toString().replace(PROPERTIES_SUFFIX, "");
        PropertiesHolder holder = super.refreshProperties(sourcePath, propHolder);
        properties.putAll(holder.getProperties());
    }
    return new PropertiesHolder(properties, lastModified);
}

From source file:org.apache.falcon.entity.FileSystemStorage.java

@Override
@SuppressWarnings("MagicConstant")
public List<FeedInstanceStatus> getListing(Feed feed, String clusterName, LocationType locationType, Date start,
        Date end) throws FalconException {

    Calendar calendar = Calendar.getInstance();
    List<Location> clusterSpecificLocation = FeedHelper.getLocations(FeedHelper.getCluster(feed, clusterName),
            feed);//from  w  w w.  j  a v a  2s  .  c  om
    Location location = getLocation(clusterSpecificLocation, locationType);
    try {
        FileSystem fileSystem = HadoopClientFactory.get().createProxiedFileSystem(getConf());
        Cluster cluster = ClusterHelper.getCluster(clusterName);
        Properties baseProperties = FeedHelper.getClusterProperties(cluster);
        baseProperties.putAll(FeedHelper.getFeedProperties(feed));
        List<FeedInstanceStatus> instances = new ArrayList<FeedInstanceStatus>();
        Date feedStart = FeedHelper.getCluster(feed, clusterName).getValidity().getStart();
        TimeZone tz = feed.getTimezone();
        Date alignedStart = EntityUtil.getNextStartTime(feedStart, feed.getFrequency(), tz, start);

        String basePath = location.getPath();
        while (!end.before(alignedStart)) {
            Properties allProperties = ExpressionHelper.getTimeVariables(alignedStart, tz);
            allProperties.putAll(baseProperties);
            String feedInstancePath = ExpressionHelper.substitute(basePath, allProperties);
            FileStatus fileStatus = getFileStatus(fileSystem, new Path(feedInstancePath));
            FeedInstanceStatus instance = new FeedInstanceStatus(feedInstancePath);

            Date date = FeedHelper.getDate(basePath, new Path(feedInstancePath), tz);
            instance.setInstance(SchemaHelper.formatDateUTC(date));
            if (fileStatus != null) {
                instance.setCreationTime(fileStatus.getModificationTime());
                ContentSummary contentSummary = fileSystem.getContentSummary(fileStatus.getPath());
                if (contentSummary != null) {
                    long size = contentSummary.getSpaceConsumed();
                    instance.setSize(size);
                    if (!StringUtils.isEmpty(feed.getAvailabilityFlag())) {
                        FileStatus doneFile = getFileStatus(fileSystem,
                                new Path(fileStatus.getPath(), feed.getAvailabilityFlag()));
                        if (doneFile != null) {
                            instance.setStatus(FeedInstanceStatus.AvailabilityStatus.AVAILABLE);
                        } else {
                            instance.setStatus(FeedInstanceStatus.AvailabilityStatus.PARTIAL);
                        }
                    } else {
                        instance.setStatus(size > 0 ? FeedInstanceStatus.AvailabilityStatus.AVAILABLE
                                : FeedInstanceStatus.AvailabilityStatus.EMPTY);
                    }
                }
            }
            instances.add(instance);
            calendar.setTime(alignedStart);
            calendar.add(feed.getFrequency().getTimeUnit().getCalendarUnit(),
                    feed.getFrequency().getFrequencyAsInt());
            alignedStart = calendar.getTime();
        }
        return instances;
    } catch (IOException e) {
        LOG.error("Unable to retrieve listing for {}:{}", locationType, getStorageUrl(), e);
        throw new FalconException("Unable to retrieve listing for (URI " + getStorageUrl() + ")", e);
    }
}

From source file:net.grinder.engine.agent.AgentImplementationEx.java

private Properties rebaseSystemClassPath(Properties properties, File curDir) {
    Properties newProperties = new Properties();
    newProperties.putAll(properties);
    StringBuilder newClassPath = new StringBuilder();
    boolean isFirst = true;
    for (String each : StringUtils.split(properties.getProperty("java.class.path"), File.pathSeparator)) {
        File file = new File(each);
        if (!file.isAbsolute()) {
            file = new File(curDir, each);
        }//from   w ww .  j a  va 2 s.com
        if (!isFirst) {
            newClassPath.append(File.pathSeparator);
        }
        isFirst = false;
        newClassPath.append(FilenameUtils.normalize(file.getAbsolutePath()));
    }
    newProperties.put("java.class.path", newClassPath.toString());
    return newProperties;
}

From source file:eu.dnetlib.maven.plugin.properties.WritePredefinedProjectProperties.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Properties properties = new Properties();
    // Add project properties
    properties.putAll(project.getProperties());
    if (includeEnvironmentVariables) {
        // Add environment variables, overriding any existing properties with the same key
        properties.putAll(getEnvironmentVariables());
    }//  www . ja  v a2 s .co m
    if (includeSystemProperties) {
        // Add system properties, overriding any existing properties with the same key
        properties.putAll(System.getProperties());
    }

    // Remove properties as appropriate
    trim(properties, exclude, include);

    String comment = "# " + new Date() + "\n";
    List<String> escapeTokens = getEscapeChars(escapeChars);
    if (antEchoPropertiesMode) {
        escapeTokens = Arrays.asList(ANT_ESCAPE_CHARS);
        comment = getAntHeader();
        properties.remove("DSTAMP");
        properties.remove("TODAY");
        properties.remove("TSTAMP");
    }

    getLog().info("Creating " + outputFile);
    writeProperties(outputFile, comment, properties, escapeTokens);
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

/**
 * Proxy configuration for this connection.
 * <p>/*w w  w  . j  a  va2  s  .  c o  m*/
 * Configure the proxy if specified in the connection and set proxy authentication data
 * from user settings.
 * @param credsProvider the credential provider to fill.
 */
@objid("e106d3cf-c3a2-4cea-9fcf-f405317e705f")
private void configProxy(CredentialsProvider credsProvider) {
    // currently not used : allow auth data to specify proxy
    if (this.auth != null) {
        Map<String, String> data = this.auth.getData();
        if (data != null) {
            if (data.containsKey("http.proxyHost")) {
                String host = data.get("http.proxyHost");
                int port = Integer.parseInt(data.get("http.proxyPort"));

                HttpHost proxy = new HttpHost(host, port);
                this.configBuilder.setProxy(proxy);

                final Properties props = new Properties();
                props.putAll(data);

                configProxyCredentials(props, "http", credsProvider);
            }
        }
    }

    // Setup proxy authentication from system properties set by Eclipse
    // see : org.eclipse.core.internal.net.ProxyType
    configProxyCredentials(System.getProperties(), "http", credsProvider);
    configProxyCredentials(System.getProperties(), "https", credsProvider);
}

From source file:com.github.jengelman.gradle.plugins.integration.TestFile.java

public void writeProperties(Map<?, ?> properties) {
    Properties props = new Properties();
    props.putAll(properties);
    try {//from w  w w . j a v  a2 s .c  om
        FileOutputStream stream = new FileOutputStream(this);
        try {
            props.store(stream, "comment");
        } finally {
            stream.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}