Examples

A Simple Example

This is a simple example to help those new to betwixt. It shows how a simple bean can be converted to xml and back again. A round trip, no less!

In order to run these simple examples, the classpath needs to contain Betwixt and all its dependencies. Note that any JAXP (1.1 or later) compliant parser can be used to replace xerces and xml-apis. JUnit is not required to run betwixt (but is needed if you want to run the unit tests in CVS).

This example is based around a very simple bean representing a person:

public class PersonBean {
    
    private String name;
    private int age;
    
    /** Need to allow bean to be created via reflection */
    public PersonBean() {}
    
    public PersonBean(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }	
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String toString() {
        return "PersonBean[name='" + name + "',age='" + age + "']";
    }
}

The basic usage pattern for writing beans using Betwixt is to create a BeanWriter, configure it and then pass a bean into the write method. Pretty easy.

Here's a simple application which converts a person bean to xml which is then sent to System.out:

import java.io.StringWriter;

import org.apache.commons.betwixt.io.BeanWriter;

public class WriteExampleApp {

    /** 
     * Create an example bean and then convert it to xml.
     */
    public static final void main(String [] args) throws Exception {
        
        // Start by preparing the writer
        // We'll write to a string 
        StringWriter outputWriter = new StringWriter(); 
        
        // Betwixt just writes out the bean as a fragment
        // So if we want well-formed xml, we need to add the prolog
        outputWriter.write("<?xml version='1.0' ?>");
        
        // Create a BeanWriter which writes to our prepared stream
        BeanWriter beanWriter = new BeanWriter(outputWriter);
        
        // Configure betwixt
        // For more details see java docs or later in the main documentation
        beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
        beanWriter.getBindingConfiguration().setMapIDs(false);
        beanWriter.enablePrettyPrint();

        // If the base element is not passed in, Betwixt will guess 
        // But let's write example bean as base element 'person'
        beanWriter.write("person", new PersonBean("John Smith", 21));
        
        // Write to System.out
        // (We could have used the empty constructor for BeanWriter 
        // but this way is more instructive)
        System.out.println(outputWriter.toString());
        
        // Betwixt writes fragments not documents so does not automatically close 
        // writers or streams.
        // This example will do no more writing so close the writer now.
        outputWriter.close();
    }
}

The basic usage pattern for reading beans is only a little more complex. This time, you need to create a BeanReader, configure it, register the bean classes that the xml will be mapped to and then parse should be called.

Here's a simple application that converts some xml to a person bean. The bean is then converted to string and the result sent to System.out:

import java.io.StringReader;

import org.apache.commons.betwixt.io.BeanReader;

public class ReadExampleApp {
    
    public static final void main(String args[]) throws Exception{
        
        // First construct the xml which will be read in
        // For this example, read in from a hard coded string
        StringReader xmlReader = new StringReader(
                    "<?xml version='1.0' ?><person><age>25</age><name>James Smith</name></person>");
        
        // Now convert this to a bean using betwixt
        // Create BeanReader
        BeanReader beanReader  = new BeanReader();
        
        // Configure the reader
        // If you're round-tripping, make sure that the configurations are compatible!
        beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
        beanReader.getBindingConfiguration().setMapIDs(false);
        
        // Register beans so that betwixt knows what the xml is to be converted to
        // Since the element mapped to a PersonBean isn't called the same 
        // as Betwixt would have guessed, need to register the path as well
        beanReader.registerBeanClass("person", PersonBean.class);
        
        // Now we parse the xml
        PersonBean person = (PersonBean) beanReader.parse(xmlReader);
        
        // send bean to system out
        System.out.println(person);
    }
    
}

A Rich Site Summary Mapping

In the RSS example from Digester there's a bean which matches this pattern.

public class Channel

    public Item[] getItems();

    public void addItem(Item item);
}

This means that the following bean does not match this naming convention, since the plural property name does not start with the singular name.

public class Foo {
    public Collection getPeople();
    public void addPerson(Person person);
}

Though these two beans do match

public class Foo {
    public Collection getPersonCollection();
    public void addPerson(Person person);
}
public class Foo {
    public Iterator getPersonIterator();
    public void addPerson(Person person);
}

The following are other valid examples of composite-getter methods and their matching adder methods.

Composite getter method Adder method
getChildren() addChild()
getPersonList() addPerson()
getItems() addItem()
getChannels() addChannel()
getSheep() addSheep()