Example usage for java.util Properties put

List of usage examples for java.util Properties put

Introduction

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

Prototype

@Override
    public synchronized Object put(Object key, Object value) 

Source Link

Usage

From source file:gobblin.util.test.RetentionTestHelper.java

/**
*
* Does gobblin retention for test data. {@link DatasetCleaner} which does retention in production can not be directly called as we need to resolve some
* runtime properties like ${testNameTempPath}. This directory contains all the setup data created for a test by {@link RetentionTestDataGenerator#setup()}.
* It is unique for each test./*from  ww w  . j av  a2 s  . c o m*/
* The default {@link ConfigClient} used by {@link DatasetCleaner} connects to config store configs. We need to provide a
* mock {@link ConfigClient} since the configs are in classpath and not on config store.
*
* @param retentionConfigClasspathResource this is the same jobProps/config files used while running a real retention job
* @param testNameTempPath temp path for this test where test data is generated
*/
public static void clean(FileSystem fs, Path retentionConfigClasspathResource,
        Optional<Path> additionalJobPropsClasspathResource, Path testNameTempPath) throws Exception {

    Properties additionalJobProps = new Properties();
    if (additionalJobPropsClasspathResource.isPresent()) {
        try (final InputStream stream = RetentionTestHelper.class.getClassLoader()
                .getResourceAsStream(additionalJobPropsClasspathResource.get().toString())) {
            additionalJobProps.load(stream);
        }
    }

    if (retentionConfigClasspathResource.getName().endsWith(".job")) {

        Properties jobProps = new Properties();
        try (final InputStream stream = RetentionTestHelper.class.getClassLoader()
                .getResourceAsStream(retentionConfigClasspathResource.toString())) {
            jobProps.load(stream);
            for (Entry<Object, Object> entry : jobProps.entrySet()) {
                jobProps.put(entry.getKey(), StringUtils.replace((String) entry.getValue(),
                        "${testNameTempPath}", testNameTempPath.toString()));
            }
        }

        MultiCleanableDatasetFinder finder = new MultiCleanableDatasetFinder(fs, jobProps);
        for (Dataset dataset : finder.findDatasets()) {
            ((CleanableDataset) dataset).clean();
        }
    } else {
        Config testConfig = ConfigFactory.parseResources(retentionConfigClasspathResource.toString())
                .withFallback(ConfigFactory.parseMap(ImmutableMap.of("testNameTempPath",
                        PathUtils.getPathWithoutSchemeAndAuthority(testNameTempPath).toString())))
                .resolve();

        ConfigClient client = mock(ConfigClient.class);
        when(client.getConfig(any(String.class))).thenReturn(testConfig);
        Properties jobProps = new Properties();
        jobProps.setProperty(CleanableDatasetBase.SKIP_TRASH_KEY, Boolean.toString(true));
        jobProps.setProperty(ConfigurationKeys.CONFIG_MANAGEMENT_STORE_URI, "dummy");

        jobProps.putAll(additionalJobProps);

        @SuppressWarnings("unchecked")
        DatasetsFinder<CleanableDataset> finder = (DatasetsFinder<CleanableDataset>) GobblinConstructorUtils
                .invokeFirstConstructor(
                        Class.forName(
                                testConfig.getString(MultiCleanableDatasetFinder.DATASET_FINDER_CLASS_KEY)),
                        ImmutableList.of(fs, jobProps, testConfig, client),
                        ImmutableList.of(fs, jobProps, client));

        for (CleanableDataset dataset : finder.findDatasets()) {
            dataset.clean();
        }
    }
}

From source file:org.pentaho.support.cmd.CommandLineUtility.java

/**
 * sets bi-server paths//from w ww  .ja  v  a 2s  . com
 * 
 * @param prop
 */
