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

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

Introduction

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

Prototype

public PropertiesConfiguration(URL url) throws ConfigurationException 

Source Link

Document

Creates and loads the extended properties from the specified URL.

Usage

From source file:fr.jetoile.hadoopunit.component.SolrBootstrap.java

private void loadConfig() throws BootstrapException {
    HadoopUtils.setHadoopHome();//from   w  w  w .j a  va 2 s. c  om
    try {
        configuration = new PropertiesConfiguration(HadoopUnitConfig.DEFAULT_PROPS_FILE);
    } catch (ConfigurationException e) {
        throw new BootstrapException("bad config", e);
    }
    solrDirectory = configuration.getString(SOLR_DIR_KEY);
    solrCollectionInternalName = configuration.getString(SOLR_COLLECTION_INTERNAL_NAME);

}

From source file:apacheCommonsTest.testConfig.java

@Test
public void config() throws ConfigurationException, FileNotFoundException, DocumentException {

    //xml config test
    DOMConfigurator.configureAndWatch("res/gameConfig/log4j.xml");
    XMLConfiguration goodsxml = new XMLConfiguration("res/goods.xml");
    HierarchicalConfiguration.Node node = goodsxml.getRoot();
    int count = node.getChild(0).getAttributeCount(); //
    String id = (String) node.getChild(0).getAttribute(3).getValue();

    SAXReader read = new SAXReader();
    Document doc = null;//  w  w  w.ja  v  a  2 s  .  c om
    doc = read.read(new FileInputStream("res/goods.xml"));

    XMLConfiguration xmlConfiguration = new XMLConfiguration(
            Config.DEFAULT_VALUE.FILE_PATH.GAME_XML_DATA_LEVEL);
    //        AttributeMap nodeList= (AttributeMap) xmlConfiguration.getDocument().getElementsByTagName("itemDrop");

    //        Boolean auto = xmlConfiguration.getBoolean("basic.autoRelaodConfig",false) ;
    //        long  refresh=xmlConfiguration.getLong("basic.refreshDelay");
    //        System.out.println(auto);
    //        FileChangedReloadingStrategy reloadingStrategy=new FileChangedReloadingStrategy();
    //        reloadingStrategy.setRefreshDelay(xmlConfiguration.getLong("basic.refreshDelay"));
    //        xmlConfiguration.setReloadingStrategy(reloadingStrategy);

    //properties config
    PropertiesConfiguration config = new PropertiesConfiguration("res/client.properties");
    FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); //default 5000
    config.setReloadingStrategy(strategy);
    System.out.println(config.getInt("num"));
    System.out.println(config.getString("host", "127.0.0.1"));

}

From source file:eu.matejkormuth.ts3bot.Bot.java

/**
 * Boots up Bot./*w  w  w  . j ava 2s . c o m*/
 */
public void boot() {
    if (this.configuration != null) {
        throw new RuntimeException("Bot is already booted up!");
    }

    this.logger.info("Booting up...");

    this.logger.info("Reading configuration...");
    try {
        this.configuration = new PropertiesConfiguration("bot.properties");
    } catch (ConfigurationException e) {
        this.logger.error("Error while loading configuration from bot.properties: {}", e.getMessage());
        try {
            this.configuration = new PropertiesConfiguration(
                    this.getClass().getClassLoader().getResource("bot.properties"));
        } catch (ConfigurationException e2) {
            this.logger.error("Error while loading configuration from jar: {}", e2.getMessage());
            this.configuration = new PropertiesConfiguration();
            this.configuration.setHeader("TS3 Bot configuration.");
            this.configuration.setFileName("bot.properties");
        }
    }

    // Connect to teamspeak server.
    String name = this.configuration.getString("query.login");
    String pass = this.configuration.getString("query.password");
    String ip = this.configuration.getString("server.ip");
    if (name == null || pass == null || ip == null) {
        // Can't continue without these values.
        throw new RuntimeException(
                "Can't get query login, query password or server ip address from config! Can't continue!");
    }

    boolean flood = this.configuration.getBoolean("server.preventflood", false);
    boolean autoRegister = this.configuration.getBoolean("server.autoRegisterChannelEvents", true);
    String nickname = this.configuration.getString("bot.name", "TS3Bot");
    this.logger.info("Connecting to teamspeak server {}...", ip);
    QueryCreditnals creds = new QueryCreditnals(name, pass);
    this.queryConnection = new QueryConnection(creds, ip, nickname, flood, autoRegister); // nickname will never be null...
    // Connect to server.
    this.queryConnection.connect();

    // Some default services.
    List<Object> services = this.configuration.getList("bot.services");
    // In case we have only one service.
    if (services.size() == 0) {
        if (this.configuration.getString("bot.service") != null) {
            services.add(this.configuration.getString("bot.service"));
        }
    }

    // Create all services.
    this.logger.info("Loading services...");
    for (Object o : services) {
        try {
            Class<?> clazz = Class.forName(o.toString());
            if (Service.class.isAssignableFrom(clazz)) {
                Service service = (Service) clazz.getConstructor().newInstance();
                this.services.add(service);
            } else {
                this.logger.error(
                        "Specified service " + o.toString() + " does not extend Service class! Can't load it.");
            }
        } catch (Exception e) {
            this.logger.error("Can't load service {}! Problem: {}", o.toString(), e.getMessage());
            this.logger.error(e.toString());
        }
    }

    this.logger.info("Starting services...");
    // Start services.
    for (Service service : this.services) {
        if (service.isAsynchronous()) {
            this.logger.info("Enabling service asynchronously " + service.getClass().getSimpleName() + "...");
            final Service s = service;
            // Start thread for service.
            new Thread(new Runnable() {
                public void run() {
                    s.setBot(Bot.this);
                    Bot.this.eventBus.register(s);
                    s.enable();
                }
            }, "service/" + service.getClass().getSimpleName()).run();
        } else {
            try {
                this.logger
                        .info("Enabling service synchronously " + service.getClass().getSimpleName() + "...");
                service.setBot(this);
                this.eventBus.register(service);
                service.enable();
            } catch (Exception e) {
                this.logger.error("Can't enable service! Problem: {}", e.getMessage());
                this.logger.error(e.toString());
            }
        }
    }

    this.logger.info("Finished loading!");

    // Start reading commands from console.
    this.consoleReader = new ConsoleReader();
    this.consoleReader.setBot(this);
    this.consoleReader.enable();
}

