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.ecm.core.io.download.DownloadService.DownloadContext;
048import org.nuxeo.runtime.api.Framework;
049import org.nuxeo.runtime.transaction.TransactionHelper;
050
051/**
052 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
053 */
054@Provider
055@Produces({ "*/*", "text/plain" })
056public class BlobWriter implements MessageBodyWriter<Blob> {
057
058    private static final Log log = getLog(BlobWriter.class);
059
060    public static final String BLOB_ID = "blobId";
061
062    @Context
063    private HttpServletRequest request;
064
065    @Context
066    private HttpServletResponse response;
067
068    @Context
069    private ServletContext servletContext;
070
071    @Override
072    public void writeTo(Blob blob, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
073            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
074        // Ensure transaction is committed before writing blob to response
075        commitAndReopenTransaction();
076        // we don't want JAX-RS default headers (like Content-Type: text/plain)
077        // to be written, we control everything from the DownloadService
078        httpHeaders.clear();
079        if (Framework.isTestModeSet()) {
080            // TODO remove this test-specific code
081            String filename = blob.getFilename();
082            if (filename != null) {
083                String contentDisposition = DownloadHelper.getRFC2231ContentDisposition(request, filename);
084                response.setHeader("Content-Disposition", contentDisposition);
085            }
086            response.setContentType(blob.getMimeType());
087            if (blob.getEncoding() != null) {
088                try {
089                    response.setCharacterEncoding(blob.getEncoding());
090                } catch (IllegalArgumentException e) {
091                    // ignore invalid encoding
092                }
093            }
094            transferBlob(blob, entityStream);
095        } else {
096            String reason = blob instanceof JSONBlob ? "webengine" : "download";
097            DownloadContext context = DownloadContext.builder(request, response)
098                                                     .blob(blob)
099                                                     .reason(reason)
100                                                     .build();
101            Framework.getService(DownloadService.class).downloadBlob(context);
102        }
103    }
104
105    protected void commitAndReopenTransaction() {
106        if (TransactionHelper.isTransactionActiveOrMarkedRollback()) {
107            TransactionHelper.commitOrRollbackTransaction();
108            TransactionHelper.startTransaction();
109        }
110    }
111
112    protected void transferBlob(Blob blob, OutputStream entityStream) throws IOException {
113        if (entityStream instanceof BufferingServletOutputStream) {
114            ((BufferingServletOutputStream)entityStream).stopBuffering();
115        }
116        blob.transferTo(entityStream);
117        entityStream.flush();
118    }
119
120    @Override
121    public long getSize(Blob arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
122        long n = arg0.getLength();
123        return n <= 0 ? -1 : n;
124    }
125
126    @Override
127    public boolean isWriteable(Class<?> arg0, Type type, Annotation[] arg2, MediaType arg3) {
128        return Blob.class.isAssignableFrom(arg0);
129    }
130
131}