001/*
002 * (C) Copyright 2006-2009 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 *     Nuxeo
016 */
017
018package org.nuxeo.ecm.platform.publisher.remoting.restHandler;
019
020import java.io.ByteArrayInputStream;
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.OutputStream;
024import java.lang.annotation.Annotation;
025import java.lang.reflect.Type;
026
027import javax.ws.rs.WebApplicationException;
028import javax.ws.rs.core.MediaType;
029import javax.ws.rs.core.MultivaluedMap;
030import javax.ws.rs.ext.MessageBodyWriter;
031import javax.ws.rs.ext.Provider;
032
033@Provider
034public class RemotePubMessageWriter implements MessageBodyWriter<RemotePubResult> {
035
036    protected static final int BUFFER_SIZE = 4096 * 16;
037
038    public long getSize(RemotePubResult arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
039        return -1;
040    }
041
042    public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
043        return RemotePubResult.class.isAssignableFrom(arg0);
044    }
045
046    public void writeTo(RemotePubResult result, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
047            MultivaluedMap<String, Object> arg5, OutputStream stream) throws IOException, WebApplicationException {
048        String xmlString = result.asXML();
049        InputStream in = new ByteArrayInputStream(xmlString.getBytes());
050        byte[] buffer = new byte[BUFFER_SIZE];
051        int read;
052        while ((read = in.read(buffer)) != -1) {
053            stream.write(buffer, 0, read);
054        }
055    }
056
057}