List of usage examples for org.apache.commons.configuration.tree ConfigurationNode getValue
Object getValue();
From source file:Cresendo.java
public static void main(String[] args) { String cfgFileReceiver = null; // Path to config file for eif receiver agent String cfgFileEngine = null; // Path to config file for xml event engine Options opts = null; // Command line options HelpFormatter hf = null; // Command line help formatter // Setup the message record which will contain text written to the log file ////from ww w . j av a2s . c om // The message logger object is created when the "-l" is processed // as this object need to be associated with a log file // LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", ""); // Get the directory separator (defaults to "/") // dirSep = System.getProperty("file.separator", "/"); // Initialise the structure containing the event handler objects // Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10); // Process the command line arguments // try { opts = new Options(); hf = new HelpFormatter(); opts.addOption("h", "help", false, "Command line arguments help"); opts.addOption("i", "instance name", true, "Name of cresendo instance"); opts.addOption("l", "log dir", true, "Path to log file directory"); opts.addOption("c", "config dir", true, "Path to configuarion file directory"); opts.getOption("l").setRequired(true); opts.getOption("c").setRequired(true); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opts, args); // Print out some help and exit // if (cl.hasOption('h')) { hf.printHelp("Options", opts); System.exit(0); } // Set the instance name // if (cl.hasOption('i')) { instanceName = cl.getOptionValue('i'); // Set to something other than "default" } // Setup the message and trace logging objects for the EventEngine // if (cl.hasOption('l')) { // Setup the the paths to the message, trace and status log files // logDir = cl.getOptionValue("l"); logPath = logDir + dirSep + instanceName + "-engine.log"; tracePath = logDir + dirSep + instanceName + "-engine.trace"; statusPath = logDir + dirSep + instanceName + "-engine.status"; } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'l' is a required option", opts); System.exit(1); } // Read the receiver and engine config files in the config directory // if (cl.hasOption('c')) { // Setup and check path to eif config file for TECAgent receiver object // configDir = cl.getOptionValue("c"); cfgFileReceiver = configDir + dirSep + instanceName + ".conf"; checkConfigFile(cfgFileReceiver); // Setup and check path to xml config file for the EventEngine // cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml"; checkConfigFile(cfgFileEngine); } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'c' is a required option", opts); System.exit(1); } } catch (UnrecognizedOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingArgumentException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (ParseException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Main program // try { // ===================================================================== // Setup the message, trace and status logger objects // try { msgHandler = new FileHandler("cresendo", "message handler", logPath); msgHandler.openDevice(); msgLogger = new MessageLogger("cresendo", "message log"); msgLogger.addHandler(msgHandler); trcHandler = new FileHandler("cresendo", "trace handler", tracePath); trcHandler.openDevice(); trcLogger = new TraceLogger("cresendo", "trace log"); trcLogger.addHandler(trcHandler); statLogger = new StatusLogger(statusPath); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Add the shutdown hook // Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName)); // --------------------------------------------------------------------- // ===================================================================== // Load and parse the xml event engine configuration file // // msg.setText("Loading xml engine from: '" + cfgFileEngine + "'"); try { XMLConfiguration xmlProcessor = new XMLConfiguration(); xmlProcessor.setFileName(cfgFileEngine); // Validate the xml against a document type declaration // xmlProcessor.setValidating(true); // Don't interpolate the tag contents by splitting them on a delimiter // (ie by default a comma) // xmlProcessor.setDelimiterParsingDisabled(true); // This will throw a ConfigurationException if the xml document does not // conform to its dtd. By doing this we hopefully catch any errors left // behind after the xml configuration file has been edited. // xmlProcessor.load(); // Setup the trace flag // ConfigurationNode engine = xmlProcessor.getRootNode(); List rootAttribute = engine.getAttributes(); for (Iterator it = rootAttribute.iterator(); it.hasNext();) { ConfigurationNode attr = (ConfigurationNode) it.next(); String attrName = attr.getName(); String attrValue = (String) attr.getValue(); if (attrValue == null || attrValue == "") { System.err.println("\n Error: The value of the attribute '" + attrName + "'" + "\n in the xml file '" + cfgFileEngine + "'" + "\n is not set"); System.exit(1); } if (attrName.matches("trace")) { if (attrValue.matches("true") || attrValue.matches("on")) { trcLogger.setLogging(true); } } if (attrName.matches("status")) { if (attrValue.matches("true") || attrValue.matches("on")) { statLogger.setLogging(true); } else { statLogger.setLogging(false); } } if (attrName.matches("interval")) { if (!attrValue.matches("[0-9]+")) { System.err.println("\n Error: The value of the interval attribute in: '" + cfgFileEngine + "'" + "\n should only contain digits from 0 to 9." + "\n It currently contains: '" + attrValue + "'"); System.exit(1); } statLogger.setInterval(Integer.parseInt(attrValue)); } } // Now build and instantiate the list of classes that will process events // received by the TECAgent receiver in a chain like manner. // List classes = xmlProcessor.configurationsAt("class"); for (Iterator it = classes.iterator(); it.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next(); // sub contains now all data contained in a single <class></class> tag set // String className = sub.getString("name"); // Log message // msg.setText(msg.getText() + "\n Instantiated event handler class: '" + className + "'"); // The angle brackets describing the class of object held by the // Vector are implemented by Java 1.5 and have 2 effects. // // 1. The list accepts only elements of that class and nothing else // (Of course thanks to Auto-Wrap you can also add double-values) // // 2. the get(), firstElement() ... Methods don't return a Object, but // they deliver an element of the class. // Vector<Class> optTypes = new Vector<Class>(10, 10); Vector<Object> optValues = new Vector<Object>(10, 10); for (int i = 0; i <= sub.getMaxIndex("option"); i++) { Object optValue = null; String optVarName = sub.getString("option(" + i + ")[@varname]"); String optJavaType = sub.getString("option(" + i + ")[@javatype]"); // Use the specified java type in order to make the method call // to the heirarchical sub object [painful :-((] // if (optJavaType.matches("byte")) { optTypes.addElement(byte.class); optValue = sub.getByte("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("short")) { optTypes.addElement(byte.class); optValue = sub.getShort("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("int")) { optTypes.addElement(int.class); optValue = sub.getInt("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("long")) { optTypes.addElement(long.class); optValue = sub.getLong("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("float")) { optTypes.addElement(float.class); optValue = sub.getFloat("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("double")) { optTypes.addElement(double.class); optValue = sub.getDouble("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("boolean")) { optTypes.addElement(boolean.class); optValue = sub.getBoolean("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = false; // Set to something nullish } } else if (optJavaType.matches("String")) { optTypes.addElement(String.class); optValue = sub.getString("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = ""; // Set it to something nullish } } else { System.err.println( "Error: Unsupported java type found in xml config: '" + optJavaType + "'"); System.exit(1); } // Add option value element // // System.out.println("Option value is: '" + optValue.toString() + "'\n"); // optValues.addElement(optValue); // Append to message text // String msgTemp = msg.getText(); msgTemp += "\n option name: '" + optVarName + "'"; msgTemp += "\n option type: '" + optJavaType + "'"; msgTemp += "\n option value: '" + optValues.lastElement().toString() + "'"; msg.setText(msgTemp); } try { // Instantiate the class with the java reflection api // Class klass = Class.forName(className); // Setup an array of paramater types in order to retrieve the matching constructor // Class[] types = optTypes.toArray(new Class[optTypes.size()]); // Get the constructor for the class which matches the parameter types // Constructor konstruct = klass.getConstructor(types); // Create an instance of the event handler // IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray()); // Add the instance to the list of event handlers // eventHandler.addElement(eventProcessor); } catch (InvocationTargetException e) { System.err.println("Error: " + e.toString()); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: class name not found: '" + className + "' \n" + e.toString()); System.exit(1); } catch (Exception e) { System.err.println( "Error: failed to instantiate class: '" + className + "' \n" + e.toString()); System.exit(1); } } } catch (ConfigurationException cex) // Something went wrong loading the xml file { System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString()); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // --------------------------------------------------------------------- // ===================================================================== // Setup the TECAgent receiver // Reader cfgIn = null; try { cfgIn = new FileReader(cfgFileReceiver); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Start the TECAgent receiver and register the event engine handler // TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false); EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger); receiver.registerListener(ee); // Construct message and send it to the message log // String text = "\n Cresendo instance '" + instanceName + "' listening for events on port '" + receiver.getConfigVal("ServerPort") + "'"; msg.setText(msg.getText() + text); msgLogger.log(msg); // Send message to log // --------------------------------------------------------------------- // ===================================================================== // Initiate status logging // if (statLogger.isLogging()) { int seconds = statLogger.getInterval(); while (true) { try { statLogger.log(); } catch (Exception ex) { System.err.println("\n An error occurred while writing to '" + statusPath + "'" + "\n '" + ex.toString() + "'"); } Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds } } // --------------------------------------------------------------------- } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } }
From source file:com.aol.advertising.qiao.util.XmlConfigUtil.java
public static Map<String, Object> parseSingleNodeAttributes(HierarchicalConfiguration config, String key) { Map<String, Object> result = null; // get a subnode configuration for the node specified by the given key SubnodeConfiguration c = config.configurationAt(key); if (c != null) { Node root = c.getRoot();//from ww w. j a v a 2 s. c o m result = new HashMap<String, Object>(root.getAttributeCount()); List<?> attrs = root.getAttributes(); for (Object attr : attrs) { ConfigurationNode nd = (ConfigurationNode) attr; result.put(nd.getName(), nd.getValue()); } } return result; }
From source file:com.aol.advertising.qiao.util.XmlConfigUtil.java
/** * Parse xml configuration and return a list of attributes belonging to one * or more elements with the specific key. It returns a list preserving the * order of elements in xml./* w w w. j av a2 s . c o m*/ * * @param config * @param key * identifies xml elements with the specific tag * @return */ public static List<Map<String, Object>> parseMultiNodesAttributes(HierarchicalConfiguration config, String key) { List<Map<String, Object>> result = null; // get a list of subnode configurations for all configuration nodes // selected by the given key, e.g. "node.inbound.listener" List<?> list = config.configurationsAt(key); if (list != null) { result = new ArrayList<Map<String, Object>>(); for (Iterator<?> iter = list.iterator(); iter.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) iter.next(); Node root = sub.getRoot(); Map<String, Object> attributes = new HashMap<String, Object>(root.getAttributeCount()); // get attribute nodes List<?> attrs = root.getAttributes(); for (Object attr : attrs) { ConfigurationNode nd = (ConfigurationNode) attr; attributes.put(nd.getName(), nd.getValue()); } result.add(attributes); } } return result; }
From source file:com.qspin.qtaste.config.XMLConfiguration.java
/** * Fetches the specified property. This task is delegated to the associated * expression engine.// www .ja va 2 s . c o m * * @param key the key to be looked up * @return the found value */ @Override public List<Object> getProperty(String key) { List<?> nodes = fetchNodeList(key); if (nodes.size() == 0) { return null; } else { List<Object> list = new ArrayList<Object>(); for (Iterator<?> it = nodes.iterator(); it.hasNext();) { ConfigurationNode node = (ConfigurationNode) it.next(); if (node.getValue() != null) { list.add(node.getValue()); } } if (list.size() < 1) { return null; } else { return list; } } }
From source file:com.github.mbredel.commons.configuration.YAMLConfiguration.java
/** * Constructs a YAML map, i.e. String -> Object from a given * configuration node./*ww w . j a v a 2s . co m*/ * * @param node The configuration node to create a map from. * @return A Map that contains the configuration node information. */ public Map<String, Object> constructMap(ConfigurationNode node) { Map<String, Object> map = new HashMap<>(node.getChildrenCount()); for (ConfigurationNode cNode : node.getChildren()) { if (cNode.getChildren().isEmpty()) { map.put(cNode.getName(), cNode.getValue()); } else { map.put(cNode.getName(), constructMap(cNode)); } } return map; }
From source file:com.gamma.dam.conf.db.DBConfigReader.java
/** * Instantiates a new DB config reader./*from w ww . j a v a 2 s.co m*/ */ private DBConfigReader() { String basePath = ResourceProperties.instance().getValue(ResourceProperties.DATABASE_CONF); String home = System.getProperty("DAM_HOME"); if (home != null) { basePath = home + File.separator + basePath; } try { XMLConfiguration xml = new XMLConfiguration(basePath); ReloadingStrategy strategy = new FileChangedReloadingStrategy(); xml.setReloadingStrategy(strategy); Node node = xml.getRoot(); if (node.hasChildren()) { for (ConfigurationNode n : node.getChildren()) { DBConfig db = new DBConfig(); String name = null; if (n.getAttributeCount() > 0) { for (ConfigurationNode attr : n.getAttributes()) { switch (attr.getName()) { case "id": break; case "name": name = (String) attr.getValue(); break; default: break; } } } db.parse(n); dbs.put(name, db); } } } catch (ConfigurationException e) { throw new DAMConfigurationException(e); } }
From source file:com.gamma.dam.conf.db.DBConfig.java
/** * Parses the.//from w w w . j a v a 2 s . co m * * @param node the node */ public void parse(ConfigurationNode node) { if (node.getChildrenCount() > 0) { for (ConfigurationNode n : node.getChildren()) { String name = n.getName(); String val = (String) n.getValue(); switch (name) { case "host": setHost(val); break; case "port": setPort(val); break; case "database": setDatabase(val); break; case "username": setUsername(val); break; case "password": setPassword(val); break; case "driver": setDriver(val); break; case "idleMaxAgeInMinutes": setIdleMaxAgeInMinutes(val); break; case "idleConnectionTestPeriodInMinutes": setIdleConnectionTestPeriodInMinutes(val); break; case "maxConnectionsPerPartition": setMaxConnectionsPerPartition(val); break; case "minConnectionsPerPartition": setMinConnectionsPerPartition(val); break; case "partitionCount": setPartitionCount(val); break; case "acquireIncrement": setAcquireIncrement(val); break; case "statementsCacheSize": setStatementsCacheSize(val); break; default: break; } } } }
From source file:core.commonapp.server.data.RequiredDataReader.java
/** * Initialize data reader/*from www .ja v a2s . co 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:com.photon.phresco.plugins.xcode.Instrumentation.java
private void generateXMLReport(String location) { try {//w w w . jav a2 s .co m String startTime = ""; int total, pass, fail; total = pass = fail = 0; config = new XMLPropertyListConfiguration(location); ArrayList list = (ArrayList) config.getRoot().getChild(0).getValue(); String key; DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement(XMLConstants.TESTSUITES_NAME); doc.appendChild(root); Element testSuite = doc.createElement(XMLConstants.TESTSUITE_NAME); testSuite.setAttribute(XMLConstants.NAME, "FunctionalTestSuite"); root.appendChild(testSuite); for (Object object : list) { XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object; startTime = config.getRoot().getChild(2).getValue().toString(); break; } for (Object object : list) { XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object; ConfigurationNode con = config.getRoot().getChild(0); key = con.getName(); if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.PASS)) { pass++; total++; Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME); child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue()); child1.setAttribute(XMLConstants.RESULT, (String) con.getValue()); String endTime = config.getRoot().getChild(2).getValue().toString(); long differ = getTimeDiff(startTime, endTime); startTime = endTime; child1.setAttribute(XMLConstants.TIME, differ + ""); testSuite.appendChild(child1); } else if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.ERROR)) { fail++; total++; Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME); child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue()); child1.setAttribute(XMLConstants.RESULT, (String) con.getValue()); String endTime = config.getRoot().getChild(2).getValue().toString(); long differ = getTimeDiff(startTime, endTime); startTime = endTime; child1.setAttribute(XMLConstants.TIME, differ + ""); testSuite.appendChild(child1); } } testSuite.setAttribute(XMLConstants.TESTS, String.valueOf(total)); testSuite.setAttribute(XMLConstants.SUCCESS, String.valueOf(pass)); testSuite.setAttribute(XMLConstants.FAILURES, String.valueOf(fail)); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.INDENT, "yes"); File file = new File(project.getBasedir().getAbsolutePath() + File.separator + xmlResult); Writer bw = new BufferedWriter(new FileWriter(file)); StreamResult result = new StreamResult(bw); DOMSource source = new DOMSource(doc); trans.transform(source, result); } catch (Exception e) { getLog().error("Interrupted while generating XML file"); } }
From source file:au.org.intersect.dms.instrument.harvester.WindowsIniLogParser.java
private Map<String, Object> parseFields(String sectionName, Map<String, Object> sectionMap, ConfigurationNode node) { if (node.getReference() == null && node.getChildrenCount() == 0) { String sectionProperty = sectionName + "." + node.getName(); if ((mode == Mode.EXCLUSION && !findMatch(sectionProperty.trim())) || (mode == Mode.INCLUSION && findMatch(sectionProperty.trim()))) { String name = node.getName(); String value = node.getValue().toString(); MetadataField field = mapField(name, value); value = convertPropertyValue(sectionProperty, field.getValue()); sectionMap.put(AbstractHarvester.toXML(field.getName()), AbstractHarvester.toXML(value)); }// w ww . j av a2 s. com } return sectionMap; }