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

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

Introduction

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

Prototype

public XMLConfiguration(URL url) throws ConfigurationException 

Source Link

Document

Creates a new instance of XMLConfiguration.

Usage

From source file:org.accada.hal.impl.sim.multi.BatchSimulatorServer.java

/**
 * Initiziale and start BatchSimulatorServer:
 * <ul><li>set controller</li>
 * <li>check and load properties from properties file PROPERTIES_FILE_LOCATION</li>
 * <li>check the batch file location</li></ul>
 *//* w ww .  jav a 2 s . c o m*/
public void initialize(SimulatorServerController controller, String propFile, String defaultPropFile)
        throws SimulatorServerException {
    this.controller = controller;

    // load properties
    XMLConfiguration props;
    URL fileurl = ResourceLocator.getURL(propFile, defaultPropFile, this.getClass());
    try {
        props = new XMLConfiguration(fileurl);
    } catch (ConfigurationException ce) {
        throw new SimulatorServerException("Could not load the properties file.");
    }

    // check properties
    if (!props.containsKey("batchfile")) {
        throw new SimulatorServerException("Property 'batchfile' not found.");
    }
    if (!props.containsKey("iterations")) {
        throw new SimulatorServerException("Property 'iterations' not found.");
    }

    // get properties
    batchFile = props.getString("batchfile");
    try {
        iterations = props.getInt("iterations");
    } catch (NumberFormatException e) {
        throw new SimulatorServerException("Property 'iterations' must be a number");
    }

    // check batch file
    if (!new File(batchFile).exists()) {
        throw new SimulatorServerException("Batch file '" + batchFile + "' not found.");
    }

    start();
}

From source file:org.accada.hal.impl.sim.multi.SimulatorServerController.java

