source: trunk/src/main/java/omq/common/util/Serializers/KryoImp.java @ 50

Last change on this file since 50 was 44, checked in by stoda, 11 years ago

Objectmq converted to maven project

File size: 1.9 KB
Line 
1package omq.common.util.Serializers;
2
3import java.io.ByteArrayOutputStream;
4
5import com.esotericsoftware.kryo.Kryo;
6import com.esotericsoftware.kryo.io.Input;
7import com.esotericsoftware.kryo.io.Output;
8
9import omq.common.event.Event;
10import omq.common.event.EventWrapper;
11import omq.common.message.Request;
12import omq.common.message.Response;
13import omq.exception.SerializerException;
14import omq.server.RemoteObject;
15
16/**
17 *
18 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
19 *
20 */
21public 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}
Note: See TracBrowser for help on using the repository browser.