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.lametrictime.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 org.openhab.binding.lametrictime.api.common.impl.GsonGenerator;
33 import org.osgi.service.component.annotations.Component;
35 import com.google.gson.Gson;
38 * JSON reader/writer for Jersey using GSON.
40 * @author Simon Kaufmann - Initial contribution
45 @Produces(MediaType.APPLICATION_JSON)
46 @Consumes(MediaType.APPLICATION_JSON)
48 public class GsonProvider<T> implements MessageBodyReader<T>, MessageBodyWriter<T> {
50 private final Gson gson;
52 public GsonProvider() {
53 gson = GsonGenerator.create();
57 public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
62 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
67 public void writeTo(T object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
68 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
69 throws IOException, WebApplicationException {
70 try (OutputStream stream = entityStream) {
71 entityStream.write(gson.toJson(object).getBytes(StandardCharsets.UTF_8));
77 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
82 public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
83 MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
84 throws IOException, WebApplicationException {
85 try (InputStreamReader reader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
86 return gson.fromJson(reader, type);