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.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.lametrictime.internal.api.common.impl.GsonGenerator;
34 import org.osgi.service.component.annotations.Component;
36 import com.google.gson.Gson;
39 * JSON reader/writer for Jersey using GSON.
41 * @author Simon Kaufmann - Initial contribution
46 @Produces(MediaType.APPLICATION_JSON)
47 @Consumes(MediaType.APPLICATION_JSON)
49 public class GsonProvider<T> implements MessageBodyReader<T>, MessageBodyWriter<T> {
51 private final Gson gson;
53 public GsonProvider() {
54 gson = GsonGenerator.create();
58 public long getSize(T t, @Nullable Class<?> type, @Nullable Type genericType, Annotation @Nullable [] annotations,
59 @Nullable MediaType mediaType) {
64 public boolean isWriteable(@Nullable Class<?> type, @Nullable Type genericType, Annotation @Nullable [] annotations,
65 @Nullable MediaType mediaType) {
70 public void writeTo(T object, @Nullable Class<?> type, @Nullable Type genericType,
71 Annotation @Nullable [] annotations, @Nullable MediaType mediaType,
72 @Nullable MultivaluedMap<String, Object> httpHeaders, @Nullable OutputStream entityStream)
73 throws IOException, WebApplicationException {
74 try (OutputStream stream = entityStream) {
75 entityStream.write(gson.toJson(object).getBytes(StandardCharsets.UTF_8));
81 public boolean isReadable(@Nullable Class<?> type, @Nullable Type genericType, Annotation @Nullable [] annotations,
82 @Nullable MediaType mediaType) {
87 public T readFrom(@Nullable Class<T> type, @Nullable Type genericType, Annotation @Nullable [] annotations,
88 @Nullable MediaType mediaType, @Nullable MultivaluedMap<String, String> httpHeaders,
89 @Nullable InputStream entityStream) throws IOException, WebApplicationException {
90 try (InputStreamReader reader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
91 return gson.fromJson(reader, type);