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