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