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  import java.nio.charset.Charset;
27  
28  import javax.ws.rs.Produces;
29  import javax.ws.rs.WebApplicationException;
30  import javax.ws.rs.core.MediaType;
31  import javax.ws.rs.core.MultivaluedMap;
32  import javax.ws.rs.ext.MessageBodyWriter;
33  import javax.ws.rs.ext.Provider;
34  
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.rest.Constants;
37  
38  /**
39   * An adapter between Jersey and Object.toString(). Hooks up plain text output
40   * to the Jersey content handling framework. 
41   * Jersey will first call getSize() to learn the number of bytes that will be
42   * sent, then writeTo to perform the actual I/O.
43   */
44  @Provider
45  @Produces(Constants.MIMETYPE_TEXT)
46  @InterfaceAudience.Private
47  public class PlainTextMessageBodyProducer 
48    implements MessageBodyWriter<Object> {
49  
50    private ThreadLocal<byte[]> buffer = new ThreadLocal<byte[]>();
51  
52    @Override
53    public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
54        MediaType arg3) {
55      return true;
56    }
57  
58    @Override
59    public long getSize(Object object, Class<?> type, Type genericType,
60        Annotation[] annotations, MediaType mediaType) {
61      byte[] bytes = object.toString().getBytes(Charset.forName("UTF-8"));
62      buffer.set(bytes);
63      return bytes.length;
64    }
65  
66    @Override
67    public void writeTo(Object object, Class<?> type, Type genericType,
68        Annotation[] annotations, MediaType mediaType,
69        MultivaluedMap<String, Object> httpHeaders, OutputStream outStream)
70        throws IOException, WebApplicationException {
71      byte[] bytes = buffer.get();
72      outStream.write(bytes);
73      buffer.remove();
74    }	
75  }