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() 

Source Link

Document

Creates a new instance of XMLConfiguration.

Usage

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

/**
 * Tests whether attribute splitting can be disabled.
 *//* w w w  .ja  va2 s.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 disabling both delimiter parsing and attribute splitting.
 *//*from   w w  w  . j  a  va  2  s.  c o  m*/
@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]"));
}

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

/**
 * Tests modifying an XML document and saving it with schema validation
 * enabled./*from   w  w  w  .j a  v  a  2 s.  c om*/
 */
@Test
@Ignore
public void testSaveWithValidation() throws Exception {
    CatalogResolver resolver = new CatalogResolver();
    resolver.setCatalogFiles(CATALOG_FILES);
    conf = new XMLConfiguration();
    conf.setEntityResolver(resolver);
    conf.setFileName(testFile2);
    conf.setSchemaValidation(true);
    conf.load();
    conf.setProperty("Employee.SSN", "123456789");
    conf.validate();
    conf.save(testSaveConf);
    conf = new XMLConfiguration(testSaveConf);
    assertEquals("123456789", conf.getString("Employee.SSN"));
}

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

/**
 * Tests modifying an XML document and validating it against the schema.
 */// w ww  . j a v a2 s. com
@Test
@Ignore
public void testSaveWithValidationFailure() throws Exception {
    CatalogResolver resolver = new CatalogResolver();
    resolver.setCatalogFiles(CATALOG_FILES);
    conf = new XMLConfiguration();
    conf.setEntityResolver(resolver);
    conf.setFileName(testFile2);
    conf.setSchemaValidation(true);
    conf.load();
    conf.setProperty("Employee.Email", "JohnDoe@apache.org");
    try {
        conf.validate();
        fail("No validation failure on save");
    } catch (Exception e) {
        Throwable cause = e.getCause();
        assertNotNull("No cause for exception on save", cause);
        assertTrue("Incorrect exception on save", cause instanceof SAXParseException);
    }
}

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

/**
 * Tests whether an attribute can be set to an empty string. This test is
 * related to CONFIGURATION-446./* w w w.  java2  s .com*/
 */
@Test
public void testEmptyAttribute() throws ConfigurationException {
    String key = "element3[@value]";
    conf.setProperty(key, "");
    assertTrue("Key not found", conf.containsKey(key));
    assertEquals("Wrong value", "", conf.getString(key));
    conf.save(testSaveConf);
    conf = new XMLConfiguration();
    conf.load(testSaveConf);
    assertTrue("Key not found after save", conf.containsKey(key));
    assertEquals("Wrong value after save", "", conf.getString(key));
}

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/*from  www  .j a va2s.co  m*/
* @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: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/*w  ww .  j  a  v a  2  s.co  m*/
* @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:FocusingField.java

License:asdf

public void saveXML(String path) { // x,y,r
    XMLConfiguration hConfig = new XMLConfiguration();
    hConfig.setRootElementName("focusingHistory");
    if (comment != null) {
        String comment_esc = comment.replace(",", "\\,");
        //          hConfig.addProperty("comment","<![CDATA["+comment_esc+ "]]>");
        hConfig.addProperty("comment", comment_esc);
    }//from   w  ww  . j a v  a  2 s  .c  om
    if (serialNumber != null)
        hConfig.addProperty("serialNumber", serialNumber);
    if (lensSerial != null)
        hConfig.addProperty("lensSerial", lensSerial);
    hConfig.addProperty("lens_center_x", pX0_distortions); // distortions center, not aberrations!
    hConfig.addProperty("lens_center_y", pY0_distortions);

    hConfig.addProperty("PIXEL_SIZE", PIXEL_SIZE);
    hConfig.addProperty("sensorWidth", sensorWidth);
    hConfig.addProperty("sensorHeight", sensorHeight);

    if ((sampleCoord != null) && (sampleCoord.length > 0) && (sampleCoord[0] != null)
            && (sampleCoord[0].length > 0)) {
        hConfig.addProperty("samples_x", sampleCoord[0].length);
        hConfig.addProperty("samples_y", sampleCoord.length);
        for (int i = 0; i < sampleCoord.length; i++)
            for (int j = 0; j < sampleCoord[i].length; j++) {
                //          double coord[] = {sampleCoord[i][j][0],sampleCoord[i][j][1]};
                hConfig.addProperty("sample_" + i + "_" + j, sampleCoord[i][j][0] + sep + sampleCoord[i][j][1]);
            }
    }
    hConfig.addProperty("measurements", this.measurements.size());
    for (int i = 0; i < this.measurements.size(); i++) {
        FocusingFieldMeasurement meas = this.measurements.get(i);
        String prefix = "measurement_" + i + ".";
        if (meas.timestamp != null)
            hConfig.addProperty(prefix + "timestamp", meas.timestamp);
        hConfig.addProperty(prefix + "temperature", meas.temperature);
        hConfig.addProperty(prefix + "motors", meas.motors[0] + sep + meas.motors[1] + sep + meas.motors[2]);
        hConfig.addProperty(prefix + "sample", meas.asListString());
    }
    File file = new File(path);
    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(file));
        hConfig.save(writer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    this.historyPath = path;
}

From source file:nl.knaw.huygens.timbuctoo.config.Configuration.java

public Configuration(String configFile) throws ConfigurationException {
    xmlConfig = new XMLConfiguration();
    xmlConfig.setDelimiterParsingDisabled(true);
    xmlConfig.clear();/*from w w w.  j  ava 2s  .  co  m*/
    InputStream in = Configuration.class.getClassLoader().getResourceAsStream(configFile);
    try {
        xmlConfig.load(in);
    } catch (ConfigurationException e) {
        System.err.println("ERROR: unable to load configuration!");
        throw e;
    }
}

From source file:openlr.properties.OpenLRPropertiesReader.java

/**
 * Load properties from stream.//from  w w  w. ja  va  2  s  .c  om
 * 
 * @param iStream
 *            the i stream
 * @param isXML
 *            the is xml
 * @return the configuration
 * @throws OpenLRPropertyException
 *             the open lr property exception
 */
public static FileConfiguration loadPropertiesFromStream(final InputStream iStream, final boolean isXML)
        throws OpenLRPropertyException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("load OpenLR properties file");
    }
    if (iStream == null) {
        LOG.error("Cannot find the OpenLR properties file.");
        throw new OpenLRPropertyException(PropertyError.PROPERTIES_FILE_NOT_FOUND);
    }
    try {
        FileConfiguration conf;
        if (isXML) {
            conf = new XMLConfiguration();
        } else {
            conf = new PropertiesConfiguration();
        }
        conf.load(iStream);
        return conf;
    } catch (ConfigurationException e) {
        throw new OpenLRPropertyException(PropertyError.MISSING_PROPERTY, e);
    }
}