Example usage for org.apache.commons.configuration XMLConfiguration load

List of usage examples for org.apache.commons.configuration XMLConfiguration load

Introduction

In this page you can find the example usage for org.apache.commons.configuration XMLConfiguration load.

Prototype

public void load() throws ConfigurationException 

Source Link

Usage

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   w ww . j a v  a 2  s .  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.bytelightning.opensource.pokerface.PokerFaceApp.java

public static void main(String[] args) {
    if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) {
        System.err.println("PokerFace requires at least Java v8 to run.");
        return;//  w  w  w  .  java 2  s .co  m
    }
    // Configure the command line options parser
    Options options = new Options();
    options.addOption("h", false, "help");
    options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https.");
    options.addOption("keystore", true, "Filepath for PokerFace certificate keystore.");
    options.addOption("storepass", true, "The store password of the keystore.");
    options.addOption("keypass", true, "The key password of the keystore.");
    options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target
    options.addOption("servercpu", true, "Number of cores the server should use.");
    options.addOption("targetcpu", true, "Number of cores the http targets should use.");
    options.addOption("trustany", false, "Ignore certificate identity errors from target servers.");
    options.addOption("files", true, "Filepath to a directory of static files.");
    options.addOption("config", true, "Path for XML Configuration file.");
    options.addOption("scripts", true, "Filepath for root scripts directory.");
    options.addOption("library", true, "JavaScript library to load into global context.");
    options.addOption("watch", false, "Dynamically watch scripts directory for changes.");
    options.addOption("dynamicTargetScripting", false,
            "WARNING! This option allows scripts to redirect requests to *any* other remote server.");

    CommandLine cmdLine = null;
    // parse the command line.
    try {
        CommandLineParser parser = new PosixParser();
        cmdLine = parser.parse(options, args);
        if (args.length == 0 || cmdLine.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(120);
            formatter.printHelp(PokerFaceApp.class.getSimpleName(), options);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        return;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return;
    }

    XMLConfiguration config = new XMLConfiguration();
    try {
        if (cmdLine.hasOption("config")) {
            Path tmp = Utils.MakePath(cmdLine.getOptionValue("config"));
            if (!Files.exists(tmp))
                throw new FileNotFoundException("Configuration file does not exist.");
            if (Files.isDirectory(tmp))
                throw new FileNotFoundException("'config' path is not a file.");
            // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it.
            config.setEntityResolver(new DefaultEntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
                    InputSource retVal = super.resolveEntity(publicId, systemId);
                    if ((retVal == null) && (systemId != null)) {
                        try {
                            URL entityURL;
                            if (systemId.endsWith("/PokerFace_v1Config.xsd"))
                                entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd");
                            else
                                entityURL = new URL(systemId);
                            URLConnection connection = entityURL.openConnection();
                            connection.setUseCaches(false);
                            InputStream stream = connection.getInputStream();
                            retVal = new InputSource(stream);
                            retVal.setSystemId(entityURL.toExternalForm());
                        } catch (Throwable e) {
                            return retVal;
                        }
                    }
                    return retVal;
                }

            });
            config.setSchemaValidation(true);
            config.setURL(tmp.toUri().toURL());
            config.load();
            if (cmdLine.hasOption("listen"))
                System.out.println("IGNORING 'listen' option because a configuration file was supplied.");
            if (cmdLine.hasOption("target"))
                System.out.println("IGNORING 'target' option(s) because a configuration file was supplied.");
            if (cmdLine.hasOption("scripts"))
                System.out.println("IGNORING 'scripts' option because a configuration file was supplied.");
            if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option(s) because a configuration file was supplied.");
        } else {
            String[] serverStrs;
            String[] addr = { null };
            String[] port = { null };
            serverStrs = cmdLine.getOptionValues("listen");
            if (serverStrs == null)
                throw new MissingOptionException("No listening addresses specified specified");
            for (int i = 0; i < serverStrs.length; i++) {
                String addrStr;
                String alias = null;
                String protocol = null;
                Boolean https = null;
                int addrPos = serverStrs[i].indexOf('=');
                if (addrPos >= 0) {
                    if (addrPos < 2)
                        throw new IllegalArgumentException("Invalid http argument.");
                    else if (addrPos + 1 >= serverStrs[i].length())
                        throw new IllegalArgumentException("Invalid http argument.");
                    addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length());
                    String[] types = serverStrs[i].substring(0, addrPos).split(",");
                    for (String type : types) {
                        if (type.equalsIgnoreCase("http"))
                            break;
                        else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure"))
                            https = true;
                        else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl"))
                            protocol = type.toUpperCase();
                        else
                            alias = type;
                    }
                } else
                    addrStr = serverStrs[i];
                ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80);
                config.addProperty("server.listen(" + i + ")[@address]", addr[0]);
                config.addProperty("server.listen(" + i + ")[@port]", port[0]);
                if (alias != null)
                    config.addProperty("server.listen(" + i + ")[@alias]", alias);
                if (protocol != null)
                    config.addProperty("server.listen(" + i + ")[@protocol]", protocol);
                if (https != null)
                    config.addProperty("server.listen(" + i + ")[@secure]", https);
            }
            String servercpu = cmdLine.getOptionValue("servercpu");
            if (servercpu != null)
                config.setProperty("server[@cpu]", servercpu);
            String clientcpu = cmdLine.getOptionValue("targetcpu");
            if (clientcpu != null)
                config.setProperty("targets[@cpu]", clientcpu);

            // Configure static files
            if (cmdLine.hasOption("files")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("files"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Files directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'files' path is not a directory.");
                config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri());
            }

            // Configure scripting
            if (cmdLine.hasOption("scripts")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Scripts directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'scripts' path is not a directory.");
                config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri());
                config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch"));
                String[] libraries = cmdLine.getOptionValues("library");
                if (libraries != null) {
                    for (int i = 0; i < libraries.length; i++) {
                        Path lib = Utils.MakePath(libraries[i]);
                        if (!Files.exists(lib))
                            throw new FileNotFoundException(
                                    "Script library does not exist [" + libraries[i] + "].");
                        if (Files.isDirectory(lib))
                            throw new FileNotFoundException(
                                    "Script library is not a file [" + libraries[i] + "].");
                        config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri());
                    }
                }
            } else if (cmdLine.hasOption("watch"))
                System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified.");
            else if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option as no 'scripts' directory was specified.");
        }
        String keyStorePath = cmdLine.getOptionValue("keystore");
        if (keyStorePath != null)
            config.setProperty("keystore", keyStorePath);
        String keypass = cmdLine.getOptionValue("keypass");
        if (keypass != null)
            config.setProperty("keypass", keypass);
        String storepass = cmdLine.getOptionValue("storepass");
        if (storepass != null)
            config.setProperty("storepass", keypass);
        if (cmdLine.hasOption("trustany"))
            config.setProperty("targets[@trustAny]", true);

        config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting"));

        String[] targetStrs = cmdLine.getOptionValues("target");
        if (targetStrs != null) {
            for (int i = 0; i < targetStrs.length; i++) {
                int uriPos = targetStrs[i].indexOf('=');
                if (uriPos < 2)
                    throw new IllegalArgumentException("Invalid target argument.");
                else if (uriPos + 1 >= targetStrs[i].length())
                    throw new IllegalArgumentException("Invalid target argument.");
                String patternStr = targetStrs[i].substring(0, uriPos);
                String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length());
                String alias;
                try {
                    URL url = new URL(urlStr);
                    alias = url.getUserInfo();
                    String scheme = url.getProtocol();
                    if ((!"http".equals(scheme)) && (!"https".equals(scheme)))
                        throw new IllegalArgumentException("Invalid target uri scheme.");
                    int port = url.getPort();
                    if (port < 0)
                        port = url.getDefaultPort();
                    urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath();
                    String ref = url.getRef();
                    if (ref != null)
                        urlStr += "#" + ref;
                } catch (MalformedURLException ex) {
                    throw new IllegalArgumentException("Malformed target uri");
                }
                config.addProperty("targets.target(" + i + ")[@pattern]", patternStr);
                config.addProperty("targets.target(" + i + ")[@url]", urlStr);
                if (alias != null)
                    config.addProperty("targets.target(" + i + ")[@alias]", alias);
            }
        }
        //         config.save(System.out);
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        return;
    }
    // If we get here, we have a possibly valid configuration.
    try {
        final PokerFace p = new PokerFace();
        p.config(config);
        if (p.start()) {
            PokerFace.Logger.warn("Started!");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        PokerFace.Logger.warn("Initiating shutdown...");
                        p.stop();
                        PokerFace.Logger.warn("Shutdown completed!");
                    } catch (Throwable e) {
                        PokerFace.Logger.error("Failed to shutdown cleanly!");
                        e.printStackTrace(System.err);
                    }
                }
            });
        } else {
            PokerFace.Logger.error("Failed to start!");
            System.exit(-1);
        }
    } catch (Throwable e) {
        e.printStackTrace(System.err);
    }
}

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);//w w  w  .  j a v  a  2 s  . c o m
    config.load();
    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);/*from  www .j  a  va2  s  . c o  m*/
    xmlConfig.load();
    config.addConfiguration(xmlConfig);

    xmlConfigAsDocument = DOMUtil.parseFile(filename);
}

