/* 
 * 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.OutputStream;

/**
 * A utility class for sending an array of bytes to an HTTP server or client.
 * Example usage:
 * <pre>
 * HttpClient client = new RetryHttpClient("http://example.net");
 * byte buf[] = "This is only a test".getBytes();
 * DataPoster dataPoster = new ByteArrayDataPoster(buf);
 * RequestLine rl = new RequestLineImpl( ... );
 * ClientRequest request = new ClientRequestImpl(rl, dataPoster);
 *
 * client.writeRequest(request);
 * ClientResponse response = client.readResponse();
 * </pre>
 */
public class ByteArrayDataPoster implements DataPoster {

	private byte data[];
	private int len;
	private int off;

	/**
	 * Constructs a <code>ByteArrayDataPoster</code>,
	 * which will send an entire byte array.
	 */
	public ByteArrayDataPoster(byte[] data) {
		if (data == null)
			throw new IllegalArgumentException("Null byte[]");
		this.data = data;
		this.off = 0;
		this.len = data.length;
	}

	/**
	 * Constructs a <code>ByteArrayDataPoster</code>
	 * which will send part of a byte array.
	 *
	 * @param data source data array
	 * @param off zero-based offset in source
	 * @param len length of array to send
	 */
	public ByteArrayDataPoster(byte[] data, int off, int len) {
		if (data == null)
			throw new IllegalArgumentException("Null byte[]");
		this.data = data;
		this.off = off;
		this.len = len;
	}

	/**
	 * Writes the byte array to the supplied output stream.
	 */
	public void sendData(OutputStream os)
		throws IOException
	{ 
		if (os == null)
			throw new IllegalArgumentException("OutputStream is null");
		os.write(data, off, len);
		os.flush();
	}

	public String toString() {
		return "ByteArrayDataPoster data=" + data.length + " off=" + off + " len=" + len;
	}
}
