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 019 package org.apache.hadoop.lib.wsrs; 020 021 import org.apache.hadoop.classification.InterfaceAudience; 022 import org.json.simple.JSONObject; 023 024 import javax.ws.rs.Produces; 025 import javax.ws.rs.WebApplicationException; 026 import javax.ws.rs.core.MediaType; 027 import javax.ws.rs.core.MultivaluedMap; 028 import javax.ws.rs.ext.MessageBodyWriter; 029 import javax.ws.rs.ext.Provider; 030 import java.io.IOException; 031 import java.io.OutputStream; 032 import java.io.OutputStreamWriter; 033 import java.io.Writer; 034 import java.lang.annotation.Annotation; 035 import java.lang.reflect.Type; 036 import java.util.Map; 037 038 @Provider 039 @Produces(MediaType.APPLICATION_JSON) 040 @InterfaceAudience.Private 041 public class JSONMapProvider implements MessageBodyWriter<Map> { 042 private static final String ENTER = System.getProperty("line.separator"); 043 044 @Override 045 public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) { 046 return Map.class.isAssignableFrom(aClass); 047 } 048 049 @Override 050 public long getSize(Map map, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) { 051 return -1; 052 } 053 054 @Override 055 public void writeTo(Map map, Class<?> aClass, Type type, Annotation[] annotations, 056 MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap, 057 OutputStream outputStream) throws IOException, WebApplicationException { 058 Writer writer = new OutputStreamWriter(outputStream); 059 JSONObject.writeJSONString(map, writer); 060 writer.write(ENTER); 061 writer.flush(); 062 } 063 064 }