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.windcentrale.internal.dto;
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;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import com.google.gson.Gson;
30 import com.google.gson.stream.JsonWriter;
33 * Utility class for working with test data in unit tests.
35 * @author Wouter Born - Initial contribution
38 public class DataUtil {
40 private final Gson gson;
42 public DataUtil(Gson gson) {
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;
51 InputStream inputStream = new FileInputStream(filePath);
52 return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
55 public <T> T fromJson(String fileName, Type typeOfT) throws IOException {
56 try (Reader reader = openDataReader(fileName)) {
57 return gson.fromJson(reader, typeOfT);
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"));
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();