Example usage for org.apache.commons.configuration2 PropertiesConfiguration setProperty

List of usage examples for org.apache.commons.configuration2 PropertiesConfiguration setProperty

Introduction

In this page you can find the example usage for org.apache.commons.configuration2 PropertiesConfiguration setProperty.

Prototype

@Override
    public final void setProperty(final String key, final Object value) 

Source Link

Usage

From source file:com.streamsets.datacollector.cli.sch.SchAdmin.java

/**
 * Update dpm.properties file with new configuration.
 *//*from ww  w  . j  a  va 2s . c o m*/
private static void updateDpmProperties(Context context, String dpmBaseURL, List<String> labels,
        boolean enableSch) {
    if (context.skipUpdatingDpmProperties) {
        return;
    }

    try {
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
                PropertiesConfiguration.class)
                        .configure(new Parameters().properties()
                                .setFileName(context.runtimeInfo.getConfigDir() + "/dpm.properties")
                                .setThrowExceptionOnMissing(true)
                                .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                                .setIncludesAllowed(false));
        PropertiesConfiguration config = null;
        config = builder.getConfiguration();
        config.setProperty(RemoteSSOService.DPM_ENABLED, Boolean.toString(enableSch));
        config.setProperty(RemoteSSOService.DPM_BASE_URL_CONFIG, dpmBaseURL);
        config.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, APP_TOKEN_FILE_PROP_VAL);
        if (labels != null && labels.size() > 0) {
            config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, StringUtils.join(labels, ','));
        } else {
            config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, "");
        }
        builder.save();
    } catch (ConfigurationException e) {
        throw new RuntimeException(Utils.format("Updating dpm.properties file failed: {}", e.getMessage()), e);
    }
}

From source file:com.wavemaker.commons.properties.PropertiesWriter.java

/**
 * This api use apache commons property configuration to persist properties into file
 * and this api will avoid writing current date as comment into property file.
 *
 * @param os/*from   ww w  . ja v a 2  s.  co m*/
 */
protected void storeSansDate(OutputStream os) {
    PropertiesConfiguration configuration = new PropertiesConfiguration();
    configuration.getLayout().setGlobalSeparator("=");
    Enumeration enumeration = properties.keys();
    boolean canComment = true;
    while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        if (canComment && StringUtils.isNotBlank(comments)) {
            configuration.getLayout().setComment(key, comments);
            canComment = false;
        }
        configuration.setProperty(key, properties.get(key));
    }
    try {
        configuration.getLayout().save(configuration, new OutputStreamWriter(os));

    } catch (ConfigurationException e) {
        throw new WMRuntimeException("Unable to write properties to output stream", e);
    } finally {
        IOUtils.closeSilently(os);
    }
    configuration.clear();
}

From source file:org.jbb.lib.properties.FreshInstallPropertiesCreator.java

private static void addMissingProperties(PropertiesConfiguration reference, PropertiesConfiguration target) {
    Lists.newArrayList(reference.getKeys()).stream().filter(propertyKey -> !target.containsKey(propertyKey))
            .forEach(missingKey -> target.setProperty(missingKey, reference.getProperty(missingKey)));
}

From source file:org.jbb.lib.properties.UpdateFilePropertyChangeListener.java

