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

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


import org.cyberneko.html.parsers.DOMParser;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import woolpack.dom.DomContext;
import woolpack.dom.DomExpression;
import woolpack.utils.ReaderFactory;

/**
 * CyberNeko HTML Parser を使用して{@link Reader}から DOM ノードを生成する{@link DomExpression}。
 * JSE5 以外のライブラリとしてCyberNeko HTML Parser (とそれが使用する Xerces4J)を使用する。
 * @author nakamura
 *
 */
public class ToNodeUsingNeko implements DomExpression{
	private final ReaderFactory factory;
	
	/**
	 * コンストラクタ。
	 * @param factory {@link Reader}の生成器。
	 * @throws NullPointerException 引数が null の場合。
	 */
	public ToNodeUsingNeko(final ReaderFactory factory){
		factory.getClass();
		this.factory = factory;
	}

	/**
	 * @throws NullPointerException 引数が null の場合。
	 * @throws RuntimeException ({@link SAXException}または{@link IOException})DOM ノードの生成に失敗した場合。
	 */
	public void interpret(final DomContext context) {
		final DOMParser parser = new DOMParser();
		try {
			final Reader r = factory.newInstance(context.getId());
			if(r == null){
				throw new RuntimeException(new FileNotFoundException("not found: " + context.getId()));
			}
			try{
				parser.parse(new InputSource(r));
			} catch (final SAXException e) {
				throw new RuntimeException(e);
			}finally{
				r.close();
			}
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
		context.setNode(parser.getDocument());
	}
}
