# Persistence API Tutorial

## Challenge

Suppose that you need a easy way to persist some objects in the file system. Not just one, but a whole collection. The real problem arrives when you start using java.io API in order to create one output stream for each object, showing itself to be really painful - although simple.

Imagine that you have the following Java class, a basic Author class (stolen from some other tutorial):

    package com.thoughtworks.xstream;

    public class Author {
            private String name;
            public Author(String name) {
                    this.name = name;
            }
            public String getName() {
                    return name;
            }
    }

By using the XmlArrayList implementation of java.util.List you get an easy way to write all authors to disk

The XmlArrayList (and related collections) receives a PersistenceStrategy during its construction. This Strategy decides what to do with each of its elements. The basic implementation - our need - is the FilePersistenceStrategy, capable of writing different files to a base directory.

    // prepares the file strategy to directory /tmp
    PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));

We can easily create an XmlArrayList from that strategy:

    // prepares the file strategy to directory /tmp
    PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));
    // creates the list:
    List list = new XmlArrayList(strategy);

## Adding elements

Now that we have an XmlArrayList object in our hands, we are able to add, remove and search for objects as usual. Let's add five authors and play around with our list:

    package org.codehaus.xstream.examples;

    public class AddAuthors {

    	public static void main(String[] args) {

    		// prepares the file strategy to directory /tmp
    		PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));
    		// creates the list:
    		List list = new XmlArrayList(strategy);

    		// adds four authors
    		list.add(new Author("joe walnes"));
    		list.add(new Author("joerg schaible"));
    		list.add(new Author("mauro talevi"));
    		list.add(new Author("guilherme silveira"));

    		// adding an extra author
    		Author mistake = new Author("mama");
    		list.add(mistake);

    	}
    }

If we check the /tmp directory, there are five files: int@1.xml, int@2.xml, int@3.xml, int@4.xml, int@5.xml, each one containing the XML serialized form of our authors.

## Playing around

Let's remove mama from the list and iterate over all authors:

    package org.codehaus.xstream.examples;

    public class RemoveMama {

    	public static void main(String[] args) {

    		// prepares the file strategy to directory /tmp
    		PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));
    		// looks up the list:
    		List list = new XmlArrayList(strategy);

    		// remember the list is still there! the files int@[1-5].xml are still in /tmp!
    		// the list was persisted!

    		for(Iterator it = list.iterator(); it.hasNext(); ) {
    			Author author = (Author) it.next();
    			if(author.getName().equals("mama")) {
    				System.out.println("Removing mama...");
    				it.remove();
    			} else {
    				System.out.println("Keeping " + author.getName());
    			}
    		}

    	}
    }

The result?

    Keeping joe walnes
    Keeping joerg schaible
    Keeping mauro talevi
    Keeping guilherme silveira
    Removing mama...

## Local Converter

Another use case is to split the XML into master/detail documents by declaring a local converter for a collection (or map) based on the collection types in XStream's persistence package. Think about a volume grouping different type of documents:

    public abstract class AbstractDocument {
    	String title;
    }
    public class TextDocument extends AbstractDocument {
    	List chapters = new ArrayList();
    }
    public class ScannedDocument {
    	List images = new ArrayList();
    }
    public Volume {
    	List documents = new ArrayList();
    }

The documents might be big (especially the ones with the scanned pages), therefore it might be nice to separate each document into an own file. With the help of a local converter utilizing an XmlArrayList this is straight forward:

    public final class PersistenceArrayListConverter implements Converter {
    	private XStream xstream;

    	public PersistenceArrayListConverter(XStream xstream) {
    		this.xstream = xstream;
    	}

    	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    		File dir = new File(System.getProperty("user.home"), "documents");
    		XmlArrayList list = new XmlArrayList(new FilePersistenceStrategy(dir, xstream));
    		context.convertAnother(dir);
    		list.addAll((Collection)source); // generate the external files
    	}

    	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    		File directory = (File)context.convertAnother(null, File.class);
    		XmlArrayList persistentList = new XmlArrayList(new FilePersistenceStrategy(directory, xstream));
    		ArrayList list = new ArrayList(persistentList); // read all files
    		persistentList.clear(); // remove files
    		return list;
    	}

    	public boolean canConvert(Class type) {
    		return type == ArrayList.class;
    	}
    }

This converter will use a given XStream to store each element of an ArrayList into an own file located in the user's home directory in the folder documents. The master XML will now contain the name of the target folder instead of the marshalled documents. In our case those documents are destroyed if the volume is unmarshalled again. See the initialization of the XStream:

    XStream = new XStream();
    xstream.alias("volume", Volume.class);
    xstream.registerLocalConverter(Volume.class, "documents", new PersistenceArrayListConverter(xstream));

    Volume volume = new Volume();
    volume.documents.addAll(...); // add a lot of documents
    String xml = xstream.toXML(volume);

The resulting XML will be very simple:

    <volume>~/documents</volume>

The documents can be found in individual files in the target folder with names like int@<index>.xml.

## Going further

From this point on, you can implement different PersistentStrategy algorithms in order to generate other behaviour (e.g. persisting the objects in a database) using your XmlArrayList collection, or try the other implementations: XmlSet and XmlMap and you may create your own local converters. As an alternative to a converter you might use the persistent collection type directly as member instance, the effect is similar - give it a try!

See also XBird that makes usage of this XStream API to support object persistence.

# Software

- About XStream
- News
- Change History
- About Versioning

# Evaluating XStream

- Two Minute Tutorial
- Object references
- Tweaking the Output
- License
- Download
- References
- Statistics

# Using XStream

- Architecture Overview
- Converters
- Frequently Asked Questions
- Users' Mailing List
- JavaDoc Core
- JavaDoc Benchmark
- Reporting Issues

# Tutorials

- Two Minute Tutorial
- Alias Tutorial
- Annotations Tutorial
- Converter Tutorial
- Object Streams Tutorial
- Persistence API Tutorial
- JSON Tutorial

# Developing XStream

- How to Contribute
- Developers' Mailing List
- Development Team
- Source Repository
- Continuous Integration