001/* 002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * matic 016 */ 017package org.nuxeo.ecm.automation.jaxrs.io; 018 019import java.io.IOException; 020import java.io.OutputStream; 021import java.lang.annotation.Annotation; 022import java.lang.reflect.Type; 023 024import javax.ws.rs.Produces; 025import javax.ws.rs.WebApplicationException; 026import javax.ws.rs.core.Context; 027import javax.ws.rs.core.MediaType; 028import javax.ws.rs.core.MultivaluedMap; 029import javax.ws.rs.ext.MessageBodyWriter; 030import javax.ws.rs.ext.Provider; 031 032import org.codehaus.jackson.JsonEncoding; 033import org.codehaus.jackson.JsonFactory; 034import org.codehaus.jackson.JsonGenerator; 035import org.codehaus.jackson.JsonNode; 036 037/** 038 * @author bstefanescu 039 */ 040@Provider 041@Produces("application/json") 042public class JsonTreeWriter implements MessageBodyWriter<JsonNode> { 043 044 @Context 045 JsonFactory factory; 046 047 @Override 048 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { 049 return JsonNode.class.isAssignableFrom(type); 050 } 051 052 @Override 053 public long getSize(JsonNode t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { 054 return -1; 055 } 056 057 @Override 058 public void writeTo(JsonNode t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, 059 MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, 060 WebApplicationException { 061 JsonGenerator jg = factory.createJsonGenerator(entityStream, JsonEncoding.UTF8); 062 jg.writeTree(t); 063 jg.flush(); 064 } 065 066}