From source file:eu.learnpad.configuration.LearnpadPropertiesConfigurationSource.java

@Override
public void initialize() throws InitializationException {
    // Register the Commons Properties Configuration, looking for a
    // xwiki.properties file
    // in the XWiki path somewhere.
    URL xwikiPropertiesUrl = null;
    try {/* w  w w .j a v a 2 s  .c  om*/
        xwikiPropertiesUrl = this.environment.getResource(LEARNPAD_PROPERTIES_FILE);
        if (xwikiPropertiesUrl != null) {
            setConfiguration(new PropertiesConfiguration(xwikiPropertiesUrl));
        } else {
            // We use a debug logging level here since we consider it's ok
            // that there's no XWIKI_PROPERTIES_FILE
            // available, in which case default values are used.
            this.logger.debug("No configuration file [{}] found. Using default configuration values.",
                    LEARNPAD_PROPERTIES_FILE);
        }
    } catch (Exception e) {
        // Note: if we cannot read the configuration file for any reason we
        // log a warning but continue since XWiki
        // will use default values for all configurable elements.
        this.logger.warn("Failed to load configuration file [{}]. Using default configuration values. "
                + "Internal error [{}]", LEARNPAD_PROPERTIES_FILE, e.getMessage());
    }

    // If no Commons Properties Configuration has been set, use a default
    // empty Commons Configuration
    // implementation.
    if (xwikiPropertiesUrl == null) {
        setConfiguration(new BaseConfiguration());
    }
}

From source file:com.shadwelldacunha.byteswipe.core.ConfigHandler.java

