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

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

Introduction

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

Prototype

public void setProperty(String key, Object value) 

Source Link

Document

Sets a new value for the specified property.

Usage

From source file:org.apache.whirr.ClusterSpecTest.java

@Test(expected = ConfigurationException.class)
public void testInstanceTemplateNotFoundForHardwareId() throws Exception {
    PropertiesConfiguration conf = new PropertiesConfiguration("whirr-core-test.properties");
    conf.setProperty("whirr.instance-templates", "1 role1+role2");
    conf.setProperty("whirr.templates.role1.hardware-id", "m1.large");

    ClusterSpec.withTemporaryKeys(conf);
}

From source file:org.apache.whirr.ClusterSpecTest.java

@Test(expected = IllegalArgumentException.class)
public void testFailIfRunningAsRootOrClusterUserIsRoot() throws ConfigurationException {
    PropertiesConfiguration conf = new PropertiesConfiguration("whirr-core-test.properties");
    conf.setProperty("whirr.cluster-user", "root");

    ClusterSpec.withNoDefaults(conf);//from   www . j  a v  a2s . c om
}

From source file:org.apache.wookie.server.ContextListener.java

public void contextInitialized(ServletContextEvent event) {
    try {/*from  ww w  . j  av  a  2 s  .  c  om*/
        ServletContext context = event.getServletContext();

        /* 
         *  load the widgetserver.properties file and put it into this context
         *  as an attribute 'properties' available to all resources
         */
        PropertiesConfiguration configuration;
        File localPropsFile = new File(
                System.getProperty("user.dir") + File.separator + "local.widgetserver.properties");
        if (localPropsFile.exists()) {
            configuration = new PropertiesConfiguration(localPropsFile);
            _logger.info("Using local widget server properties file: " + localPropsFile.toString());
        } else {
            configuration = new PropertiesConfiguration("widgetserver.properties");
            configuration.setFile(localPropsFile);
            configuration.save();
            _logger.info("Using default widget server properties, configure your local server using: "
                    + localPropsFile.toString());
        }
        context.setAttribute("properties", (Configuration) configuration);

        /*
         * Merge in system properties overrides
         */
        Iterator<Object> systemKeysIter = System.getProperties().keySet().iterator();
        while (systemKeysIter.hasNext()) {
            String key = systemKeysIter.next().toString();
            if (configuration.containsKey(key) || key.startsWith("widget.")) {
                String setting = configuration.getString(key);
                String override = System.getProperty(key);
                if ((override != null) && (override.length() > 0) && !override.equals(setting)) {
                    configuration.setProperty(key, override);
                    if (setting != null) {
                        _logger.info("Overridden server configuration property: " + key + "=" + override);
                    }
                }
            }
        }

        /*
         * Initialize persistence manager factory now, not on first request
         */
        PersistenceManagerFactory.initialize(configuration);

        /*
         * Initialise the locale handler
         */
        LocaleHandler.getInstance().initialize(configuration);
        final Locale locale = new Locale(configuration.getString("widget.default.locale"));
        final Messages localizedMessages = LocaleHandler.getInstance().getResourceBundle(locale);

        /* 
        *  load the opensocial.properties file and put it into this context
        *  as an attribute 'opensocial' available to all resources
        */
        PropertiesConfiguration opensocialConfiguration;
        File localOpenSocialPropsFile = new File(
                System.getProperty("user.dir") + File.separator + "local.opensocial.properties");
        if (localOpenSocialPropsFile.exists()) {
            opensocialConfiguration = new PropertiesConfiguration(localOpenSocialPropsFile);
            _logger.info("Using local open social properties file: " + localOpenSocialPropsFile.toString());
        } else {
            opensocialConfiguration = new PropertiesConfiguration("opensocial.properties");
            opensocialConfiguration.setFile(localOpenSocialPropsFile);
            opensocialConfiguration.save();
            _logger.info("Using default open social properties, configure your local server using: "
                    + localOpenSocialPropsFile.toString());
        }
        context.setAttribute("opensocial", (Configuration) opensocialConfiguration);

        /*
         * Load installed features
         */
        PropertiesConfiguration featuresConfiguration;
        File localFeaturesPropsFile = new File(
                System.getProperty("user.dir") + File.separator + "local.features.properties");
        if (localFeaturesPropsFile.exists()) {
            featuresConfiguration = new PropertiesConfiguration(localFeaturesPropsFile);
            _logger.info("Loading local features file: " + localOpenSocialPropsFile.toString());
        } else {
            featuresConfiguration = new PropertiesConfiguration("features.properties");
            featuresConfiguration.setFile(localFeaturesPropsFile);
            featuresConfiguration.save();
            _logger.info("Loading default features, configure your local server using: "
                    + localFeaturesPropsFile.toString());
        }
        FeatureLoader.loadFeatures(featuresConfiguration);

        /*
         * Run diagnostics
         */
        Diagnostics.run(context, configuration);

        /*
         * Start hot-deploy widget watcher
         */
        if (configuration.getBoolean("widget.hot_deploy")) {
            startWatcher(context, configuration, localizedMessages);
        } else {
            _logger.info(localizedMessages.getString("WidgetHotDeploy.0"));
        }
    } catch (ConfigurationException ex) {
        _logger.error("ConfigurationException thrown: " + ex.toString());
    }
}

