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