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.rest.provider.producer;
019
020import java.io.IOException;
021import java.io.OutputStream;
022import java.lang.annotation.Annotation;
023import java.lang.reflect.Type;
024import org.apache.hadoop.hbase.rest.Constants;
025import org.apache.hadoop.hbase.rest.ProtobufMessageHandler;
026import org.apache.yetus.audience.InterfaceAudience;
027
028import org.apache.hbase.thirdparty.javax.ws.rs.Produces;
029import org.apache.hbase.thirdparty.javax.ws.rs.WebApplicationException;
030import org.apache.hbase.thirdparty.javax.ws.rs.core.MediaType;
031import org.apache.hbase.thirdparty.javax.ws.rs.core.MultivaluedMap;
032import org.apache.hbase.thirdparty.javax.ws.rs.ext.MessageBodyWriter;
033import org.apache.hbase.thirdparty.javax.ws.rs.ext.Provider;
034
035/**
036 * An adapter between Jersey and ProtobufMessageHandler implementors. Hooks up protobuf output
037 * producing methods to the Jersey content handling framework. Jersey will first call getSize() to
038 * learn the number of bytes that will be sent, then writeTo to perform the actual I/O.
039 */
040@Provider
041@Produces({ Constants.MIMETYPE_PROTOBUF, Constants.MIMETYPE_PROTOBUF_IETF })
042@InterfaceAudience.Private
043public class ProtobufMessageBodyProducer implements MessageBodyWriter<ProtobufMessageHandler> {
044
045  @Override
046  public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
047    MediaType mediaType) {
048    return ProtobufMessageHandler.class.isAssignableFrom(type);
049  }
050
051  @Override
052  public long getSize(ProtobufMessageHandler m, Class<?> type, Type genericType,
053    Annotation[] annotations, MediaType mediaType) {
054    // deprecated by JAX-RS 2.0 and ignored by Jersey runtime
055    return -1;
056  }
057
058  @Override
059  public void writeTo(ProtobufMessageHandler m, Class<?> type, Type genericType,
060    Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
061    OutputStream entityStream) throws IOException, WebApplicationException {
062    entityStream.write(m.createProtobufOutput());
063  }
064}