/**
 * EntityUnmarshaller.java
 * Created Jun 23, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.entities.bind;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.w3c.dom.Node;

/**
 * Unmarshals an object using the Castor API
 * 
 * @author Sahil Verma
 */
public class EntityUnmarshaller<T> {
	
	/**
	 * Creates an EntityUnmarshaller
	 */
	protected EntityUnmarshaller() {
	}
	
	/**
	 * Returns a new instance of the unmarshaller
	 * 
	 * @param <T>
	 * @return
	 */
	public static <T> EntityUnmarshaller<T> newInstance() {
		return new EntityUnmarshaller<T>();
	}
	
	/**
	 * Unmarshals the DOM equivalent of an object whose type is T using the specified Castor
	 * mapping
	 * 
	 * @param node
	 * @param mapping
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public T unmarshal(Node node, Mapping mapping) {
		T t = null;
		Unmarshaller unmarshaller = new Unmarshaller();
		
		try {
			unmarshaller.setMapping(mapping);
			t = (T) unmarshaller.unmarshal(node);
		} catch (MarshalException e) {
			throw new RuntimeException("Failed to unmarshal", e);
		} catch (ValidationException e) {
			throw new RuntimeException("Failed to unmarshal", e);
		} catch (MappingException e) {
			throw new RuntimeException("Invalid mapping file", e);
		}
		
		return t;
	}
}
