View Javadoc

1   /*
2    * Copyright 2010 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  
21  package org.apache.hadoop.hbase.rest.provider.producer;
22  
23  import java.io.IOException;
24  import java.io.OutputStream;
25  import java.lang.annotation.Annotation;
26  import java.lang.reflect.Type;
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.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  public class PlainTextMessageBodyProducer 
46    implements MessageBodyWriter<Object> {
47  
48    private ThreadLocal<byte[]> buffer = new ThreadLocal<byte[]>();
49  
50    @Override
51    public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
52        MediaType arg3) {
53      return true;
54    }
55  
56  	@Override
57  	public long getSize(Object object, Class<?> type, Type genericType,
58  			Annotation[] annotations, MediaType mediaType) {
59      byte[] bytes = object.toString().getBytes(); 
60  	  buffer.set(bytes);
61      return bytes.length;
62  	}
63  
64  	@Override
65  	public void writeTo(Object object, Class<?> type, Type genericType,
66  			Annotation[] annotations, MediaType mediaType,
67  			MultivaluedMap<String, Object> httpHeaders, OutputStream outStream)
68  			throws IOException, WebApplicationException {
69      byte[] bytes = buffer.get();
70  		outStream.write(bytes);
71      buffer.remove();
72  	}	
73  }