private static void setBIServerPath(Properties prop) {

    prop.put(CMDConstant.TOM_PATH, prop.getProperty(CMDConstant.BI_TOM_PATH));

    WEB_XML = new StringBuilder();
    WEB_XML.append(prop.getProperty(CMDConstant.BI_TOM_PATH)).append(File.separator).append(CMDConstant.WEB_APP)
            .append(File.separator).append(CMDConstant.PENTAHO).append(File.separator)
            .append(CMDConstant.WEB_INF).append(File.separator).append(CMDConstant.WEB_XML);

    prop.put(CMDConstant.WEB_XML_PATH, WEB_XML.toString());

    if (getInstallationType() != 3) {

        prop.put(CMDConstant.PENTAHO_SOLU_PATH,
                prop.getProperty(CMDConstant.BI_PATH) + File.separator + CMDConstant.PENTAHO_SOL_DIR);
    }

    if (getInstallationType() == 1) {

        prop.put(CMDConstant.LOG_FILE_PATH,
                prop.getProperty(CMDConstant.BI_TOM_PATH) + File.separator + CMDConstant.WEB_APP
                        + File.separator + CMDConstant.PENTAHO + File.separator + CMDConstant.WEB_INF
                        + File.separator + CMDConstant.CLASSES + File.separator + CMDConstant.LOG4J_XML);
    } else {

        prop.put(CMDConstant.LOG_FILE_PATH, prop.getProperty(CMDConstant.BI_TOM_PATH) + File.separator
                + CMDConstant.TOM_LOG + File.separator + CMDConstant.LOG_FILE);
    }

}

From source file:jo.alexa.sim.ui.logic.RuntimeLogic.java

public static TransactionBean send(RuntimeBean runtime, String text) {
    TransactionBean trans = new TransactionBean();
    trans.setRequestType(RequestLogic.INTENT_REQUEST);
    trans.setInputText(text);/*from   ww  w.  j a  va2s. c  o  m*/
    List<MatchBean> matches = MatchLogic.parseInput(runtime.getApp(), text);
    if (matches.size() == 0) {
        trans.setError(new IllegalArgumentException("No suitable parse for input"));
    } else {
        trans.setInputMatch(matches.get(0));
        String intentName = trans.getInputMatch().getIntent().getIntent();
        Properties slotValues = new Properties();
        for (SlotBean slot : trans.getInputMatch().getValues().keySet())
            slotValues.put(slot.getName(), trans.getInputMatch().getValues().get(slot));
        try {
            trans.setTransactionStart(System.currentTimeMillis());
            ResponseBean response = RequestLogic.performIntentRequest(runtime.getApp(), intentName, slotValues);
            trans.setTransactionEnd(System.currentTimeMillis());
            trans.setOutputData(response);
            trans.setOutputText(response.getOutputSpeechText());
        } catch (IOException e) {
            trans.setError(e);
        }
    }
    runtime.getHistory().add(trans);
    runtime.firePropertyChange("history", null, runtime.getHistory());
    return trans;
}

From source file:org.pentaho.support.cmd.CommandLineUtility.java

/**
 * sets di-server paths//from w ww.  j  a  v  a2s .co m
 * 
 * @param prop
 */
private static void setDIServerPath(Properties prop) {

    prop.put(CMDConstant.TOM_PATH, prop.getProperty(CMDConstant.DI_TOM_PATH));

    WEB_XML = new StringBuilder();
    WEB_XML.append(prop.getProperty(CMDConstant.DI_TOM_PATH)).append(File.separator)
            .append(prop.getProperty(CMDConstant.PENTAHO_DI)).append(File.separator)
            .append(prop.getProperty(CMDConstant.WEB_APP)).append(File.separator)
            .append(prop.getProperty(CMDConstant.WEB_INF)).append(File.separator)
            .append(prop.getProperty(CMDConstant.WEB_XML));

    prop.put(CMDConstant.WEB_XML_PATH, WEB_XML.toString());

    if (getInstallationType() != 3) {

        prop.put(CMDConstant.PENTAHO_SOLU_PATH,
                prop.getProperty(CMDConstant.DI_PATH) + File.separator + CMDConstant.PENTAHO_SOL_DIR);
    }

    if (getInstallationType() == 1) {

        prop.put(CMDConstant.LOG_FILE_PATH,
                prop.getProperty(CMDConstant.DI_TOM_PATH) + File.separator + CMDConstant.WEB_APP
                        + File.separator + CMDConstant.PENTAHO_DI + File.separator + CMDConstant.WEB_INF
                        + File.separator + CMDConstant.CLASSES + File.separator + CMDConstant.LOG4J_XML);
    } else {

        prop.put(CMDConstant.LOG_FILE_PATH, prop.getProperty(CMDConstant.DI_TOM_PATH) + File.separator
                + CMDConstant.TOM_LOG + File.separator + CMDConstant.LOG_FILE);
    }

}

