Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2010-2011. Axon Framework
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.axonframework.serializer;
 
 
 import java.util.UUID;

Serializer that uses XStream to serialize and deserialize arbitrary objects. The XStream instance is configured to deal with the Classes used in Axon Framework in the most compact fashion.

When running on a Sun JVM, XStream does not pose any restrictions on classes to serialize. On other JVM's, however, you need to either implement Serializable, or provide a default constructor (accessible under the JVM's security policy). That means that for portability, you should do either of these two.

Author(s):
Allard Buijze
Since:
1.2
See also:
com.thoughtworks.xstream.XStream
 
 public class XStreamSerializer implements Serializer<Object> {
     private static final Charset DEFAULT_CHARSET_NAME = Charset.forName("UTF-8");
 
     private final XStream xStream;
     private final Charset charset;

    
Initialize a generic serializer using the UTF-8 character set. A default XStream instance (with com.thoughtworks.xstream.io.xml.XppDriver) is used to perform the serialization.
 
     public XStreamSerializer() {
         this();
     }

    
Initialize a generic serializer using the UTF-8 character set. The provided XStream instance is used to perform the serialization.

Parameters:
xStream XStream instance to use
 
     public XStreamSerializer(XStream xStream) {
         this(xStream);
     }

    
Initialize the serializer using the given charset. A default XStream instance (with com.thoughtworks.xstream.io.xml.XppDriver) is used to perform the serialization.

Parameters:
charset The character set to use
 
     public XStreamSerializer(Charset charset) {
         this(charsetnew XStream(new XppDriver()));
     }

    
Initialize the serializer using the given charset and xStream instance. The xStream instance is configured with several converters for the most common types in Axon.

Parameters:
charset The character set to use
xStream The XStream instance to use
 
     public XStreamSerializer(Charset charsetXStream xStream) {
         this. = charset;
         this. = xStream;
        xStream.registerConverter(new JodaTimeConverter());
        xStream.addImmutableType(UUID.class);
        xStream.addImmutableType(AggregateIdentifier.class);
        xStream.addImmutableType(StringAggregateIdentifier.class);
        xStream.addImmutableType(UUIDAggregateIdentifier.class);
        xStream.registerConverter(new AggregateIdentifierConverter());
        xStream.aliasPackage("axon.domain""org.axonframework.domain");
        xStream.aliasPackage("axon.es""org.axonframework.eventsourcing");
        xStream.alias("uuid-id"UUIDAggregateIdentifier.class);
        xStream.alias("aggregate-id"StringAggregateIdentifier.class);
        xStream.alias("string-id"StringAggregateIdentifier.class);
        // for backward compatibility
        xStream.alias("localDateTime"DateTime.class);
        xStream.alias("dateTime"DateTime.class);
        xStream.alias("uuid"UUID.class);
        xStream.useAttributeFor(EventBase.class"eventRevision");
    }

    
Serialize the given object to Compact XML (see com.thoughtworks.xstream.io.xml.CompactWriter) and write the bytes to the given outputStream. Bytes are written using the character set provided during initialization of the serializer.

Parameters:
object The object to serialize.
outputStream The stream to write bytes to
See also:
com.thoughtworks.xstream.io.xml.CompactWriter
    @Override
    public void serialize(Object objectOutputStream outputStream) {
        .marshal(objectnew CompactWriter(new OutputStreamWriter(outputStream)));
    }

    
Serialize the given object and write the bytes to the given writer.

Parameters:
object The object to serialize
writer The writer to write the serialized object o
    public void serialize(Object objectHierarchicalStreamWriter writer) {
        .marshal(objectwriter);
    }

    
    @Override
    public byte[] serialize(Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serialize(objectbaos);
        return baos.toByteArray();
    }

    
    @Override
    public Object deserialize(InputStream inputStream) {
        return .fromXML(new InputStreamReader(inputStream));
    }

    
    @Override
    public Object deserialize(byte[] bytes) {
        return .fromXML(new InputStreamReader(new ByteArrayInputStream(bytes), ));
    }

    
Deserialize the object provided by the given hierarchicalStreamReader.

Parameters:
hierarchicalStreamReader The reader providing the hierarchical (e.g. xml) data.
Returns:
the deserialized object
    public Object deserialize(HierarchicalStreamReader hierarchicalStreamReader) {
        return .unmarshal(hierarchicalStreamReader);
    }

    
Adds an alias to use instead of the fully qualified class name.

Parameters:
name The alias to use
type The Class to use the alias for
See also:
com.thoughtworks.xstream.XStream.alias(java.lang.String,java.lang.Class)
    public void addAlias(String nameClass type) {
        .alias(nametype);
    }

    
Add an alias for a package. This allows long package names to be shortened considerably. Will also use the alias for subpackages of the provided package.

E.g. an alias of "axoncore" for the package "org.axonframework.core" will use "axoncore.repository" for the package "org.axonframework.core.repository".

Parameters:
alias The alias to use.
pkgName The package to use the alias for
See also:
com.thoughtworks.xstream.XStream.aliasPackage(java.lang.String,java.lang.String)
    public void addPackageAlias(String aliasString pkgName) {
        .aliasPackage(aliaspkgName);
    }

    
Adds an alias to use for a given field in the given class.

Parameters:
alias The alias to use instead of the original field name
definedIn The class that defines the field.
fieldName The name of the field to use the alias for
See also:
com.thoughtworks.xstream.XStream.aliasField(java.lang.String,java.lang.Class,java.lang.String)
    public void addFieldAlias(String aliasClass definedInString fieldName) {
        .aliasField(aliasdefinedInfieldName);
    }

    
Returns a reference to the underlying com.thoughtworks.xstream.XStream instance, that does the actual serialization.

Returns:
the XStream instance that does the actual (de)serialization.
See also:
com.thoughtworks.xstream.XStream
    public XStream getXStream() {
        return ;
    }

    
Returns the character set used to convert character to bytes and vice versa.

Returns:
the character set used to convert character to bytes and vice versa
    public Charset getCharset() {
        return ;
    }

    
XStream Converter to serialize DateTime classes as a String.
    private static final class JodaTimeConverter implements Converter {

        
        @Override
        public boolean canConvert(Class type) {
            return type != null && DateTime.class.getPackage().equals(type.getPackage());
        }
        @Override
        public void marshal(Object sourceHierarchicalStreamWriter writerMarshallingContext context) {
            writer.setValue(source.toString());
        }
        @Override
        public Object unmarshal(HierarchicalStreamReader readerUnmarshallingContext context) {
            try {
                Constructor constructor = context.getRequiredType().getConstructor(Object.class);
                return constructor.newInstance(reader.getValue());
            } catch (Exception e) {
                throw new SerializationException(String.format(
                        "An exception occurred while deserializing a Joda Time object: %s",
                        context.getRequiredType().getSimpleName()), e);
            }
        }
    }
New to GrepCode? Check out our FAQ X