package com.foo ;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.List ;

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;

public class UnmarshallTest {
	
	public static void main(String[] args) {
		String rootDir = "c:/castortest/working/" ;
		String dataFileName = "OrderExample.xml" ;
		String mappingFileName = "OrderMapping.xml" ;
		if (0 < args.length) {
			rootDir = args[0] ;
		}
		try {
			File inputXMLData = new File(rootDir + dataFileName) ;
			Reader inputXMLReader = new FileReader(inputXMLData) ;
			UnmarshallTest test = new UnmarshallTest() ;
			System.out.println("Reading sample data from " + rootDir + dataFileName) ;
			Order order = test.test(inputXMLReader, rootDir + mappingFileName) ;
		} catch (FileNotFoundException e) {
			e.printStackTrace() ;
		} catch (Throwable t) {
			t.printStackTrace() ;
		}
	}

	public Order test(Reader inputXMLReader, String mappingFileName) {
		try {
			Mapping testMapping= new org.exolab.castor.mapping.Mapping();
			System.out.println("Loading mapping from     " + mappingFileName) ;
			testMapping.loadMapping(mappingFileName);
			Unmarshaller unmarshaller = new Unmarshaller(Order.class);
			// unmarshaller.setIgnoreExtraElements(true) ;
			unmarshaller.setMapping(testMapping);   
			Order order = (Order)(unmarshaller.unmarshal(inputXMLReader));
			System.out.println("" + order) ;
			return order ;
		} catch (MarshalException e) {
			e.printStackTrace() ;
			throw new RuntimeException("Castor MarshalException") ;
		} catch (MappingException e) {
			e.printStackTrace();
			throw new RuntimeException("Castor mapping exception") ;
		} catch (ValidationException e) {   
			e.printStackTrace() ;
			throw new RuntimeException("XML Validation exception") ;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("IOexception") ;
		}
	}
    
}