From source file:m.c.m.proxyma.ProxymaServlet.java

/**
 * Initialize the servlet and the proxyma environment.
 *///  w w w  . j a  va  2 s  . c o  m
@Override
public void init() {
    try {
        //Obtain configuration parameters..
        ServletConfig config = this.getServletConfig();
        String proxymaConfigFile = this.getInitParameter("ProxymaConfigurationFile");
        String proxymaContextName = this.getInitParameter("ProxymaContextName");
        String proxymaLogsDirectory = this.getInitParameter("ProxymaLogsDir");

        //if the config file init-parameter is notspecified use the default configuration
        if (proxymaConfigFile == null)
            proxymaConfigFile = config.getServletContext().getRealPath("/WEB-INF/proxyma-config.xml");

        //Hack to get the servlet path reading it directly from the deployment descriptor.
        //Valid until apache will put a getServletMappings() method into the ServletConfig class.
        XMLConfiguration deploymentDescriptor = null;
        try {
            deploymentDescriptor = new XMLConfiguration();
            deploymentDescriptor.setFile(new File(config.getServletContext().getRealPath("/WEB-INF/web.xml")));
            deploymentDescriptor.setValidating(false);
            deploymentDescriptor.load();
        } catch (ConfigurationException ex) {
            Logger.getLogger("").log(Level.SEVERE, "Unable to load web.xml", ex);
        }
        deploymentDescriptor.setExpressionEngine(new XPathExpressionEngine());
        String servletPath = deploymentDescriptor
                .getString("servlet-mapping[servlet-name='" + config.getServletName() + "']/url-pattern");
        String proxymaServletContext = config.getServletContext().getContextPath()
                + servletPath.replaceFirst("/\\*$", GlobalConstants.EMPTY_STRING);

        //Check if the logs directory init-parameter ends with "/"
        if (!proxymaLogsDirectory.endsWith("/")) {
            proxymaLogsDirectory = proxymaLogsDirectory + "/";
        }

        //Create a new proxyma facade
        this.proxyma = new ProxymaFacade();

        //Create a new proxyma context
        this.proxymaContext = proxyma.createNewContext(proxymaContextName, proxymaServletContext,
                proxymaConfigFile, proxymaLogsDirectory);

        //Create a reverse proxy engine for this servlet thread
        this.proxymaEngine = proxyma.createNewProxyEngine(proxymaContext);
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    }
}

