View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.rest.provider.producer;
21  
22  import java.io.IOException;
23  import java.io.OutputStream;
24  import java.lang.annotation.Annotation;
25  import java.lang.reflect.Type;
26  
27  import javax.ws.rs.Produces;
28  import javax.ws.rs.WebApplicationException;
29  import javax.ws.rs.core.MediaType;
30  import javax.ws.rs.core.MultivaluedMap;
31  import javax.ws.rs.ext.MessageBodyWriter;
32  import javax.ws.rs.ext.Provider;
33  
34  import org.apache.hadoop.hbase.classification.InterfaceAudience;
35  import org.apache.hadoop.hbase.rest.Constants;
36  
37  /**
38   * An adapter between Jersey and Object.toString(). Hooks up plain text output
39   * to the Jersey content handling framework. 
40   * Jersey will first call getSize() to learn the number of bytes that will be
41   * sent, then writeTo to perform the actual I/O.
42   */
43  @Provider
44  @Produces(Constants.MIMETYPE_TEXT)
45  @InterfaceAudience.Private
46  public class PlainTextMessageBodyProducer 
47    implements MessageBodyWriter<Object> {
48  
49    private ThreadLocal<byte[]> buffer = new ThreadLocal<byte[]>();
50  
51    @Override
52    public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
53        MediaType arg3) {
54      return true;
55    }
56  
57    @Override
58    public long getSize(Object object, Class<?> type, Type genericType,
59        Annotation[] annotations, MediaType mediaType) {
60      byte[] bytes = object.toString().getBytes(); 
61      buffer.set(bytes);
62      return bytes.length;
63    }
64  
65    @Override
66    public void writeTo(Object object, Class<?> type, Type genericType,
67        Annotation[] annotations, MediaType mediaType,
68        MultivaluedMap<String, Object> httpHeaders, OutputStream outStream)
69        throws IOException, WebApplicationException {
70      byte[] bytes = buffer.get();
71      outStream.write(bytes);
72      buffer.remove();
73    }	
74  }