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

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

import woolpack.utils.CheckUtils;
import woolpack.utils.ReaderFactory;
import woolpack.utils.UtilsConstants;
import woolpack.utils.XmlTransformerFactory;

/**
 * {@link ReaderFactory}と{@link XmlTransformerFactory}
 * を使用して DOM ノードを生成する{@link DomExpression}。
 * 
 * @author nakamura
 * 
 */
public class XmlToNode implements DomExpression {
	private final ReaderFactory readerFactory;

	private final XmlTransformerFactory transformerFactory;

	/**
	 * コンストラクタ。
	 * 
	 * @param readerFactory
	 *            {@link Reader}のファクトリ。
	 * @throws NullPointerException
	 *             引数が null の場合。
	 */
	public XmlToNode(final ReaderFactory readerFactory) {
		this(readerFactory, UtilsConstants.TRANSFORMER_FACTORY);
	}

	/**
	 * コンストラクタ。
	 * 
	 * @param readerFactory
	 *            {@link Reader}のファクトリ。
	 * @param transformerFactory
	 *            {@link woolpack.utils.XmlTransformer}のファクトリ。
	 * @throws NullPointerException
	 *             引数のいずれかが null の場合。
	 */
	public XmlToNode(final ReaderFactory readerFactory,
			final XmlTransformerFactory transformerFactory) {
		CheckUtils.checkNotNull(readerFactory);
		CheckUtils.checkNotNull(transformerFactory);
		this.readerFactory = readerFactory;
		this.transformerFactory = transformerFactory;

	}

	/**
	 * @throws NullPointerException
	 *             引数が null の場合。
	 * @throws IllegalStateException (
	 *             {@link org.xml.sax.SAXException}または{@link IOException})DOM
	 *             ノードの生成に失敗した場合。
	 */
	public void interpret(final DomContext context) {
		final DOMResult result = new DOMResult();
		try {
			final Reader r = readerFactory.newInstance(context.getId());
			if (r == null) {
				throw new IllegalStateException(new FileNotFoundException(
						"not found : " + context.getId()));
			}
			try {
				final Source source = new StreamSource(r);
				transformerFactory.newInstance().transform(source, result);
			} finally {
				r.close();
			}
		} catch (final IOException e) {
			throw new IllegalStateException(e);
		}
		context.setNode(result.getNode());
	}
}
