import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.io.InputStreamReader;

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.junit.Before;
import org.junit.Test;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class CastorMappingTest
{
	private static final String	TEST_SCHEMA	= "castor_mapping_test_schema.xsd";
	private static final String	MAPPING		= "castor_mapping.xml";
	private static final String	TEST_DATA	= "castor_mapping_test.xml";

	private InputSource			mappingSource;
	private InputSource			schemaSource;
	private InputStreamReader	testData;

	@Before
	public void setUp()
	{
		mappingSource = new InputSource( this.getClass().getResourceAsStream(
				MAPPING ) );
		assertNotNull( mappingSource );
		schemaSource = new InputSource( this.getClass().getResourceAsStream(
				TEST_SCHEMA ) );
		assertNotNull( schemaSource );
		testData = new InputStreamReader( this.getClass().getResourceAsStream(
				TEST_DATA ) );
		assertNotNull( testData );

	}

	/**
	 * Highlights an issue with castor mapping while using a XML schema.
	 *
	 * @throws ValidationException
	 * @throws MarshalException
	 *
	 */
	@Test
	public void test_castorMapping() throws MappingException, MarshalException,
			ValidationException
	{

		Mapping mapping = new Mapping();
		mapping.loadMapping( mappingSource );

		Unmarshaller unmarshaller = new Unmarshaller( mapping );

		// used to load the schema
		unmarshaller.setEntityResolver( new EntityResolver()
		{
			public InputSource resolveEntity( String publicId, String systemId )
					throws SAXException, IOException
			{
				return schemaSource;
			}
		} );

		unmarshaller.setValidation( true );
		unmarshaller.setIgnoreExtraAttributes( false );
		unmarshaller.setIgnoreExtraElements( false );

		Blackadder theFirst = ( Blackadder ) unmarshaller.unmarshal( testData );

		assertNotNull( theFirst );
	}
}
