001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.webengine.jaxrs.views;
016
017import java.io.IOException;
018import java.io.OutputStream;
019import java.lang.annotation.Annotation;
020import java.lang.reflect.Type;
021
022import javax.ws.rs.Produces;
023import javax.ws.rs.core.MediaType;
024import javax.ws.rs.core.MultivaluedMap;
025import javax.ws.rs.ext.MessageBodyWriter;
026import javax.ws.rs.ext.Provider;
027
028import org.nuxeo.ecm.platform.rendering.api.RenderingException;
029import org.nuxeo.ecm.platform.rendering.api.View;
030
031/**
032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
033 */
034@Provider
035@Produces("*/*")
036public class ViewMessageBodyWriter implements MessageBodyWriter<View> {
037
038    @Override
039    public void writeTo(View t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
040            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
041        try {
042            t.render(entityStream);
043        } catch (RenderingException e) {
044            throw new IOException("Failed to render view: " + t, e);
045        }
046    }
047
048    @Override
049    public long getSize(View arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
050        return -1;
051    }
052
053    @Override
054    public boolean isWriteable(Class<?> arg0, Type type, Annotation[] arg2, MediaType arg3) {
055        return View.class.isAssignableFrom(arg0);
056    }
057
058}