/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * 文字列のバイト配列表現を返す{@link ReaderFactory}。
 * 適用しているパターン：Adapter。
 * @author nakamura
 *
 */
public class StringInputStreamFactory implements InputStreamFactory {
	private final byte[] array;
	
	/**
	 * コンストラクタ。
	 * @param charset 文字セット。
	 * @param s バイト配列の元になる文字列。
	 * @throws NullPointerException 引数が null の場合。
	 * @throws RuntimeException ({@link UnsupportedEncodingException})バイト配列への変換に失敗した場合。
	 */
	public StringInputStreamFactory(final String charset, final String s){
		try {
			if(charset == null || charset.length() == 0){
				this.array = s.getBytes();
			}else{
				this.array = s.getBytes(charset);
			}
		} catch (final UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public InputStream newInstance(final String id) throws IOException {
		return new ByteArrayInputStream(array);
	}
}
