

package gov.va.med.cds.testharness.vhim400;


import gov.va.med.cds.testharness.util.XpathAsserterInterface;

import org.junit.Assert;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;


/**
 * Uses JaxP to compare xpath xpressions against xml instance
 */
public class Vhim400XpathAsserter
    implements
        XpathAsserterInterface
{
    private Map<String, String> namespaceResolver = new HashMap<String, String>();
    private javax.xml.xpath.XPath xpath = null;


    /**
     * Sets up namespace resolution based on VHIM namespaces
     * 
     */
    public Vhim400XpathAsserter( )
    {
        // Setup namespaces for xpath processing
        javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();

        namespaceResolver.put( "allergies", "Allergies" );
        namespaceResolver.put( "common", "Common" );
        namespaceResolver.put( "clinicaldata", "Clinicaldata" );
        namespaceResolver.put( "vitals", "Vitals" );
        namespaceResolver.put( "act", "Act" );
        namespaceResolver.put( "participation", "Participation" );

        xpath = factory.newXPath();

        xpath.setNamespaceContext( new NamespaceContext()
        {

            public String getNamespaceURI( String arg0 )
            {
                return namespaceResolver.get( arg0 );
            }


            public String getPrefix( String arg0 )
            {
                return "";
            }


            public Iterator getPrefixes( String arg0 )
            {
                return null;
            }

        } );
    }


    /* (non-Javadoc)
     * @see gov.va.med.cds.testharness.vhim3400.XpathAsserterInterface#assertXpathCompare(java.lang.String, java.lang.String, java.lang.String)
     */
    public void assertXpathCompare( String sourceXml, String xpathExpression, String controlXml )
        throws XPathExpressionException
    {
        XPathExpression expression = xpath.compile( xpathExpression );
        String result = expression.evaluate( new org.xml.sax.InputSource( new StringReader( sourceXml ) ) );
        Assert.assertEquals( result, controlXml, "The result of the xpath expression \"" + xpathExpression + "\" failed." );
    }


    /* (non-Javadoc)
     * @see gov.va.med.cds.testharness.vhim3400.XpathAsserterInterface#getXpath()
     */
    public javax.xml.xpath.XPath getXpath( )
    {
        return xpath;
    }
}
