]> git.basschouten.com Git - openhab-addons.git/blob
4f7b403140389806583989398d5838b06b73ad08
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.sensibo.internal;
14
15 import static org.junit.Assert.assertEquals;
16
17 import java.io.IOException;
18 import java.lang.reflect.Type;
19 import java.time.ZonedDateTime;
20
21 import org.apache.commons.io.IOUtils;
22 import org.openhab.binding.sensibo.internal.dto.AbstractRequest;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonObject;
27 import com.google.gson.JsonParser;
28 import com.google.gson.TypeAdapter;
29 import com.google.gson.stream.JsonReader;
30 import com.google.gson.stream.JsonWriter;
31
32 /**
33  * @author Arne Seime - Initial contribution
34  */
35 public class WireHelper {
36
37     private final Gson gson;
38
39     public WireHelper() {
40         gson = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() {
41             @Override
42             public void write(final JsonWriter out, final ZonedDateTime value) throws IOException {
43                 out.value(value.toString());
44             }
45
46             @Override
47             public ZonedDateTime read(final JsonReader in) throws IOException {
48                 return ZonedDateTime.parse(in.nextString());
49             }
50         }).setPrettyPrinting().create();
51     }
52
53     public <T> T deSerializeResponse(final String jsonClasspathName, final Type type) throws IOException {
54         final String json = IOUtils.toString(WireHelper.class.getResourceAsStream(jsonClasspathName));
55
56         final JsonParser parser = new JsonParser();
57         final JsonObject o = parser.parse(json).getAsJsonObject();
58         assertEquals("success", o.get("status").getAsString());
59
60         return gson.fromJson(o.get("result"), type);
61     }
62
63     public <T> T deSerializeFromClasspathResource(final String jsonClasspathName, final Type type) throws IOException {
64         final String json = IOUtils.toString(WireHelper.class.getResourceAsStream(jsonClasspathName));
65         return deSerializeFromString(json, type);
66     }
67
68     public <T> T deSerializeFromString(final String json, final Type type) throws IOException {
69         return gson.fromJson(json, type);
70     }
71
72     public <T> String serialize(final AbstractRequest req) throws IOException {
73         return gson.toJson(req);
74     }
75 }