001    /*
002     * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved.
003     *
004     * Cloudera, Inc. licenses this file to you under the Apache License,
005     * Version 2.0 (the "License"). You may not use this file except in
006     * compliance with the License. You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
011     * CONDITIONS OF ANY KIND, either express or implied. See the License for
012     * the specific language governing permissions and limitations under the
013     * License.
014     */
015    package com.cloudera.lib.wsrs;
016    
017    import org.json.simple.JSONStreamAware;
018    
019    import javax.ws.rs.Produces;
020    import javax.ws.rs.WebApplicationException;
021    import javax.ws.rs.core.MediaType;
022    import javax.ws.rs.core.MultivaluedMap;
023    import javax.ws.rs.ext.MessageBodyWriter;
024    import javax.ws.rs.ext.Provider;
025    import java.io.IOException;
026    import java.io.OutputStream;
027    import java.io.OutputStreamWriter;
028    import java.io.Writer;
029    import java.lang.annotation.Annotation;
030    import java.lang.reflect.Type;
031    
032    @Provider
033    @Produces(MediaType.APPLICATION_JSON)
034    public class JSONProvider implements MessageBodyWriter<JSONStreamAware> {
035      private static final String ENTER = System.getProperty("line.separator");
036    
037      @Override
038      public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
039        return JSONStreamAware.class.isAssignableFrom(aClass);
040      }
041    
042      @Override
043      public long getSize(JSONStreamAware jsonStreamAware, Class<?> aClass, Type type, Annotation[] annotations,
044                          MediaType mediaType) {
045        return -1;
046      }
047    
048      @Override
049      public void writeTo(JSONStreamAware jsonStreamAware, Class<?> aClass, Type type, Annotation[] annotations,
050                          MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap,
051                          OutputStream outputStream) throws IOException, WebApplicationException {
052        Writer writer = new OutputStreamWriter(outputStream);
053        jsonStreamAware.writeJSONString(writer);
054        writer.write(ENTER);
055        writer.flush();
056      }
057    
058    }