Example usage for org.apache.commons.configuration HierarchicalConfiguration getLong

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getLong

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration getLong.

Prototype

public long getLong(String key) 

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
    //// w  ww. java2s . 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:com.norconex.collector.http.delay.impl.GenericDelayResolver.java

@Override
public void loadFromXML(Reader in) throws IOException {
    try {//from  w  ww  .j  a va2s.c o m
        XMLConfiguration xml = ConfigurationUtil.newXMLConfiguration(in);
        defaultDelay = xml.getLong("[@default]", defaultDelay);
        ignoreRobotsCrawlDelay = xml.getBoolean("[@ignoreRobotsCrawlDelay]", ignoreRobotsCrawlDelay);
        scope = xml.getString("[@scope]", SCOPE_CRAWLER);
        List<HierarchicalConfiguration> nodes = xml.configurationsAt("schedule");
        for (HierarchicalConfiguration node : nodes) {
            schedules.add(new DelaySchedule(node.getString("[@dayOfWeek]", null),
                    node.getString("[@dayOfMonth]", null), node.getString("[@time]", null), node.getLong("")));
        }
    } catch (ConfigurationException e) {
        throw new IOException("Cannot load XML.", e);
    }
}

From source file:com.norconex.collector.http.delay.impl.DefaultDelayResolver.java

