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

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

Introduction

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

Prototype

public Iterator getKeys() 

Source Link

Usage

From source file:com.dfki.av.sudplan.Configuration.java

/**
 * Initialize the {@link XMLConfiguration} for the application.
 *
 * @return the {@link #XML_CONFIG} to return.
 *///from w ww .  ja v a2 s  .  co  m
private static XMLConfiguration initConfig() {
    log.debug("Init sudplan3D user home...");
    String userHomeDir = VisSettings.USER_HOME_DIR;

    log.info("Init sudplan3D configuration...");
    // Check whether the sudplan3D config file already exists.
    final File userConfigFile = new File(userHomeDir + "/config/sudplan3D.xml");
    if (!userConfigFile.exists()) {
        log.debug("No configuration file existing.");
        installConfigFile(userConfigFile, userHomeDir, userHomeDir);
    } else {
        log.debug("Configuration file existing. Checking version ...");
        if (!isConfigFileSupported(userConfigFile)) {
            log.debug("Configuration file not supported.");
            log.debug("Delete old configuration file.");
            boolean deleted = userConfigFile.delete();
            if (deleted) {
                installConfigFile(userConfigFile, userHomeDir, userHomeDir);
            } else {
                log.error("Could not delete file {}", userConfigFile.getAbsolutePath());
                log.warn("Using old configuration file.");
            }
        } else {
            log.debug("Configuration file supported.");
        }
    }

    XMLConfiguration xmlConfig = null;
    try {
        xmlConfig = new XMLConfiguration(userConfigFile);
        xmlConfig.setAutoSave(true);
        for (Iterator<String> it = xmlConfig.getKeys(); it.hasNext();) {
            String key = it.next();
            log.debug("{} : {}", key, xmlConfig.getString(key));
        }
    } catch (ConfigurationException ex) {
        log.error(ex.toString());
    }
    return xmlConfig;
}

From source file:com.beginner.core.utils.PropertyUtil.java

/**
 * ?XML?KEY?TestResourcesUtil/* w w  w.  jav a  2  s . com*/
 * @param fileName      XML???
 * @return List<String>   ?
 * @throws Exception   ?
 */
public static List<String> getXmlProperties(String fileName) throws Exception {

    if (StringUtils.isBlank(fileName))
        throw new IllegalArgumentException("The fileName cannot be null and cannot be empty.");

    XMLConfiguration config = null;
    Iterator<String> properties = null;
    List<String> list = new ArrayList<String>();
    try {
        config = new XMLConfiguration(fileName);
        properties = config.getKeys();
        while (properties.hasNext()) {
            String key = (String) properties.next();
            list.add(key);
        }
    } catch (Exception e) {
        throw new Exception();
    }
    return list;
}

From source file:edu.hawaii.soest.pacioos.text.TextSourceFactory.java

/**
 * Configure and return a simple text-based source driver instance using the given XML-based
 * configuration file.//from w w w. j  a  va 2s  . co m
 * 
 * @param configLocation  the path to the file on disk or in a jar
 * @return  a new instance of a subclassed SimpleTextSource
 * @throws ConfigurationException
 */
