]> git.basschouten.com Git - openhab-addons.git/blob
b5d8451d7f23adf24a24ec3b833caba00399283f
[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.windcentrale.internal.dto;
14
15 import java.io.BufferedReader;
16 import java.io.FileInputStream;
17 import java.io.FileNotFoundException;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.io.Reader;
22 import java.io.StringWriter;
23 import java.lang.reflect.Type;
24 import java.nio.charset.StandardCharsets;
25 import java.util.stream.Collectors;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28
29 import com.google.gson.Gson;
30 import com.google.gson.stream.JsonWriter;
31
32 /**
33  * Utility class for working with test data in unit tests.
34  *
35  * @author Wouter Born - Initial contribution
36  */
37 @NonNullByDefault
38 public class DataUtil {
39
40     private final Gson gson;
41
42     public DataUtil(Gson gson) {
43         this.gson = gson;
44     }
45
46     @SuppressWarnings("null")
47     public Reader openDataReader(String fileName) throws FileNotFoundException {
48         String packagePath = (DataUtil.class.getPackage().getName()).replace(".", "/");
49         String filePath = "src/test/resources/" + packagePath + "/" + fileName;
50
51         InputStream inputStream = new FileInputStream(filePath);
52         return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
53     }
54
55     public <T> T fromJson(String fileName, Type typeOfT) throws IOException {
56         try (Reader reader = openDataReader(fileName)) {
57             return gson.fromJson(reader, typeOfT);
58         }
59     }
60
61     public String fromFile(String fileName) throws IOException {
62         try (Reader reader = openDataReader(fileName)) {
63             return new BufferedReader(reader).lines().parallel().collect(Collectors.joining("\n"));
64         }
65     }
66
67     public String toJson(Object object) {
68         StringWriter writer = new StringWriter();
69         JsonWriter jsonWriter = new JsonWriter(writer);
70         jsonWriter.setIndent("  ");
71         gson.toJson(object, object.getClass(), jsonWriter);
72         return writer.toString();
73     }
74 }