Java Code Examples for org.apache.commons.configuration.XMLConfiguration#load()

The following examples show how to use org.apache.commons.configuration.XMLConfiguration#load() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Configuration.java    From java-cme-mdp3-handler with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Loads and parse CME MDP Configuration.
 *
 * @param uri URI to CME MDP Configuration (config.xml, usually available on CME FTP)
 * @throws ConfigurationException if failed to parse configuration file
 * @throws MalformedURLException  if URI to Configuration is malformed
 */
private void load(final URI uri) throws ConfigurationException, MalformedURLException {
    // todo: if to implement the same via standard JAXB then dep to apache commons configuration will be not required
    final XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);
    configuration.load(uri.toURL());
    for (final HierarchicalConfiguration channelCfg : configuration.configurationsAt("channel")) {
        final ChannelCfg channel = new ChannelCfg(channelCfg.getString("[@id]"), channelCfg.getString("[@label]"));

        for (final HierarchicalConfiguration connCfg : channelCfg.configurationsAt("connections.connection")) {
            final String id = connCfg.getString("[@id]");
            final FeedType type = FeedType.valueOf(connCfg.getString("type[@feed-type]"));
            final TransportProtocol protocol = TransportProtocol.valueOf(connCfg.getString("protocol").substring(0, 3));
            final Feed feed = Feed.valueOf(connCfg.getString("feed"));
            final String ip = connCfg.getString("ip");
            final int port = connCfg.getInt("port");
            final List<String> hostIPs = Arrays.asList(connCfg.getStringArray("host-ip"));

            final ConnectionCfg connection = new ConnectionCfg(feed, id, type, protocol, ip, hostIPs, port);
            channel.addConnection(connection);
            connCfgs.put(connection.getId(), connection);
        }
        channelCfgs.put(channel.getId(), channel);
    }
}
 
Example 2
Source File: XmlConfigParser.java    From onos with Apache License 2.0 6 votes vote down vote up
public static HierarchicalConfiguration loadXml(InputStream xmlStream) {
    try {
        XMLConfiguration cfg = new XMLConfiguration();
        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        //Disabling DTDs in order to avoid XXE xml-based attacks.
        disableFeature(dbfactory, DISALLOW_DTD_FEATURE);
        disableFeature(dbfactory, DISALLOW_EXTERNAL_DTD);
        dbfactory.setXIncludeAware(false);
        dbfactory.setExpandEntityReferences(false);
        cfg.setDocumentBuilder(dbfactory.newDocumentBuilder());
        cfg.load(xmlStream);
        return cfg;
    } catch (ConfigurationException | ParserConfigurationException e) {
        throw new IllegalArgumentException("Cannot load xml from Stream", e);
    }
}
 
Example 3
Source File: SettingsLoader.java    From opensoc-streaming with Apache License 2.0 6 votes vote down vote up
public static Map<String, JSONObject> loadRegexAlerts(String config_path)
		throws ConfigurationException, ParseException {
	XMLConfiguration alert_rules = new XMLConfiguration();
	alert_rules.setDelimiterParsingDisabled(true);
	alert_rules.load(config_path);

	//int number_of_rules = alert_rules.getList("rule.pattern").size();

	String[] patterns = alert_rules.getStringArray("rule.pattern");
	String[] alerts = alert_rules.getStringArray("rule.alert");

	JSONParser pr = new JSONParser();
	Map<String, JSONObject> rules = new HashMap<String, JSONObject>();

	for (int i = 0; i < patterns.length; i++)
		rules.put(patterns[i], (JSONObject) pr.parse(alerts[i]));

	return rules;
}
 
Example 4
Source File: SequentialHostBalancerTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testBalancerStorageSequentialSingle() throws Exception {

    SequentialHostBalancer balancer = new SequentialHostBalancer();

    String balancerConfig = "<essvcenter><balancer hosts=\"elm1\" /></essvcenter>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));

    VMwareDatacenterInventory inventory = new VMwareDatacenterInventory();

    VMwareHost elm = inventory.addHostSystem((VMwareDatacenterInventoryTest
            .createHostSystemProperties("elm1", "128", "1")));
    elm.setEnabled(true);

    balancer.setInventory(inventory);

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm1", elm.getName());

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm1", elm.getName());
}
 
