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.JSONObject;
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 import java.util.Map;
032
033 @Provider
034 @Produces(MediaType.APPLICATION_JSON)
035 public class JSONMapProvider implements MessageBodyWriter<Map> {
036 private static final String ENTER = System.getProperty("line.separator");
037
038 @Override
039 public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
040 return Map.class.isAssignableFrom(aClass);
041 }
042
043 @Override
044 public long getSize(Map map, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
045 return -1;
046 }
047
048 @Override
049 public void writeTo(Map map, 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 JSONObject.writeJSONString(map, writer);
054 writer.write(ENTER);
055 writer.flush();
056 }
057
058 }