Example usage for java.util Properties store

List of usage examples for java.util Properties store

Introduction

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

Prototype

public void store(OutputStream out, String comments) throws IOException 

Source Link

Document

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the #load(InputStream) load(InputStream) method.

Usage

From source file:gobblin.scheduler.JobConfigFileMonitorTest.java

@Test
public void testAddNewJobConfigFile() throws Exception {
    final Logger log = LoggerFactory.getLogger("testAddNewJobConfigFile");
    log.info("testAddNewJobConfigFile: start");
    AssertWithBackoff assertWithBackoff = AssertWithBackoff.create().logger(log).timeoutMs(15000);
    assertWithBackoff.assertEquals(new GetNumScheduledJobs(), 3, "3 scheduled jobs");

    /* Set a time gap, to let the monitor recognize the "3-file" status as old status,
    so that new added file can be discovered */
    Thread.sleep(1000);//from  w  ww . j  a va2  s. c o  m

    // Create a new job configuration file by making a copy of an existing
    // one and giving a different job name
    Properties jobProps = new Properties();
    jobProps.load(new FileReader(new File(this.jobConfigDir, "GobblinTest1.pull")));
    jobProps.setProperty(ConfigurationKeys.JOB_NAME_KEY, "Gobblin-test-new");
    this.newJobConfigFile = new File(this.jobConfigDir, "Gobblin-test-new.pull");
    jobProps.store(new FileWriter(this.newJobConfigFile), null);

    assertWithBackoff.assertEquals(new GetNumScheduledJobs(), 4, "4 scheduled jobs");

    Set<String> jobNames = Sets.newHashSet(this.jobScheduler.getScheduledJobs());
    Set<String> expectedJobNames = ImmutableSet.<String>builder()
            .add("GobblinTest1", "GobblinTest2", "GobblinTest3", "Gobblin-test-new").build();

    Assert.assertEquals(jobNames, expectedJobNames);
    log.info("testAddNewJobConfigFile: end");
}

From source file:com.alibaba.antx.config.resource.DefaultAuthenticationHandler.java

private boolean savePasswordFile(Properties passwords) throws IOException, FileNotFoundException {
    File tmp = File.createTempFile(passwordFile.getName() + ".", ".tmp", passwordFile.getParentFile());
    OutputStream os = null;/*ww w  . j a  v  a  2  s. c  om*/

    tmp.deleteOnExit();

    try {
        os = new FileOutputStream(tmp);
        passwords.store(os, "Passwords for antxconfig");
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
            }
        }
    }

    passwordFile.delete();

    return tmp.renameTo(passwordFile);
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Write the properties object to the specified string file path.
 *
 * @param properties an instance of a {@link java.util.Properties} object.
 * @param path       the  {@link java.nio.file.Path} that the properties will be written to.
 * @param message    the message that is included in the header of properties files.
 * @throws IOException an {@link java.io.IOException} if their was a problem writing to the file.
 */// w w w.j a v a  2 s. co  m
