001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.webengine.model.io;
023
024import static org.apache.commons.logging.LogFactory.getLog;
025
026import java.io.IOException;
027import java.io.OutputStream;
028import java.lang.annotation.Annotation;
029import java.lang.reflect.Type;
030
031import javax.servlet.ServletContext;
032import javax.servlet.http.HttpServletRequest;
033import javax.servlet.http.HttpServletResponse;
034import javax.ws.rs.Produces;
035import javax.ws.rs.core.Context;
036import javax.ws.rs.core.MediaType;
037import javax.ws.rs.core.MultivaluedMap;
038import javax.ws.rs.ext.MessageBodyWriter;
039import javax.ws.rs.ext.Provider;
040
041import org.apache.commons.logging.Log;
042import org.nuxeo.ecm.core.api.Blob;
043import org.nuxeo.ecm.core.api.impl.blob.JSONBlob;
044import org.nuxeo.ecm.core.io.download.BufferingServletOutputStream;
045import org.nuxeo.ecm.core.io.download.DownloadHelper;
046import org.nuxeo.ecm.core.io.download.DownloadService;
047import org.nuxeo.runtime.api.Framework;
048import org.nuxeo.runtime.transaction.TransactionHelper;
049
050/**
051 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
052 */
053@Provider
054@Produces({ "*/*", "text/plain" })
055public class BlobWriter implements MessageBodyWriter<Blob> {
056
057    private static final Log log = getLog(BlobWriter.class);
058
059    public static final String BLOB_ID = "blobId";
060
061    @Context
062    private HttpServletRequest request;
063
064    @Context
065    private HttpServletResponse response;
066
067    @Context
068    private ServletContext servletContext;
069
070    @Override
071    public void writeTo(Blob blob, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
072            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
073        // Ensure transaction is committed before writing blob to response
074        commitAndReopenTransaction();
075        // we don't want JAX-RS default headers (like Content-Type: text/plain)
076        // to be written, we control everything from the DownloadService
077        httpHeaders.clear();
078        if (Framework.isTestModeSet()) {
079            // TODO remove this test-specific code
080            String filename = blob.getFilename();
081            if (filename != null) {
082                String contentDisposition = DownloadHelper.getRFC2231ContentDisposition(request, filename);
083                response.setHeader("Content-Disposition", contentDisposition);
084            }
085            response.setContentType(blob.getMimeType());
086            if (blob.getEncoding() != null) {
087                try {
088                    response.setCharacterEncoding(blob.getEncoding());
089                } catch (IllegalArgumentException e) {
090                    // ignore invalid encoding
091                }
092            }
093            transferBlob(blob, entityStream);
094        } else {
095            DownloadService downloadService = Framework.getService(DownloadService.class);
096            String reason = blob instanceof JSONBlob ? "webengine" : "download";
097            downloadService.downloadBlob(request, response, null, null, blob, blob.getFilename(), reason);
098        }
099    }
100
101    protected void commitAndReopenTransaction() {
102        if (TransactionHelper.isTransactionActiveOrMarkedRollback()) {
103            TransactionHelper.commitOrRollbackTransaction();
104            TransactionHelper.startTransaction();
105        }
106    }
107
108    protected void transferBlob(Blob blob, OutputStream entityStream) throws IOException {
109        if (entityStream instanceof BufferingServletOutputStream) {
110            ((BufferingServletOutputStream)entityStream).stopBuffering();
111        }
112        blob.transferTo(entityStream);
113        entityStream.flush();
114    }
115
116    @Override
117    public long getSize(Blob arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
118        long n = arg0.getLength();
119        return n <= 0 ? -1 : n;
120    }
121
122    @Override
123    public boolean isWriteable(Class<?> arg0, Type type, Annotation[] arg2, MediaType arg3) {
124        return Blob.class.isAssignableFrom(arg0);
125    }
126
127}