/*
 * 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 org.xml.sax.SAXException;

import woolpack.utils.ReaderFactory;
import woolpack.utils.UtilsConstants;
import woolpack.utils.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){
		readerFactory.getClass();
		transformerFactory.getClass();
		this.readerFactory = readerFactory;
		this.transformerFactory = transformerFactory;
		
	}

	/**
	 * @throws NullPointerException 引数が null の場合。
	 * @throws RuntimeException ({@link 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 RuntimeException(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 RuntimeException(e);
		}
		context.setNode(result.getNode());
	}
}