@Override
public void propertyChange(PropertyChangeEvent evt) {
    for (String propertyFile : propFiles) {
        try {/*from  w  ww .j  a va2 s.  com*/
            FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
                    PropertiesConfiguration.class).configure(
                            new Parameters().properties().setFileName(propertyFile).setIncludesAllowed(false));
            builder.setAutoSave(true);
            PropertiesConfiguration conf = builder.getConfiguration();
            evt.setPropagationId(propertyFile);
            conf.setProperty(evt.getPropertyName(), evt.getNewValue());
        } catch (ConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

From source file:org.powertac.samplebroker.core.BrokerRunner.java

public void processCmdLine(String[] args) {
    OptionParser parser = new OptionParser();
    OptionSpec<String> jmsUrlOption = parser.accepts("jms-url").withRequiredArg().ofType(String.class);
    OptionSpec<File> configOption = parser.accepts("config").withRequiredArg().ofType(File.class);
    OptionSpec<Integer> repeatCountOption = parser.accepts("repeat-count").withRequiredArg()
            .ofType(Integer.class);
    OptionSpec<Integer> repeatHoursOption = parser.accepts("repeat-hours").withRequiredArg()
            .ofType(Integer.class);
    OptionSpec<String> queueNameOption = parser.accepts("queue-name").withRequiredArg().ofType(String.class);
    OptionSpec<String> serverQueueOption = parser.accepts("server-queue").withRequiredArg()
            .ofType(String.class);
    parser.accepts("ipc-adapter");
    //parser.accepts("no-ntp");
    parser.accepts("interactive");
    OptionSpec<String> propOption = parser.accepts("prop").withRequiredArg().ofType(String.class);

    // do the parse
    OptionSet options = parser.parse(args);

    File configFile = null;/*from www. j  a  va  2s.c  o m*/
    //String jmsUrl = null;
    //boolean noNtp = false;
    //boolean interactive = false;
    //String queueName = null;
    //String serverQueue = null;
    Integer repeatCount = 1;
    Integer repeatHours = 0;
    long end = 0l;
    PropertiesConfiguration cliProps = new PropertiesConfiguration();

    try {
        // process broker options
        System.out.println("<options");
        if (options.has(configOption)) {
            configFile = options.valueOf(configOption);
            System.out.println(" config=\"" + configFile.getName() + "\"");
        }
        if (options.has(jmsUrlOption)) {
            cliProps.setProperty("samplebroker.core.powerTacBroker.jmsBrokerUrl",
                    options.valueOf(jmsUrlOption));
            System.out.print(" jms-url=\"" + options.valueOf(jmsUrlOption) + "\"");
        }
        //if (options.has("no-ntp")) {
        //  noNtp = true;
        //  System.out.println("  no ntp - estimate offset");
        //}
        if (options.has(repeatCountOption)) {
            repeatCount = options.valueOf(repeatCountOption);
            System.out.print(" repeat-count=\"" + repeatCount + "\"");
        } else if (options.has(repeatHoursOption)) {
            repeatHours = options.valueOf(repeatHoursOption);
            System.out.print(" repeat-hours=\"" + repeatHours + "\"");
            long now = new Date().getTime();
            end = now + 1000 * 3600 * repeatHours;
        }
        if (options.has(queueNameOption)) {
            cliProps.setProperty("samplebroker.core.powerTacBroker.brokerQueueName",
                    options.valueOf(queueNameOption));
            System.out.print(" queue-name=\"" + options.valueOf(queueNameOption) + "\"");
        }
        if (options.has(serverQueueOption)) {
            cliProps.setProperty("samplebroker.core.powerTacBroker.serverQueueName",
                    options.valueOf(serverQueueOption));
            System.out.print(" server-queue=\"" + options.valueOf(serverQueueOption) + "\"");
        }
        if (options.has("interactive")) {
            cliProps.setProperty("samplebroker.core.powerTacBroker.interactive", "true");
            System.out.print(" interactive=\"true\"");
        }
        if (options.has("ipc-adapter")) {
            cliProps.setProperty("samplebroker.core.brokerMessageReceiver.ipcAdapter", "true");
            System.out.println("Using ipc-adapter to pass raw xml.");
        }
        if (options.has(propOption)) {
            List<String> values = options.valuesOf(propOption);
            for (String value : values) {
                int colon = value.indexOf(":");
                if (colon > 0) {
                    String name = value.substring(0, colon);
                    String val = value.substring(colon + 1);
                    cliProps.setProperty(name, val);
                    System.out.print(" " + name + "=" + val);
                }
            }
        }
        System.out.println("/>");

        // at this point, we are either done, or we need to repeat
        int counter = 0;
        while ((null != repeatCount && repeatCount > 0) || (new Date().getTime() < end)) {
            counter += 1;

            // initialize and run
            if (null == context) {
                context = new ClassPathXmlApplicationContext("broker.xml");
            } else {
                context.close();
                context.refresh();
            }

            // Re-open the logfiles
            reopenLogs(counter);
            IdGenerator.recycle();

            // get the broker reference and delegate the rest
            context.registerShutdownHook();
            broker = (PowerTacBroker) context.getBeansOfType(PowerTacBroker.class).values().toArray()[0];
            System.out.println("Starting session " + counter);
            log.info("Starting session {}", counter);
            broker.startSession(cliProps, configFile, end);
            if (null != repeatCount)
                repeatCount -= 1;
        }
    } catch (OptionException e) {
        System.err.println("Bad command argument: " + e.toString());
    }
}

From source file:org.roda_project.commons_ip.model.impl.bagit.BagitUtils.java

public static IPDescriptiveMetadata createBagitMetadata(Map<String, String> metadata, List<String> ancestors,
        Path metadataPath) {/* w  ww  .ja va2 s  .  c  o m*/
    try {
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new Configurations()
                .propertiesBuilder(metadataPath.toFile());
        Files.createFile(metadataPath);
        PropertiesConfiguration config = builder.getConfiguration();

        for (Entry<String, String> entry : metadata.entrySet()) {
            config.setProperty(entry.getKey(), entry.getValue());
        }

        for (String ancestor : ancestors) {
            config.addProperty(IPConstants.BAGIT_PARENT, ancestor);
        }

        builder.save();
    } catch (IOException | ConfigurationException e) {
        LOGGER.error("Could not save bagit metadata content on file", e);
    }

    return new IPDescriptiveMetadata(metadataPath.getFileName().toString(), new IPFile(metadataPath),
            new MetadataType(BAGIT), "");
}

From source file:org.talend.dataprep.encrypt.PropertiesEncryption.java

/**
 * Applies the specified function to the specified set of parameters contained in the input file.
 *
 * @param input The specified name of file to encrypt
 * @param mustBeModified the specified set of parameters
 * @param function the specified function to apply to the set of specified parameters
 *//*from w w w  .  ja v a  2s . c om*/
private void modifyAndSave(String input, Set<String> mustBeModified, Function<String, String> function) {
    Path inputFilePath = Paths.get(input);
    if (Files.exists(inputFilePath) && Files.isRegularFile(inputFilePath) && Files.isReadable(inputFilePath)) {
        try {
            Parameters params = new Parameters();
            FileBasedConfigurationBuilder<PropertiesConfiguration> builder = //
                    new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class) //
                            .configure(params.fileBased() //
                                    .setFile(inputFilePath.toFile())); //
            PropertiesConfiguration config = builder.getConfiguration();
            for (String key : mustBeModified) {
                config.setProperty(key, function.apply(config.getString(key)));
            }
            builder.save();
        } catch (ConfigurationException e) {
            LOGGER.error("unable to read {} {}", input, e);
        }
    } else {
        LOGGER.debug("No readable file at {}", input);
    }
}

From source file:org.xwiki.test.ui.AllITs.java

@XWikiExecutorSuite.PreStart
public void preStart(List<XWikiExecutor> executors) throws Exception {
    XWikiExecutor executor = executors.get(0);

    repositoryUtil = new RepositoryUtils();

    LOGGER.info("Adding repository to xwiki.properties");

    PropertiesConfiguration properties = executor.loadXWikiPropertiesConfiguration();

    // Put self and Maven as extensions repository
    properties.setProperty("extension.repositories",
            Arrays.asList("self:xwiki:http://localhost:8080/xwiki/rest",
                    "maven-test:maven:" + repositoryUtil.getMavenRepository().toURI()));
    // Disable core extension resolve because Jetty is not ready when it starts
    properties.setProperty("extension.core.resolve", false);

    executor.saveXWikiProperties();/*from   w ww  . j  a v a2s. c o  m*/
}

From source file:uk.co.hadoopathome.kafkastreams.integration.StreamingDroolsIntegrationTest.java

@Test
public void testApplication() throws Exception {
    PropertiesConfiguration properties = ConfigurationReader.getProperties("config.properties");
    properties.setProperty("bootstrapServers", CLUSTER.bootstrapServers());
    properties.setProperty("zookeeperServers", CLUSTER.zookeeperConnect());

    String inputTopic = (String) properties.getProperty("inputTopic");
    String outputTopic = (String) properties.getProperty("outputTopic");
    CLUSTER.createTopic(inputTopic);/* w w  w  . j av  a 2 s. c o m*/
    CLUSTER.createTopic(outputTopic);

    List<String> inputValues = Arrays.asList("Hello", "Canal", "Camel");
    List<String> expectedOutput = Arrays.asList("0Hello", "Canal", "0Camel");
    String statePath = (String) properties.getProperty(StreamsConfig.STATE_DIR_CONFIG);
    IntegrationTestUtils.purgeLocalStreamsState(statePath);

    KafkaStreams streams = KafkaStreamsRunner.runKafkaStream(properties);

    Properties producerConfig = createProducerConfig();
    IntegrationTestUtils.produceValuesSynchronously(inputTopic, inputValues, producerConfig);

    Properties consumerConfig = createConsumerConfig();
    List<String> actualOutput = IntegrationTestUtils.waitUntilMinValuesRecordsReceived(consumerConfig,
            outputTopic, expectedOutput.size());
    assertThat(actualOutput).containsExactlyElementsOf(expectedOutput);
    streams.close();
}