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