From source file:ch.admin.suis.msghandler.config.SedexCertConfigFactory.java

/**
 * Factory constructor./*from ww w  . j a  v a  2  s.c  o  m*/
 *
 * @param configFile File object referencing the file certificateConfiguration.xml rom the sedex configuratioon.
 * @throws ConfigurationException if the file doen't exist or if doesn't conform to the required XML Schema.
 */
public SedexCertConfigFactory(File configFile) throws ConfigurationException {
    FileUtils.isFile(configFile, ".certificateConfigFile[@filePath]");

    XMLConfiguration xmlConfig = new XMLConfiguration();
    // disable the schema validation by XMLConfiguration, since the config file does not contain a schema location
    xmlConfig.setSchemaValidation(false);
    xmlConfig.setFile(configFile);
    try {
        XMLValidator.validateSedexCertificateConfig(configFile);
        xmlConfig.load();
    } catch (ConfigurationException ex) {
        LOG.error("XML File: " + configFile.getAbsolutePath()
                + " could not be loaded. It seems the XML file is not valid");
        throw ex;
    }
    parseFile(xmlConfig, configFile.getAbsolutePath());
}

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 ww. j av  a 2 s  .c  om
        // 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:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Tests whether attribute splitting can be disabled.
 *//*from   w ww. j ava2s .  com*/
