1 | package omq.common.util.Serializers; |
---|
2 | |
---|
3 | import java.io.ByteArrayInputStream; |
---|
4 | import java.io.ByteArrayOutputStream; |
---|
5 | import java.io.ObjectInputStream; |
---|
6 | import java.io.ObjectOutputStream; |
---|
7 | |
---|
8 | import omq.common.message.Request; |
---|
9 | import omq.common.message.Response; |
---|
10 | import omq.exception.SerializerException; |
---|
11 | import omq.server.RemoteObject; |
---|
12 | |
---|
13 | /** |
---|
14 | * Java serialize implementation. It uses the default java serialization. |
---|
15 | * |
---|
16 | * @author Sergi Toda <sergi.toda@estudiants.urv.cat> |
---|
17 | * |
---|
18 | */ |
---|
19 | public class JavaImp implements ISerializer { |
---|
20 | |
---|
21 | @Override |
---|
22 | public byte[] serialize(Object obj) throws SerializerException { |
---|
23 | try { |
---|
24 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); |
---|
25 | ObjectOutputStream output = new ObjectOutputStream(stream); |
---|
26 | output.writeObject(obj); |
---|
27 | |
---|
28 | output.flush(); |
---|
29 | output.close(); |
---|
30 | |
---|
31 | byte[] bArray = stream.toByteArray(); |
---|
32 | |
---|
33 | stream.flush(); |
---|
34 | stream.close(); |
---|
35 | |
---|
36 | return bArray; |
---|
37 | } catch (Exception e) { |
---|
38 | throw new SerializerException("Serialize -> " + e.getMessage(), e); |
---|
39 | } |
---|
40 | } |
---|
41 | |
---|
42 | @Override |
---|
43 | public Request deserializeRequest(byte[] bytes, RemoteObject obj) throws SerializerException { |
---|
44 | return (Request) deserializeObject(bytes); |
---|
45 | } |
---|
46 | |
---|
47 | @Override |
---|
48 | public Response deserializeResponse(byte[] bytes, Class<?> type) throws SerializerException { |
---|
49 | return (Response) deserializeObject(bytes); |
---|
50 | } |
---|
51 | |
---|
52 | public Object deserializeObject(byte[] bytes) throws SerializerException { |
---|
53 | try { |
---|
54 | ByteArrayInputStream input = new ByteArrayInputStream(bytes); |
---|
55 | ObjectInputStream objInput = new ObjectInputStream(input); |
---|
56 | |
---|
57 | Object obj = objInput.readObject(); |
---|
58 | |
---|
59 | objInput.close(); |
---|
60 | input.close(); |
---|
61 | |
---|
62 | return obj; |
---|
63 | } catch (Exception e) { |
---|
64 | throw new SerializerException("Deserialize -> " + e.getMessage(), e); |
---|
65 | } |
---|
66 | } |
---|
67 | |
---|
68 | } |
---|