default void writeToFile(Properties properties, Path path, String message) throws IOException {
    Validate.notNull(properties);
    Validate.notNull(path);
    Validate.notNull(message);
    System.out.println(path);

    Files.deleteIfExists(path);

    try {

        properties.store(Files.newBufferedWriter(path, Charset.defaultCharset()), message);
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

}

From source file:de.tudarmstadt.ukp.dkpro.core.performance.Stopwatch.java

@Override
public void collectionProcessComplete() throws AnalysisEngineProcessException {
    super.collectionProcessComplete();

    if (isDownstreamTimer()) {
        getLogger().info("Results from Timer '" + timerName + "' after processing all documents.");

        DescriptiveStatistics statTimes = new DescriptiveStatistics();
        for (Long timeValue : times) {
            statTimes.addValue((double) timeValue / 1000);
        }//from w w w. j ava  2 s.  c o  m
        double sum = statTimes.getSum();
        double mean = statTimes.getMean();
        double stddev = statTimes.getStandardDeviation();

        StringBuilder sb = new StringBuilder();
        sb.append("Estimate after processing " + times.size() + " documents.");
        sb.append("\n");

        Formatter formatter = new Formatter(sb, Locale.US);

        formatter.format("Aggregated time: %,.1fs\n", sum);
        formatter.format("Time / Document: %,.3fs (%,.3fs)\n", mean, stddev);

        formatter.close();

        getLogger().info(sb.toString());

        if (outputFile != null) {
            try {
                Properties props = new Properties();
                props.setProperty(KEY_SUM, "" + sum);
                props.setProperty(KEY_MEAN, "" + mean);
                props.setProperty(KEY_STDDEV, "" + stddev);
                OutputStream out = new FileOutputStream(outputFile);
                props.store(out, "timer " + timerName + " result file");
            } catch (FileNotFoundException e) {
                throw new AnalysisEngineProcessException(e);
            } catch (IOException e) {
                throw new AnalysisEngineProcessException(e);
            }
        }
    }
}

From source file:gobblin.runtime.job_catalog.FSJobCatalogHelperTest.java

@BeforeClass
public void setUp() throws IOException {
    this.jobConfigDir = java.nio.file.Files
            .createTempDirectory(String.format("gobblin-test_%s_job-conf", this.getClass().getSimpleName()))
            .toFile();/*from  ww w  .j a v a  2 s .c om*/
    FileUtils.forceDeleteOnExit(this.jobConfigDir);
    this.subDir1 = new File(this.jobConfigDir, "test1");
    this.subDir11 = new File(this.subDir1, "test11");
    this.subDir2 = new File(this.jobConfigDir, "test2");

    this.subDir1.mkdirs();
    this.subDir11.mkdirs();
    this.subDir2.mkdirs();

    this.sysConfig = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
            .put(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY, this.jobConfigDir.getAbsolutePath())
            .build());
    ImmutableFSJobCatalog.ConfigAccessor cfgAccess = new ImmutableFSJobCatalog.ConfigAccessor(this.sysConfig);
    this.loader = new PullFileLoader(new Path(jobConfigDir.toURI()), FileSystem.get(new Configuration()),
            cfgAccess.getJobConfigurationFileExtensions(), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS);
    this.converter = new ImmutableFSJobCatalog.JobSpecConverter(new Path(this.jobConfigDir.toURI()),
            Optional.of(FSJobCatalog.CONF_EXTENSION));

    Properties rootProps = new Properties();
    rootProps.setProperty("k1", "a1");
    rootProps.setProperty("k2", "a2");
    // test-job-conf-dir/root.properties
    rootProps.store(new FileWriter(new File(this.jobConfigDir, "root.properties")), "");

    Properties jobProps1 = new Properties();
    jobProps1.setProperty("k1", "c1");
    jobProps1.setProperty("k3", "b3");
    jobProps1.setProperty("k6", "a6");
    // test-job-conf-dir/test1/test11.pull
    jobProps1.store(new FileWriter(new File(this.subDir1, "test11.pull")), "");

    Properties jobProps2 = new Properties();
    jobProps2.setProperty("k7", "a7");
    // test-job-conf-dir/test1/test12.PULL
    jobProps2.store(new FileWriter(new File(this.subDir1, "test12.PULL")), "");

    Properties jobProps3 = new Properties();
    jobProps3.setProperty("k1", "d1");
    jobProps3.setProperty("k8", "a8");
    jobProps3.setProperty("k9", "${k8}");
    // test-job-conf-dir/test1/test11/test111.pull
    jobProps3.store(new FileWriter(new File(this.subDir11, "test111.pull")), "");

    Properties props2 = new Properties();
    props2.setProperty("k2", "b2");
    props2.setProperty("k5", "a5");
    // test-job-conf-dir/test2/test.properties
    props2.store(new FileWriter(new File(this.subDir2, "test.PROPERTIES")), "");

    Properties jobProps4 = new Properties();
    jobProps4.setProperty("k5", "b5");
    // test-job-conf-dir/test2/test21.PULL
    jobProps4.store(new FileWriter(new File(this.subDir2, "test21.PULL")), "");
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.SaveModelUtils.java

public static void writeModelParameters(TaskContext aContext, File aOutputFolder, List<String> aFeatureSet,
        List<Object> aFeatureParameters) throws Exception {
    // write meta collector data
    // automatically determine the required metaCollector classes from the
    // provided feature
    // extractors
    Set<Class<? extends MetaCollector>> metaCollectorClasses;
    try {//  w ww.java  2s  .com
        metaCollectorClasses = TaskUtils.getMetaCollectorsFromFeatureExtractors(aFeatureSet);
    } catch (ClassNotFoundException e) {
        throw new ResourceInitializationException(e);
    } catch (InstantiationException e) {
        throw new ResourceInitializationException(e);
    } catch (IllegalAccessException e) {
        throw new ResourceInitializationException(e);
    }

    // collect parameter/key pairs that need to be set
    Map<String, String> metaParameterKeyPairs = new HashMap<String, String>();
    for (Class<? extends MetaCollector> metaCollectorClass : metaCollectorClasses) {
        try {
            metaParameterKeyPairs.putAll(metaCollectorClass.newInstance().getParameterKeyPairs());
        } catch (InstantiationException e) {
            throw new ResourceInitializationException(e);
        } catch (IllegalAccessException e) {
            throw new ResourceInitializationException(e);
        }
    }

    Properties parameterProperties = new Properties();
    for (Entry<String, String> entry : metaParameterKeyPairs.entrySet()) {
        File file = new File(aContext.getStorageLocation(META_KEY, AccessMode.READWRITE), entry.getValue());

        String name = file.getName();
        String subFolder = aOutputFolder.getAbsoluteFile() + "/" + name;
        File targetFolder = new File(subFolder);
        copyToTargetLocation(file, targetFolder);
        parameterProperties.put(entry.getKey(), name);

        // should never be reached
    }

    for (int i = 0; i < aFeatureParameters.size(); i = i + 2) {

        String key = (String) aFeatureParameters.get(i).toString();
        String value = aFeatureParameters.get(i + 1).toString();

        if (valueExistAsFileOrFolderInTheFileSystem(value)) {
            String name = new File(value).getName();
            String destination = aOutputFolder + "/" + name;
            copyToTargetLocation(new File(value), new File(destination));
            parameterProperties.put(key, name);
            continue;
        }
        parameterProperties.put(key, value);
    }

    FileWriter writer = new FileWriter(new File(aOutputFolder, MODEL_PARAMETERS));
    parameterProperties.store(writer, "");
    writer.close();
}

From source file:gobblin.util.SchedulerUtilsTest.java

@BeforeClass
public void setUp() throws IOException {
    this.jobConfigDir = java.nio.file.Files
            .createTempDirectory(String.format("gobblin-test_%s_job-conf", this.getClass().getSimpleName()))
            .toFile();/* w ww  . j  a va 2s  .c om*/
    FileUtils.forceDeleteOnExit(this.jobConfigDir);
    this.subDir1 = new File(this.jobConfigDir, "test1");
    this.subDir11 = new File(this.subDir1, "test11");
    this.subDir2 = new File(this.jobConfigDir, "test2");

    this.subDir1.mkdirs();
    this.subDir11.mkdirs();
    this.subDir2.mkdirs();

    Properties rootProps = new Properties();
    rootProps.setProperty("k1", "a1");
    rootProps.setProperty("k2", "a2");
    // test-job-conf-dir/root.properties
    rootProps.store(new FileWriter(new File(this.jobConfigDir, "root.properties")), "");

    Properties props1 = new Properties();
    props1.setProperty("k1", "b1");
    props1.setProperty("k3", "a3");
    // test-job-conf-dir/test1/test.properties
    props1.store(new FileWriter(new File(this.subDir1, "test.properties")), "");

    Properties jobProps1 = new Properties();
    jobProps1.setProperty("k1", "c1");
    jobProps1.setProperty("k3", "b3");
    jobProps1.setProperty("k6", "a6");
    // test-job-conf-dir/test1/test11.pull
    jobProps1.store(new FileWriter(new File(this.subDir1, "test11.pull")), "");

    Properties jobProps2 = new Properties();
    jobProps2.setProperty("k7", "a7");
    // test-job-conf-dir/test1/test12.PULL
    jobProps2.store(new FileWriter(new File(this.subDir1, "test12.PULL")), "");

    Properties jobProps3 = new Properties();
    jobProps3.setProperty("k1", "d1");
    jobProps3.setProperty("k8", "a8");
    jobProps3.setProperty("k9", "${k8}");
    // test-job-conf-dir/test1/test11/test111.pull
    jobProps3.store(new FileWriter(new File(this.subDir11, "test111.pull")), "");

    Properties props2 = new Properties();
    props2.setProperty("k2", "b2");
    props2.setProperty("k5", "a5");
    // test-job-conf-dir/test2/test.properties
    props2.store(new FileWriter(new File(this.subDir2, "test.PROPERTIES")), "");

    Properties jobProps4 = new Properties();
    jobProps4.setProperty("k5", "b5");
    // test-job-conf-dir/test2/test21.PULL
    jobProps4.store(new FileWriter(new File(this.subDir2, "test21.PULL")), "");
}

From source file:com.netspective.medigy.model.TestCase.java

protected HibernateConfiguration getHibernateConfiguration()
        throws HibernateException, FileNotFoundException, IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Properties logProperties = new Properties();
    logProperties.setProperty("handlers", "java.util.logging.ConsoleHandler");
    logProperties.setProperty("java.util.logging.ConsoleHandler.formatter",
            "java.util.logging.SimpleFormatter");
    logProperties.setProperty("org.hibernate.level", "WARNING");
    logProperties.store(out, "Generated by " + TestCase.class.getName());
    LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(out.toByteArray()));

    final HibernateConfiguration config = new HibernateConfiguration();

    final Properties hibProperties = new Properties();
    hibProperties.setProperty(Environment.DIALECT, HSQLDialect.class.getName());
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".driver_class", "org.hsqldb.jdbcDriver");
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".url",
            "jdbc:hsqldb:" + databaseDirectory + "/db");
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".username", "sa");
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".password", "");
    hibProperties.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    hibProperties.setProperty(Environment.SHOW_SQL, "false");
    config.addProperties(hibProperties);

    for (final Class c : com.netspective.medigy.reference.Catalog.ALL_REFERENCE_TYPES)
        config.addAnnotatedClass(c);//from ww  w.  j  a v  a  2 s  .  c  om

    try {
        config.configure("com/netspective/medigy/hibernate.cfg.xml");
    } catch (HibernateException e) {
        log.error(e);
        throw new RuntimeException(e);
    }
    config.registerReferenceEntitiesAndCaches();
    return config;
}

