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.master.http.gson;
019
020import java.util.function.Supplier;
021import javax.inject.Singleton;
022import org.apache.hadoop.hbase.http.gson.GsonMessageBodyWriter;
023import org.apache.hadoop.hbase.http.jersey.SupplierFactoryAdapter;
024import org.apache.yetus.audience.InterfaceAudience;
025
026import org.apache.hbase.thirdparty.com.google.gson.Gson;
027import org.apache.hbase.thirdparty.javax.ws.rs.core.Feature;
028import org.apache.hbase.thirdparty.javax.ws.rs.core.FeatureContext;
029import org.apache.hbase.thirdparty.javax.ws.rs.ext.MessageBodyWriter;
030import org.apache.hbase.thirdparty.org.glassfish.hk2.utilities.binding.AbstractBinder;
031import org.apache.hbase.thirdparty.org.glassfish.hk2.utilities.binding.ServiceBindingBuilder;
032
033/**
034 * Used to register with (shaded) Jersey the presence of Entity serialization using (shaded) Gson.
035 */
036@InterfaceAudience.Private
037public class GsonSerializationFeature implements Feature {
038
039  @Override
040  public boolean configure(FeatureContext context) {
041    context.register(new Binder());
042    return true;
043  }
044
045  /**
046   * Register this feature's provided functionality and defines their lifetime scopes.
047   */
048  private static class Binder extends AbstractBinder {
049
050    @Override
051    protected void configure() {
052      bindFactory(GsonFactory::buildGson).to(Gson.class).in(Singleton.class);
053      bind(GsonMessageBodyWriter.class).to(MessageBodyWriter.class).in(Singleton.class);
054    }
055
056    /**
057     * Helper method for smoothing over use of {@link SupplierFactoryAdapter}. Inspired by internal
058     * implementation details of jersey itself.
059     */
060    private <T> ServiceBindingBuilder<T> bindFactory(Supplier<T> supplier) {
061      return bindFactory(new SupplierFactoryAdapter<>(supplier));
062    }
063  }
064}