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  import java.util.Map;
28  import java.util.WeakHashMap;
29  
30  import javax.ws.rs.Produces;
31  import javax.ws.rs.WebApplicationException;
32  import javax.ws.rs.core.MediaType;
33  import javax.ws.rs.core.MultivaluedMap;
34  import javax.ws.rs.ext.MessageBodyWriter;
35  import javax.ws.rs.ext.Provider;
36  
37  import org.apache.hadoop.hbase.rest.Constants;
38  
39  /**
40   * An adapter between Jersey and Object.toString(). Hooks up plain text output
41   * to the Jersey content handling framework. 
42   * Jersey will first call getSize() to learn the number of bytes that will be
43   * sent, then writeTo to perform the actual I/O.
44   */
45  @Provider
46  @Produces(Constants.MIMETYPE_TEXT)
47  public class PlainTextMessageBodyProducer 
48    implements MessageBodyWriter<Object> {
49  
50    private Map<Object, byte[]> buffer = new WeakHashMap<Object, 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(); 
62  	  buffer.put(object, 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  		outStream.write(buffer.remove(object));
72  	}	
73  }