001/*
002 * (C) Copyright 2011 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 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.platform.web.common.requestcontroller.filter;
020
021import java.io.IOException;
022import java.io.PrintWriter;
023
024import javax.servlet.http.HttpServletResponse;
025import javax.servlet.http.HttpServletResponseWrapper;
026
027import org.nuxeo.ecm.core.io.download.BufferingServletOutputStream;
028
029/**
030 * Buffers the response until {@link #stopBuffering()} is called.
031 * <p>
032 * This allows a container to commit a transaction before the body is written to the client.
033 */
034public class BufferingHttpServletResponse extends HttpServletResponseWrapper {
035
036    protected BufferingServletOutputStream bufferingOutputStream;
037
038    /**
039     * A {@link HttpServletResponse} wrapper that buffers all data until {@link #stopBuffering()} is called.
040     * <p>
041     * {@link #stopBuffering()} <b>MUST</b> be called in a {@code finally} statement in order for resources to be closed
042     * properly.
043     */
044    public BufferingHttpServletResponse(HttpServletResponse response) throws IOException {
045        super(response);
046        bufferingOutputStream = new BufferingServletOutputStream(response.getOutputStream());
047    }
048
049    @Override
050    public BufferingServletOutputStream getOutputStream() throws IOException {
051        return bufferingOutputStream;
052    }
053
054    @Override
055    public PrintWriter getWriter() throws IOException {
056        return bufferingOutputStream.getWriter();
057    }
058
059    /**
060     * Stops buffering and sends any buffered data to the response's output stream.
061     */
062    public void stopBuffering() throws IOException {
063        bufferingOutputStream.stopBuffering();
064    }
065
066
067
068    /**
069     * Don't flush if we are still buffering.
070     */
071    @Override
072    public void flushBuffer() throws IOException {
073        bufferingOutputStream.flush();
074    }
075
076}