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