package jp.cssj.cti.resolver;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

/**
 * ストリームから得られるリソースに対するSourceの実装です。
 * 
 * @author <a href="mailto:miyabe at gnn.co.jp">MIYABE Tatsuhiko </a>
 * @version $Id: StreamSource.java,v 1.4 2005/08/18 04:51:26 harumanx Exp $
 */
public class StreamSource implements Source {
	private final String uri, mimeType, encoding;

	private final InputStream in;

	private final Reader reader;

	public StreamSource(String uri, String mimeType, InputStream in) {
		this.uri = SourceUtils.normalize(uri);
		this.mimeType = mimeType;
		this.in = in;
		this.encoding = null;
		this.reader = null;
	}

	public StreamSource(String uri, String mimeType, String encoding,
			Reader reader) {
		this.uri = SourceUtils.normalize(uri);
		this.mimeType = mimeType;
		this.in = null;
		this.encoding = encoding;
		this.reader = reader;
	}

	public StreamSource(String uri, String mimeType, String encoding,
			InputStream in) throws UnsupportedEncodingException {
		this.uri = SourceUtils.normalize(uri);
		this.mimeType = mimeType;
		this.encoding = encoding;
		if (encoding == null) {
			this.in = in;
			this.reader = null;
		} else {
			this.in = null;
			this.reader = new InputStreamReader(in, encoding);
		}
	}

	public StreamSource(String uri, String mimeType, Reader reader) {
		this(uri, mimeType, null, reader);
	}

	public String getURI() {
		return this.uri;
	}

	public String getMimeType() {
		return this.mimeType;
	}

	public String getEncoding() {
		return this.encoding;
	}

	public boolean isCharacterStream() {
		return this.reader != null;
	}

	public InputStream getInputStream() {
		if (this.isCharacterStream()) {
			throw new UnsupportedOperationException();
		}
		return this.in;
	}

	public Reader getReader() {
		if (!this.isCharacterStream()) {
			throw new UnsupportedOperationException();
		}
		return this.reader;
	}

	public boolean isFile() {
		return false;
	}

	public File getFile() {
		return null;
	}
}