From source file:org.codetrack.database.DatabaseConfiguration.java

/**
 * Save database configuration/*from   w  ww  .  j a v  a 2  s  .  c o m*/
 *
 * @param databaseParameters
 */
public void saveRegisteredDatabase(DatabaseParameters databaseParameters) {

    try {

        String databasePropertiesName = getCodetrackConfigPath() + FILE_SEPARATOR + "database-"
                + databaseParameters.getName() + ".properties";

        File file = new File(databasePropertiesName);

        if (!file.exists())
            file.createNewFile();

        PropertiesConfiguration dbpc = new PropertiesConfiguration(file);

        dbpc.setProperty("name", databaseParameters.getName());
        dbpc.setProperty("engine", databaseParameters.getEngine().name());
        dbpc.setProperty("user", databaseParameters.getUser());
        dbpc.setProperty("password", databaseParameters.getPassword());
        dbpc.setProperty("url", databaseParameters.getUrl());
        dbpc.setProperty("path", databaseParameters.getPath());

        dbpc.save();

    } catch (Exception e) {
        throw new DatabaseError("Error on load database properties file", e,
                DatabaseError.DATABASE_OPEN_CONFIG_ERROR);
    }

}

From source file:org.dataconservancy.packaging.tool.model.PropertiesConfigurationParametersBuilder.java

@Override
public void buildParameters(PackageGenerationParameters params, OutputStream outputStream)
        throws ParametersBuildException {
    PropertiesConfiguration props = new PropertiesConfiguration();

    for (String key : params.getKeys()) {
        props.setProperty(key, params.getParam(key));
    }/* w  w w  . j  a  v  a2s  . c o  m*/

    try {
        props.save(new OutputStreamWriter(outputStream));
    } catch (ConfigurationException e) {
        throw new ParametersBuildException(e);
    }
}

From source file:org.dspace.statistics.content.StatisticsDataWorkflow.java

protected Date getOldestWorkflowItemDate() throws SolrServerException {
    ConfigurationService configurationService = new DSpace().getConfigurationService();
    String workflowStartDate = configurationService.getProperty("usage-statistics.workflow-start-date");
    if (workflowStartDate == null) {
        //Query our solr for it !
        QueryResponse oldestRecord = SolrLogger.query(getQuery(), null, null, 1, 0, null, null, null, null,
                "time", true);
        if (0 < oldestRecord.getResults().getNumFound()) {
            SolrDocument solrDocument = oldestRecord.getResults().get(0);
            Date oldestDate = (Date) solrDocument.getFieldValue("time");
            //Store the date, we only need to retrieve this once !
            try {
                //Also store it in the solr-statics configuration file, the reason for this being that the sort query
                //can be very time consuming & we do not want this delay each time we want to see workflow statistics
                String solrConfigDir = configurationService.getProperty("dspace.dir") + File.separator
                        + "config" + File.separator + "modules" + File.separator + "usage-statistics.cfg";
                PropertiesConfiguration config = new PropertiesConfiguration(solrConfigDir);
                config.setProperty("workflow-start-date", new DCDate(oldestDate));
                config.save();/* ww  w  .j  a  va  2  s.  c  om*/
            } catch (ConfigurationException e) {
                log.error("Error while storing workflow start date", e);
            }
            //ALso store it in our local config !
            configurationService.setProperty("usage-statistics.workflow-start-date",
                    new DCDate(oldestDate).toString());

            //Write to file
            return oldestDate;
        } else {
            return null;
        }

    } else {
        return new DCDate(workflowStartDate).toDate();
    }
}

From source file:org.janusgraph.core.JanusGraphFactory.java

