View Javadoc

1   /*
2    * Created on Nov 7, 2003
3    * 
4    * Copyright neotechnologies.org
5    */
6   package org.neo.swarm.util.serialize;
7   
8   import java.io.ByteArrayInputStream;
9   import java.io.ByteArrayOutputStream;
10  import java.io.IOException;
11  import java.io.ObjectInputStream;
12  import java.io.ObjectOutputStream;
13  import java.io.Serializable;
14  
15  /***
16   * This object does.....
17   * 
18   * @author neil.avery
19   */
20  public class StandardSerializer implements Serializer, Serializable {
21  	
22  	public StandardSerializer(){
23  	}
24  	
25  	/*
26  	 * (non-Javadoc)
27  	 * 
28  	 * @see org.neo.swarm.util.serialize.Serializer#serialize(java.lang.Object)
29  	 */
30  	public byte[] serialize(Object object) throws SerializationException {
31  		try {
32  			
33  			// serialise it!
34  			ByteArrayOutputStream baos = new ByteArrayOutputStream();
35  			ObjectOutputStream os = new ObjectOutputStream(baos);
36  			os.writeObject(object);
37  			os.flush();
38  			os.close();
39  			baos.close();
40  			//System.out.println("ser size:"+ baos.toByteArray().length);
41  			return baos.toByteArray();
42  		} catch (IOException e) {
43  			e.printStackTrace();
44  			return new byte[0];
45  		}
46  	}
47  
48  	/*
49  	 * (non-Javadoc)
50  	 * 
51  	 * @see org.neo.swarm.util.serialize.Serializer#deserialize(byte[])
52  	 */
53  	public Object deserialize(byte[] data) throws SerializationException {
54  		// deserialise it!
55  		try {
56  			ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
57  
58  			return in.readObject();
59  		} catch (IOException e) {
60  			e.printStackTrace();
61  			return null;
62  		} catch (ClassNotFoundException e) {
63  			return null;
64  		}
65  	}
66  }