1 | package omq.common.util.Serializers; |
---|
2 | |
---|
3 | import java.util.List; |
---|
4 | |
---|
5 | import omq.common.message.Request; |
---|
6 | import omq.common.message.Response; |
---|
7 | import omq.exception.OmqException; |
---|
8 | import omq.exception.SerializerException; |
---|
9 | import omq.server.RemoteObject; |
---|
10 | |
---|
11 | import com.google.gson.Gson; |
---|
12 | import com.google.gson.JsonArray; |
---|
13 | import com.google.gson.JsonElement; |
---|
14 | import com.google.gson.JsonObject; |
---|
15 | import com.google.gson.JsonParser; |
---|
16 | |
---|
17 | public class GsonImp implements ISerializer { |
---|
18 | private final Gson gson = new Gson(); |
---|
19 | |
---|
20 | @Override |
---|
21 | public byte[] serialize(Object obj) throws SerializerException { |
---|
22 | String json = gson.toJson(obj); |
---|
23 | return json.getBytes(); |
---|
24 | } |
---|
25 | |
---|
26 | @Override |
---|
27 | public Request deserializeRequest(byte[] bytes, RemoteObject obj) throws SerializerException { |
---|
28 | String json = new String(bytes); |
---|
29 | |
---|
30 | JsonParser parser = new JsonParser(); |
---|
31 | JsonObject jsonObj = parser.parse(json).getAsJsonObject(); |
---|
32 | |
---|
33 | String id = jsonObj.get("id").getAsString(); |
---|
34 | String method = jsonObj.get("method").getAsString(); |
---|
35 | boolean async = jsonObj.get("async").getAsBoolean(); |
---|
36 | |
---|
37 | List<Class<?>> types = obj.getParams(method); |
---|
38 | |
---|
39 | try { |
---|
40 | JsonArray jsonArgs = (JsonArray) jsonObj.get("params"); |
---|
41 | |
---|
42 | // TODO: if (jsonArgs.size() == types.size()) |
---|
43 | int length = jsonArgs.size(); |
---|
44 | Object[] arguments = new Object[length]; |
---|
45 | |
---|
46 | int i = 0; |
---|
47 | for (JsonElement element : jsonArgs) { |
---|
48 | arguments[i] = gson.fromJson(element, types.get(i)); |
---|
49 | i++; |
---|
50 | } |
---|
51 | return new Request(id, method, async, arguments); |
---|
52 | } catch (NullPointerException e) { |
---|
53 | return new Request(id, method, async, null); |
---|
54 | } |
---|
55 | } |
---|
56 | |
---|
57 | @Override |
---|
58 | public Response deserializeResponse(byte[] bytes, Class<?> type) throws SerializerException { |
---|
59 | String json = new String(bytes); |
---|
60 | |
---|
61 | JsonParser parser = new JsonParser(); |
---|
62 | JsonObject jsonObj = parser.parse(json).getAsJsonObject(); |
---|
63 | |
---|
64 | String id = jsonObj.get("id").getAsString(); |
---|
65 | String idOmq = jsonObj.get("idOmq").getAsString(); |
---|
66 | |
---|
67 | JsonElement jsonElement = jsonObj.get("result"); |
---|
68 | Object result = gson.fromJson(jsonElement, type); |
---|
69 | |
---|
70 | JsonElement jsonError = jsonObj.get("error"); |
---|
71 | OmqException error = gson.fromJson(jsonError, OmqException.class); |
---|
72 | |
---|
73 | return new Response(id, idOmq, result, error); |
---|
74 | } |
---|
75 | |
---|
76 | } |
---|