List of usage examples for org.apache.commons.configuration XMLConfiguration XMLConfiguration
public XMLConfiguration(URL url) throws ConfigurationException
XMLConfiguration
. From source file:au.com.dw.testdatacapturej.config.Configuration.java
/** * Load the setter configurations from file. * //from w w w .j a v a2s. c o m * An example of the XML structure: * * <setter class="dummy.Classname"> * <argument> * <field-name>paramFieldName</field-name> * <alternative>ignore</alternative> * </argument> * <argument> * <field-name>param2FieldName</field-name> * <alternative>ignore</alternative> * </argument> * * . * . * . * * Note that the <alternative> tag is currently unused, it is a placeholder for future dev is we * want to substitute a setter method name. * */ private void readSetterConfigFile(String[] configFileNames) { XMLConfiguration xmlConfig = null; try { for (String fileName : configFileNames) { xmlConfig = new XMLConfiguration(fileName); if (xmlConfig != null) { // get all the setter nodes and iterate through them List<?> constructorNodes = xmlConfig.configurationsAt("setter"); for (Iterator<?> it = constructorNodes.iterator(); it.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next(); // sub contains now all data about a single field String className = sub.getString("[@class]"); List<String> paramFieldNames = configUtil.toStringList(sub.getList("field.field-name")); if (paramFieldNames != null && !paramFieldNames.isEmpty()) { setters.put(className, paramFieldNames); } } } } } catch (ConfigurationException cex) { cex.printStackTrace(); } }
From source file:com.legstar.config.commons.LegStarConfigCommons.java
/** * Loads an XML configuration from file. * /*from ww w. j ava 2 s . c o m*/ * @param configFileName the configuration file name * @return the in-memory XML configuration * @throws LegStarConfigurationException if configuration failed to load */ protected HierarchicalConfiguration loadGeneralConfig(final String configFileName) throws LegStarConfigurationException { try { if (_log.isDebugEnabled()) { _log.debug("Loading configuration file: " + configFileName); } /* First try as if it is a single configuration file */ HierarchicalConfiguration generalConfig = new XMLConfiguration(configFileName); /* * If the first tag is additional, then this is a combined * configuration * that needs to be loaded in a specific way. */ if (generalConfig.configurationsAt("additional").size() > 0) { DefaultConfigurationBuilder dcb = new DefaultConfigurationBuilder(); dcb.setFileName(configFileName); generalConfig = (HierarchicalConfiguration) dcb.getConfiguration(true) .getConfiguration(DefaultConfigurationBuilder.ADDITIONAL_NAME); } generalConfig.setExpressionEngine(new XPathExpressionEngine()); return generalConfig; } catch (ConfigurationException e) { throw new LegStarConfigurationException(e); } }
From source file:br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader.java
/** * Returns the configuration class according to specified resource name and configuration type. * /*from ww w . j av a2 s . c o m*/ * @param resource * @param type * @return a configuration */ private org.apache.commons.configuration.Configuration getConfiguration(String resource, ConfigType type) { org.apache.commons.configuration.Configuration config = null; try { switch (type) { case SYSTEM: config = new SystemConfiguration(); break; case PROPERTIES: config = new PropertiesConfiguration(resource + ".properties"); break; case XML: config = new XMLConfiguration(resource + ".xml"); break; default: throw new ConfigurationException( bundle.getString("configuration-type-not-implemented-yet", type.name())); } } catch (Exception cause) { throw new ConfigurationException( bundle.getString("error-creating-configuration-from-resource", resource), cause); } return config; }
From source file:eu.eubrazilcc.lvl.core.conf.ConfigurationManager.java
private Configuration configuration() { if (dont_use == null) { synchronized (Configuration.class) { if (dont_use == null && urls != null) { try { XMLConfiguration main = null; // sorting secondary configurations ensures that combination always result the same final SortedMap<String, XMLConfiguration> secondary = newTreeMap(); // extract main configuration for (final URL url : urls) { final String filename = getName(url.getPath()); if (MAIN_CONFIG.equalsIgnoreCase(filename)) { main = new XMLConfiguration(url); LOGGER.info("Loading main configuration from: " + url.toString()); } else if (!IGNORE_LIST.contains(getName(url.getPath()))) { secondary.put(filename, new XMLConfiguration(url)); LOGGER.info("Loading secondary configuration from: " + url.toString()); } else { LOGGER.info("Ignoring: " + url.toString()); }/*w w w . j a va 2s.c o m*/ } if (main != null) { final CombinedConfiguration configuration = new CombinedConfiguration( new OverrideCombiner()); configuration.addConfiguration(main, MAIN_CONFIG); for (final Map.Entry<String, XMLConfiguration> entry : secondary.entrySet()) { configuration.addConfiguration(entry.getValue(), entry.getKey()); } if (LOGGER.isDebugEnabled()) { String names = ""; for (final String name : configuration.getConfigurationNameList()) { names += name + " "; } LOGGER.trace("Loading configuration from: " + names); } final List<String> foundNameList = newArrayList(); // get main property will fail if the requested property is missing configuration.setThrowExceptionOnMissing(true); final File rootDir = getFile("lvl-root", configuration, foundNameList, true, null); final File localCacheDir = getFile("storage.local-cache", configuration, foundNameList, true, null); final File htdocsDir = getFile("storage.htdocs", configuration, foundNameList, false, null); final String dbName = getString("database.name", configuration, foundNameList, "lvldb"); final String dbUsername = getString("database.credentials.username", configuration, foundNameList, null); final String dbPassword = getString("database.credentials.password", configuration, foundNameList, null); final ImmutableList<String> dbHosts = getStringList("database.hosts.host", Pattern.compile("^[\\w]+:[\\d]+$"), configuration, foundNameList, newArrayList("localhost:27017")); final boolean brokerEmbedded = getBoolean("broker.embedded", configuration, foundNameList, true); final ImmutableList<String> messageBrokers = getStringList("messaging.hosts.host", Pattern.compile("^[\\w]+:[\\d]+$"), configuration, foundNameList, newArrayList("localhost:61616")); final String smtpHost = getString("smtp.host", configuration, foundNameList, "localhost"); final int smtpPort = getInteger("smtp.port", configuration, foundNameList, 25); final String smtpSupportEmail = getString("smtp.support-email", configuration, foundNameList, "support@example.com"); final String smtpNoreplyEmail = getString("smtp.noreply-email", configuration, foundNameList, "noreply@example.com"); final String portalEndpoint = getString("portal.endpoint", configuration, foundNameList, null); final String wfHostname = getString("workflow.endpoint.hostname", configuration, foundNameList, "localhost"); final boolean wfSecure = getBoolean("workflow.endpoint.secure", configuration, foundNameList, false); final int wfPort = getInteger("workflow.endpoint.port", configuration, foundNameList, wfSecure ? 443 : 80); final String wfUsername = getString("workflow.credentials.username", configuration, foundNameList, null); final String wfPasswd = getString("workflow.credentials.password", configuration, foundNameList, null); // get secondary property will return null if the requested property is missing configuration.setThrowExceptionOnMissing(false); final String linkedInAPIKey = getString("authz-server.linkedin.api-key", configuration, foundNameList, null); final String linkedInSecretKey = getString("authz-server.linkedin.secret-key", configuration, foundNameList, null); final String googleAPIKey = getString("rest-service.google.api-key", configuration, foundNameList, null); // get other (free-format) properties final Iterator<String> keyIterator = configuration.getKeys(); final Map<String, String> othersMap = new Hashtable<String, String>(); while (keyIterator.hasNext()) { final String key = keyIterator.next(); if (key != null && !foundNameList.contains(key)) { final String value = configuration.getString(key); if (value != null) { othersMap.put(key, value); } } } dont_use = new Configuration(rootDir, localCacheDir, htdocsDir, dbName, dbUsername, dbPassword, dbHosts, brokerEmbedded, messageBrokers, smtpHost, smtpPort, smtpSupportEmail, smtpNoreplyEmail, portalEndpoint, wfHostname, wfSecure, wfPort, wfUsername, wfPasswd, linkedInAPIKey, linkedInSecretKey, googleAPIKey, othersMap); LOGGER.info(dont_use.toString()); } else { throw new IllegalStateException("Main configuration not found"); } } catch (IllegalStateException e1) { throw e1; } catch (ConfigurationException e2) { throw new IllegalStateException(e2); } catch (Exception e) { LOGGER.error("Failed to load configuration", e); } } } } return dont_use; }
From source file:com.microrisc.simply.init.SimpleInitObjectsFactory.java
/** * Creates and returns mapper of device interfaces to theirs implementing classes. * @param configuration source configuration * @return mapper of device interfaces to theirs implementing classes. * @throws java.lang.Exception if an error has occured during creating of * mapper//from w w w . j av a 2s .co m */ protected ImplClassesMapper createImplClassesMapper(Configuration configuration) throws Exception { String mappingFile = configuration.getString("implClassesMapping.configFile"); XMLConfiguration mapperConfig = new XMLConfiguration(mappingFile); // get all "interfaceMappings" nodes List<HierarchicalConfiguration> implMappings = mapperConfig.configurationsAt("implMapping"); // if no implementation class mapping exists, throw Exception if (implMappings.isEmpty()) { throw new SimplyException("Implementation mapping: No implementation class mapping exist"); } // mapping Map<Class, Class> ifaceToImpl = new HashMap<>(); // read in all impl mappings for (HierarchicalConfiguration implMapping : implMappings) { String ifaceStr = implMapping.getString("interface"); String implStr = implMapping.getString("implClass"); Class ifaceClass = Class.forName(ifaceStr); Class implClass = Class.forName(implStr); ifaceToImpl.put(ifaceClass, implClass); } return new SimpleImplClassesMapper(ifaceToImpl); }
From source file:edu.kit.dama.staging.util.StagingConfigurationManager.java
/** * Perform the configuration for the staging. This covers reading the * configuration from one supported source (env. variable, file, resource) * and the actual setup. If anything fails the staging will not work and a * StagingIntitializationException is thrown. *///from w w w . j a va 2 s. c o m private void configure() { boolean initialized = false; try { LOGGER.debug("Searching for staging configuration URL"); URL configUrl = DataManagerSettings.getConfigurationURL(); if (configUrl == null) { throw new StagingIntitializationException("No configuration file found."); } LOGGER.debug("Trying to configure staging from URL {}", configUrl); stagingConfig = new HierarchicalConfiguration(new XMLConfiguration(configUrl)) .configurationAt(STAGING_CONFIG_ROOT); initialized = true; } catch (org.apache.commons.configuration.ConfigurationException ce) { LOGGER.warn("Failed to configure staging using provided configuration", ce); } if (!initialized) { throw new StagingIntitializationException( "Staging not initialized. Probably, the provided configuration is invalid."); } LOGGER.debug("Configuring staging persistence"); configurePU(stagingConfig); LOGGER.debug("Obtaining staging access points from database"); List<StagingAccessPointConfiguration> accessPoints = StagingConfigurationPersistence.getSingleton(stagingPU) .findAllAccessPointConfigurations(); for (StagingAccessPointConfiguration accessPoint : accessPoints) { configureAccessPoint(accessPoint); } LOGGER.debug("Configurung external adapters"); configureAdapters(stagingConfig); LOGGER.debug("Configuring remote access"); configureRemoteAccess(stagingConfig); LOGGER.debug("Configuring mail notification"); configureMailNotifier(); LOGGER.debug("Configuration finished."); }
From source file:com.epam.ngb.cli.app.ConfigurationLoader.java
private Configuration loadXmlConfiguration(String filename) { XMLConfiguration config;/* www .ja v a2 s. c o m*/ try { config = new XMLConfiguration(getClass().getResource(filename)); } catch (ConfigurationException e) { throw new ApplicationException(MessageConstants.getMessage(ERROR_LOAD_CONFIG_FILE, filename), e); } return config; }
From source file:edu.cornell.med.icb.R.RConnectionPool.java
/** * Configure the rserve instances available to this pool using an xml based * configuration at the specified URL.//from w ww . j a v a 2s .com * @param configurationURL The URL of the configuration to use * @throws ConfigurationException if the configuration cannot be built from the url */ private void configure(final URL configurationURL) throws ConfigurationException { configuration = new XMLConfiguration(configurationURL); configure(configuration); }
From source file:edu.usc.goffish.gofs.tools.GoFSDeployGraph.java
@SuppressWarnings("deprecation") public static void main(String[] args) throws IOException { if (args.length < REQUIRED_ARGS) { PrintUsageAndQuit(null);// w ww .j ava2s . com } if (args.length == 1 && args[0].equals("-help")) { PrintUsageAndQuit(null); } // optional arguments boolean overwriteGraph = false; PartitionerMode partitionerMode = PartitionerMode.METIS; ComponentizerMode componentizerMode = ComponentizerMode.WCC; MapperMode mapperMode = MapperMode.ROUNDROBIN; PartitionedFileMode partitionedFileMode = PartitionedFileMode.DEFAULT; DistributerMode distributerMode = DistributerMode.SCP; int instancesGroupingSize = 1; int numSubgraphBins = -1; // optional sub arguments Path metisBinaryPath = null; String[] extraMetisOptions = null; Path partitioningPath = null; Path partitionedGMLFilePath = null; // parse optional arguments int i = 0; OptArgLoop: for (i = 0; i < args.length - REQUIRED_ARGS; i++) { switch (args[i]) { case "-overwriteGraph": overwriteGraph = true; break; case "-partitioner": i++; if (args[i].equals("stream")) { partitionerMode = PartitionerMode.STREAM; } else if (args[i].startsWith("metis")) { String[] subargs = parseSubArgs('=', args[i]); if (subargs[0].equals("metis")) { partitionerMode = PartitionerMode.METIS; if (subargs.length > 1) { try { metisBinaryPath = Paths.get(subargs[1]); if (!metisBinaryPath.isAbsolute()) { throw new InvalidPathException(metisBinaryPath.toString(), "metis binary path must be absolute"); } } catch (InvalidPathException e) { PrintUsageAndQuit("metis binary - " + e.getMessage()); } if (subargs.length > 2) { extraMetisOptions = parseSubArgs(' ', subargs[2]); } } } else { PrintUsageAndQuit(null); } } else if (args[i].startsWith("predefined")) { String[] subargs = parseSubArgs('=', args[i]); if (subargs[0].equals("predefined")) { partitionerMode = PartitionerMode.PREDEFINED; if (subargs.length < 2) { PrintUsageAndQuit(null); } try { partitioningPath = Paths.get(subargs[1]); } catch (InvalidPathException e) { PrintUsageAndQuit("partitioning file - " + e.getMessage()); } } else { PrintUsageAndQuit(null); } } else { PrintUsageAndQuit(null); } break; case "-intermediategml": if (args[i + 1].startsWith("save")) { i++; String[] subargs = parseSubArgs('=', args[i]); if (subargs[0].equals("save")) { if (subargs.length < 2) { PrintUsageAndQuit(null); } partitionedFileMode = PartitionedFileMode.SAVE; try { partitionedGMLFilePath = Paths.get(subargs[1]); } catch (InvalidPathException e) { PrintUsageAndQuit("partitioned gml file - " + e.getMessage()); } } } else { partitionedFileMode = PartitionedFileMode.READ; } break; case "-componentizer": i++; switch (args[i]) { case "single": componentizerMode = ComponentizerMode.SINGLE; break; case "wcc": componentizerMode = ComponentizerMode.WCC; break; default: PrintUsageAndQuit(null); } break; case "-distributer": i++; switch (args[i]) { case "scp": distributerMode = DistributerMode.SCP; break; case "write": distributerMode = DistributerMode.WRITE; break; default: PrintUsageAndQuit(null); } break; case "-mapper": i++; if (args[i].equalsIgnoreCase("roundrobin")) { mapperMode = MapperMode.ROUNDROBIN; } else { PrintUsageAndQuit(null); } break; case "-serializer:instancegroupingsize": i++; try { if (args[i].equalsIgnoreCase("ALL")) { instancesGroupingSize = Integer.MAX_VALUE; } else { instancesGroupingSize = Integer.parseInt(args[i]); if (instancesGroupingSize < 1) { PrintUsageAndQuit("Serialization instance grouping size must be greater than zero"); } } } catch (NumberFormatException e) { PrintUsageAndQuit("Serialization instance grouping size - " + e.getMessage()); } break; case "-serializer:numsubgraphbins": i++; try { numSubgraphBins = Integer.parseInt(args[i]); if (instancesGroupingSize < 1) { PrintUsageAndQuit("Serialization number of subgraph bins must be greater than zero"); } } catch (NumberFormatException e) { PrintUsageAndQuit("Serialization number of subgraph bins - " + e.getMessage()); } break; default: break OptArgLoop; } } if (args.length - i < REQUIRED_ARGS) { PrintUsageAndQuit(null); } // required arguments IInternalNameNode nameNode = null; Class<? extends IInternalNameNode> nameNodeType = null; URI nameNodeLocation = null; String graphId = null; int numPartitions = 0; Path gmlTemplatePath = null; List<Path> gmlInstancePaths = new LinkedList<>(); // parse required arguments try { nameNodeType = NameNodeProvider.loadNameNodeType(args[i]); i++; } catch (ReflectiveOperationException e) { PrintUsageAndQuit("name node type - " + e.getMessage()); } try { nameNodeLocation = new URI(args[i]); i++; } catch (URISyntaxException e) { PrintUsageAndQuit("name node location - " + e.getMessage()); } try { nameNode = NameNodeProvider.loadNameNode(nameNodeType, nameNodeLocation); } catch (ReflectiveOperationException e) { PrintUsageAndQuit("error loading name node - " + e.getMessage()); } graphId = args[i++]; try { numPartitions = Integer.parseInt(args[i]); i++; } catch (NumberFormatException e) { PrintUsageAndQuit("number of partitions - " + e.getMessage()); } Path gmlInputFile = null; try { gmlInputFile = Paths.get(args[i]); i++; } catch (InvalidPathException e) { PrintUsageAndQuit(e.getMessage()); } // finished parsing args if (i < args.length) { PrintUsageAndQuit("Unrecognized argument \"" + args[i] + "\""); } // ensure name node is available if (!nameNode.isAvailable()) { throw new IOException("Name node at " + nameNode.getURI() + " is not available"); } // ensure there are data nodes available Set<URI> dataNodes = nameNode.getDataNodes(); if (dataNodes == null || dataNodes.isEmpty()) { throw new IllegalArgumentException("name node does not have any data nodes available for deployment"); } // ensure graph id does not exist (unless to be overwritten) IntCollection partitions = nameNode.getPartitionDirectory().getPartitions(graphId); if (partitions != null) { if (!overwriteGraph) { throw new IllegalArgumentException( "graph id \"" + graphId + "\" already exists in name node partition directory"); } else { for (int partitionId : partitions) { nameNode.getPartitionDirectory().removePartitionMapping(graphId, partitionId); } } } IGraphLoader loader = null; IPartitioner partitioner = null; if (partitionedFileMode != PartitionedFileMode.READ) { XMLConfiguration configuration; try { configuration = new XMLConfiguration(gmlInputFile.toFile()); configuration.setDelimiterParsingDisabled(true); //read the template property gmlTemplatePath = Paths.get(configuration.getString("template")); //read the instance property for (Object instance : configuration.getList("instances.instance")) { gmlInstancePaths.add(Paths.get(instance.toString())); } } catch (ConfigurationException | InvalidPathException e) { PrintUsageAndQuit("gml input file - " + e.getMessage()); } // create loader loader = new GMLGraphLoader(gmlTemplatePath); // create partitioner switch (partitionerMode) { case METIS: if (metisBinaryPath == null) { partitioner = new MetisPartitioner(); } else { partitioner = new MetisPartitioner(metisBinaryPath, extraMetisOptions); } break; case STREAM: partitioner = new StreamPartitioner(new LDGObjectiveFunction()); break; case PREDEFINED: partitioner = new PredefinedPartitioner( MetisPartitioning.read(Files.newInputStream(partitioningPath))); break; default: PrintUsageAndQuit(null); } } // create componentizer IGraphComponentizer graphComponentizer = null; switch (componentizerMode) { case SINGLE: graphComponentizer = new SingleComponentizer(); break; case WCC: graphComponentizer = new WCCComponentizer(); break; default: PrintUsageAndQuit(null); } // create mapper IPartitionMapper partitionMapper = null; switch (mapperMode) { case ROUNDROBIN: partitionMapper = new RoundRobinPartitionMapper(nameNode.getDataNodes()); break; default: PrintUsageAndQuit(null); } // create serializer ISliceSerializer serializer = nameNode.getSerializer(); if (serializer == null) { throw new IOException("name node at " + nameNode.getURI() + " returned null serializer"); } // create distributer IPartitionDistributer partitionDistributer = null; switch (distributerMode) { case SCP: partitionDistributer = new SCPPartitionDistributer(serializer, instancesGroupingSize, numSubgraphBins); break; case WRITE: partitionDistributer = new DirectWritePartitionDistributer(serializer, instancesGroupingSize, numSubgraphBins); break; } GMLPartitionBuilder partitionBuilder = null; try { System.out.print("Executing command: DeployGraph"); for (String arg : args) { System.out.print(" " + arg); } System.out.println(); // perform deployment long time = System.currentTimeMillis(); switch (partitionedFileMode) { case DEFAULT: partitionBuilder = new GMLPartitionBuilder(graphComponentizer, gmlTemplatePath, gmlInstancePaths); deploy(nameNode.getPartitionDirectory(), graphId, numPartitions, loader, partitioner, partitionBuilder, null, partitionMapper, partitionDistributer); break; case SAVE: //save partitioned gml files partitionBuilder = new GMLPartitionBuilder(partitionedGMLFilePath, graphComponentizer, gmlTemplatePath, gmlInstancePaths); //partitioned gml input file name format as graphid_numpartitions_paritioningtype_serializer String intermediateGMLInputFile = new StringBuffer().append(graphId).append("_") .append(numPartitions).append("_").append(partitionerMode.name().toLowerCase()).append("_") .append(serializer.getClass().getSimpleName().toLowerCase()).toString(); deploy(nameNode.getPartitionDirectory(), graphId, numPartitions, loader, partitioner, partitionBuilder, intermediateGMLInputFile, partitionMapper, partitionDistributer); break; case READ: //read partitioned gml files partitionBuilder = new GMLPartitionBuilder(graphComponentizer); partitionBuilder.new XMLConfigurationBuilder(gmlInputFile.toFile().getAbsolutePath()) .readIntermediateGMLFile(); deploy(nameNode.getPartitionDirectory(), graphId, numPartitions, partitionBuilder, partitionMapper, partitionDistributer); break; } System.out.println("finished [total " + (System.currentTimeMillis() - time) + "ms]"); } finally { if (partitionBuilder != null) partitionBuilder.close(); } }
From source file:com.intuit.tank.proxy.config.CommonsProxyConfiguration.java
public static boolean save(int port, boolean followRedirect, String outputFile, Set<ConfigInclusionExclusionRule> inclusions, Set<ConfigInclusionExclusionRule> exclusions, Set<ConfigInclusionExclusionRule> bodyInclusions, Set<ConfigInclusionExclusionRule> bodyExclusions, String fileName) {/*from w w w . j av a2 s. c om*/ ConfigurationNode node = getConfNode("recording-proxy-config", "", false); ConfigurationNode portNode = getConfNode("proxy-port", String.valueOf(port), false); ConfigurationNode followRedirectNode = getConfNode("follow-redirects", Boolean.toString(followRedirect), false); ConfigurationNode outputFileNode = getConfNode("output-file", outputFile, false); ConfigurationNode inclusionsNode = getConfNode("inclusions", "", false); ConfigurationNode exclusionsNode = getConfNode("exclusions", "", false); ConfigurationNode bodyInclusionsNode = getConfNode("body-inclusions", "", false); ConfigurationNode bodyExclusionsNode = getConfNode("body-exclusions", "", false); updateRuleParentNode(inclusions, inclusionsNode); updateRuleParentNode(exclusions, exclusionsNode); updateRuleParentNode(bodyInclusions, bodyInclusionsNode); updateRuleParentNode(bodyExclusions, bodyExclusionsNode); node.addChild(portNode); node.addChild(followRedirectNode); node.addChild(outputFileNode); node.addChild(inclusionsNode); node.addChild(exclusionsNode); node.addChild(bodyInclusionsNode); node.addChild(bodyExclusionsNode); HierarchicalConfiguration hc = new HierarchicalConfiguration(); hc.setRootNode(node); XMLConfiguration xmlConfiguration = new XMLConfiguration(hc); xmlConfiguration.setRootNode(node); try { xmlConfiguration.save(new File(fileName)); } catch (ConfigurationException e) { e.printStackTrace(); } return true; }