package nuts.core.oxm.adapter;

import java.io.StringWriter;

import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import junit.framework.TestCase;

import nuts.core.beans.BeanHandlerFactory;
import nuts.core.beans.TestA;
import nuts.core.beans.TestB;
import nuts.core.lang.StringUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

/**
 */
public class AdapterFactoryTest extends TestCase {
	/**
	 * log
	 */
	private static Log log = LogFactory.getLog(AdapterFactoryTest.class);

	private static class TransformerErrorListener implements ErrorListener {
		public void error(TransformerException exception)
				throws TransformerException {
			throw exception;
		}

		public void fatalError(TransformerException exception)
				throws TransformerException {
			throw exception;
		}

		public void warning(TransformerException exception)
				throws TransformerException {
			log.warn(exception.getMessage(), exception);
		}
	}

	/**
	 */
	public void test01() throws Exception {
		BeanHandlerFactory.setInstance(new BeanHandlerFactory());
		
		TestB b = new TestB();
		TestA a = new TestA();
		
		b.setTestA(a);
		a.setTestB(b);
		
		AdapterFactory adapterFactory = new AdapterFactory();
		
		Document xml = adapterFactory.adaptDocument(a, "test");
		
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setErrorListener(new TransformerErrorListener());
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		
		DOMSource src = new DOMSource(xml);

		StringWriter sw = new StringWriter();
		transformer.transform(src, new StreamResult(sw));
		log.info(StringUtils.prettifyXml(sw.toString()));
	}
}
