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

Last change on this file since 75 was 72, checked in by stoda, 11 years ago

Events deleted instead of them there's a new example of how to use the observer pattern

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