Example 5
Source File: SequentialStorageBalancerTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingle() throws Exception {

    SequentialStorageBalancer balancer = new SequentialStorageBalancer();

    String balancerConfig = "<host><balancer storage=\"elm1\" /></host>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));

    VMwareDatacenterInventory inventory = new VMwareDatacenterInventory();

    VMwareStorage elm = inventory.addStorage("host",
            VMwareDatacenterInventoryTest.createDataStoreProperties("elm1",
                    "100", "100"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("90%"));

    balancer.setInventory(inventory);

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm1", elm.getName());

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm1", elm.getName());
}
 
Example 6
Source File: ApplicationArchive.java    From onos with Apache License 2.0 5 votes vote down vote up
private ApplicationDescription parsePlainAppDescription(InputStream stream)
        throws IOException {
    XMLConfiguration cfg = new XMLConfiguration();
    cfg.setAttributeSplittingDisabled(true);
    cfg.setDelimiterParsingDisabled(true);
    try {
        cfg.load(stream);
        return loadAppDescription(cfg);
    } catch (ConfigurationException e) {
        throw new IOException("Unable to parse " + APP_XML, e);
    }
}
 
Example 7
Source File: YangXmlUtils.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Method to read an input stream into a XMLConfiguration.
 * @param xmlStream inputstream containing XML description
 * @return the XMLConfiguration object
 */
public XMLConfiguration loadXml(InputStream xmlStream) {
    XMLConfiguration cfg = new XMLConfiguration();
    try {
        cfg.load(xmlStream);
        return cfg;
    } catch (ConfigurationException e) {
        throw new IllegalArgumentException("Cannot load xml from Stream", e);
    }
}
 
Example 8
Source File: LogTableFormatConfigView.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private void importFromFile(FileObject file) throws ConfigurationException, IOException {
  try (InputStream is = file.getContent().getInputStream()) {
    final XMLConfiguration xmlConfiguration = new XMLConfiguration();
    xmlConfiguration.load(is);
    final List<ColumnLayout> columnLayouts = loadColumnLayouts(xmlConfiguration);
    importColumnLayouts(columnLayouts);
    otrosApplication.getStatusObserver().updateStatus(String.format("Column layouts have been imported from %s", file.getName().getFriendlyURI()));
  } finally {
    Utils.closeQuietly(file);
  }
}
 
Example 9
Source File: ApplicationArchive.java    From onos with Apache License 2.0 5 votes vote down vote up
private String getSelfContainedBundleCoordinates(ApplicationDescription desc) {
    try {
        XMLConfiguration cfg = new XMLConfiguration();
        cfg.setAttributeSplittingDisabled(true);
        cfg.setDelimiterParsingDisabled(true);
        cfg.load(appFile(desc.name(), FEATURES_XML));
        return cfg.getString("feature.bundle")
                .replaceFirst("wrap:", "")
                .replaceFirst("\\$Bundle-.*$", "");
    } catch (ConfigurationException e) {
        log.warn("Self-contained application {} has no features.xml", desc.name());
        return null;
    }
}
 
Example 10
Source File: MonetaConfiguration.java    From moneta with Apache License 2.0 5 votes vote down vote up
protected static final XMLConfiguration loadConfigurationFromStream(
		InputStream configurationStream) {
	XMLConfiguration config = new XMLConfiguration();
	try {
		config.load(configurationStream);
	} catch (ConfigurationException e) {
		throw new MonetaException("Moneta configuration file not loaded from classpath", e)
			.addContextValue("configFileName", DEFAULT_CONFIGURATION_FILE_NAME);
	}
	finally {
		IOUtils.closeQuietly(configurationStream);
	}
	return config;
}
 
Example 11
Source File: AbstractScriptRunner.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
protected GeneratedScript prepareScript(TestScriptDescription description) throws Exception {
    logger.info("Prepare script started [{}]", description.getMatrixFileName());

    GeneratedScript script = generateJavaSourcesFromMatrix(description);

    File binFolder = workspaceDispatcher.createFolder(FolderType.REPORT, description.getWorkFolder(), "bin");

    // parent class loader must be specified for new web-gui
    ILanguageFactory languageFactory = languageManager.getLanguageFactory(description.getLanguageURI());
    ClassLoader classLoader = languageFactory.createClassLoader(binFolder.toURI().toURL(), getClass().getClassLoader());

    // load Script Settings
    File scriptFile = workspaceDispatcher.getFile(FolderType.REPORT, description.getSettingsPath());
    XMLConfiguration scriptConfig = new XMLConfiguration();
    scriptConfig.setDelimiterParsingDisabled(true);
    scriptConfig.load(scriptFile);
    ScriptSettings scriptSettings = new ScriptSettings();
    scriptSettings.load(scriptConfig);
    scriptSettings.setScriptName(description.getMatrixFileName());

    // prepare script logger logger
    Logger scriptLogger = createScriptLogger(scriptSettings, description.getWorkFolder());

    description.setScriptConfiguration(AML.PACKAGE_NAME + "." + AML.CLASS_NAME, classLoader, scriptLogger, scriptSettings);
    description.setProgress(50);
    logger.info("Prepare script completed [{}]", description.getMatrixFileName());
    return script;
}
 
Example 12
Source File: EquipartitionStorageBalancerTest.java    From development with Apache License 2.0 5 votes vote down vote up
private EquipartitionStorageBalancer getBalancer(String storages)
        throws ConfigurationException {
    EquipartitionStorageBalancer balancer = new EquipartitionStorageBalancer();
    String balancerConfig = "<host><balancer storage=\"" + storages
            + "\" /></host>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));
    return balancer;
}
 
Example 13
Source File: EquipartitionHostBalancerTest.java    From development with Apache License 2.0 5 votes vote down vote up
private EquipartitionHostBalancer getBalancer(double memWeight,
        double cpuWeight, double vmWeight) throws ConfigurationException {
    EquipartitionHostBalancer balancer = new EquipartitionHostBalancer();
    String balancerConfig = "<essvcenter><balancer hosts=\"host1,host2,host3,host4,host5\" "
            + "memoryWeight=\""
            + memWeight
            + "\" cpuWeight=\""
            + cpuWeight
            + "\" vmWeight=\"" + vmWeight + "\" /></essvcenter>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));
    return balancer;
}
 
Example 14
Source File: EquipartitionHostBalancerTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testBalancer_wrongConfig() throws Exception {
    // wrong configuration values should simply be ignored
    EquipartitionHostBalancer balancer = new EquipartitionHostBalancer();
    String balancerConfig = "<essvcenter><balancer hosts=\"host1,host2,host3,host4,host5\" "
            + "memoryWeight=\"wrong\" cpuWeight=\"wrong\" vmWeight=\"\" /></essvcenter>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));
}
 
Example 15
Source File: RORClient.java    From development with Apache License 2.0 5 votes vote down vote up
private void getRespStream(XMLConfiguration result, GetMethod get)
		throws ConfigurationException, IOException {
	InputStream in = null;
	try {
		in = get.getResponseBodyAsStream();
		result.load(in);
	} finally {
		if (in != null) {
			in.close();
		}
	}

}
 
Example 16
Source File: XPathUtils.java    From qaf with MIT License 5 votes vote down vote up
/**
 * 
 * @param src
 * @return
 */
public static XMLConfiguration read(String src) {
	try {
		// remove all namespaces from xml
		src = removeNSAndPreamble(src);
		XMLConfiguration config = new XMLConfiguration();
		config.setDelimiterParsingDisabled(true);
		config.load(new ByteArrayInputStream(src.getBytes()));
		config.setExpressionEngine(new XPathExpressionEngine());
		return config;

	} catch (ConfigurationException e) {
		throw new RuntimeException(e);
	}
}
 
Example 17
Source File: SequentialStorageBalancerTest.java    From development with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultiple() throws Exception {

    SequentialStorageBalancer balancer = new SequentialStorageBalancer();

    String balancerConfig = "<host><balancer storage=\"elm1,elm2,elm3,elm4\" /></host>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));

    VMwareDatacenterInventory inventory = new VMwareDatacenterInventory();

    // elm1 does not provide enough resources with respect to configured
    // limit
    VMwareStorage elm = inventory.addStorage("host",
            VMwareDatacenterInventoryTest.createDataStoreProperties("elm1",
                    "100", "40"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("50%"));

    elm = inventory.addStorage("host", VMwareDatacenterInventoryTest
            .createDataStoreProperties("elm2", "100", "100"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("90%"));

    elm = inventory.addStorage("host", VMwareDatacenterInventoryTest
            .createDataStoreProperties("elm3", "100", "100"));
    elm.setEnabled(false);
    elm.setLimit(VMwareValue.parse("90%"));

    elm = inventory.addStorage("host", VMwareDatacenterInventoryTest
            .createDataStoreProperties("elm4", "100", "100"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("90%"));

    balancer.setInventory(inventory);

    // getting elm2 since elm1 is not applicable
    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm2", elm.getName());

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm2", elm.getName());

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm2", elm.getName());

}
 
Example 18
Source File: SequentialStorageBalancerTest.java    From development with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleReduce() throws Exception {

    SequentialStorageBalancer balancer = new SequentialStorageBalancer();

    String balancerConfig = "<host><balancer storage=\"elm1,elm2,elm3\" /></host>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));

    VMwareDatacenterInventory inventory = new VMwareDatacenterInventory();

    VMwareStorage elm = inventory.addStorage("host",
            VMwareDatacenterInventoryTest.createDataStoreProperties("elm1",
                    "100", "100"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("90%"));

    elm = inventory.addStorage("host", VMwareDatacenterInventoryTest
            .createDataStoreProperties("elm2", "100", "100"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("90%"));

    balancer.setInventory(inventory);

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm1", elm.getName());

    // Now shorten list, so "elm2" is not longer next element
    inventory = new VMwareDatacenterInventory();

    elm = inventory.addStorage("host", VMwareDatacenterInventoryTest
            .createDataStoreProperties("elm3", "100", "100"));
    elm.setEnabled(true);
    elm.setLimit(VMwareValue.parse("90%"));
    balancer.setInventory(inventory);

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm3", elm.getName());
}
 
Example 19
Source File: SequentialHostBalancerTest.java    From development with Apache License 2.0 4 votes vote down vote up
@Test
public void testBalancerStorageSequentialMultiple() throws Exception {

    SequentialHostBalancer balancer = new SequentialHostBalancer();

    String balancerConfig = "<essvcenter><balancer hosts=\"elm3,elm2,elm1,elm4\" /></essvcenter>";
    XMLConfiguration xmlConfiguration = new XMLHostConfiguration();
    xmlConfiguration.load(new StringReader(balancerConfig));
    balancer.setConfiguration(xmlConfiguration.configurationAt("balancer"));

    VMwareDatacenterInventory inventory = new VMwareDatacenterInventory();

    VMwareHost elm = inventory.addHostSystem((VMwareDatacenterInventoryTest
            .createHostSystemProperties("elm1", "128", "1")));
    elm.setEnabled(true);

    elm = inventory.addHostSystem((VMwareDatacenterInventoryTest
            .createHostSystemProperties("elm2", "128", "1")));
    elm.setEnabled(true);

    elm = inventory.addHostSystem((VMwareDatacenterInventoryTest
            .createHostSystemProperties("elm3", "128", "1")));
    elm.setEnabled(false);

    elm = inventory.addHostSystem((VMwareDatacenterInventoryTest
            .createHostSystemProperties("elm4", "128", "1")));
    elm.setEnabled(true);

    balancer.setInventory(inventory);

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm2", elm.getName());

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm2", elm.getName());

    elm = balancer.next(properties);
    assertNotNull(elm);
    assertEquals("elm2", elm.getName());
}
 
Example 20
Source File: TestSettings.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testServerSettings()
{
	try
	{
		String configFilePath = new File(".").getCanonicalPath();

		String fileFQN = configFilePath + File.separator
		+ "cfg" + File.separator
		+ "config.xml";

		if(new File(fileFQN).exists())
		{
			XMLConfiguration config = new XMLConfiguration( fileFQN );
			config.load();

			Object servers = config.getProperty("Environment.ConnectionManager.Services.Service[@name]");

			if(servers instanceof Collection<?>)
			{
				for(int i = 0 ; i < ((Collection<?>) servers).size(); i++)
				{
					String key = String.format( "Environment.ConnectionManager.Services.Service(%d)[@type]", i );
					String keyValue = config.getString(key );

                       if("NTG-Server".equals(keyValue))
					{
						String instIdKey = String.format( "Environment.ConnectionManager.Services.Service(%d).strategies.strategy.instrumentID", i );
						Object prop = config.getList(instIdKey);

						if(prop instanceof Collection<?>)
						{
                               NTGServerSettings serverSettings = new NTGServerSettings();
                               Map<String, NTGServerStrategy> strategy = new HashMap<String, NTGServerStrategy>();

							int j = 0 ;

							for(Object instrValue : (Collection<?>)prop)
							{
								//String symbol = config.getString(String.format( "Environment.ConnectionManager.Services.Service(%d).strategies.strategy(%d).instrumentID", i, j));
								String symbol = instrValue.toString();

								if(! strategy.containsKey( symbol ))
								{
									String strategyValueString = config.getString(String.format( "Environment.ConnectionManager.Services.Service(%d).strategies.strategy(%d).strategyValue", i, j));
                                       NTGServerStrategy strategyValue =
                                               Enum.valueOf(NTGServerStrategy.class, strategyValueString);
									strategy.put( symbol, strategyValue );
								}
								++j;
							}

							int heartbeatTimeout = config.getInt(String.format("Environment.ConnectionManager.Services.Service(%d).heartbeatTimeout", i ));
							int maxMissedHeartbeats = config.getInt(String.format("Environment.ConnectionManager.Services.Service(%d).maxMissedHeartbeats", i ));
							int serverPort = config.getInt( String.format("Environment.ConnectionManager.Services.Service(%d).serverPort", i ));
							String serverIP = config.getString(String.format("Environment.ConnectionManager.Services.Service(%d).serverIP", i ));

							serverSettings.setHeartbeatTimeout( heartbeatTimeout );
							serverSettings.setMaxMissedHeartbeats( maxMissedHeartbeats );
							serverSettings.setServerPort( serverPort ) ;
							serverSettings.setServerIP( serverIP ) ;

							serverSettings.setStrategy( strategy );
						}
						break;
					}
					Assert.fail();
				}
			}
		}
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		Assert.fail();
	}
}