From source file:de.hybris.platform.b2b.mock.MockitoTenant.java

private static Map<String, String> loadRawConfigFile() throws IOException {
    final Properties tempProps = new Properties();
    // 1. first, try to load the following files
    final PlatformConfig config = Utilities.getPlatformConfig();
    ConfigUtil.loadRuntimeProperties(tempProps, config);
    // 3. all system properties have the highest priority
    for (final Map.Entry entry : System.getProperties().entrySet()) {
        tempProps.put(entry.getKey(), ((String) entry.getValue()).trim());
    }/* w  ww . j a v a  2 s. c o  m*/
    // do trimming etc.
    final Map<String, String> props = new HashMap<String, String>();
    for (final Iterator<?> it = tempProps.keySet().iterator(); it.hasNext();) {
        final String key = (String) it.next();
        String value = tempProps.getProperty(key);
        int idx = value.indexOf('#');
        if (idx > 0) {
            if (value.charAt(idx - 1) == ('\\')) {
                idx = -1; // wenn escaped, dann nicht!
            }
        }
        if (idx > 0) {
            value = value.substring(0, idx);
        }
        value = value.trim();
        value = value.replace("\\#", "#");
        value = value.replace("{tab}", "\t");
        // if( value!=null && value.length()>1) value=value.trim();
        // value = Config.trim( value, "\t".toCharArray() );
        props.put(key, value);
    }
    return props;
}

From source file:Main.java

/**
 * Get a subset of the system properties for names that match at least one of the given prefixes.
 * @throws SecurityException  As in {@link System#getProperties}.
 *///  w  w w . ja  v  a 2  s  . c om
public static Properties getProperties(String... prefixes) {
    Properties result = new Properties();
    // Properties should be a Map<String, String>, but it's not defined that way.  Depending on the
    // implementation, it may even allow clients to put non-string entries.
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
        for (String prefix : prefixes) {
            if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith(prefix)) {
                result.put(entry.getKey(), entry.getValue());
                break;
            }
        }
    }
    return result;
}

From source file:io.druid.query.extraction.namespace.TestKafkaExtractionCluster.java

