Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  *
  *
  * This file incorporates work covered by the following copyright and
  * permission notice:
  *
  * Copyright 2004 The Apache Software Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.coyote.http11;
 
 
 
Output buffer.

Author(s):
Remy Maucherat
 
 public class InternalOutputBuffer 
     implements OutputBufferByteChunk.ByteOutputChannel {
 
 
     // -------------------------------------------------------------- Constants
 
 
     // ----------------------------------------------------------- Constructors
 

    
Default constructor.
 
     public InternalOutputBuffer(Response response) {
         this(response.);
     }
 
     
    // START GlassFish Issue 798
    
Create a new InternalOutputBuffer and configure the enable/disable the socketBuffer mechanism.
    public InternalOutputBuffer(Response responseint headerBufferSize
            boolean useSocketBuffer) {
        
        this(response,headerBufferSize);
        this. = useSocketBuffer;
        if ( useSocketBuffer ){
            .allocate(headerBufferSizeheaderBufferSize);
        }
    }
    // END GlassFish Issue 798
    
    
    
Alternate constructor.
    public InternalOutputBuffer(Response responseint headerBufferSize) {
        this. = response;
         = response.getMimeHeaders();
         = new byte[headerBufferSize];
         = new OutputFilter[0];
         = new OutputFilter[0];
         = -1;
         = new ByteChunk();
        .setByteOutputChannel(this);
         = false;
         = false;
    }
    // -------------------------------------------------------------- Variables
    // START GlassFish Issue 646
    
Logger.
    protected static final com.sun.org.apache.commons.logging.Log log 
        = com.sun.org.apache.commons.logging.
            LogFactory.getLog(InternalOutputBuffer.class);
    // END GlassFish Issue 646

    
    
The string manager for this package.
    protected static final StringManager sm =
        StringManager.getManager(.);
    // ----------------------------------------------------- Instance Variables


    
Associated Coyote response.
    protected Response response;


    
Headers of the associated request.
    protected MimeHeaders headers;


    
Committed flag.
    protected boolean committed;


    
Finished flag.
    protected boolean finished;


    
Pointer to the current read buffer.
    protected byte[] buf;


    
Position in the buffer.
    protected int pos;


    
Underlying output stream.
    protected OutputStream outputStream;


    
Underlying output buffer.
    protected OutputBuffer outputStreamOutputBuffer;


    
Filter library. Note: Filter[0] is always the "chunked" filter.
    protected OutputFilter[] filterLibrary;


    
Active filter (which is actually the top of the pipeline).
    protected OutputFilter[] activeFilters;


    
Index of the last active filter.
    protected int lastActiveFilter;


    
Socket buffer.
    protected ByteChunk socketBuffer;


    
Socket buffer (extra buffering to reduce number of packets sent).
    protected boolean useSocketBuffer = false;
    // ------------------------------------------------------------- Properties


    
Set the underlying socket output stream.
    public void setOutputStream(OutputStream outputStream) {
        // FIXME: Check for null ?
        this. = outputStream;
    }


    
Get the underlying socket output stream.
    public OutputStream getOutputStream() {
        return ;
    }


    
Set the socket buffer size.
    public void setSocketBuffer(int socketBufferSize) {
        if (socketBufferSize > 500) {
             = true;
            .allocate(socketBufferSizesocketBufferSize);
        } else {
             = false;
        }
    }


    
Add an output filter to the filter library.
    public void addFilter(OutputFilter filter) {
        OutputFilter[] newFilterLibrary = 
            new OutputFilter[. + 1];
        for (int i = 0; i < .i++) {
            newFilterLibrary[i] = [i];
        }
        newFilterLibrary[.] = filter;
         = newFilterLibrary;
    }


    
Get filters.
    public OutputFilter[] getFilters() {
        return ;
    }


    
Clear filters.
    public void clearFilters() {
         = new OutputFilter[0];
         = -1;
    }


    
Add an output filter to the filter library.
    public void addActiveFilter(OutputFilter filter) {
        if ( == -1) {
            filter.setBuffer();
        } else {
            for (int i = 0; i <= i++) {
                if ([i] == filter)
                    return;
            }
            filter.setBuffer([]);
        }
        [++] = filter;
        filter.setResponse();
    }
    // --------------------------------------------------------- Public Methods


    
Flush the response.

Throws:
java.io.IOException an undelying I/O error occured
    public void flush()
        throws IOException {
        if (!) {
            // Send the connector a request for commit. The connector should
            // then validate the headers, send them (using sendHeader) and 
            // set the filters accordingly.
            .action(.null);
        }
        // Flush the current buffer
        if () {
            .flushBuffer();
        }
    }

  
    
Reset current response.

Throws:
java.lang.IllegalStateException if the response has already been committed
    public void reset() {
        if ()
            throw new IllegalStateException(/*FIXME:Put an error message*/);
        // Recycle Request object
        .recycle();
    }


    
Recycle the output buffer. This should be called when closing the connection.
    public void recycle() {
        // Recycle Request object
        .recycle();
        .recycle();
         = null;
         = 0;
         = -1;
         = false;
         = false;
    }


    
End processing of current HTTP request. Note: All bytes of the current request should have been already consumed. This method only resets all the pointers so that we are ready to parse the next HTTP request.
    public void nextRequest() {
        // Recycle Request object
        .recycle();
        .recycle();
        // Recycle filters
        for (int i = 0; i <= i++) {
            [i].recycle();
        }
        // Reset pointers
         = 0;
         = -1;
         = false;
         = false;
    }


    
End request.

Throws:
java.io.IOException an undelying I/O error occured
    public void endRequest()
        throws IOException {
        if (!) {
            // Send the connector a request for commit. The connector should
            // then validate the headers, send them (using sendHeader) and 
            // set the filters accordingly.
            .action(.null);
        }
        if ()
            return;
        if ( != -1)
            [].end();
        if () {
            .flushBuffer();
        }
         = true;
    }
    // ------------------------------------------------ HTTP/1.1 Output Methods


    
Send an acknoledgement.
    public void sendAck()
        throws IOException {
        if (!){
            realWriteBytes(.,0,
                        ..);
        }
    }


    
Send the response status line.
    public void sendStatus() {
        // Write protocol name
        write("HTTP/1.1 ");
        // Write status code
        int status = .getStatus();
	switch (status) {
	case 200:
            write("200");
	    break;
	case 400:
            write("400");
	    break;
	case 404:
            write("404");
	    break;
        default:
	    write(status);
	}
        write(" ");
        // Write message
        String message = .getMessage();
        if (message == null) {
            write(getMessage(status));
        } else {
            write(message);
        }
        // End the response status line
        if ( System.getSecurityManager() != null ){
           AccessController.doPrivileged(
                new PrivilegedAction(){
                    public Object run(){
                        write(.);
                        return null;
                    }
                }
           );
        } else {
            write(.);
        }
    }
    private String getMessage(final int message){
        if (System.getSecurityManager() != null){
           return (String)AccessController.doPrivileged(
                new PrivilegedAction(){
                    public Object run(){
                        return HttpMessages.getMessage(message); 
                    }
                }
           );
        } else {
            return HttpMessages.getMessage(message);
        }
    }

    
Send a header.

Parameters:
name Header name
value Header value
    public void sendHeader(MessageBytes nameMessageBytes value) {
        write(name);
        write(": ");
        write(value);
        write(.);
    }


    
Send a header.

Parameters:
name Header name
value Header value
    public void sendHeader(ByteChunk nameByteChunk value) {
        write(name);
        write(": ");
        write(value);
        write(.);
    }


    
Send a header.

Parameters:
name Header name
value Header value
    public void sendHeader(String nameString value) {
        write(name);
        write(": ");
        write(value);
        write(.);
    }


    
End the header block.
    public void endHeaders() {
        write(.);
    }
    // --------------------------------------------------- OutputBuffer Methods


    
Write the contents of a byte chunk.

Parameters:
chunk byte chunk
Returns:
number of bytes written
Throws:
java.io.IOException an undelying I/O error occured
    public int doWrite(ByteChunk chunkResponse res
        throws IOException {
        if (!) {
            // Send the connector a request for commit. The connector should
            // then validate the headers, send them (using sendHeaders) and 
            // set the filters accordingly.
            .action(.null);
        }
        if ( == -1)
            return .doWrite(chunkres);
        else
            return [].doWrite(chunkres);
    }
    // ------------------------------------------------------ Protected Methods
    /*
     * Commit the response.
     * 
     * @throws IOException an undelying I/O error occured
     */
    public void commit()
        throws IOException {
        // The response is now committed
         = true;
        .setCommitted(true);
        if ( > 0) {
            // Sending the response header buffer
            if () {
                .append(, 0, );
            } else {
                .write(, 0, );
            }
        }
    }


    
This method will write the contents of the specyfied message bytes buffer to the output stream, without filtering. This method is meant to be used to write the response header.

Parameters:
mb data to be written
    protected void write(MessageBytes mb) {
        if (mb.getType() == .) {
            ByteChunk bc = mb.getByteChunk();
            write(bc);
        } else if (mb.getType() == .) {
            CharChunk cc = mb.getCharChunk();
            write(cc);
        } else {
            write(mb.toString());
        }
    }


    
This method will write the contents of the specyfied message bytes buffer to the output stream, without filtering. This method is meant to be used to write the response header.

Parameters:
bc data to be written
    protected void write(ByteChunk bc) {
        // Writing the byte chunk to the output buffer
        System.arraycopy(bc.getBytes(), bc.getStart(), ,
                         bc.getLength());
         =  + bc.getLength();
    }


    
This method will write the contents of the specyfied char buffer to the output stream, without filtering. This method is meant to be used to write the response header.

Parameters:
cc data to be written
    protected void write(CharChunk cc) {
        int start = cc.getStart();
        int end = cc.getEnd();
        char[] cbuf = cc.getBuffer();
        for (int i = starti < endi++) {
            char c = cbuf[i];
            // Note:  This is clearly incorrect for many strings,
            // but is the only consistent approach within the current
            // servlet framework.  It must suffice until servlet output
            // streams properly encode their output.
            if ((c <= 31) && (c != 9)) {
                c = ' ';
            } else if (c == 127) {
                c = ' ';
            }
            [++] = (bytec;
        }
    }


    
This method will write the contents of the specyfied byte buffer to the output stream, without filtering. This method is meant to be used to write the response header.

Parameters:
b data to be written
    public void write(byte[] b) {
        // Writing the byte chunk to the output buffer
        System.arraycopy(b, 0, b.length);
         =  + b.length;
    }


    
This method will write the contents of the specyfied String to the output stream, without filtering. This method is meant to be used to write the response header.

Parameters:
s data to be written
    protected void write(String s) {
        if (s == null)
            return;
        // From the Tomcat 3.3 HTTP/1.0 connector
        int len = s.length();
        for (int i = 0; i < leni++) {
            char c = s.charAt (i);
            // Note:  This is clearly incorrect for many strings,
            // but is the only consistent approach within the current
            // servlet framework.  It must suffice until servlet output
            // streams properly encode their output.
            if ((c <= 31) && (c != 9)) {
                c = ' ';
            } else if (c == 127) {
                c = ' ';
            }
            [++] = (bytec;
        }
    }


    
This method will print the specified integer to the output stream, without filtering. This method is meant to be used to write the response header.

Parameters:
i data to be written
    protected void write(int i) {
        write(String.valueOf(i));
    }


    
Callback to write data from the buffer.
    public void realWriteBytes(byte cbuf[], int offint len)
        throws IOException {
        if (len > 0) {
            .write(cbufofflen);
        }
    }
    // ----------------------------------- OutputStreamOutputBuffer Inner Class


    
This class is an output buffer which will write data to an output stream.
    protected class OutputStreamOutputBuffer 
        implements OutputBuffer {


        
Write chunk.
        public int doWrite(ByteChunk chunkResponse res
            throws IOException {
            if () {
                .append(chunk.getBuffer(), chunk.getStart(), 
                                   chunk.getLength());
            } else {
                .write(chunk.getBuffer(), chunk.getStart(), 
                                   chunk.getLength());
            }
            return chunk.getLength();
        }
    }
New to GrepCode? Check out our FAQ X