[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 | /** |
---|
| 15 | * |
---|
| 16 | * @author Sergi Toda <sergi.toda@estudiants.urv.cat> |
---|
| 17 | * |
---|
| 18 | */ |
---|
| 19 | public class KryoImp implements ISerializer { |
---|
| 20 | private final Kryo kryo = new Kryo(); |
---|
| 21 | |
---|
| 22 | @Override |
---|
| 23 | public byte[] serialize(Object obj) throws SerializerException { |
---|
| 24 | try { |
---|
| 25 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); |
---|
| 26 | Output output = new Output(stream); |
---|
| 27 | kryo.writeObject(output, 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, Request.class); |
---|
| 46 | } |
---|
| 47 | |
---|
| 48 | @Override |
---|
| 49 | public Response deserializeResponse(byte[] bytes, Class<?> type) throws SerializerException { |
---|
| 50 | return (Response) deserializeObject(bytes, Response.class); |
---|
| 51 | } |
---|
| 52 | |
---|
| 53 | public Object deserializeObject(byte[] bytes, Class<?> type) throws SerializerException { |
---|
| 54 | try { |
---|
| 55 | Input input = new Input(bytes); |
---|
| 56 | Object obj = kryo.readObject(input, type); |
---|
| 57 | |
---|
| 58 | input.close(); |
---|
| 59 | return obj; |
---|
| 60 | } catch (Exception e) { |
---|
| 61 | throw new SerializerException("Deserialize -> " + e.getMessage(), e); |
---|
| 62 | } |
---|
| 63 | } |
---|
| 64 | |
---|
| 65 | } |
---|