@BeforeClass
public static void setupStatic() throws Exception {
    zkTestServer = new TestingServer(-1, new File(tmpDir.getAbsolutePath() + "/zk"), true);
    zkClient = new ZkClient(zkTestServer.getConnectString(), 10000, 10000, ZKStringSerializer$.MODULE$);
    if (!zkClient.exists("/kafka")) {
        zkClient.create("/kafka", null, CreateMode.PERSISTENT);
    }/*from w  w  w .  j  a v  a2s.co m*/

    log.info("---------------------------Started ZK---------------------------");

    final Properties serverProperties = new Properties();
    serverProperties.putAll(kafkaProperties);
    serverProperties.put("broker.id", "0");
    serverProperties.put("log.dir", tmpDir.getAbsolutePath() + "/log");
    serverProperties.put("log.cleaner.enable", "true");
    serverProperties.put("host.name", "127.0.0.1");
    serverProperties.put("zookeeper.connect", zkTestServer.getConnectString() + "/kafka");
    serverProperties.put("zookeeper.session.timeout.ms", "10000");
    serverProperties.put("zookeeper.sync.time.ms", "200");

    kafkaConfig = new KafkaConfig(serverProperties);

    final long time = DateTime.parse("2015-01-01").getMillis();
    kafkaServer = new KafkaServer(kafkaConfig, new Time() {

        @Override
        public long milliseconds() {
            return time;
        }

        @Override
        public long nanoseconds() {
            return milliseconds() * 1_000_000;
        }

        @Override
        public void sleep(long ms) {
            try {
                Thread.sleep(ms);
            } catch (InterruptedException e) {
                throw Throwables.propagate(e);
            }
        }
    });
    kafkaServer.startup();
    int sleepCount = 0;
    while (!kafkaServer.kafkaController().isActive()) {
        Thread.sleep(10);
        if (++sleepCount > 100) {
            throw new InterruptedException("Controller took to long to awaken");
        }
    }

    log.info("---------------------------Started Kafka Server---------------------------");

    ZkClient zkClient = new ZkClient(zkTestServer.getConnectString() + "/kafka", 10000, 10000,
            ZKStringSerializer$.MODULE$);
    try {
        final Properties topicProperties = new Properties();
        topicProperties.put("cleanup.policy", "compact");
        if (!AdminUtils.topicExists(zkClient, topicName)) {
            AdminUtils.createTopic(zkClient, topicName, 1, 1, topicProperties);
        }

        log.info("---------------------------Created topic---------------------------");

        Assert.assertTrue(AdminUtils.topicExists(zkClient, topicName));
    } finally {
        zkClient.close();
    }
    fnCache.clear();
    final Properties kafkaProducerProperties = makeProducerProperties();
    Producer<byte[], byte[]> producer = new Producer<byte[], byte[]>(
            new ProducerConfig(kafkaProducerProperties));
    try {
        producer.send(new KeyedMessage<byte[], byte[]>(topicName, StringUtils.toUtf8("abcdefg"),
                StringUtils.toUtf8("abcdefg")));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    } finally {
        producer.close();
    }

    System.setProperty("druid.extensions.searchCurrentClassloader", "false");

    injector = Initialization.makeInjectorWithModules(
            GuiceInjectors.makeStartupInjectorWithModules(ImmutableList.<Module>of()),
            ImmutableList.of(new Module() {
                @Override
                public void configure(Binder binder) {
                    binder.bindConstant().annotatedWith(Names.named("serviceName")).to("test");
                    binder.bindConstant().annotatedWith(Names.named("servicePort")).to(0);
                }
            }, new NamespacedExtractionModule(), new KafkaExtractionNamespaceModule() {
                @Override
                public Properties getProperties(@Json ObjectMapper mapper, Properties systemProperties) {
                    final Properties consumerProperties = new Properties(kafkaProperties);
                    consumerProperties.put("zookeeper.connect", zkTestServer.getConnectString() + "/kafka");
                    consumerProperties.put("zookeeper.session.timeout.ms", "10000");
                    consumerProperties.put("zookeeper.sync.time.ms", "200");
                    return consumerProperties;
                }
            }));
    renameManager = injector.getInstance(KafkaExtractionManager.class);

    log.info("--------------------------- placed default item via producer ---------------------------");
    extractionCacheManager = injector.getInstance(NamespaceExtractionCacheManager.class);
    extractionCacheManager.schedule(new KafkaExtractionNamespace(topicName, namespace));
    long start = System.currentTimeMillis();
    while (renameManager.getBackgroundTaskCount() < 1) {
        Thread.sleep(10); // wait for map populator to start up
        if (System.currentTimeMillis() > start + 60_000) {
            throw new ISE("renameManager took too long to start");
        }
    }
    log.info("--------------------------- started rename manager ---------------------------");
}

From source file:com.teamsun.framework.util.ConvertUtil.java

/**
 * Method to convert a ResourceBundle to a Properties object.
 * //from   w  w w .  j  a va 2s  .  c om
 * @param rb
 *            a given resource bundle
 * @return Properties a populated properties object
 */
public static Properties convertBundleToProperties(ResourceBundle rb) {
    Properties props = new Properties();

    for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
        String key = (String) keys.nextElement();
        props.put(key, rb.getString(key));
    }

    return props;
}

From source file:deployer.TestUtils.java

