]> git.basschouten.com Git - openhab-addons.git/blob
197c46b3d3bcccd9dfad20421571bb17ccfb0456
[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.tplinksmarthome.internal.model;
14
15 import java.io.IOException;
16 import java.nio.charset.StandardCharsets;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19
20 import com.google.gson.Gson;
21
22 /**
23  * Util class for reading test resources.
24  *
25  * @author Hilbrand Bouwkamp - Initial contribution
26  */
27 @NonNullByDefault
28 public final class ModelTestUtil {
29
30     public static final Gson GSON = GsonUtil.createGson();
31
32     private ModelTestUtil() {
33         // Util class
34     }
35
36     /**
37      * Util method to read a json file into it's data class.
38      *
39      * @param <T> Type of the class the json data represents.
40      * @param gson gson class
41      * @param filename filename of the json file to read. The file is read relative to the directory of this class
42      * @param clazz Data class expected to be read from the json file
43      * @return instance of clazz with read data from json file
44      * @throws IOException when file could not be read.
45      */
46     public static <T> T jsonFromFile(String filename, Class<T> clazz) throws IOException {
47         return GSON.fromJson(readJson(filename), clazz);
48     }
49
50     /**
51      * Util method to read a json file. It normalizes the string by removing returns, tabs and spaces. It's not very
52      * smart as it removes spaces inside json values as well. But this method is mainly intended be able to compare 2
53      * json strings.
54      *
55      * @param filename filename of the json file to read. The file is read relative to the directory of this class
56      * @return read json string
57      * @throws IOException when file could not be read.
58      */
59     public static String readJson(String filename) throws IOException {
60         return new String(ModelTestUtil.class.getResourceAsStream(filename + ".json").readAllBytes(),
61                 StandardCharsets.UTF_8).replaceAll("[\n\r\t ]", "");
62     }
63 }