]> git.basschouten.com Git - openhab-addons.git/blob
f7277b9c55740f5969b5d5801d090ae1dfeccf5a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.jupiter.api.Assertions.assertEquals;
16
17 import java.io.IOException;
18 import java.lang.reflect.Type;
19 import java.nio.charset.StandardCharsets;
20 import java.time.ZonedDateTime;
21
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 = new String(WireHelper.class.getResourceAsStream(jsonClasspathName).readAllBytes(),
55                 StandardCharsets.UTF_8);
56
57         final JsonObject o = JsonParser.parseString(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 = new String(WireHelper.class.getResourceAsStream(jsonClasspathName).readAllBytes(),
65                 StandardCharsets.UTF_8);
66         return deSerializeFromString(json, type);
67     }
68
69     public <T> T deSerializeFromString(final String json, final Type type) throws IOException {
70         return gson.fromJson(json, type);
71     }
72
73     public <T> String serialize(final AbstractRequest req) throws IOException {
74         return gson.toJson(req);
75     }
76 }