001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.http.gson;
019
020import java.io.IOException;
021import java.io.OutputStream;
022import java.io.OutputStreamWriter;
023import java.io.Writer;
024import java.lang.annotation.Annotation;
025import java.lang.reflect.Type;
026import java.nio.charset.Charset;
027import java.nio.charset.IllegalCharsetNameException;
028import java.nio.charset.StandardCharsets;
029import java.nio.charset.UnsupportedCharsetException;
030import java.util.Optional;
031import javax.inject.Inject;
032import org.apache.yetus.audience.InterfaceAudience;
033import org.slf4j.Logger;
034import org.slf4j.LoggerFactory;
035
036import org.apache.hbase.thirdparty.com.google.gson.Gson;
037import org.apache.hbase.thirdparty.javax.ws.rs.Produces;
038import org.apache.hbase.thirdparty.javax.ws.rs.WebApplicationException;
039import org.apache.hbase.thirdparty.javax.ws.rs.core.MediaType;
040import org.apache.hbase.thirdparty.javax.ws.rs.core.MultivaluedMap;
041import org.apache.hbase.thirdparty.javax.ws.rs.ext.MessageBodyWriter;
042
043/**
044 * Implements JSON serialization via {@link Gson} for JAX-RS.
045 */
046@InterfaceAudience.Private
047@Produces(MediaType.APPLICATION_JSON)
048public final class GsonMessageBodyWriter<T> implements MessageBodyWriter<T> {
049  private static final Logger logger = LoggerFactory.getLogger(GsonMessageBodyWriter.class);
050
051  private final Gson gson;
052
053  @Inject
054  public GsonMessageBodyWriter(Gson gson) {
055    this.gson = gson;
056  }
057
058  @Override
059  public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
060    MediaType mediaType) {
061    return mediaType == null || MediaType.APPLICATION_JSON_TYPE.isCompatible(mediaType);
062  }
063
064  @Override
065  public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations,
066    MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
067    throws IOException, WebApplicationException {
068    final Charset outputCharset = requestedCharset(mediaType);
069    try (Writer writer = new OutputStreamWriter(entityStream, outputCharset)) {
070      gson.toJson(t, writer);
071    }
072  }
073
074  private static Charset requestedCharset(MediaType mediaType) {
075    return Optional.ofNullable(mediaType).map(MediaType::getParameters)
076      .map(params -> params.get("charset")).map(c -> {
077        try {
078          return Charset.forName(c);
079        } catch (IllegalCharsetNameException e) {
080          logger.debug("Client requested illegal Charset '{}'", c);
081          return null;
082        } catch (UnsupportedCharsetException e) {
083          logger.debug("Client requested unsupported Charset '{}'", c);
084          return null;
085        } catch (Exception e) {
086          logger.debug("Error while resolving Charset '{}'", c, e);
087          return null;
088        }
089      }).orElse(StandardCharsets.UTF_8);
090  }
091}