List of usage examples for org.apache.commons.configuration XMLConfiguration XMLConfiguration
public XMLConfiguration(URL url) throws ConfigurationException
XMLConfiguration
. From source file:jdbc.pool.CXMLManager.java
/** * Constructs the Configuration Manager around a supplied xml file. * //from w w w .j a va2 s . co m * @param file * XML configuration file. * @throws ConfigurationException */ protected CXMLManager(File file) throws ConfigurationException { super(file); xmlPoolConfig = new XMLConfiguration(file); logger_ = Logger.getLogger(this.getClass().getName()); }
From source file:com.dfki.av.sudplan.Configuration.java
/** * Save the configuration file {@code config/sudplan3D.xml} from the * resources to the the file {@code file}. Adding the additional properties * {@code sudplan3D.user.dir} and {@code sudplan3D.working.dir}. * * @param file the configuration {@link File} * @param userHomeDir the user home directory * @param workingDir the working directory *//*from w ww.java2s . c o m*/ private static void installConfigFile(File file, String userHomeDir, String workingDir) { log.debug("Installing configuration to {}...", file.getAbsoluteFile()); try { ClassLoader loader = Configuration.class.getClassLoader(); URL url = loader.getResource("config/sudplan3D.xml"); XMLConfiguration xmlInitialConfig = new XMLConfiguration(url); xmlInitialConfig.addProperty("sudplan3D.user.dir", userHomeDir); xmlInitialConfig.addProperty("sudplan3D.working.dir", workingDir); xmlInitialConfig.save(file); } catch (ConfigurationException ex) { log.error(ex.toString()); } }
From source file:com.tamnd.core.util.ZConfig.java
private static Configuration LoadFromFile(String path) throws ConfigurationException { if (path.endsWith(".ini") || path.endsWith(".properties")) { HierarchicalINIConfiguration config = new HierarchicalINIConfiguration(); config.setDelimiterParsingDisabled(true); config.setFileName(path);/*w w w. ja v a 2 s. com*/ config.load(); return config; } else if (path.endsWith(".xml")) { return new XMLConfiguration(path); } else { throw new ConfigurationException("Unknown configuration file extension"); } }
From source file:com.github.technosf.posterer.transports.commons.CommonsConfiguratorPropertiesImpl.java
/** * @param prefix/*from w w w . j a va2s. co m*/ * @throws IOException * @throws ConfigurationException */ @Inject public CommonsConfiguratorPropertiesImpl(@Named("PropertiesPrefix") final String prefix) throws IOException, ConfigurationException { super(prefix); if (!propsFile.exists() || FileUtils.sizeOf(propsFile) < blankfile.length()) // Touch the properties file { FileUtils.writeStringToFile(propsFile, blankfile); } FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); strategy.setRefreshDelay(5000); config = new XMLConfiguration(propsFile); config.setExpressionEngine(new XPathExpressionEngine()); config.setReloadingStrategy(strategy); initializeRequestSet(); }
From source file:core.commonapp.server.data.RequiredDataReader.java
/** * Initialize data reader// w ww .java 2 s. c o m * * if there are relationships that need to be defined. In the xml define the * forgein relation first. Then reference the relation as the value of the * columns with ${RelationType.KeyValue}. The relation type is the class * name with no package. i.e. 'forgeinKey=${GeoType._STATE}' */ public void read(String filename) { try { log.debug("Reading data file {0}.", filename); XMLConfiguration reader = new XMLConfiguration(getClass().getResource(filename)); List<SubnodeConfiguration> records = reader.configurationsAt("record"); for (SubnodeConfiguration record : records) { String beanName = record.getString("[@bean]"); Object object = context.getBean(beanName); ConfigurationNode node = record.getRootNode(); List<ConfigurationNode> attributes = node.getAttributes(); // attempt to load from db, if found then use it to update // instead of a new object to insert Object dbObject = null; String key = record.getString("[@key]"); if (object instanceof Keyable && key != null) { Keyable keyable = (Keyable) object; // FIXME: Find existing record // KeyedCache cache = context.getBean(KeyedCache.class); // // // KeyedCacheStore<?> store = cache.getCacheStore(object.getClass()); // // // // // Object dao = context.getBean("defaultDao"); // dbObject = ((DefaultDao) dao).getEntityManager().createQuery(" from " + object.getClass() + " where key = " + key); if (dbObject != null) { log.debug("Found keyed object in database (dbObject={0}).", dbObject); // set the object to the one in the db so we can update the // fields with data from xml object = dbObject; } } for (ConfigurationNode attribute : attributes) { String name = attribute.getName(); String value = (String) attribute.getValue(); if (value.startsWith("$")) { // remove the wrapping ${...} // TODO: reg expr error check format value = value.substring(2); value = value.substring(0, value.length() - 1); log.debug("Static data reference found (refId={0})", value); // set method String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method method = getMethod(object, methodName); method.invoke(object, referenceMap.get(value)); } else if ("%CURRENT_TIMESTAMP".equals(value)) { String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method method = getMethod(object, methodName); method.invoke(object, new Date()); } else if ("refId".equals(name)) { referenceMap.put(value, object); log.debug("Adding declared reference object by id (refId={0},object={1}).", value, object); } else if (!"bean".equals(name)) { String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method method = getMethod(object, methodName); method.invoke(object, value); } } // if the object is keyable then infer the reference if (object instanceof Keyable) { Keyable keyable = (Keyable) object; String refId = keyable.getClass().getSimpleName().replace("HibernateImpl", "") + "." + keyable.getKey(); referenceMap.put(refId, object); log.debug("Inferred reference for object (refId={0},object={1}).", refId, object); } // add object to list for saving dataObjects.add(object); } } catch (ConfigurationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }
From source file:ezbake.IntentQuery.Sample.MongoDatasource.Server.MongoExternalDataSourceHandler.java
/*********** <tablesMetaData>/*from w w w . j a v a 2 s .c o m*/ <num_table>1</num_table> <tables> <table> <name>impalaTest_users</name> <num_columns>6</num_columns> <init_string></init_string> <columns> <column> <name>user_id</name> <primitiveType>INT</primitiveType> <len></len> <precision></precision> <scale></scale> <ops>LT,LE,EQ,NEQ,GE,GT</ops> </column> ... <column> </column> <columns> </table> <table> </table> </tables> </tablesMetaData> ***********/ private void parseDataSourceMetadata() { table_metadata_map = new HashMap<String, TableMetadata>(); try { Configuration xmlConfig = new XMLConfiguration(impalaExternalDsConfigFile); dbHost = xmlConfig.getString("mongodb.host"); dbPort = xmlConfig.getInt("mongodb.port"); dbName = xmlConfig.getString("mongodb.database_name"); String key = null; String table_name = null; int num_columns = -1; String init_str = null; List<TableColumnDesc> table_col_desc_list = new ArrayList<TableColumnDesc>(); int total_tables = xmlConfig.getInt("tablesMetaData.num_table"); for (int i = 0; i < total_tables; i++) { // get table name key = String.format("tablesMetaData.tables.table(%d).name", i); table_name = xmlConfig.getString(key); // get table number of columns key = String.format("tablesMetaData.tables.table(%d).num_columns", i); num_columns = xmlConfig.getInt(key); // get table init_string key = String.format("tablesMetaData.tables.table(%d).init_string", i); init_str = xmlConfig.getString(key); // get columns String col_name = null; String col_type = null; int col_len = 0; int col_precision = 0; int col_scale = 0; Set<String> col_ops = null; for (int j = 0; j < num_columns; j++) { key = String.format("tablesMetaData.tables.table(%d).columns.column(%d).name", i, j); col_name = xmlConfig.getString(key); key = String.format("tablesMetaData.tables.table(%d).columns.column(%d).primitiveType", i, j); col_type = xmlConfig.getString(key); if (col_type.equals("CHAR")) { key = String.format("tablesMetaData.tables.table(%d).columns.column(%d).len", i, j); col_len = xmlConfig.getInt(key); } else if (col_type.equals("DECIMAL")) { key = String.format("tablesMetaData.tables.table(%d).columns.column(%d).precision", i, j); col_precision = xmlConfig.getInt(key); key = String.format("tablesMetaData.tables.table(%d).columns.column(%d).scale", i, j); col_scale = xmlConfig.getInt(key); } key = String.format("tablesMetaData.tables.table(%d).columns.column(%d).ops", i, j); //List<String> opsList = xmlConfig.getList(key); String[] opsArray = xmlConfig.getStringArray(key); col_ops = new HashSet<String>(Arrays.asList(opsArray)); TableColumnDesc tableColumnDesc = new TableColumnDesc(col_name, col_type, col_len, col_precision, col_scale, col_ops); table_col_desc_list.add(tableColumnDesc); } TableMetadata tableMetadata = new TableMetadata(table_name, num_columns, init_str, table_col_desc_list); System.out.println(tableMetadata); table_metadata_map.put(table_name, tableMetadata); } } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.vmware.qe.framework.datadriven.config.DDComponentsConfig.java
private DDComponentsConfig() throws DDException { log.info("Initializing Components..."); final XMLConfiguration ddconfig; try {/*from ww w.j av a 2 s .com*/ log.info("Config file '{}'", DD_COMPONENT_CONFIG_FILE_NAME); URL cfgFile = this.getClass().getResource(DD_COMPONENT_CONFIG_FILE_NAME); log.info("Loading Components from: {}", cfgFile); ddconfig = new XMLConfiguration(cfgFile.getFile()); } catch (Exception e) { throw new DDException("Error loading File: " + DD_COMPONENT_CONFIG_FILE_NAME, e); } List<HierarchicalConfiguration> suppliers = ddconfig.configurationsAt(TAG_DATA_SUPPLIER); for (HierarchicalConfiguration supplier : suppliers) { String name = supplier.getString(TAG_NAME); String className = supplier.getString(TAG_CLASS); Class<?> clazz = registerClass(className); DataSupplier dataSupplier; try { dataSupplier = (DataSupplier) clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DDException("Error in creating supplier instance", e); } dataSupplierMap.put(name, dataSupplier); if (supplier.getBoolean(TAG_DEFAULT_ATTR, false)) { if (dataSupplierMap.containsKey(KEY_DEFAULT)) { throw new DDException("multiple default supplier configuration found!!!"); } else { dataSupplierMap.put(KEY_DEFAULT, dataSupplier); } } } log.info("Data Suppliers: {}", dataSupplierMap.keySet()); List<HierarchicalConfiguration> generators = ddconfig.configurationsAt(TAG_DATA_GENERATOR); for (HierarchicalConfiguration generator : generators) { String name = generator.getString(TAG_NAME); String className = generator.getString(TAG_CLASS); Class<?> clazz = registerClass(className); DataGenerator dataGenerator; try { dataGenerator = (DataGenerator) clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DDException("Error in creating generator instance", e); } dataGeneratorMap.put(name, dataGenerator); if (generator.getBoolean(TAG_DEFAULT_ATTR, false)) { if (dataGeneratorMap.containsKey(KEY_DEFAULT)) { throw new DDException("multiple default supplier configuration found!!!"); } else { dataGeneratorMap.put(KEY_DEFAULT, dataGenerator); } } } log.info("Data Generators: {}", dataGeneratorMap.keySet()); List<HierarchicalConfiguration> filters = ddconfig.configurationsAt(TAG_DATA_FILTER); for (HierarchicalConfiguration filter : filters) { String name = filter.getString(TAG_NAME); String className = filter.getString(TAG_CLASS); Class<?> clazz = registerClass(className); DataFilter dataFilter; try { dataFilter = (DataFilter) clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DDException("Error in creating filter instance", e); } dataFilterMap.put(name, dataFilter); } log.info("Data Filters {}", dataFilterMap.keySet()); // No default for filters, all will be applied... List<HierarchicalConfiguration> instanceCreators = ddconfig.configurationsAt(TAG_INSTANCE_CREATOR); for (HierarchicalConfiguration instanceCreator : instanceCreators) { String name = instanceCreator.getString(TAG_NAME); String className = instanceCreator.getString(TAG_CLASS); Class<?> clazz = registerClass(className); TestInstanceCreator testInstanceCreator; try { testInstanceCreator = (TestInstanceCreator) clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DDException("Error in creating testInstanceCreator instance", e); } instanceCreatorMap.put(name, testInstanceCreator); if (instanceCreator.getBoolean(TAG_DEFAULT_ATTR, false)) { instanceCreatorMap.put(KEY_DEFAULT, testInstanceCreator); } } log.info("Instance Creators: {}", instanceCreatorMap.keySet()); List<HierarchicalConfiguration> dataInjectors = ddconfig.configurationsAt(TAG_DATA_INJECTOR); for (HierarchicalConfiguration dataInjector : dataInjectors) { String name = dataInjector.getString(TAG_NAME); String className = dataInjector.getString(TAG_CLASS); Class<?> clazz = registerClass(className); DataInjector dataInjectorObj; try { dataInjectorObj = (DataInjector) clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DDException("Error in creating DataInjector instance", e); } dataInjectorMap.put(name, dataInjectorObj); if (dataInjector.getBoolean(TAG_DEFAULT_ATTR, false)) { dataInjectorMap.put(KEY_DEFAULT, dataInjectorObj); } } log.info("Data Injectors : {}", dataInjectorMap.keySet()); }
From source file:net.handle.servlet.OpenHandleServlet.java
/** * <p>/* www . ja v a2 s .com*/ * Performs steps necessary to correctly configure and initialize this * servlet. At present, this consists of the following: * </p> * <ol> * <li>Attempting to load a custom config, if one is specified as an * init-param using the key 'config'.</li> * <li>Loading the default config if no custom config is available.</li> * <li>Loading up an instance of {@link Settings} from the config.</li> * <li>Initializing an instance of {@link OpenHandle} to act as a resolver.</li> * </ol> * <p> * A custom configuration detailing available templates, handle client * options, and request parameter names can be specified as an init-param: * </p> * * <pre> * <init-param> * <param-name>config</param-name> * <param-value>/WEB-INF/OpenHandle.xml</param-value> * </init-param> * </pre> * * <p> * The path specified as a value must point to a resource obtainable via * {@link ServletContext#getResource(String)}. * </p> * * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); // start with a null configuration Configuration configuration = null; // has a custom config been specified? String customConfig = config.getInitParameter("config"); if (isNotBlank(customConfig)) { try { configuration = new XMLConfiguration(getServletContext().getResource(customConfig)); } catch (Exception e) { LOG.error("Could not load custom configuration '" + customConfig + "'. Proceeding to load default configuration.", e); } } // load the default config try { configuration = new XMLConfiguration(OpenHandleServlet.class.getResource("/OpenHandle.xml")); } catch (Exception e) { throw new ServletException("Could not load default configuration", e); } try { // load settings settings = new Settings(configuration); // initialize resolver resolver = new OpenHandle(settings.getPreferredProtocols(), settings.isTraceMessages()); } catch (SettingsException e) { throw new ServletException(e); } try { Properties properties = new Properties(); properties.load(OpenHandleServlet.class.getResourceAsStream("/velocity.properties")); velocity = new VelocityEngine(); velocity.setApplicationAttribute(ServletContext.class.getName(), getServletContext()); velocity.init(properties); } catch (Exception e) { throw new ServletException("Could not initialize velocity engine", e); } }
From source file:ch.kostceco.tools.kostval.service.impl.ConfigurationServiceImpl.java
private XMLConfiguration getConfig() { if (this.config == null) { try {/*from ww w . ja va 2 s. c o m*/ String path = "configuration/kostval.conf.xml"; URL locationOfJar = KOSTVal.class.getProtectionDomain().getCodeSource().getLocation(); String locationOfJarPath = locationOfJar.getPath(); if (locationOfJarPath.endsWith(".jar")) { File file = new File(locationOfJarPath); String fileParent = file.getParent(); path = fileParent + "/" + path; } config = new XMLConfiguration(path); } catch (ConfigurationException e) { LOGGER.logError(getTextResourceService().getText(MESSAGE_XML_MODUL_Ca_SIP) + getTextResourceService().getText(MESSAGE_XML_CONFIGURATION_ERROR_1)); LOGGER.logError(getTextResourceService().getText(MESSAGE_XML_MODUL_Ca_SIP) + getTextResourceService().getText(MESSAGE_XML_CONFIGURATION_ERROR_2)); LOGGER.logError(getTextResourceService().getText(MESSAGE_XML_MODUL_Ca_SIP) + getTextResourceService().getText(MESSAGE_XML_CONFIGURATION_ERROR_3)); System.exit(1); } } return config; }
From source file:edu.emory.library.tast.submission.SubmissionAttributes.java
private SubmissionAttribute[] loadConfig() { try {//from www. j a v a2s. c o m ArrayList list = new ArrayList(); Document document = new XMLConfiguration("submission-attributes.xml").getDocument(); Node mainNode = document.getFirstChild(); if (mainNode != null) { if (mainNode.getNodeType() == Node.ELEMENT_NODE) { NodeList attrs = mainNode.getChildNodes(); for (int j = 0; j < attrs.getLength(); j++) { if (attrs.item(j).getNodeType() == Node.ELEMENT_NODE) { SubmissionAttribute attr = SubmissionAttribute.fromXML(attrs.item(j)); if (attr.getKey() == null) { list.add(attr); } else { map.put(attr.getKey(), attr); } } } } } return (SubmissionAttribute[]) list.toArray(new SubmissionAttribute[] {}); } catch (ConfigurationException e) { e.printStackTrace(); } return null; }