/**
 * Load a properties file containing a JanusGraph graph configuration.
 * <p/>//  w  w  w  . j a  va  2  s  .c  om
 * <ol>
 * <li>Load the file contents into a {@link org.apache.commons.configuration.PropertiesConfiguration}</li>
 * <li>For each key that points to a configuration object that is either a directory
 * or local file, check
 * whether the associated value is a non-null, non-absolute path. If so,
 * then prepend the absolute path of the parent directory of the provided configuration {@code file}.
 * This has the effect of making non-absolute backend
 * paths relative to the config file's directory rather than the JVM's
 * working directory.
 * <li>Return the {@link ReadConfiguration} for the prepared configuration file</li>
 * </ol>
 * <p/>
 *
 * @param file A properties file to load
 * @return A configuration derived from {@code file}
 */
@SuppressWarnings("unchecked")
private static ReadConfiguration getLocalConfiguration(File file) {
    Preconditions.checkArgument(file != null && file.exists() && file.isFile() && file.canRead(),
            "Need to specify a readable configuration file, but was given: %s", file.toString());

    try {
        PropertiesConfiguration configuration = new PropertiesConfiguration(file);

        final File tmpParent = file.getParentFile();
        final File configParent;

        if (null == tmpParent) {
            /*
             * null usually means we were given a JanusGraph config file path
             * string like "foo.properties" that refers to the current
             * working directory of the process.
             */
            configParent = new File(System.getProperty("user.dir"));
        } else {
            configParent = tmpParent;
        }

        Preconditions.checkNotNull(configParent);
        Preconditions.checkArgument(configParent.isDirectory());

        // TODO this mangling logic is a relic from the hardcoded string days; it should be deleted and rewritten as a setting on ConfigOption
        final Pattern p = Pattern.compile("(" + Pattern.quote(STORAGE_NS.getName()) + "\\..*" + "("
                + Pattern.quote(STORAGE_DIRECTORY.getName()) + "|" + Pattern.quote(STORAGE_CONF_FILE.getName())
                + ")" + "|" + Pattern.quote(INDEX_NS.getName()) + "\\..*" + "("
                + Pattern.quote(INDEX_DIRECTORY.getName()) + "|" + Pattern.quote(INDEX_CONF_FILE.getName())
                + ")" + ")");

        final Iterator<String> keysToMangle = Iterators.filter(configuration.getKeys(),
                new Predicate<String>() {
                    @Override
                    public boolean apply(String key) {
                        if (null == key)
                            return false;
                        return p.matcher(key).matches();
                    }
                });

        while (keysToMangle.hasNext()) {
            String k = keysToMangle.next();
            Preconditions.checkNotNull(k);
            String s = configuration.getString(k);
            Preconditions.checkArgument(StringUtils.isNotBlank(s),
                    "Invalid Configuration: key %s has null empty value", k);
            configuration.setProperty(k, getAbsolutePath(configParent, s));
        }
        return new CommonsConfiguration(configuration);
    } catch (ConfigurationException e) {
        throw new IllegalArgumentException("Could not load configuration at: " + file, e);
    }
}

From source file:org.janusgraph.hadoop.Cassandra3InputFormatIT.java

@Override
protected PropertiesConfiguration getGraphConfiguration() throws ConfigurationException, IOException {
    final PropertiesConfiguration config = super.getGraphConfiguration();
    config.setProperty("gremlin.hadoop.graphInputFormat",
            "org.janusgraph.hadoop.formats.cassandra.Cassandra3InputFormat");
    return config;
}

From source file:org.janusgraph.hadoop.CassandraInputFormatIT.java

protected Graph getGraph() throws ConfigurationException, IOException {
    final PropertiesConfiguration config = new PropertiesConfiguration(
            "target/test-classes/cassandra-read.properties");
    Path baseOutDir = Paths.get((String) config.getProperty("gremlin.hadoop.outputLocation"));
    baseOutDir.toFile().mkdirs();/*from w w  w.j a v  a2 s . co  m*/
    String outDir = Files.createTempDirectory(baseOutDir, null).toAbsolutePath().toString();
    config.setProperty("gremlin.hadoop.outputLocation", outDir);
    return GraphFactory.open(config);
}

From source file:org.janusgraph.hadoop.HBaseInputFormatIT.java

protected Graph getGraph() throws IOException, ConfigurationException {
    final PropertiesConfiguration config = new PropertiesConfiguration(
            "target/test-classes/hbase-read.properties");
    Path baseOutDir = Paths.get((String) config.getProperty("gremlin.hadoop.outputLocation"));
    baseOutDir.toFile().mkdirs();/* w ww.ja  va  2s.  c o m*/
    String outDir = Files.createTempDirectory(baseOutDir, null).toAbsolutePath().toString();
    config.setProperty("gremlin.hadoop.outputLocation", outDir);
    return GraphFactory.open(config);
}