public SimulatorServerController(String propFile, String defaultPropFile) throws SimulatorServerException {
    // load properties
    try {//from   ww w .j av a  2 s  .  c  o  m
        URL fileurl = ResourceLocator.getURL(propFile, defaultPropFile, this.getClass());
        propsConfig = new XMLConfiguration(fileurl);
    } catch (ConfigurationException ce) {
        throw new SimulatorServerException("Could not load property file.");
    }

    // get properties
    simType = propsConfig.getString("simType");
    String simTypePropFile = propsConfig.getString("simTypePropFile");
    port = propsConfig.getInt("port");

    // try to open server socket
    try {
        serverSocket = new ServerSocket(port);
    } catch (IOException e) {
        throw new SimulatorServerException("Could not open the server socket.");
    }

    // start register socket
    registerSocket = new RegisterSocket();
    registerSocket.start();

    // try to initialize the MutliSimulatorEngine (GraphicSimulatorServer or BatchSimulatorServer)
    LOG.info("SimulatorServerEngine: " + simType);
    try {
        Class simClass = Class.forName(simType);
        SimulatorServerEngine simulator = (SimulatorServerEngine) simClass.getConstructor(new Class[0])
                .newInstance(new Object[0]);
        simulator.initialize(this, simTypePropFile, simTypeDefaultPropFile);
    } catch (ClassNotFoundException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (IllegalArgumentException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (SecurityException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (InstantiationException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (IllegalAccessException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (InvocationTargetException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (NoSuchMethodException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (SimulatorServerException e) {
        throw new SimulatorServerException(e.getMessage());
    }
}

From source file:org.accada.hal.impl.sim.SimulatorClient.java

/**
 * implements the initialize method of the SimulatorEngine
 * /*ww  w  .j  a va  2  s  .  c o m*/
 * @param controller 
 *          the SimulatorController
 * @param propFile
 *          the path and name of the configuration file
 * @throws SimulatorServerException
 */
public void initialize(SimulatorController controller, String propFile) throws SimulatorServerException {
    // TODO: adjust to xml properties file, move configuration from constructor to initialization.
    this.controller = controller;

    // load properties
    URL url = ResourceLocator.getURL(propFile, defaultPropFile, this.getClass());
    try {
        config = new XMLConfiguration(url);
    } catch (ConfigurationException ce) {
        throw new SimulatorServerException("SimulatorClient configuration file not found.");
    }

    // check properties
    if (!config.containsKey("host")) {
        throw new SimulatorServerException("Property 'host' not found.");
    }
    if (!config.containsKey("port")) {
        throw new SimulatorServerException("Property 'port' not found.");
    }
    if (!config.containsKey("timeout")) {
        throw new SimulatorServerException("Property 'timeout' not found.");
    }
    if (!config.containsKey("waittime")) {
        throw new SimulatorServerException("Property 'waittime' not found.");
    }

    // get properties
    host = config.getString("host");
    try {
        port = config.getInt("port");
        timeout = config.getInt("timeout");
        waittime = config.getInt("waittime");
    } catch (NumberFormatException e) {
        throw new SimulatorServerException("Properties 'port', 'timeout' and 'waittime' must be numbers");
    }

    tryToConnect();
}

From source file:org.accada.reader.rp.proxy.Result.java

/**
 * Constructor set handshake and load timeout from properties file.
 * /*from  w  w  w. j  av  a  2  s  .  c  om*/
 * @param handshake stores message format and transport protocol
 */
public Result(Handshake handshake) {

    this.handshake = handshake;

    XMLConfiguration conf;
    URL fileurl = ResourceLocator.getURL(PROPERTIES_FILE, DEFAULT_PROPERTIES_FILE, this.getClass());
    try {
        conf = new XMLConfiguration(fileurl);
        timeout = conf.getInt("timeout");
    } catch (Exception e) {
        timeout = 60000;
        LOG.warn("Invalid property file '" + PROPERTIES_FILE + "'. Timeout set to 60 000 ms");
    }

}

From source file:org.accada.reader.rprm.core.msg.MessageLayer.java

/**
 * Reads the management agent properties from a file.
 *
 * @param propFile//w  w w.  ja  v a2 s .  c om
 *            The properties file
 * @throws ReaderProtocolException
 */
private void readMgmtAgentProperties(String propFile, String defaultPropFile) {
    XMLConfiguration conf;
    URL fileurl = ResourceLocator.getURL(propFile, defaultPropFile, this.getClass());
    try {
        conf = new XMLConfiguration(fileurl);
        MessageLayer.mgmtAgentType = AgentType.valueOf(conf.getString("mgmtAgentType").toUpperCase());
        mgmtAgentAddress = conf.getString("mgmtAgentAddress");
        mgmtAgentPort = conf.getInt("mgmtAgentPort");
        mgmtSimulatorStart = conf.getBoolean("mgmtSimulatorStart");
    } catch (ConfigurationException e) {
        log.error("Failed to read the management agent information from " + propFile
                + "\n -> Start default SNMP agent.");
        MessageLayer.mgmtAgentType = AgentType.SNMP;
    }
}

From source file:org.accada.reader.rprm.core.ReaderDevice.java

/**
 * Resets all internal state variables of the reader to a default
 * configuration. The documentation of the reader shall provide a definition
 * what the default settings are/*from  w ww.  ja va  2s .c  o m*/
 * @param propFile
 *           The location of the property file
 * @throws ReaderProtocolException
 *            "Reader not found", "Failed to read properties file",
 *            "wrong valueTrigger in property file", "wrong edgeTrigger in
 *            property file"
 */
public final void resetToDefaultSettings(final String propFile, final String defaultPropFile)
        throws ReaderProtocolException {
    // operational status is DOWN before resetting
    setOperStatus(OperationalStatus.DOWN);

    //init lists
    sources = new Hashtable();
    dataSelectors = new Hashtable();
    notificationChannels = new Hashtable();
    triggers = new Hashtable();
    tagSelectors = new Hashtable();
    tagFields = new Hashtable();
    readPoints = new Hashtable();
    readers = new Hashtable<String, HardwareAbstraction>();
    valueTriggers = new Hashtable();
    edgeTriggers = new Hashtable();
    currentSource = null;
    alarmChannels = new Hashtable<String, AlarmChannel>();
    ioPorts = new Hashtable<String, IOPort>();

    // properties
    XMLConfiguration conf;
    URL fileurl = ResourceLocator.getURL(propFile, defaultPropFile, this.getClass());
    try {
        conf = new XMLConfiguration(fileurl);
    } catch (ConfigurationException e) {
        System.out.println(e.getMessage());
        throw new ReaderProtocolException("Failed to read properties file (" + propFile + ")",
                MessagingConstants.ERROR_UNKNOWN);
    }

    // get properties
    setEPC(conf.getString("epc"));
    setName(conf.getString("name"));
    setManufacturer(conf.getString("manufacturer"));
    setManufacturerDescription(conf.getString("manufacturerDescription"));
    setModel(conf.getString("model"));
    setHandle(conf.getInt("handle"));
    setRole(conf.getString("role"));

    setMaxSourceNumber(conf.getInt("maxSourceNumber"));
    setMaxTagSelectorNumber(conf.getInt("maxTagSelectorNumber"));
    setMaxTriggerNumber(conf.getInt("maxTriggerNumber"));

    // get readers
    SubnodeConfiguration readerConf = conf.configurationAt("readers");
    for (int i = 0; i <= readerConf.getMaxIndex("reader"); i++) {
        // key to current reader
        String key = "reader(" + i + ")";

        // reader's name
        String readerName = readerConf.getString(key + ".name");
        //System.out.println(readerName);

        // get reader
        if (!readers.containsKey(readerName)) {
            // reflection
            String rClass = readerConf.getString(key + ".class");
            String prop = readerConf.getString(key + ".properties");
            try {
                Class cls = Class.forName(rClass);
                Class[] partypes = new Class[] { String.class, String.class };
                Constructor ct = cls.getConstructor(partypes);
                Object[] arglist = new Object[] { readerName, prop };
                HardwareAbstraction ha = (HardwareAbstraction) ct.newInstance(arglist);
                readers.put(readerName, ha);

            } catch (Exception e) {
                log.error(e.getMessage() + "|" + e.getCause());
                throw new ReaderProtocolException("Reader not found", MessagingConstants.ERROR_UNKNOWN);
            }
        }
    }

    // configure readpoints
    SubnodeConfiguration rpConf = conf.configurationAt("readers");
    for (int i = 0; i <= rpConf.getMaxIndex("reader"); i++) {
        // key to current reader
        String key = "reader(" + i + ")";
        // name of the reader
        String readerName = rpConf.getString(key + ".name");
        // get reader
        HardwareAbstraction tempHardwareAbstraction = (HardwareAbstraction) readers.get(readerName);
        // get readpoints
        for (int j = 0; j <= rpConf.getMaxIndex(key + ".readpoint"); j++) {
            String rp = rpConf.getString(key + ".readpoint(" + j + ")");
            // System.out.println(" "+rps[j]);
            AntennaReadPoint.create(rp, this, tempHardwareAbstraction);
        }
    }

    // configure sources
    SubnodeConfiguration sourceConf = conf.configurationAt("sources");
    for (int i = 0; i <= sourceConf.getMaxIndex("source"); i++) {
        String key = "source(" + i + ")";
        // name of the source
        String sourceName = sourceConf.getString(key + ".name");
        // get source
        Source tempSource;
        if (!sources.containsKey(sourceName)) {
            tempSource = Source.create(sourceName, this);
        } else {
            tempSource = getSource(sourceName);
        }
        // fixed
        if (sourceConf.getString(key + ".fixed").equals("true")) {
            tempSource.setFixed(true);
        } else {
            tempSource.setFixed(false);
        }
        // reader's readpoints
        for (int j = 0; j <= sourceConf.getMaxIndex(key + ".readpoint"); j++) {
            String rp = sourceConf.getString(key + ".readpoint(" + j + ")");
            // System.out.println(" "+rp);
            tempSource.addReadPoints(new ReadPoint[] { getReadPoint(rp) });
        }
    }

    // set current Source
    setCurrentSource(getSource(conf.getString("currentSource")));

    // set defaults
    setDefaults();

    // get io triggers
    getIoTriggers(conf);

    // information used for the reader management implementation
    setDescription(conf.getString("description"));
    setLocationDescription(conf.getString("locationDescription"));
    setContact(conf.getString("contact"));
    serialNumber = conf.getString("serialNumber");
    dhcpServerFinder
            .setMacAddress(DHCPServerFinder.macAddressStringToByteArray(conf.getString("macAddress"), "-"));

    operStatusAlarmControl = new TTOperationalStatusAlarmControl("OperStatusAlarmControl", false,
            AlarmLevel.ERROR, 0, OperationalStatus.ANY, OperationalStatus.ANY);

    freeMemoryAlarmControl = new EdgeTriggeredAlarmControl("FreeMemoryAlarmControl", false, AlarmLevel.CRITICAL,
            0, 100, 1000, EdgeTriggeredAlarmDirection.FALLING);

    if ((alarmManager == null) && (mgmtAgent != null)) {
        AlarmProcessor alarmProcessor = null;
        switch (MessageLayer.mgmtAgentType) {
        case SNMP:
            alarmProcessor = new SnmpAlarmProcessor((SnmpAgent) mgmtAgent);
            break;
        // case ...:
        }
        alarmManager = new AlarmManager(alarmProcessor, this);
        alarmManager.start();
    }

    // configure alarm channels
    SubnodeConfiguration alarmChanConf = conf.configurationAt("alarmChannels");
    String host = "";
    int port = -1;
    for (int i = 0; i <= alarmChanConf.getMaxIndex("alarmChannel"); i++) {
        String key = "alarmChannel(" + i + ")";
        // name of the alarm channel
        String alarmChanName = alarmChanConf.getString(key + ".name");
        // get alarm channel
        try {
            host = alarmChanConf.getString(key + ".host");
            port = alarmChanConf.getInt(key + ".port");
            try {
                AlarmChannel.create(alarmChanName, new Address("udp://" + host + ":" + port), this);
            } catch (MalformedURLException mfue) {
                log.error(alarmChanName + ": invalid address");
            }
            host = "";
            port = -1;
        } catch (ReaderProtocolException rpe) {
            // next
        }
    }

    // operational status is UP after resetting
    setOperStatus(OperationalStatus.UP);

}

From source file:org.acoustid.server.ApplicationContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    ServletContext servletContext = event.getServletContext();
    String configFileName = servletContext.getInitParameter("config");
    logger.info("Loading configuration from " + configFileName);
    XMLConfiguration config;/*from  www . ja  va  2s.  c  om*/
    try {
        config = new XMLConfiguration(configFileName);
    } catch (ConfigurationException ex) {
        throw new RuntimeException("Couldn't load configuration file", ex);
    }
    Injector injector = Guice.createInjector(new ServerModule(config));
    logger.debug("Setting injector");
    servletContext.setAttribute(INJECTOR_ATTRIBUTE_NAME, injector);
}

From source file:org.ambraproject.configuration.ConfigurationStore.java

/**
 * Given a URL, determine whether it represents properties or xml and load it as a
 * commons-config Configuration instance.
 *//*  w  w  w  .j av  a  2s .  c  o  m*/
private static AbstractConfiguration getConfigurationFromUrl(URL url) throws ConfigurationException {
    if (url.getFile().endsWith("properties"))
        return new PropertiesConfiguration(url);
    else
        return new XMLConfiguration(url);
}

From source file:org.ambraproject.configuration.ConfigurationStore.java

public static void addJournalResources(CombinedConfiguration root, CombinedConfiguration defaults, String path)
        throws ConfigurationException {

    Collection<String> journals = root.getList(JOURNALS);
    String journalTemplatePath = root.getString(ConfigurationStore.JOURNAL_TEMPLATE_DIR, "/");

    for (String journal : journals) {

        String resourcePath = journalTemplatePath
                + (journalTemplatePath.endsWith("/") ? "journals/" : "/journals/") + journal + path;

        File defaultsXmlFile = new File(resourcePath);
        if (defaultsXmlFile.isFile() && defaultsXmlFile.canRead()) {
            defaults.addConfiguration(new XMLConfiguration(defaultsXmlFile));
            log.info("Added resource '" + resourcePath + "' to configuration");
        }/* w  w  w.j av a  2  s . co m*/
    }
}

From source file:org.ambraproject.queue.MessageServiceImplTest.java

@BeforeClass
public void readConfiguration() throws ConfigurationException {
    String fileName = getClass().getClassLoader().getResource("queue/configuration.xml").getFile();
    configuration = new XMLConfiguration(fileName);
}