@Override
public void loadFromXML(Reader in) throws IOException {
    try {//from  w w  w  .j  a  va 2 s. com
        XMLConfiguration xml = ConfigurationLoader.loadXML(in);
        defaultDelay = xml.getLong("[@default]", defaultDelay);
        ignoreRobotsCrawlDelay = xml.getBoolean("[@ignoreRobotsCrawlDelay]", ignoreRobotsCrawlDelay);
        scope = xml.getString("[@scope]", SCOPE_CRAWLER);
        List<HierarchicalConfiguration> nodes = xml.configurationsAt("schedule");
        for (HierarchicalConfiguration node : nodes) {
            schedules.add(new DelaySchedule(node.getString("[@dayOfWeek]", null),
                    node.getString("[@dayOfMonth]", null), node.getString("[@time]", null), node.getLong("")));
        }
    } catch (ConfigurationException e) {
        throw new IOException("Cannot load XML.", e);
    }
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

private void parseTopologyView(HierarchicalConfiguration areaConfig, Obj parent, Network n,
        ObjectBroker objectBroker, Hashtable<String, EntityImpl> entityById,
        Hashtable<String, DatapointImpl> datapointById, Hashtable<String, String> resourceById) {
    for (int areaIdx = 0; areaIdx < sizeOfConfiguration(areaConfig.getProperty("area.[@id]")); areaIdx++) {
        String areaId = areaConfig.getString("area(" + areaIdx + ").[@id]");
        String areaName = arrayToString(areaConfig.getStringArray("area(" + areaIdx + ").[@name]"));
        String areaDescription = arrayToString(
                areaConfig.getStringArray("area(" + areaIdx + ").[@description]"));
        String areaMediaTypeId = areaConfig.getString("area(" + areaIdx + ").[@mediaTypeId]");
        long areaAddress = areaConfig.getLong("area(" + areaIdx + ").[@address]");

        String areaMediaType = null;
        if (areaMediaTypeId != null) {
            areaMediaType = resourceById.get(areaMediaTypeId);
        }/*from  w w  w . ja  v  a  2s  .  c o m*/

        AreaImpl area = new AreaImpl(areaId, areaName, areaDescription, areaAddress, areaMediaType);

        // add part to parent part
        if (parent instanceof ViewTopologyImpl)
            ((ViewTopologyImpl) parent).addArea(area);
        else if (parent instanceof DomainImpl)
            ((AreaImpl) parent).addArea(area);
        else
            parent.add(area);

        objectBroker.addObj(area, true);

        // add instances to part
        HierarchicalConfiguration concreteArea = areaConfig.configurationAt("area(" + areaIdx + ")");

        for (int instanceIdx = 0; instanceIdx < sizeOfConfiguration(
                concreteArea.getProperty("instance.[@id]")); instanceIdx++) {
            String instanceId = concreteArea.getString("instance(" + instanceIdx + ").[@id]");
            long address = concreteArea.getLong("instance(" + instanceIdx + ").[@address]");

            Obj addInstance = area.addInstance(entityById.get(instanceId), address);
            objectBroker.addObj(addInstance, true);

        }

        // recursively add more domains
        parseTopologyView(concreteArea, area, n, objectBroker, entityById, datapointById, resourceById);
    }
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

private void parseFunctionalView(HierarchicalConfiguration groupConfig, Obj parent, Network n,
        ObjectBroker objectBroker, Hashtable<String, EntityImpl> entityById,
        Hashtable<String, DatapointImpl> datapointById, KNXConnector knxConnector,
        Hashtable<String, String> groupAddressByDatapointId) {
    for (int groupsIdx = 0; groupsIdx < sizeOfConfiguration(
            groupConfig.getProperty("group.[@id]")); groupsIdx++) {
        String groupId = groupConfig.getString("group(" + groupsIdx + ").[@id]");
        String groupName = arrayToString(groupConfig.getStringArray("group(" + groupsIdx + ").[@name]"));
        String groupDescription = arrayToString(
                groupConfig.getStringArray("group(" + groupsIdx + ").[@description]"));
        long groupAddress = groupConfig.getLong("group(" + groupsIdx + ").[@address]");

        GroupImpl group = new GroupImpl(groupId, groupName, groupDescription, groupAddress);

        // add part to parent part
        if (parent instanceof ViewFunctionalImpl)
            ((ViewFunctionalImpl) parent).addGroup(group);
        else if (parent instanceof GroupImpl)
            ((GroupImpl) parent).addGroup(group);
        else//  ww  w. jav a  2 s.c  o m
            parent.add(group);

        objectBroker.addObj(group, true);

        // add instances to part
        HierarchicalConfiguration concreteGroup = groupConfig.configurationAt("group(" + groupsIdx + ")");

        for (int instanceIdx = 0; instanceIdx < sizeOfConfiguration(
                concreteGroup.getProperty("instance.[@id]")); instanceIdx++) {
            String instanceId = concreteGroup.getString("instance(" + instanceIdx + ").[@id]");
            String connector = concreteGroup.getString("instance(" + instanceIdx + ").[@connector]");

            try {
                DatapointImpl dp = datapointById.get(instanceId);
                if (dp == null) {
                    log.warning("No datapoint type found for instance: " + instanceId);
                    continue;
                }
                Class<?> clazz = dp.getClass();

                if (clazz != null) {
                    Constructor<?> constructor = clazz.getConstructor(KNXConnector.class, DataPointInit.class);
                    Object[] object = new Object[2];
                    object[0] = knxConnector;

                    DataPointInit dptInit = new DataPointInit();
                    dptInit.setName("function");
                    dptInit.setReadable(dp.isValueReadable());
                    dptInit.setWritable(dp.isValueWritable());
                    dptInit.setGroupAddress(
                            new GroupAddress(Integer.parseInt(groupAddressByDatapointId.get(instanceId))));

                    object[1] = dptInit;
                    DatapointImpl dataPoint = (DatapointImpl) constructor.newInstance(object);

                    group.addFunction(dataPoint);
                    objectBroker.addObj(dataPoint, true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            group.addInstance(datapointById.get(instanceId), connector);
        }

        // recursively add more parts
        parseFunctionalView(concreteGroup, group, n, objectBroker, entityById, datapointById, knxConnector,
                groupAddressByDatapointId);
    }
}

From source file:nz.co.jsrsolutions.ds3.provider.EodDataProviderFactory.java

public static EodDataProvider create(HierarchicalConfiguration appConfig, String type)
        throws EodDataProviderException {

    // TODO: Use reflection here.  Probably need a Builder to abstract away different construction arguments
    if (type.compareTo(EODDATADATAPROVIDER_KEY) == 0) {

        String serviceUrl = appConfig.getString("eodDataProviders.eodDataProvider(0).serviceUrl");
        String username = appConfig.getString("eodDataProviders.eodDataProvider(0).username");
        String password = appConfig.getString("eodDataProviders.eodDataProvider(0).password");
        long timeout = appConfig.getLong("eodDataProviders.eodDataProvider(0).timeout");

        return new EodDataEodDataProvider(serviceUrl, username, password, timeout);

    } else {/*  w w  w . j a v  a 2  s . c  o  m*/

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("Unknown data provider type [ ");
        stringBuffer.append(type);
        stringBuffer.append(" ] ");
        throw new EodDataProviderException(stringBuffer.toString());

    }

}

From source file:org.apache.james.container.spring.mailbox.MaxQuotaConfigurationReader.java

private Map<String, Long> parseMaxMessageConfiguration(HierarchicalConfiguration config, String entry) {
    List<HierarchicalConfiguration> maxMessageConfiguration = config.configurationAt("maxQuotaManager")
            .configurationsAt(entry);/*from www .j  av  a2  s  . c om*/
    Map<String, Long> result = new HashMap<String, Long>();
    for (HierarchicalConfiguration conf : maxMessageConfiguration) {
        result.put(conf.getString("quotaRoot"), conf.getLong("value"));
    }
    return result;
}

From source file:org.apache.james.fetchmail.FetchScheduler.java

@PostConstruct
public void init() throws Exception {
    enabled = conf.getBoolean("[@enabled]", false);
    if (enabled) {
        int numThreads = conf.getInt("threads", 5);
        String jmxName = conf.getString("jmxName", "fetchmail");
        String jmxPath = "org.apache.james:type=component,name=" + jmxName + ",sub-type=threadpool";

        /*/*from   w w w .java  2 s .c om*/
        The scheduler service that is used to trigger fetch tasks.
        */
        ScheduledExecutorService scheduler = new JMXEnabledScheduledThreadPoolExecutor(numThreads, jmxPath,
                "scheduler");
        MailQueue queue = queueFactory.getQueue(MailQueueFactory.SPOOL);

        List<HierarchicalConfiguration> fetchConfs = conf.configurationsAt("fetch");
        for (HierarchicalConfiguration fetchConf : fetchConfs) {
            // read configuration
            Long interval = fetchConf.getLong("interval");

            FetchMail fetcher = new FetchMail();

            fetcher.setLog(logger);
            fetcher.setDNSService(dns);
            fetcher.setUsersRepository(urepos);
            fetcher.setMailQueue(queue);
            fetcher.setDomainList(domainList);

            fetcher.configure(fetchConf);

            // initialize scheduling
            schedulers.add(scheduler.scheduleWithFixedDelay(fetcher, 0, interval, TimeUnit.MILLISECONDS));
        }

        if (logger.isInfoEnabled())
            logger.info("FetchMail Started");
    } else {
        if (logger.isInfoEnabled())
            logger.info("FetchMail Disabled");
    }
}

From source file:org.bgp4j.config.nodes.impl.PeerConfigurationParser.java

public PeerConfiguration parseConfiguration(HierarchicalConfiguration config) throws ConfigurationException {
    PeerConfigurationImpl peerConfig = new PeerConfigurationImpl();
    List<HierarchicalConfiguration> clientConfigs = config.configurationsAt("Client");
    List<HierarchicalConfiguration> capabilityConfigs = config.configurationsAt("Capabilities");

    try {//from w  w w .  jav a2 s .c o m
        peerConfig.setPeerName(config.getString("[@name]"));
    } catch (NoSuchElementException e) {
        throw new ConfigurationException("peer name not set", e);
    }

    if (clientConfigs.size() > 1) {
        throw new ConfigurationException("duplicate <Client/> element");
    } else if (clientConfigs.size() == 0) {
        throw new ConfigurationException("missing <Client/> element");
    } else
        peerConfig.setClientConfig(clientConfigurationParser.parseConfig(clientConfigs.get(0)));

    if (capabilityConfigs.size() > 1) {
        throw new ConfigurationException("duplicate <Capabilities/> element");
    } else if (capabilityConfigs.size() == 1)
        peerConfig.setCapabilities(capabilityParser.parseConfig(capabilityConfigs.get(0)));

    try {
        peerConfig.setLocalAS(config.getInt("AutonomousSystem[@local]"));
    } catch (NoSuchElementException e) {
        throw new ConfigurationException("local AS number not given", e);
    }
    try {
        peerConfig.setRemoteAS(config.getInt("AutonomousSystem[@remote]"));
    } catch (NoSuchElementException e) {
        throw new ConfigurationException("remote AS number not given", e);
    }

    try {
        long identifier = config.getLong("BgpIdentifier[@local]");

        if (!isValidBgpIdentifier(identifier))
            throw new ConfigurationException("Invalid local BGP identifier: " + identifier);

        peerConfig.setLocalBgpIdentifier(identifier);
    } catch (NoSuchElementException e) {
        throw new ConfigurationException("local BGP identifier not given", e);
    }
    try {
        long identifier = config.getLong("BgpIdentifier[@remote]");

        if (!isValidBgpIdentifier(identifier))
            throw new ConfigurationException("Invalid remote BGP identifier: " + identifier);

        peerConfig.setRemoteBgpIdentifier(identifier);
    } catch (NoSuchElementException e) {
        throw new ConfigurationException("remote BGP identifier not given", e);
    }

    peerConfig.setHoldTime(config.getInt("Timers[@holdTime]", 0));
    peerConfig.setIdleHoldTime(config.getInt("Timers[@idleHoldTime]", 0));
    peerConfig.setDelayOpenTime(config.getInt("Timers[@delayOpenTime]", 0));
    peerConfig.setConnectRetryTime(config.getInt("Timers[@connectRetryTime]", 0));
    peerConfig.setAutomaticStartInterval(config.getInt("Timers[@automaticStartInterval]", 0));

    peerConfig.setAllowAutomaticStart(config.getBoolean("Options[@allowAutomaticStart]", true));
    peerConfig.setAllowAutomaticStop(config.getBoolean("Options[@allowAutomaticStop]", false));
    peerConfig.setDampPeerOscillation(config.getBoolean("Options[@dampPeerOscillation]", false));
    peerConfig.setCollisionDetectEstablishedState(
            config.getBoolean("Options[@collisionDetectEstablishedState]", false));
    peerConfig.setDelayOpen(config.getBoolean("Options[@delayOpen]", false));
    peerConfig.setPassiveTcpEstablishment(config.getBoolean("Options[@passiveTcpEstablishment]", false));
    peerConfig.setHoldTimerDisabled(config.getBoolean("Options[@holdTimerDisabled]", false));

    return peerConfig;
}

From source file:org.lable.oss.dynamicconfig.serialization.yaml.YamlDeserializerTest.java

@Test
public void testLoad() throws ConfigurationException, IOException, ClassNotFoundException {
    HierarchicalConfigurationDeserializer deserializer = new YamlDeserializer();
    HierarchicalConfiguration config = deserializer.deserialize(IOUtils.toInputStream(testYaml));

    // Type checking.
    assertThat(config.getString("type.string"), is("Okay"));

    List list = config.getList("type.listOfStrings");
    for (Object o : list) {
        assertThat(o, instanceOf(String.class));
    }//from  w w  w .j  a  v a 2  s .  com
    assertThat(list.size(), is(3));
    assertThat(list.get(0), is("One"));
    assertThat(list.get(1), is("Two"));
    assertThat(list.get(2), is(""));

    assertThat(config.getBoolean("type.booleanFalse"), is(false));
    assertThat(config.getBoolean("type.booleanTrue"), is(true));

    list = config.getList("type.listOfIntegers");
    for (Object o : list) {
        assertThat(o, instanceOf(Integer.class));
    }
    assertThat(list.size(), is(5));
    assertThat(list.get(0), is(1));
    assertThat(list.get(4), is(-1));

    assertThat(config.getLong("type.long"), is(1000000000000L));

    // Tree model
    assertThat(config.getString("tree.branchL1a.branchL2a.branchL3a"), is("leaf_a"));
    assertThat(config.getString("tree.branchL1a.branchL2b.branchL3h"), is("leaf_h"));
    // Trim, because this value is defined as a multi-line value.
    assertThat(config.getString("tree.branchL1a.branchL2b.branchL3i").trim(), is("leaf_i"));
}