/**
 * Marshaller.java
 * Created Jun 20, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.entities.bind;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * Marshals an object of a type into its equivalent DOM using the Castor API
 * 
 * @author Sahil Verma
 */
public class EntityMarshaller<T> {

	/**
	 * Creates a Marshaller
	 */
	protected EntityMarshaller() {
		super();
	}

	public static <T> EntityMarshaller<T> newInstance() {
		return new EntityMarshaller<T>();
	}
	
	/**
	 * Marshals the object of type T using the specified Castor mapping
	 * 
	 * @param t
	 * @param mapping
	 * @return
	 */
	public Node marshal(T t, Mapping mapping) {
		Document document = null;
		
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Marshaller marshaller = new Marshaller(document);
			
			marshaller.setMapping(mapping);
			marshaller.marshal(t);
		} catch (MarshalException e) {
			throw new RuntimeException("Failed to marshal " + t, e);
		} catch (ValidationException e) {
			throw new RuntimeException("Failed to marshal " + t, e);
		} catch (ParserConfigurationException e) {
			/* WTFF? */
		} catch (MappingException e) {
			throw new RuntimeException("Invalid mapping file", e);
		}
		
		return document;
	}
}
