/* daruma.util.EncodingConversionOutputStream */

/***************************************************************************/

package daruma.util;

import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/***************************************************************************/

/**
 * Trivial encoding conversion class for java.io.OutputStream. <p>
 *
 * Example:
 * <pre>
 *  OutputStream raw_ostream;
 *  OutputStream encoded_ostream;
 *
 *  encoded_ostream = new EncodingConversionOutputStream(raw_ostream, "utf-8");
 *
 *  encoded_ostream.print("some text");
 * </pre>
 *
 * @author YOKOTA Hiroshi
 */
public class EncodingConversionOutputStream extends FilterOutputStream {
	private String cEncoding;

	/**
	 * Create the instance.
	 *
	 * @param o   Raw output stream.
	 * @param enc Specifies conversion encoding name. Raw output
	 *            stream is convert to this encoding, and output.
	 * @exception UnsupportedEncodingException
	 */
	public EncodingConversionOutputStream(OutputStream o, String enc) throws UnsupportedEncodingException {
		super(o);

		if(! is_supported_encoding(enc)) {
			throw new UnsupportedEncodingException("Specified encoding \"" + enc + "\" is not supported by the system.");
		}

		cEncoding = enc;
	}

	/**
	 * Encoding converter. Private use only.
	 */
	private byte[] conv(byte b[]) throws UnsupportedEncodingException {
		String s = new String(b);

		return s.getBytes(cEncoding);
	}

	/**
	 * Test the encoding is supported by the system. Private use only.
	 */
	private boolean is_supported_encoding(String enc) {
		try {
			"test".getBytes(enc);
		} catch(UnsupportedEncodingException uee) {
			return false;
		}

		return true;
	}

	/**
	 * Write out some string as byte array.
	 *
	 * @param     b Output string in byte array.
	 * @exception IOException
	 */
	public void write(byte b[]) throws IOException {
		out.write(conv(b));
	}

	/**
	 * Write out some string as byte array with array offset and
	 * output length.
	 *
	 * @param     b   Output string in byte array.
	 * @param     off Array offset. Write out from this offset.
	 * @param     len Output length. Write out specified length.
	 * @exception IOException
	 */
	public void write(byte b[], int off, int len) throws IOException {
		ByteArrayOutputStream buf = new ByteArrayOutputStream();

		buf.write(b, off, len);

		write(buf.toByteArray());

		buf.close();
	}
}

/* end */
