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.sleepiq.internal;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InputStreamReader;
18 import java.io.OutputStream;
19 import java.lang.annotation.Annotation;
20 import java.lang.reflect.Type;
21 import java.nio.charset.StandardCharsets;
23 import javax.ws.rs.Consumes;
24 import javax.ws.rs.Produces;
25 import javax.ws.rs.WebApplicationException;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.MultivaluedMap;
28 import javax.ws.rs.ext.MessageBodyReader;
29 import javax.ws.rs.ext.MessageBodyWriter;
30 import javax.ws.rs.ext.Provider;
32 import com.google.gson.Gson;
35 * JSON reader/writer for Jersey using GSON.
37 * @author Simon Kaufmann - Initial contribution
42 @Produces(MediaType.APPLICATION_JSON)
43 @Consumes(MediaType.APPLICATION_JSON)
44 public class GsonProvider<T> implements MessageBodyReader<T>, MessageBodyWriter<T> {
46 private final Gson gson;
48 public GsonProvider(Gson gson) {
53 public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
58 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
63 public void writeTo(T object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
64 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
65 throws IOException, WebApplicationException {
66 try (OutputStream stream = entityStream) {
67 entityStream.write(gson.toJson(object).getBytes(StandardCharsets.UTF_8));
73 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
78 public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
79 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
80 throws IOException, WebApplicationException {
81 try (InputStreamReader reader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
82 return gson.fromJson(reader, type);