From source file:com.thoughtworks.go.agent.service.AgentAutoRegistrationPropertiesTest.java

@Test
public void shouldReturnAgentAutoRegisterPropertiesIfPresent() throws Exception {
    Properties properties = new Properties();

    properties.put(AgentAutoRegistrationProperties.AGENT_AUTO_REGISTER_KEY, "foo");
    properties.put(AgentAutoRegistrationProperties.AGENT_AUTO_REGISTER_RESOURCES, "foo, zoo");
    properties.put(AgentAutoRegistrationProperties.AGENT_AUTO_REGISTER_ENVIRONMENTS, "foo, bar");
    properties.put(AgentAutoRegistrationProperties.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");
    properties.store(new FileOutputStream(configFile), "");

    AgentAutoRegistrationProperties reader = new AgentAutoRegistrationProperties(configFile);
    assertThat(reader.agentAutoRegisterKey(), is("foo"));
    assertThat(reader.agentAutoRegisterResources(), is("foo, zoo"));
    assertThat(reader.agentAutoRegisterEnvironments(), is("foo, bar"));
    assertThat(reader.agentAutoRegisterHostname(), is("agent01.example.com"));
}

From source file:com.logsniffer.util.value.support.PropertiesBasedSource.java

@Override
public void store(final String key, final String value) throws IOException {
    if (value != null) {
        logsnifferProperties.setProperty(key, value);
    } else {//from w  ww. ja  v a 2 s . c o m
        logsnifferProperties.remove(key);
    }
    File file = new File(homeDir.getHomeDir(), CoreAppConfig.LOGSNIFFER_PROPERTIES_FILE);
    LOGGER.info("Saving config value for key '{}' to file: {}", key, file.getAbsolutePath());
    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream(file));
    } catch (IOException e) {
        LOGGER.warn("Failed to load current properties from file, continue with empty properties: "
                + file.getAbsolutePath(), e);
    }
    if (value != null) {
        properties.setProperty(key, value);
    } else {
        properties.remove(key);
    }
    properties.store(new FileOutputStream(file), null);
}