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.event.Event; |
---|
9 | import omq.common.event.EventWrapper; |
---|
10 | import omq.common.message.Request; |
---|
11 | import omq.common.message.Response; |
---|
12 | import omq.exception.SerializerException; |
---|
13 | import omq.server.remote.request.RemoteObject; |
---|
14 | |
---|
15 | /** |
---|
16 | * |
---|
17 | * @author Sergi Toda <sergi.toda@estudiants.urv.cat> |
---|
18 | * |
---|
19 | */ |
---|
20 | public class JavaImp implements ISerializer { |
---|
21 | |
---|
22 | @Override |
---|
23 | public byte[] serialize(Object obj) throws SerializerException { |
---|
24 | try { |
---|
25 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); |
---|
26 | ObjectOutputStream output = new ObjectOutputStream(stream); |
---|
27 | output.writeObject(obj); |
---|
28 | |
---|
29 | output.flush(); |
---|
30 | output.close(); |
---|
31 | |
---|
32 | byte[] bArray = stream.toByteArray(); |
---|
33 | |
---|
34 | stream.flush(); |
---|
35 | stream.close(); |
---|
36 | |
---|
37 | return bArray; |
---|
38 | } catch (Exception e) { |
---|
39 | throw new SerializerException("Serialize -> " + e.getMessage(), e); |
---|
40 | } |
---|
41 | } |
---|
42 | |
---|
43 | @Override |
---|
44 | public Request deserializeRequest(byte[] bytes, RemoteObject obj) throws SerializerException { |
---|
45 | return (Request) deserializeObject(bytes); |
---|
46 | } |
---|
47 | |
---|
48 | @Override |
---|
49 | public Response deserializeResponse(byte[] bytes, Class<?> type) throws SerializerException { |
---|
50 | return (Response) deserializeObject(bytes); |
---|
51 | } |
---|
52 | |
---|
53 | @Override |
---|
54 | public Event deserializeEvent(byte[] bytes) throws SerializerException { |
---|
55 | EventWrapper wrapper = (EventWrapper) deserializeObject(bytes); |
---|
56 | return wrapper.getEvent(); |
---|
57 | } |
---|
58 | |
---|
59 | public Object deserializeObject(byte[] bytes) throws SerializerException { |
---|
60 | try { |
---|
61 | ByteArrayInputStream input = new ByteArrayInputStream(bytes); |
---|
62 | ObjectInputStream objInput = new ObjectInputStream(input); |
---|
63 | |
---|
64 | Object obj = objInput.readObject(); |
---|
65 | |
---|
66 | objInput.close(); |
---|
67 | input.close(); |
---|
68 | |
---|
69 | return obj; |
---|
70 | } catch (Exception e) { |
---|
71 | throw new SerializerException("Deserialize -> " + e.getMessage(), e); |
---|
72 | } |
---|
73 | } |
---|
74 | |
---|
75 | } |
---|