/* 
 * E-XML Library:  For XML, XML-RPC, HTTP, and related.
 * Copyright (C) 2002-2008  Elias Ross
 * 
 * genman@noderunner.net
 * http://noderunner.net/~genman
 * 
 * 1025 NE 73RD ST
 * SEATTLE WA 98115
 * USA
 *
 * 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.
 * 
 * $Id$
 */

package net.noderunner.http;

import java.io.IOException;
import java.io.InputStream;

/**
 * Specifies an HTTP request.
 * In RFC 2616 terms, this object represents data found in the
 * <code>Request</code> body.
 */
public class ServerRequest
	extends Request
{
	private InputStream is;

	/**
	 * Constructs a <code>ServerRequest</code> by parsing an input stream.
	 */
	public ServerRequest(InputStream is)
		throws IOException
	{
		String line;
		do {
			line = HttpUtil.readHttpLine(is);
		} while (line.length() == 0);
		this.requestLine = new RequestLine(line);
		this.headers = MessageHeaders.readHeaders(is);
		this.is = is;
	}

	public InputStream getInputStream() {
		return is;
	}

	/**
	 * Reads a response's input stream until EOF.
	 * Returns the number of bytes read.
	 * If the server indicates the connection was closed, does nothing.
	 */
	public int readFully()
		throws IOException
	{
		InputStream s = HttpUtil.wrapInputStream(getInputStream(), getHeaders());
		if (s != null) {
			boolean close = getHeaders().contains(MessageHeader.MH_CONNECTION_CLOSE);
			if (!close)
				return HttpUtil.readFully(s);
		}
		return 0;
	}

	/**
	 * Returns a debug string.
	 */
	public String toString() {
		return super.toString() + " is=" + is;
	}

}