public static SimpleTextSource getSimpleTextSource(String configLocation) throws ConfigurationException {

    // Get the per-driver configuration
    XMLConfiguration xmlConfig = new XMLConfiguration();
    xmlConfig.setListDelimiter(new String("|").charAt(0));
    xmlConfig.load(configLocation);
    String connectionType = xmlConfig.getString("connectionType");

    if (log.isDebugEnabled()) {
        Iterator i = xmlConfig.getKeys();
        while (i.hasNext()) {
            String key = (String) i.next();
            String value = xmlConfig.getString(key);
            log.debug(key + ":\t\t" + value);

        }

    }

    // return the correct configuration type
    if (connectionType.equals("file")) {
        FileTextSource fileTextSource = getFileTextSource(xmlConfig);
        String filePath = xmlConfig.getString("connectionParams.filePath");
        fileTextSource.setDataFilePath(filePath);

        simpleTextSource = (SimpleTextSource) fileTextSource;

    } else if (connectionType.equals("socket")) {
        SocketTextSource socketTextSource = getSocketTextSource(xmlConfig);
        String hostName = xmlConfig.getString("connectionParams.hostName");
        socketTextSource.setHostName(hostName);
        int hostPort = xmlConfig.getInt("connectionParams.hostPort");
        socketTextSource.setHostPort(hostPort);

        simpleTextSource = (SimpleTextSource) socketTextSource;

    } else if (connectionType.equals("serial")) {
        SerialTextSource serialTextSource = getSerialTextSource(xmlConfig);
        String serialPort = xmlConfig.getString("connectionParams.serialPort");
        serialTextSource.setSerialPort(serialPort);
        int baudRate = xmlConfig.getInt("connectionParams.serialPortParams.baudRate");
        serialTextSource.setBaudRate(baudRate);
        int dataBits = xmlConfig.getInt("connectionParams.serialPortParams.dataBits");
        serialTextSource.setDataBits(dataBits);
        int stopBits = xmlConfig.getInt("connectionParams.serialPortParams.stopBits");
        serialTextSource.setStopBits(stopBits);
        String parity = xmlConfig.getString("connectionParams.serialPortParams.parity");
        serialTextSource.setParity(parity);

        simpleTextSource = (SimpleTextSource) serialTextSource;

    } else {
        throw new ConfigurationException("There was an issue parsing the configuration."
                + " The connection type of " + connectionType + " wasn't recognized.");
    }

    return simpleTextSource;

}

From source file:com.voidsearch.voidbase.config.VoidBaseConfig.java

protected XMLConfiguration mergeConfiguration(List<String> files) throws ConfigException {
    XMLConfiguration config = new XMLConfiguration();

    for (String file : files) {
        Iterator<String> keys;
        XMLConfiguration fragment;

        try {//from   w  w w .j  a  va 2 s  .  c o  m
            logger.info("Loading configuration file: " + file);
            fragment = new XMLConfiguration(file);
            keys = fragment.getKeys();
        } catch (ConfigurationException e) {
            GenericUtil.logException(e);
            throw new ConfigException("Failed to load configuration from: " + file);
        }

        while (keys.hasNext()) {
            String key = keys.next();

            // sanity check
            if (config.containsKey(key)) {
                throw new ConfigException("Collision of keys for: " + key);
            }

            // merge configuration
            config.addProperty(key, fragment.getProperty(key));
        }
    }

    return config;
}

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

/**
 * Tests whether reloads are recognized when querying the configuration's
 * keys./*  w w w. ja  v  a2  s  .  co  m*/
 */
