2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.nest.internal.sdm.dto;
15 import static org.openhab.binding.nest.internal.sdm.dto.SDMGson.GSON;
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;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import com.google.gson.stream.JsonWriter;
33 * Utility class for working with Nest SDM test data in unit tests.
35 * @author Wouter Born - Initial contribution
38 public class SDMDataUtil {
40 public static Reader openDataReader(String fileName) throws FileNotFoundException {
41 String packagePath = (SDMDataUtil.class.getPackage().getName()).replaceAll("\\.", "/");
42 String filePath = "src/test/resources/" + packagePath + "/" + fileName;
44 InputStream inputStream = new FileInputStream(filePath);
45 return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
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);
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"));
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();