001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019package org.apache.hadoop.lib.wsrs; 020 021import org.apache.commons.io.Charsets; 022import org.apache.hadoop.classification.InterfaceAudience; 023import org.json.simple.JSONObject; 024 025import javax.ws.rs.Produces; 026import javax.ws.rs.WebApplicationException; 027import javax.ws.rs.core.MediaType; 028import javax.ws.rs.core.MultivaluedMap; 029import javax.ws.rs.ext.MessageBodyWriter; 030import javax.ws.rs.ext.Provider; 031import java.io.IOException; 032import java.io.OutputStream; 033import java.io.OutputStreamWriter; 034import java.io.Writer; 035import java.lang.annotation.Annotation; 036import java.lang.reflect.Type; 037import java.util.Map; 038 039@Provider 040@Produces(MediaType.APPLICATION_JSON) 041@InterfaceAudience.Private 042public class JSONMapProvider implements MessageBodyWriter<Map> { 043 private static final String ENTER = System.getProperty("line.separator"); 044 045 @Override 046 public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) { 047 return Map.class.isAssignableFrom(aClass); 048 } 049 050 @Override 051 public long getSize(Map map, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) { 052 return -1; 053 } 054 055 @Override 056 public void writeTo(Map map, Class<?> aClass, Type type, Annotation[] annotations, 057 MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap, 058 OutputStream outputStream) throws IOException, WebApplicationException { 059 Writer writer = new OutputStreamWriter(outputStream, Charsets.UTF_8); 060 JSONObject.writeJSONString(map, writer); 061 writer.write(ENTER); 062 writer.flush(); 063 } 064 065}