@Test
public void testGetKeysWithReload() throws ConfigurationException {
    XMLConfiguration c = setUpReloadTest();
    conf.addProperty("aNewKey", "aNewValue");
    conf.save(testSaveConf);
    boolean found = false;
    for (Iterator<String> it = c.getKeys(); it.hasNext();) {
        if ("aNewKey".equals(it.next())) {
            found = true;
        }
    }
    assertTrue("Reload not performed", found);
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* retrieves all possible elements and values of an XML file (string).
* 
* @param  content the XML whose elements will be obtained.
* @return a Hashtable containing the element name (as key) and Element object containign the type (ie class and the value).
* @see Hashtable//from w ww  . j  a  v a  2s . com
* @see Element
*/
public Hashtable<String, Element> getAvailableValues(String content) throws Exception {
    Hashtable<String, Element> h = new Hashtable<String, Element>();

    XMLConfiguration x = new XMLConfiguration();
    x.setDelimiterParsingDisabled(true);
    x.load(new ByteArrayInputStream(content.getBytes()));
    Iterator it = x.getKeys();
    String method = null;
    String type = null;

    boolean hasmethod = false;
    while (it.hasNext()) {
        String s = (String) it.next();
        // make sure they have the same type?
        if (s.contains("[@")) {
            type = x.getString(s);
            if (!hasmethod) // then must be empty
            {
                h.put(s.substring(0, s.indexOf("[")), new Element(type, ""));
                type = null;
                method = null;
            }
        } else {
            hasmethod = true;
            method = s;
        }

        if (type != null && method != null) {
            if (type.endsWith("Date")) {
                h.put(method,
                        new Element(type, (new SimpleDateFormat(_dateformat)).parse(x.getString(method))));
            } else if (type.endsWith("byte[]")) {
                h.put(method, new Element(type, (byte[]) Base64.decodeBase64(x.getString(method).getBytes())));
            } else if (type.endsWith("Serializable")) {
                h.put(method, new Element(type,
                        (Serializable) getObject(Base64.decodeBase64(x.getString(method).getBytes()))));
            } else {
                h.put(method, new Element(type, x.getString(method)));
            }
            type = null;
            method = null;
            hasmethod = false;
        }
    }

    return h;
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* use this method to instantiate a JAXB object encapsulated in a FlexContainer, given an XML document and the reference class.
*
* @param  xml string contents containing the elements and values for the object.
* @param  c the reference class that wil be used for instantiation.
* @return the instantiated and value-populated object.
* @see Hashtable//from   w w w  .j  ava  2s  .  com
* @see Element
*/
public Object getJAXBObject(String xml, Class c) throws Exception {
    Object obj = c.newInstance();
    Object fc = new FlexContainer(obj);

    XMLConfiguration x = new XMLConfiguration();
    x.setDelimiterParsingDisabled(true);
    x.load(new ByteArrayInputStream(xml.getBytes()));
    Iterator it = x.getKeys();

    //Method[] m = c.getMethods();
    Vector ve = retrieveMethods(obj.getClass(), null);
    Method[] m = new Method[ve.size()];
    ve.toArray(m);

    String method = null;
    String type = null;

    boolean hasmethod = false;
    while (it.hasNext()) {
        String s = (String) it.next();
        // make sure they have the same type?
        if (s.contains("[@")) {
            type = x.getString(s);
            if (method != null) {
                hasmethod = true;
            }
        } else {
            method = s;
        }

        if (hasmethod && type != null && method != null) {
            // check if class has the method.
            for (int i = 0; i < m.length; i++) {
                if (m[i].getName().toLowerCase().equals("set" + method)) {

                    Object[] o = new Object[1];
                    Class ct = null;

                    if (type.endsWith("String")) {
                        ct = String.class;
                        o[0] = x.getString(method);
                    } else if (type.endsWith("Date")) {
                        ct = Date.class;
                        // assume use default java date format
                        //o[0] = (new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy")).parse(x.getString(method));
                        o[0] = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(x.getString(method));
                    } else if (type.endsWith("BigInteger")) {
                        ct = BigInteger.class;
                        o[0] = new BigInteger(x.getString(method));
                    } else if (type.endsWith("BigDecimal")) {
                        ct = BigDecimal.class;
                        o[0] = new BigDecimal(x.getString(method));
                    } else if (type.endsWith(".Integer")) {
                        ct = Integer.class;
                        o[0] = x.getInt(method);
                    } else if (type.endsWith("Long")) {
                        ct = Long.class;
                        o[0] = x.getLong(method);
                    } else if (type.endsWith("Double")) {
                        ct = Double.class;
                        o[0] = x.getDouble(method);
                    } else if (type.endsWith("Float")) {
                        ct = Float.class;
                        o[0] = x.getFloat(method);
                    } else if (type.endsWith("Short")) {
                        ct = Short.class;
                        o[0] = x.getShort(method);
                    } else if (type.endsWith("boolean")) {
                        ct = boolean.class;
                        o[0] = x.getBoolean(method);
                    } else if (type.endsWith("Boolean")) {
                        ct = Boolean.class;
                        o[0] = x.getBoolean(method);
                    } else if (type.endsWith("byte[]")) {
                        ct = byte[].class;
                        o[0] = Base64.decodeBase64(x.getString(method).getBytes());
                    } else if (type.endsWith("Serializable")) {
                        ct = Serializable.class;
                        o[0] = getObject(Base64.decodeBase64(x.getString(method).getBytes()));
                    } else {
                        throw new Exception("Unknown type:" + type + " for element:" + method);
                    }

                    Class[] c2 = new Class[1];
                    c2[0] = ct;
                    //Method met = c.getMethod("set"+method,c2);
                    Method met = c.getMethod(m[i].getName(), c2);
                    met.invoke(obj, o);
                    break;
                }
            }
            type = null;
            method = null;
            hasmethod = false;
        }
    }
    return obj;
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* use this method to instantiate an object given an XML document and the reference class.
*
* @param  xml string contents containing the elements and values for the object.
* @param  c the reference class that wil be used for instantiation.
* @return the instantiated and value-populated object.
* @see Hashtable//  ww w.j a v a2 s.c  om
* @see Element
*/
public Object getObject(String xml, Class c) throws Exception {
    Object obj = c.newInstance();

    XMLConfiguration x = new XMLConfiguration();
    x.setDelimiterParsingDisabled(true);
    x.load(new ByteArrayInputStream(xml.getBytes()));
    Iterator it = x.getKeys();

    //Method[] m = c.getMethods();
    Vector ve = retrieveMethods(obj.getClass(), null);
    Method[] m = new Method[ve.size()];
    ve.toArray(m);

    String method = null;
    String type = null;

    boolean hasmethod = false;
    while (it.hasNext()) {
        String s = (String) it.next();
        // make sure they have the same type?
        if (s.contains("[@")) {
            type = x.getString(s);
            if (method != null) {
                hasmethod = true;
            }
        } else {
            method = s;
        }

        if (hasmethod && type != null && method != null) {

            // check if class has the method.
            for (int i = 0; i < m.length; i++) {
                if (m[i].getName().toLowerCase().equals("set" + method)) {
                    Object[] o = new Object[1];
                    Class ct = null;

                    if (type.endsWith("String")) {
                        ct = String.class;
                        o[0] = x.getString(method);
                    } else if (type.endsWith("XMLGregorianCalendar") || type.equalsIgnoreCase("timestamp")) {
                        // dirty 'temporary' workaround
                        // 2009-01-01T10:00:00.000+08:00
                        Date d = null;
                        try {
                            d = new Date(Long.parseLong(x.getString(method)));
                        } catch (Exception a) {
                            try {
                                d = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S"))
                                        .parse(x.getString(method));
                            } catch (Exception e) {
                                try {
                                    d = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                                            .parse(x.getString(method));
                                } catch (Exception f) {
                                    try // must be a date only
                                    {
                                        d = (new SimpleDateFormat("yyyy-MM-dd")).parse(x.getString(method));
                                    } catch (Exception g) // ok must be a time?
                                    {
                                        d = (new SimpleDateFormat("HH:mm:ss")).parse(x.getString(method));
                                    }
                                }
                            }
                        }
                        GregorianCalendar gc = new GregorianCalendar();
                        gc.setTime(d);

                        XMLGregorianCalendar cal = ((new com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl())
                                .newXMLGregorianCalendar(gc));
                        ct = XMLGregorianCalendar.class;
                        o[0] = cal;
                    } else if (type.endsWith("Date")) {
                        ct = Date.class;
                        // assume use default java date format
                        //o[0] = (new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy")).parse(x.getString(method));
                        try {
                            o[0] = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(x.getString(method));
                        } catch (Exception e) {
                            //if not must be in long version
                            //o[0] = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(Long.parseLong(x.getString(method))));
                            o[0] = new Date(Long.parseLong(x.getString(method)));
                        }
                    } else if (type.endsWith("BigInteger")) {
                        ct = BigInteger.class;
                        o[0] = new BigInteger(x.getString(method));
                    } else if (type.endsWith("BigDecimal")) {
                        ct = BigDecimal.class;
                        o[0] = new BigDecimal(x.getString(method));
                    } else if (type.endsWith(".Integer") || type.equals("Integer")
                            || type.equalsIgnoreCase("int unsigned") || type.equalsIgnoreCase("tinyint")) {
                        ct = Integer.class;
                        o[0] = x.getInt(method);
                    } else if (type.endsWith("Long")) {
                        ct = Long.class;
                        o[0] = x.getLong(method);
                    } else if (type.endsWith("Double")) {
                        ct = Double.class;
                        o[0] = x.getDouble(method);
                    } else if (type.endsWith("Float")) {
                        ct = Float.class;
                        o[0] = x.getFloat(method);
                    } else if (type.endsWith("Short")) {
                        ct = Short.class;
                        o[0] = x.getShort(method);
                    } else if (type.endsWith("boolean")) {
                        ct = boolean.class;
                        o[0] = x.getBoolean(method);
                    } else if (type.endsWith("Boolean")) {
                        ct = Boolean.class;
                        o[0] = x.getBoolean(method);
                    } else if (type.endsWith("byte[]")) {
                        ct = byte[].class;
                        o[0] = x.getString(method).getBytes();
                    } else if (type.endsWith("Serializable")) {
                        ct = Serializable.class;
                        o[0] = x.getString(method).getBytes();
                    } else {
                        throw new Exception("Unknown type:" + type + " for element:" + method);
                    }

                    Class[] c2 = new Class[1];
                    c2[0] = ct;
                    //Method met = c.getMethod("set"+method,c2);
                    Method met = c.getMethod(m[i].getName(), c2);
                    met.invoke(obj, o);

                    break;
                }
            }
            type = null;
            method = null;
            hasmethod = false;
        }
    }
    return obj;
}

From source file:org.apache.tamaya.commons.XmlConfigurationFormat.java

@Override
public ConfigurationData readConfiguration(String name, InputStream inputStream) {
    PropertyValue data = PropertyValue.createObject();
    data.setMeta("name", name);
    data.setMeta("format.class", getClass().getName());
    try {/*from   ww  w .ja  v a  2 s  .  c  o  m*/
        XMLConfiguration commonXmlConfiguration;
        File file = new File(name);
        if (file.exists()) {
            commonXmlConfiguration = new XMLConfiguration(file);
        } else {
            commonXmlConfiguration = new XMLConfiguration(new URL(name));
        }
        Iterator<String> keyIter = commonXmlConfiguration.getKeys();
        while (keyIter.hasNext()) {
            String key = keyIter.next();
            ((ObjectValue) data).setValue(key, commonXmlConfiguration.getString(key));
        }
    } catch (Exception e) {
        throw new ConfigException("Failed to parse xml-file format from " + name, e);
    }
    return new ConfigurationData(name, this, data);
}

From source file:org.encuestame.core.test.config.XmlConfigurationText.java

/**
 * @throws ConfigurationException//  w  w w.java 2  s.com
 *
 */
@Test
public void testXmlFile() {
    // final ConfigurationManager configurationManager = new
    // ConfigurationManager("encuestame-config.xml");
    // System.out.println(configurationManager.getIntProperty("encuestame.database.version"));
    XMLConfiguration xmlConfiguration = null;
    try {
        Resource res = new ClassPathResource("properties-test/encuestame-test-config.xml");
        // System.out.println(res.getFilename());
        // System.out.println(res.getFile().getAbsolutePath());
        xmlConfiguration = new XMLConfiguration(res.getFile());
        // System.out.println(xmlConfiguration.getString("encuestame.database.version"));
        // System.out.println(xmlConfiguration.getString("database.version"));
        xmlConfiguration.setAutoSave(true);
        xmlConfiguration.addProperty("juan", "juan");

        // System.out.println(xmlConfiguration.getString("administration"));
        // System.out.println(xmlConfiguration.getString("version"));

        // System.out.println(xmlConfiguration.getRootElementName());
        // System.out.println(xmlConfiguration.getKeys());
        final Iterator i = xmlConfiguration.getKeys();
        while (i.hasNext()) {
            Object object = (Object) i.next();
            //System.out.println(object);
        }

        // System.out.println(xmlConfiguration.getList("social-networks.social-network.social-network-name"));
        // System.out.println(xmlConfiguration.getList("social-networks.social-network.social-network-name").size());
        // System.out.println(xmlConfiguration.getList("social-networks"));
        // System.out.println(xmlConfiguration.getList("social-networks").size());

        List fields = xmlConfiguration.configurationsAt("tables.table(0).fields.field");
        for (Iterator it = fields.iterator(); it.hasNext();) {
            HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
            // sub contains all data about a single field
            String fieldName = sub.getString("name");
            String fieldType = sub.getString("type");
        }

    } catch (ConfigurationException e) {

        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}