private void checkDefaults(String file) {
    try {//from ww  w . j  ava  2s.  c om
        PropertiesConfiguration defConfig = new PropertiesConfiguration(
                Utilities.getResource("byteswipe.properties"));
        Iterator<String> defKeys = defConfig.getKeys();

        //Add missing keys
        while (defKeys.hasNext()) {
            String key = defKeys.next();
            if (!config.containsKey(key)) {
                config.addProperty(key, defConfig.getProperty(key));
            }
        }

        config.save();
        //TODO: Handle exceptions
    } catch (ConfigurationException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:com.torodb.DefaultBuildProperties.java

public DefaultBuildProperties(String propertiesFile) {
    PropertiesConfiguration properties;//from   w w  w .  j ava2  s .co  m
    try {
        properties = new PropertiesConfiguration(Resources.getResource(propertiesFile));
    } catch (ConfigurationException e) {
        throw new RuntimeException("Cannot read build properties file '" + propertiesFile + "'");
    }

    fullVersion = properties.getString("version");
    Matcher matcher = FULL_VERSION_PATTERN.matcher(fullVersion);
    if (!matcher.matches()) {
        throw new RuntimeException("Invalid version string '" + fullVersion + "'");
    }
    majorVersion = Integer.parseInt(matcher.group(1));
    minorVersion = Integer.parseInt(matcher.group(2));
    subVersion = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
    extraVersion = matcher.group(4);

    // DateUtils.parseDate may be replaced by SimpleDateFormat if using Java7
    try {
        buildTime = DateUtils.parseDate(properties.getString("buildTimestamp"),
                new String[] { ISO8601_FORMAT_STRING });
    } catch (ParseException e) {
        throw new RuntimeException("buildTimestamp property not in ISO8601 format");
    }

    gitCommitId = properties.getString("gitCommitId");
    gitBranch = properties.getString("gitBranch");
    gitRemoteOriginURL = properties.getString("gitRemoteOriginURL");

    javaVersion = properties.getString("javaVersion");
    javaVendor = properties.getString("javaVendor");
    javaVMSpecificationVersion = properties.getString("javaVMSpecificationVersion");
    javaVMVersion = properties.getString("javaVMVersion");

    osName = properties.getString("osName");
    osArch = properties.getString("osArch");
    osVersion = properties.getString("osVersion");
}

From source file:ch.cyclops.gatekeeper.GKDriver.java

/**
 * Constructor class, creates the object given the configuration file path.
 * <p>/*from  w  ww . j av a 2  s .  c o m*/
 * @param confFile  Path to the driver configuration file
 * @param uid   gatekeeper user-id
 * @param pass  gatekeeper account password
 */
public GKDriver(String confFile, int uid, String pass) {
    CompositeConfiguration config = new CompositeConfiguration();
    config.addConfiguration(new SystemConfiguration());
    try {
        config.addConfiguration(new PropertiesConfiguration(confFile));
        //now logger configuration is done, we can start using it.
        driverLogger = Logger.getLogger("gatekeeper-driver.Driver");
        gatekeeperUri = config.getProperty("gatekeeper.uri").toString();
        gatekeeperPort = Integer.parseInt(config.getProperty("gatekeeper.port").toString());
        adminUserId = Integer.toString(uid, 10);
        adminPassword = pass;
        internalStatus = true;
        adminToken = "";
        driverLogger.info("gatekeeper driver initialized properly.");
    } catch (Exception ex) {
        internalStatus = false;
        if (driverLogger != null)
            driverLogger.fatal("Error initializing driver: " + ex.getMessage());
    }
}

From source file:fr.jetoile.hadoopunit.component.KafkaBootstrap.java

private void loadConfig() throws BootstrapException {
    HadoopUtils.setHadoopHome();/* ww  w  .  ja  v a2s.c  o  m*/
    try {
        configuration = new PropertiesConfiguration(HadoopUnitConfig.DEFAULT_PROPS_FILE);
    } catch (ConfigurationException e) {
        throw new BootstrapException("bad config", e);
    }
    host = configuration.getString(HadoopUnitConfig.KAFKA_HOSTNAME_KEY);
    port = configuration.getInt(HadoopUnitConfig.KAFKA_PORT_KEY);
    brokerId = configuration.getInt(HadoopUnitConfig.KAFKA_TEST_BROKER_ID_KEY);
    tmpDirectory = configuration.getString(HadoopUnitConfig.KAFKA_TEST_TEMP_DIR_KEY);
    zookeeperConnectionString = configuration.getString(HadoopUnitConfig.ZOOKEEPER_HOST_KEY) + ":"
            + configuration.getInt(HadoopUnitConfig.ZOOKEEPER_PORT_KEY);

}

From source file:com.xemantic.tadedon.configuration.Configurations.java

public static PropertiesConfiguration newPropertiesConfiguration(File confFile) {
    checkArgument(confFile.exists(), "confFile %s does not exist", confFile);
    try {//from w w  w  .ja va2 s .com
        return new PropertiesConfiguration(confFile);
    } catch (ConfigurationException e) {
        throw new RuntimeException("Cannot create configuration", e);
    }
}

From source file:fr.inria.atlanmod.neoemf.data.blueprints.option.BlueprintsResourceSaveTest.java

@Test
public void testSaveGraphResourceNoOption() throws IOException, ConfigurationException {
    resource.save(Collections.emptyMap());

    File configFile = new File(file() + configFileName);
    assertThat(configFile).exists(); // "Config file does not exist"

    PropertiesConfiguration configuration = new PropertiesConfiguration(configFile);
    assertThat(configuration.containsKey(BlueprintsResourceOptions.GRAPH_TYPE)).isTrue();
    assertThat(configuration.getString(BlueprintsResourceOptions.GRAPH_TYPE))
            .isEqualTo(BlueprintsResourceOptions.GRAPH_TYPE_DEFAULT);
    assertThat(getKeyCount(configuration)).isEqualTo(3); // "Too much content in the .properties file"
}