@Test
public void testAttributeSplittingDisabled() throws ConfigurationException {
    List<Object> values = conf.getList("expressions[@value2]");
    assertEquals("Wrong number of attribute values", 2, values.size());
    assertEquals("Wrong value 1", "a", values.get(0));
    assertEquals("Wrong value 2", "b|c", values.get(1));
    XMLConfiguration conf2 = new XMLConfiguration();
    conf2.setAttributeSplittingDisabled(true);
    conf2.setFile(conf.getFile());
    conf2.load();
    assertEquals("Attribute was split", "a,b|c", conf2.getString("expressions[@value2]"));
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Tests string properties with list delimiters when delimiter parsing is
 * disabled//from w ww.j  av  a  2  s  . com
 */
@Test
public void testDelimiterParsingDisabled() throws ConfigurationException {
    XMLConfiguration conf2 = new XMLConfiguration();
    conf2.setDelimiterParsingDisabled(true);
    conf2.setFile(new File(testProperties));
    conf2.load();

    assertEquals("a,b,c", conf2.getString("split.list3[@values]"));
    assertEquals(0, conf2.getMaxIndex("split.list3[@values]"));
    assertEquals("a\\,b\\,c", conf2.getString("split.list4[@values]"));
    assertEquals("a,b,c", conf2.getString("split.list1"));
    assertEquals(0, conf2.getMaxIndex("split.list1"));
    assertEquals("a\\,b\\,c", conf2.getString("split.list2"));
    conf2 = new XMLConfiguration();
    conf2.setExpressionEngine(new XPathExpressionEngine());
    conf2.setDelimiterParsingDisabled(true);
    conf2.setFile(new File(testProperties));
    conf2.load();

    assertEquals("a,b,c", conf2.getString("split/list3/@values"));
    assertEquals(0, conf2.getMaxIndex("split/list3/@values"));
    assertEquals("a\\,b\\,c", conf2.getString("split/list4/@values"));
    assertEquals("a,b,c", conf2.getString("split/list1"));
    assertEquals(0, conf2.getMaxIndex("split/list1"));
    assertEquals("a\\,b\\,c", conf2.getString("split/list2"));
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Tests disabling both delimiter parsing and attribute splitting.
 *///from   w w w . j a v a 2 s.com
@Test
public void testAttributeSplittingAndDelimiterParsingDisabled() throws ConfigurationException {
    conf.clear();
    conf.setDelimiterParsingDisabled(true);
    conf.load();
    List<Object> values = conf.getList("expressions[@value2]");
    assertEquals("Wrong number of attribute values", 2, values.size());
    assertEquals("Wrong value 1", "a,b", values.get(0));
    assertEquals("Wrong value 2", "c", values.get(1));
    XMLConfiguration conf2 = new XMLConfiguration();
    conf2.setAttributeSplittingDisabled(true);
    conf2.setDelimiterParsingDisabled(true);
    conf2.setFile(conf.getFile());
    conf2.load();
    assertEquals("Attribute was split", "a,b|c", conf2.getString("expressions[@value2]"));
}