All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.xsocket.connection.http.ChunkedBodyDataSource Maven / Gradle / Ivy

There is a newer version: 2.0-beta-1
Show newest version
/*
 *  Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
 * The latest copy of this software may be found on http://www.xsocket.org/
 */
package org.xsocket.connection.http;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.http.AbstractHttpMessage.BodyType;



/**
 * 
 * Chunked implementation of a body data source
 * 
 * 
 * @author [email protected]
 */
final class ChunkedBodyDataSource extends NonBlockingBodyDataSource implements IDataHandler, IDisconnectHandler {

	
	private static final Logger LOG = Logger.getLogger(ChunkedBodyDataSource.class.getName());
	
	private static final int STATE_READING_CHUNK = 0;
	private static final int STATE_READING_TRAILER = 1;
	private static final int STATE_CLOSED = 2;
	
	
	private int state = STATE_READING_CHUNK;

	private List trailerList = null;
	
	private int totalSize = 0;
	private int chunkSize = 0;
	private int remainingDataToRead = 0;
	
		
	private AbstractMessageHeader messageHeader = null;
	
 
	/**
	 * constructor
	 * 
	 * @param httpConnection   the http connection
	 * @param header           the message header
	 * @param encoding         the encoding to use
	 */
	ChunkedBodyDataSource(AbstractHttpConnection httpConnection, AbstractMessageHeader header, String encoding) throws IOException {
		super(encoding, httpConnection);
		
		this.messageHeader = header;
	}
	
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	BodyType getBodyType() {
		return BodyType.CHUNKED;
	}


	/**
	 * {@inheritDoc}
	 */
	public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException {
		
		try {
			if (state == STATE_READING_CHUNK) {
				readChunk(connection);
			}
			
			if (state == STATE_READING_TRAILER) {
				readTrailer(connection);
			}
			
			return true;
			
		} catch (BufferUnderflowException bue) {
			throw bue;
			
		} catch (IOException ioe) {
			if (LOG.isLoggable(Level.FINE)) {
				LOG.fine("[" + getHttpConnection().getId() + "] error occured by reading chunked body " + ioe.toString());
			}

			setIOException(ioe);
			close();
			getHttpConnection().destroy();
			return true;
		}
	}
	
	
	private void readChunk(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
		
		/////////////////////////
		// read chunk size	
		if (remainingDataToRead == 0) {   // new chunk?
			// read chunk size 
			String lengthField = connection.readStringByDelimiter("\r\n").trim();
						
			try {
				chunkSize = Integer.parseInt(lengthField, 16);
				
			} catch (NumberFormatException nfe) {

				// chunk extension?
				if (lengthField.indexOf(";") != -1) {
					lengthField	= lengthField.substring(0, lengthField.indexOf(";"));
					chunkSize = Integer.parseInt(lengthField, 16);
				} else {
					throw new IOException("http protocol error. length field expected");
				}
			}

			
			totalSize += chunkSize;

			
			// lastChunk?
			if (chunkSize == 0) {
				state = STATE_READING_TRAILER;
				return;
				
			// .. no
			} else {
				remainingDataToRead = chunkSize + 2;  // chunk data + CRLF
				
				
				if (LOG.isLoggable(Level.FINE)) {
					LOG.fine("[" + getHttpConnection().getId() + "] reading chunk size=" + remainingDataToRead);
				}
			}
		}
		
		
		try {
			/////////////////////////////
			// read chunk data
			int availableBytes = connection.available();
			ByteBuffer[] data = null;
			
			// complete chunk available?
			if (availableBytes >= remainingDataToRead) {
				// read chunk data
				if (availableBytes > 2) {
					data = connection.readByteBufferByLength(remainingDataToRead - 2);
				}
				
				// read chunk CRLF
				String crlf = connection.readStringByLength(2); 
				assert crlf.equals("\r\n") : "got " + crlf + " instead of chunk CRLF";
				
				remainingDataToRead = 0;
				
			} else {
				// read chunk data 
				if (availableBytes > 2) {
					data = connection.readByteBufferByLength(availableBytes - 2);
					remainingDataToRead -= (availableBytes - 2);
				}
			}
			
			if (data != null) {
				append(data);
				getHttpConnection().onBodyDataReceived();
			}
			
		} catch (BufferUnderflowException bue) {
			LOG.warning("error occured by reading chunk (buffer underflow exception"); 
		}
	}
	
	
	private void readTrailer(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
		String line = connection.readStringByDelimiter("\r\n");

		
		// empty line -> message has been completed
		if (line.length() == 0) {
			state = STATE_CLOSED;
			
			if (trailerList != null) {
				String[] trailers = trailerList.toArray(new String[trailerList.size()]);
				String[] headerLines = AbstractMessageHeader.unfoldingHeaderlines(trailers);
				for (String headerLine : headerLines) {
					messageHeader.addHeaderLine(headerLine);
				}
			}

			if (LOG.isLoggable(Level.FINE)) {
				LOG.fine("[" + getHttpConnection().getId() + "] complete chunk message received (body size=" + totalSize + ")");
			}

			removeBodyParser();
			setComplete(true);
			
		// trailer available
		} else {
			getTrailerList().add(line);
		}
	}
	
	
	private List getTrailerList() {
		if (trailerList == null) {
			trailerList = new ArrayList();
		}
		
		return trailerList;
	}
	
	
	public boolean onDisconnect(INonBlockingConnection connection) throws IOException {
		super.onDisconnect(connection);

		onUnderlyingHttpConnectionClosed();
		return true;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy