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