public static TarFileChecker getSampleTarBallChecker(final ArtifactType type) {
    return new TarFileChecker() {
        @Override/*from  w w w.jav  a2s .co  m*/
        public void verify(TarArchiveEntry entry, InputStream inputStream) throws Exception {
            String fileName = entry.getName();
            if (fileName.equals(CONFIG_DIRECTORY + "/app.conf")) {
                verifyConf(inputStream);
            } else if (fileName.equals("bin/myApplication.jar") && type != ArtifactType.WebApp) {
                verifyApplicationJar(inputStream);
            } else if (fileName.equals("deployments/ROOT.war") && type == ArtifactType.WebApp) {
                verifyApplicationJar(inputStream);
            } else if (fileName.equals(CONFIG_DIRECTORY + "/application.properties")) {
                verifyAppProperties(inputStream);
            } else if (fileName.equals(CONFIG_DIRECTORY + "/ssl/" + TestUtils.SERVICE_NAME + ".jks")) {
                verifySSLCert(inputStream);
            } else if (type == ArtifactType.WebApp && fileName.equals(".openshift/config/standalone.xml")) {
                verifyStandaloneFile(inputStream);
            } else {
                fail("Unexpected file in tar ball: " + fileName);
            }
        }

        private void verifyAppProperties(InputStream inputStream) throws IOException {
            Properties expected = new Properties();
            expected.put("ezbake.security.ssl.dir", CONFIG_DIRECTORY + "/ssl/" + TestUtils.SECURITY_ID);
            expected.put("service.name", TestUtils.SERVICE_NAME);
            expected.put("ezbake.security.app.id", TestUtils.SECURITY_ID);
            expected.put("application.name", TestUtils.APP_NAME);
            expected.put("ezbake.application.version", Long.toString(TestUtils.sampleVersion));

            Properties data = new Properties();
            data.load(inputStream);

            assertEquals(expected, data);
        }

        private void verifySSLCert(InputStream inputStream) throws IOException {
            String data = IOUtils.toString(inputStream);
            assertEquals(data, TestUtils.SAMPLE_SSL_DATA);
        }

        private void verifyApplicationJar(InputStream inputStream) throws IOException {
            String data = IOUtils.toString(inputStream);
            assertEquals(data, TestUtils.SAMPLE_JAR_DATA);
        }

        private void verifyConf(InputStream inputStream) throws IOException {
            String data = IOUtils.toString(inputStream);
            assertEquals(data, TestUtils.SAMPLE_CONF_DATA);
        }

        private void verifyStandaloneFile(InputStream inputStream) throws IOException {
            assertEquals(IOUtils.toString(inputStream), TestUtils.SAMPLE_STANDALONE_DATA);
        }
    };
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static void updateKeys(MgnlKeyPair keys) {
    // update filestore only when private key is present
    if (keys.getPrivateKey() != null) {
        String path = SystemProperty.getProperty(KEY_LOCATION_PROPERTY);
        try {//from  w ww  .  j  av a2s  . c om
            Properties defaultProps = new Properties();
            defaultProps.put(PRIVATE_KEY, keys.getPrivateKey());
            defaultProps.put(PUBLIC_KEY, keys.getPublicKey());
            File keystore = new File(path);
            File parentFile = keystore.getParentFile();
            if (parentFile != null) {
                parentFile.mkdirs();
            }
            FileWriter writer = new FileWriter(keystore);
            String date = new SimpleDateFormat("dd.MMM.yyyy hh:mm").format(new Date());
            defaultProps.store(writer, "generated " + date + " by " + MgnlContext.getUser().getName());
            writer.close();
        } catch (FileNotFoundException e) {
            throw new SecurityException(
                    "Failed to store private key. Please make sure the key is located in " + path, e);
        } catch (IOException e) {
            throw new SecurityException(
                    "Failed to store private key. Please make sure the key is located in " + path, e);
        }
    }
    try {
        Session session = MgnlContext.getSystemContext().getJCRSession("config");
        session.getNode("/server/activation").setProperty("publicKey", keys.getPublicKey());
        session.save();
    } catch (RepositoryException e) {
        throw new SecurityException("Failed to store public key.", e);
    }
}