package org.prevayler.foundation.serialization;

import com.thoughtworks.xstream.XStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * Writes and reads objects using XML. This serializer can be used for snapshots, journals or both.
 *
 * <p>This implementation requires the <a href="http://xstream.codehaus.org/">XStream</a>
 * Java and XML language binding framework which provides for Java object XML serialization.</p>
 *
 * <p>Note that XStream has some dependencies of its own.  It requires the standard XML API's
 * (xml-apis.jar from the <a href="http://xml.apache.org/xerces2-j/">Apache Xerces2-j</a> project or j2sdk1.4+)
 * and an XML implementation (again, provided by Xerces2 or j2sdk1.4+).</p>
 *
 * <p>To make XStream up to 10x faster, add <a href="http://www.extreme.indiana.edu/xgws/xsoap/xpp/mxp1/">XPP3</a>
 * to the classpath. XStream has the concept of a
 * <a href="http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/io/HierarchicalStreamDriver.html">HierarchicalStreamDriver</a>
 * and the default implementation for XStream is the highly performant XppDriver.  However, XStream will fall back to the DomDriver if XPP3 is
 * not found in the classpath making the XPP3 library entirely optional.</p>
 */
public class XStreamSerializer implements Serializer {

	private ThreadLocal _xstreams = new ThreadLocal() {
		protected Object initialValue() {
			return createXStream();
		}
	};

	private XStream getXStream() {
		return (XStream) _xstreams.get();
	}

	public void writeObject(OutputStream stream, Object object) throws IOException {
		OutputStreamWriter writer = new OutputStreamWriter(stream);
		getXStream().toXML(object, writer);
		writer.flush();
	}

	public Object readObject(InputStream stream) throws IOException, ClassNotFoundException {
		return getXStream().fromXML(new InputStreamReader(stream));
	}

	/**
	 * Create a new XStream instance. This must be a new instance because XStream instances are not threadsafe.
	 */
	protected XStream createXStream() {
		return new XStream();
	}

}

@@ -1527,16 +1527,317 @@
 %09%7D%0A%09%7D;%0A%0A
+%09private String _encoding;%0A%0A%09/**%0A%09 * Use the default character encoding for XML serialization.%0A%09 */%0A%09public XStreamSerializer() %7B%0A%09%09_encoding = null;%0A%09%7D%0A%0A%09/**%0A%09 * Use the specified character encoding for XML serialization.%0A%09 */%0A%09public XStreamSerializer(String encoding) %7B%0A%09%09_encoding = encoding;%0A%09%7D%0A%0A
 %09private
@@ -2011,16 +2011,36 @@
 writer =
+ _encoding == null ?
  new Out
@@ -2062,16 +2062,60 @@
 (stream)
+ : new OutputStreamWriter(stream, _encoding)
 ;%0A%09%09getX
@@ -2289,16 +2289,36 @@
 fromXML(
+_encoding == null ? 
 new Inpu
@@ -2338,16 +2338,59 @@
 (stream)
+ : new InputStreamReader(stream, _encoding)
 );%0A%09%7D%0A%0A%09

Allow specifying the character encoding for XStream serialization.