List of usage examples for org.apache.commons.configuration XMLConfiguration setFileName
public void setFileName(String fileName)
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 ////www.j av a2 s. com // 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:gda.util.persistence.LocalParameters.java
private static XMLConfiguration loadConfigurationFromFile(String filename) throws ConfigurationException { XMLConfiguration config = new XMLConfiguration(); config.setDelimiterParsingDisabled(false); // This needs to change if GDA-2492 is fixed config.setFileName(filename); config.load();/*from w w w . ja va 2 s .c o m*/ return config; }
From source file:com.evolveum.midpoint.init.StartupConfiguration.java
private void createXmlConfiguration(DocumentBuilder documentBuilder, String filename) throws ConfigurationException { XMLConfiguration xmlConfig = new XMLConfiguration(); xmlConfig.setDocumentBuilder(documentBuilder); xmlConfig.setFileName(filename); xmlConfig.load();//from w ww. j av a2s .c om config.addConfiguration(xmlConfig); xmlConfigAsDocument = DOMUtil.parseFile(filename); }
From source file:logica.EstacionMet.java
@Override public Stack<PaqueteDatos> actualizar() { // Informacion para PaqueteDatos() Integer[] sensoresID = new Integer[redSensores.length]; String[] tipo = new String[redSensores.length]; String[] medicion = new String[redSensores.length]; // Cargo el resumen de la estacion si es que existe. // Instancio el manejador de XML XMLConfiguration registro = new XMLConfiguration(); registro.setFileName(String.format("resumenes/%d.xml", ID)); try {//from w w w. j a v a 2 s .c o m // Cargo si existe el registro registro.load(); } catch (ConfigurationException ex) { // Si no existe, simplemente seteo el nombre del elemento base registro.setRootElementName("resumen"); // Y creo el archivo try { registro.save(); } catch (ConfigurationException ex1) { LOGGER.log(Level.SEVERE, null, ex1); } } // Datos de las sub-estaciones medidasPila = super.actualizar(); // Busco y guardo las mediciones de los sensores. int largo = redSensores.length; for (int i = 0; i < largo; i++) { if (redSensores[i] != null) { sensoresID[i] = redSensores[i].getID(); tipo[i] = redSensores[i].getClass().getSimpleName(); medicion[i] = redSensores[i].getMedicion(); resumenSave(registro, sensoresID[i], tipo[i], medicion[i]); } } // Agrego el los datos de esta estacion al final de los datos de las sub-estaciones medidasPila.push(new PaqueteDatos(ID, getHora(), sensoresID, tipo, medicion)); return medidasPila; }
From source file:logica.Estacion.java
/** * @brief Ubicacion de los resumenes, en un Vector<String> * //from w w w .j a v a2 s .com * Retorna la ubicacion de los resumenes de esta estacion y de sus * sub-estaciones, en un Vector<String>. * Se guardan en esa forma, primero la direccion propia y luego la de las * sub-estaciones. * * @return Direccion donde se encuentra el resumen. */ public Vector<String> getResumen() { Vector<String> direcciones = new Vector(); // Instancio el manejador de XML XMLConfiguration registro = new XMLConfiguration(); registro.setFileName(String.format("resumenes/%d.xml", ID)); // No es necesario crear el resumen si no existe // if ( !registro.getFile().exists() ) { // // Si no existe, simplemente seteo el nombre del elemento base // registro.setRootElementName("resumen"); // // Y creo el archivo // try { // registro.save(); // } catch (ConfigurationException ex1) { // LOGGER.log(Level.SEVERE, null, ex1); // } // } // getFileName() me devuelve la direccion dentro del proyecto. // getURL() me devuelve la direccion desde el root de la maquina. if (registro.getFile().exists()) direcciones.add(registro.getFileName()); for (Estacion subestacion : redEstaciones) { if (subestacion != null) direcciones.addAll(subestacion.getResumen()); } return direcciones; }
From source file:de.nec.nle.siafu.control.Controller.java
/** * Create a config file with default values. This is used when the config * file doesn't exist in the first place. * //from w ww . j a va2 s . c o m * @return the newly created configuration file. */ private XMLConfiguration createDefaultConfigFile() { System.out.println("Creating a default configuration file at " + DEFAULT_CONFIG_FILE); XMLConfiguration newConfig = new XMLConfiguration(); newConfig.setRootElementName("configuration"); newConfig.setProperty("commandlistener.enable", true); newConfig.setProperty("commandlistener.tcpport", DEFAULT_PORT); newConfig.setProperty("ui.usegui", true); newConfig.setProperty("ui.speed", DEFAULT_UI_SPEED); newConfig.setProperty("ui.gradientcache.prefill", true); newConfig.setProperty("ui.gradientcache.size", DEFAULT_CACHE_SIZE); newConfig.setProperty("output.type", "null"); newConfig.setProperty("output.csv.path", System.getProperty("user.home") + File.separator + "SiafuContext.csv"); newConfig.setProperty("output.csv.interval", DEFAULT_CSV_INTERVAL); newConfig.setProperty("output.csv.keephistory", true); try { newConfig.setFileName(DEFAULT_CONFIG_FILE); newConfig.save(); } catch (ConfigurationException e) { throw new RuntimeException("Can not create a default config file at " + DEFAULT_CONFIG_FILE, e); } return newConfig; }
From source file:io.datalayer.conf.XmlConfigurationTest.java
@Test public void testSave() throws Exception { // add an array of strings to the configuration conf.addProperty("string", "value1"); for (int i = 1; i < 5; i++) { conf.addProperty("test.array", "value" + i); }// ww w . ja v a 2 s . c om // add an array of strings in an attribute for (int i = 1; i < 5; i++) { conf.addProperty("test.attribute[@array]", "value" + i); } // add comma delimited lists with escaped delimiters conf.addProperty("split.list5", "a\\,b\\,c"); conf.setProperty("element3", "value\\,value1\\,value2"); conf.setProperty("element3[@name]", "foo\\,bar"); // save the configuration conf.save(testSaveConf.getAbsolutePath()); // read the configuration and compare the properties XMLConfiguration checkConfig = new XMLConfiguration(); checkConfig.setFileName(testSaveConf.getAbsolutePath()); checkSavedConfig(checkConfig); }
From source file:io.datalayer.conf.XmlConfigurationTest.java
/** * Tests string properties with list delimiters when delimiter parsing is * disabled/* w w w . j a va 2 s.com*/ */ @Test public void testSaveWithDelimiterParsingDisabled() throws ConfigurationException { XMLConfiguration conf = new XMLConfiguration(); conf.setExpressionEngine(new XPathExpressionEngine()); conf.setDelimiterParsingDisabled(true); conf.setAttributeSplittingDisabled(true); conf.setFile(new File(testProperties)); conf.load(); assertEquals("a,b,c", conf.getString("split/list3/@values")); assertEquals(0, conf.getMaxIndex("split/list3/@values")); assertEquals("a\\,b\\,c", conf.getString("split/list4/@values")); assertEquals("a,b,c", conf.getString("split/list1")); assertEquals(0, conf.getMaxIndex("split/list1")); assertEquals("a\\,b\\,c", conf.getString("split/list2")); // save the configuration conf.save(testSaveConf.getAbsolutePath()); // read the configuration and compare the properties XMLConfiguration checkConfig = new XMLConfiguration(); checkConfig.setFileName(testSaveConf.getAbsolutePath()); checkSavedConfig(checkConfig); XMLConfiguration config = new XMLConfiguration(); config.setFileName(testFile2); // config.setExpressionEngine(new XPathExpressionEngine()); config.setDelimiterParsingDisabled(true); config.setAttributeSplittingDisabled(true); config.load(); config.setProperty("Employee[@attr1]", "3,2,1"); assertEquals("3,2,1", config.getString("Employee[@attr1]")); config.save(testSaveFile.getAbsolutePath()); config = new XMLConfiguration(); config.setFileName(testSaveFile.getAbsolutePath()); // config.setExpressionEngine(new XPathExpressionEngine()); config.setDelimiterParsingDisabled(true); config.setAttributeSplittingDisabled(true); config.load(); config.setProperty("Employee[@attr1]", "1,2,3"); assertEquals("1,2,3", config.getString("Employee[@attr1]")); config.setProperty("Employee[@attr2]", "one, two, three"); assertEquals("one, two, three", config.getString("Employee[@attr2]")); config.setProperty("Employee.text", "a,b,d"); assertEquals("a,b,d", config.getString("Employee.text")); config.setProperty("Employee.Salary", "100,000"); assertEquals("100,000", config.getString("Employee.Salary")); config.save(testSaveFile.getAbsolutePath()); checkConfig = new XMLConfiguration(); checkConfig.setFileName(testSaveFile.getAbsolutePath()); checkConfig.setExpressionEngine(new XPathExpressionEngine()); checkConfig.setDelimiterParsingDisabled(true); checkConfig.setAttributeSplittingDisabled(true); checkConfig.load(); assertEquals("1,2,3", checkConfig.getString("Employee/@attr1")); assertEquals("one, two, three", checkConfig.getString("Employee/@attr2")); assertEquals("a,b,d", checkConfig.getString("Employee/text")); assertEquals("100,000", checkConfig.getString("Employee/Salary")); }
From source file:org.wso2.andes.configuration.AndesConfigurationManager.java
/** * initialize the configuration manager. this MUST be called at application startup. * (QpidServiceComponent bundle -> activate event) * * @throws AndesException//from w w w .jav a 2 s .c o m */ public static void initialize(int portOffset) throws AndesException { String ROOT_CONFIG_FILE_PATH; // If system property is available set conf path to that value if (componentsPath != null) { ROOT_CONFIG_FILE_PATH = Paths.get(componentsPath).toString(); } else { ROOT_CONFIG_FILE_PATH = Paths.get(System.getProperty(CARBON_HOME), "repository", "conf").toString(); } String brokerConfigFilePath = ROOT_CONFIG_FILE_PATH + File.separator + ROOT_CONFIG_FILE_NAME; log.info("Main andes configuration located at : " + brokerConfigFilePath); try { compositeConfiguration = new CompositeConfiguration(); compositeConfiguration.setDelimiterParsingDisabled(true); XMLConfiguration rootConfiguration = new XMLConfiguration(); rootConfiguration.setDelimiterParsingDisabled(true); rootConfiguration.setFileName(brokerConfigFilePath); rootConfiguration.setExpressionEngine(new XPathExpressionEngine()); rootConfiguration.load(); compositeConfiguration.addConfiguration(rootConfiguration); //Decrypt and maintain secure vault property values in a map for cross-reference. decryptConfigurationFromFile(brokerConfigFilePath); // Derive certain special properties that are not simply specified in the configuration files. addDerivedProperties(); // set carbonPortOffset coming from carbon AndesConfigurationManager.carbonPortOffset = portOffset; //set delivery timeout for a message int deliveryTimeoutForMessage = AndesConfigurationManager .readValue(AndesConfiguration.PERFORMANCE_TUNING_TOPIC_MESSAGE_DELIVERY_TIMEOUT); AndesContext.getInstance().setDeliveryTimeoutForMessage(deliveryTimeoutForMessage); } catch (ConfigurationException e) { String error = "Error occurred when trying to construct configurations from file at path : " + brokerConfigFilePath; log.error(error, e); throw new AndesException(error, e); } catch (UnknownHostException e) { String error = "Error occurred when trying to derive the bind address for messaging from configurations."; log.error(error, e); throw new AndesException(error, e); } catch (FileNotFoundException e) { String error = "Error occurred when trying to read the configuration file : " + brokerConfigFilePath; log.error(error, e); throw new AndesException(error, e); } catch (JaxenException e) { String error = "Error occurred when trying to process cipher text in file : " + brokerConfigFilePath; log.error(error, e); throw new AndesException(error, e); } catch (XMLStreamException e) { String error = "Error occurred when trying to process cipher text in file : " + brokerConfigFilePath; log.error(error, e); throw new AndesException(error, e); } }
From source file:org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.config.AuthorizationConfiguration.java
public static void initialize() throws AuthorizationException { String brokerConfigFilePath = ROOT_CONFIG_FILE_PATH + ROOT_CONFIG_FILE_NAME; if (log.isDebugEnabled()) { log.debug("Configuration located at : " + brokerConfigFilePath); }//from w w w . j a va2s. co m try { compositeConfiguration = new CompositeConfiguration(); compositeConfiguration.setDelimiterParsingDisabled(true); XMLConfiguration rootConfiguration = new XMLConfiguration(); rootConfiguration.setDelimiterParsingDisabled(true); rootConfiguration.setFileName(brokerConfigFilePath); rootConfiguration.setExpressionEngine(new XPathExpressionEngine()); rootConfiguration.load(); readConfigurationFromFile(brokerConfigFilePath); compositeConfiguration.addConfiguration(rootConfiguration); } catch (FileNotFoundException e) { String error = "Error occurred when trying to read the configuration file : " + brokerConfigFilePath; log.error(error, e); throw new AuthorizationException(error, e); } catch (JaxenException e) { String error = "Error occurred when trying to process file : " + brokerConfigFilePath; log.error(error, e); throw new AuthorizationException(error, e); } catch (XMLStreamException e) { String error = "Error occurred when trying to process file : " + brokerConfigFilePath; log.error(error, e); throw new AuthorizationException(error, e); } catch (ConfigurationException e) { String error = "Error occurred when trying to process file :" + brokerConfigFilePath; log.error(error, e); throw new AuthorizationException(error, e); } }