

package gov.va.med.cds.client.functional.vhim400;


import static gov.va.med.cds.testharness.xml.Assert.assertXmlSimilar;
import static gov.va.med.cds.testharness.xml.Assert.assertXmlValidation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gov.va.med.cds.junit.runners.Suite;
import gov.va.med.cds.junit.runners.SuiteAwareSpringRunner;
import gov.va.med.cds.testharness.vhim400.TemplateIdHelper;
import gov.va.med.cds.testharness.vhim400.builders.FilterBuilder;
import gov.va.med.cds.testharness.xml.XmlValidator;
import gov.va.med.cds.util.StreamUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.junit.After;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;


/**
 * 
 * This is abstract class that tests reading records using clinicalDataService directly thru CDSv 3.0.
 * Each class that extends this abstract class will provide specific implementation of the clinicalDataService
 *  such as EJB, SOAP etc.
 */
@ContextConfiguration( locations = { "classpath:gov/va/med/cds/config/nonWeblogicHdr2DataSourceContext.xml" } )
@RunWith( SuiteAwareSpringRunner.class )
@SuppressWarnings( "unused" )
public abstract class AbstractClient30Test
    extends
        AbstractClientDelegatedTest
{
    private static final String Vista_SiteId_580 = "580";
    private static final String Vista_SiteId_578 = "578";

    protected static String ASSIGNINGAUTHORITY_HDR_DOD = "USDOD";
    private static final String ASSIGNING_FACILITY_HDR_DOD = "200CH";
    private static final String PATIENTIDENTITY_HDR = "test_sourceid_5000";

    private static final String XPATH_ERRORSECTION = "/clinicaldata:ClinicalData/errorSection";
    private static final String REQUEST_ID_XPATH = "/clinicaldata:ClinicalData/requestId";
    private static final String ERROR_SECTION_ERRORS_XPATH = "//clinicaldata:ClinicalData/errorSection/errors";
    private static final String ERROR_SECTION_WARNINGS_XPATH = "//clinicaldata:ClinicalData/errorSection/warnings";
    private static final String ERROR_SECTION_FATAL_ERRORS_XPATH = "//clinicaldata:ClinicalData/errorSection/fatalErrors";
    
    private static final String VITALS_HTH_XPATH = "vitalSignObservationEvents[((recordSource/namespaceId[starts-with(., '200T')]) and (status != 'E'))]";
    private static final String VITALS_VISTA_XPATH = "vitalSignObservationEvents[((recordSource/namespaceId[not(starts-with(.,'200T'))]) and (status != 'E'))]";

    @Autowired
    protected JdbcTemplate hdrJdbcTemplate;


    @Test
    @Suite( groups = "appservertest" )
    /**
     * Test to create, read and delete record for Allergy Assessments Domain via 3.0
     */
    public void testAllergiesAssessments30( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.AA_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.ALLERGY_ASSESSMENT_READ_TEMPLATE_ID;

        // Make a read request with a filter that contains resolvedIdentifiers - array index
        String[] vistaPatient521 = { "USVHA", Vista_SiteId_580, "1" };
        String[][] patientIdentifiers = { vistaPatient521 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        //can re-use and add start and end dates for second read that will focus on date ranges - if the data in both hdr and vista can be located with same dates...may need jake to change script and create data with matching dates.
        Map<String, String> entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "AllergyAssessment" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        //control xml for comparison
        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testAllergiesAssessments30/expectedReadResult.xml" ) ) );
        //read without date range
        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        XmlValidator.validateXml( readResult, TemplateIdHelper.ALLERGY_ASSESSMENT_READ_TEMPLATE_ID );
        assertEquals( String.format( "Read Result: %s", readResult ), 1,
                        DocumentHelper.parseText( readResult ).selectNodes( "//patient/allergyAssessments" ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );

        //Now make a read request with single patient read filter with date range in yyyy-MM-dd format.
        entryPointFilterMap.put( FilterBuilder.START_DATE_KEY, "1992-06-29" );
        entryPointFilterMap.put( FilterBuilder.END_DATE_KEY, "2007-06-18" );
        //control xml for comparison - with date date range...
        String expectedReadResultWithDates = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testAllergiesAssessments30/expectedReadResultWithDates.xml" ) ) );
        //reading date range
        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResultForFilterWithDateRange = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        XmlValidator.validateXml( readResultForFilterWithDateRange, TemplateIdHelper.ALLERGY_ASSESSMENT_READ_TEMPLATE_ID );
        assertEquals( String.format( "Read Result: %s", readResultForFilterWithDateRange ), 1,
                        DocumentHelper.parseText( readResultForFilterWithDateRange ).selectNodes( "//patient/allergyAssessments" ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResultForFilterWithDateRange, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultWithDates, clinicalDataResponse400 ) );
    }


    @Test
    @Suite( groups = "appservertest" )
    /**
     * Test to create, read and delete record for Intolerance Conditions Domain via 3.0
     */
    public void testIntoleranceConditions30( )
        throws Exception
    {
        //NOTE - on visual examination - data does NOT look correct - getting data for wrong patient and data without patient identifiers ...   
        String filterId = TemplateIdHelper.IC_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.INTOLERANCE_CONDITION_READ_TEMPLATE_ID;
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        // Make a read request with a filter that contains resolvedIdentifiers - array index
        String[] vistaPatient521 = { "USVHA", Vista_SiteId_580, "1" };
        String[] hdrPatient = { "USDOD", "200CH", "test_sourceid_10000" };
        String[][] patientIdentifiers = { vistaPatient521, hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        //can re-use and add start and end dates for second read that will focus on date ranges - if the data in both hdr and vista can be located with same dates...may need jake to change script and create data with matching dates.
        Map<String, String> entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "IntoleranceCondition" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        // Make a read request with single patient read filter   - without date range 
        String expectedReadResult1 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testIntoleranceConditions30/expectedReadResult1.xml" ) ) );
        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult1 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResult1, TemplateIdHelper.INTOLERANCE_CONDITION_READ_TEMPLATE_ID );
        assertXmlSimilar( detachNodesFromReadResult( readResult1, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult1, clinicalDataResponse400 ) );

        //now add dates to above ...
        //Now make a read request with single patient read filter with date range in yyyy-MM-dd format.
        entryPointFilterMap.put( FilterBuilder.START_DATE_KEY, "2007-06-06" );
        entryPointFilterMap.put( FilterBuilder.END_DATE_KEY, "2007-06-13" );

        // Make a read request with single patient read filter with date range
        String expectedReadResultDateRange = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testIntoleranceConditions30/expectedReadResultWithDateRange.xml" ) ) );
        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResultWithDateRange = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResultWithDateRange, TemplateIdHelper.INTOLERANCE_CONDITION_READ_TEMPLATE_ID );
        assertXmlSimilar( detachNodesFromReadResult( readResultWithDateRange, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultDateRange, clinicalDataResponse400 ) );

        //remove date range for the other reads
        entryPointFilterMap.remove( FilterBuilder.START_DATE_KEY );
        entryPointFilterMap.remove( FilterBuilder.END_DATE_KEY );

        // Make a read request with reduced template
        filterId = TemplateIdHelper.IC_SINGLE_PATIENT_ALL_DATA_FILTER;
        readTemplateId = TemplateIdHelper.INTOLERANCE_CONDITION_REDUCED_READ_TEMPLATE_ID;
        String expectedReadResult2 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testIntoleranceConditions30/expectedReadResult2.xml" ) ) );
        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult2 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResult2, TemplateIdHelper.INTOLERANCE_CONDITION_REDUCED_READ_TEMPLATE_ID );
        assertXmlSimilar( detachNodesFromReadResult( readResult2, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult2, clinicalDataResponse400 ) );

        // Make a read request with My Health E Vet read filter        
        filterId = TemplateIdHelper.IC_SINGLE_PATIENT_ALL_DATA_FILTER;
        readTemplateId = TemplateIdHelper.MHV_INTOLERANCE_CONDITION_READ_TEMPLATE_ID;
        String expectedReadResult3 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testIntoleranceConditions30/expectedReadResult3.xml" ) ) );
        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult3 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResult3, TemplateIdHelper.MHV_INTOLERANCE_CONDITION_READ_TEMPLATE_ID );
        assertXmlSimilar( detachNodesFromReadResult( readResult3, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult3, clinicalDataResponse400 ) );

        //Make a read request with VistA Web read filter 
        filterId = TemplateIdHelper.VW_IC_SINGLE_PATIENT_FILTER;
        readTemplateId = TemplateIdHelper.VW_INTOLERANCE_CONDITION_READ_TEMPLATE_ID;
        //add the xpath needed for this filter
        entryPointFilterMap.put( FilterBuilder.X_PATH_KEY, FilterBuilder.IC_XPATH );
        String expectedReadResult4 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testIntoleranceConditions30/expectedReadResult4.xml" ) ) );
        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult4 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResult4, TemplateIdHelper.VW_INTOLERANCE_CONDITION_READ_TEMPLATE_ID );
        assertXmlSimilar( detachNodesFromReadResult( readResult4, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult4, clinicalDataResponse400 ) );

    }


    @Test
    @Suite( groups = "appservertest" )
    /**
    * Test read record for VWAllergies and Allergies template id and filter combinations.
    */
    public void testAllergies40010( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String patientIdentifier = "testId8050";
        String templateId = TemplateIdHelper.ALLERGY_ASSESSMENT_CREATEORUPDATE_TEMPLATE_ID;
        String createRequestXml = dataGenerator.createAllergyAssessmentCreateXml( templateId, requestId, patientIdentifier );
        String createResult = clinicalDataService.createClinicalData( createRequestXml, templateId, requestId );
        assertNotNull( createResult );
        // Check for an empty error section
        assertTrue( createResult.contains( "errorSection" ) );
        assertTrue( createResult.contains( requestId ) );
        assertTrue( !createResult.contains( "errors" ) );
        assertTrue( !createResult.contains( "warning" ) );
        assertTrue( !createResult.contains( "fatalErrors" ) );
        assertTrue( !createResult.contains( "exception" ) );

        templateId = TemplateIdHelper.INTOLERANCE_CONDITION_CREATEORUPDATE_TEMPLATE_ID;
        requestId = TemplateIdHelper.getUniqueIdentifier();
        createRequestXml = dataGenerator.createDODIntoleranceConditionXml( templateId, requestId, patientIdentifier );
        createResult = clinicalDataService.createClinicalData( createRequestXml, templateId, requestId );
        assertNotNull( createResult );
        // Check for an empty error section
        assertTrue( createResult.contains( "errorSection" ) );
        assertTrue( createResult.contains( requestId ) );
        assertTrue( !createResult.contains( "errors" ) );
        assertTrue( !createResult.contains( "warning" ) );
        assertTrue( !createResult.contains( "fatalErrors" ) );
        assertTrue( !createResult.contains( "exception" ) );

        // Make a read request with a filter that contains resolvedIdentifiers
        String[] hdrPatient = { "USDOD", "200CH", patientIdentifier };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "1" };
        //String[] hdrPatient = { "USDOD", "200CH", "test_sourceid_10000" };
        String[][] patientIdentifiers = { hdrPatient, vistaPatient580 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        //can re-use and add start and end dates for second read that will focus on date ranges - if the data in both hdr can be located with same dates...may need jake to change script and create data with matching dates.
        Map<String, String> entryPointFilterMapA = new HashMap<String, String>();
        entryPointFilterMapA.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "AllergyAssessment" );
        entryPointFilterMapA.put( FilterBuilder.QUERY_NAME_KEY, "AssessementQuery" );
        entryPointFilterMapA.put( FilterBuilder.X_PATH_KEY, FilterBuilder.ASSESSMENT_XPATH );

        Map<String, String> entryPointFilterMapI = new HashMap<String, String>();
        entryPointFilterMapI.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "IntoleranceCondition" );
        entryPointFilterMapI.put( FilterBuilder.QUERY_NAME_KEY, "ICQuery" );
        entryPointFilterMapI.put( FilterBuilder.X_PATH_KEY, FilterBuilder.IC_XPATH );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMapA );
        entryPointFilterMaps.add( entryPointFilterMapI );

        // Make a read request with VW Allergies filter
        String filterId = TemplateIdHelper.VW_ALLERGY_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.VW_ALLERGIES_READ_TEMPLATE_ID;
        requestId = TemplateIdHelper.getUniqueIdentifier();

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResult, TemplateIdHelper.VW_ALLERGIES_READ_TEMPLATE_ID );
        assertTrue( !readResult.contains( "/clinicaldata:ClinicalData/errorSection" ) );

        // Check for domain entry point elements
        assertTrue( readResult.contains( "<allergyAssessments>" ) );
        assertTrue( readResult.contains( "<intoleranceConditions>" ) );

        //Test with ALLERGY filter
        filterId = TemplateIdHelper.ALLERGY_SINGLE_PATIENT_ALL_DATA_FILTER;
        readTemplateId = TemplateIdHelper.ALLERGIES_READ_TEMPLATE_ID;
        requestId = TemplateIdHelper.getUniqueIdentifier();
        entryPointFilterMapA.remove( FilterBuilder.X_PATH_KEY );
        entryPointFilterMapI.remove( FilterBuilder.X_PATH_KEY );
        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        XmlValidator.validateXml( readResult, TemplateIdHelper.ALLERGIES_READ_TEMPLATE_ID );
        assertTrue( !readResult.contains( "/clinicaldata:ClinicalData/errorSection" ) );

        // Check for domain entry point elements
        assertTrue( readResult.contains( "<allergyAssessments>" ) );
        assertTrue( readResult.contains( "<intoleranceConditions>" ) );

        doIntoleranceConditionDelete( patientIdentifier );
        doAllergyAssessmentDelete( patientIdentifier );
    }


    /***
     * Read Vita signs from both VistA & HDR. Validate result against template, and compare result against expected result. 
     * @throws IOException
     */
   @Test
    @Suite( groups = "appservertest" )
    public void testVitalRead30( )
        throws IOException
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterIdVW = TemplateIdHelper.VW_VITAL_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.VITALSIGNS_READ_TEMPLATE_ID;
        String readTemplateIdVW = TemplateIdHelper.VW_VITALSIGNS_READ_TEMPLATE_ID;
        String expectedReadResultVWVitalsignsRead40010 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVitals30/readResultVWVitlsRead40010.xml" ) ) );
       
        String expectedReadResultWithDateRangeVWVitalsignsRead40010 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVitals30/readResultWithDateRangeVWVitalsignsRead40010.xml" ) ) );

        String[] vistaPatient123 = { "USVHA", Vista_SiteId_580, "123" };
        String[] vistaPatient260 = { "USVHA", Vista_SiteId_580, "260" };
        String[] hdrPatient = { "USVHA", "605", "test_sourceid_1" };
        String[] hdrVistaPatient = { "USVHA", "660", "test_sourceid_11" };
        String[][] patientIdentifiers = { hdrPatient, hdrVistaPatient, vistaPatient123, vistaPatient260 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterForVitalSignObservationEvent = new HashMap<String, String>();
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "VitalSignObservationEvent" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.X_PATH_KEY,  FilterBuilder.VITALS_XPATH );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterForVitalSignObservationEvent );

        String readFilterVW = dataGenerator.createFilterWithResolvedIdentifiers( filterIdVW, entryPointFilterMaps, resolvedPatients );

        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.START_DATE_KEY, "2005-03-16" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.END_DATE_KEY, "2007-06-30" );

        String readFilterVWwithDateRange = dataGenerator.createFilterWithResolvedIdentifiers( filterIdVW, entryPointFilterMaps, resolvedPatients );
        
        String resultVWVitalsignsRead40010 = clinicalDataService.readClinicalData( readTemplateIdVW, readFilterVW, filterIdVW, requestId );
        
        assertXmlValidation( resultVWVitalsignsRead40010, readTemplateIdVW );
        assertXmlSimilar( detachNodesFromReadResult( resultVWVitalsignsRead40010, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultVWVitalsignsRead40010, clinicalDataResponse400 ) );     

        resultVWVitalsignsRead40010 = clinicalDataService.readClinicalData( readTemplateIdVW, readFilterVWwithDateRange, filterIdVW, requestId );
        
        assertXmlValidation( resultVWVitalsignsRead40010, readTemplateIdVW );
        assertXmlSimilar( detachNodesFromReadResult( resultVWVitalsignsRead40010, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultWithDateRangeVWVitalsignsRead40010, clinicalDataResponse400 ) );
    }


    /***
     * Write/Read Lab Tests data to/from HDR. Validate result against template, and compare result against expected result. 
     * @throws IOException
     */
    @Test
    @Suite( groups = "appservertest" )
    public void testLabCreateOrUpdate40060( )
        throws IOException
    {
        String patientIdentifier = "TestIdLab1";

        // Clean up any old test data
        doDeleteLabTests( patientIdentifier );

        String templateId = TemplateIdHelper.LAB_CREATEORUPDATE_TEMPLATE_ID;
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String createRequestXml = dataGenerator.createLabEventXml( requestId, templateId, patientIdentifier );
        String createResult = clinicalDataService.createClinicalData( createRequestXml, templateId, requestId );

        assertNotNull( createResult );
        // Check for an empty error section
        assertTrue( createResult.contains( "errorSection" ) );
        assertTrue( createResult.contains( requestId ) );
        assertTrue( !createResult.contains( "errors" ) );
        assertTrue( !createResult.contains( "warning" ) );
        assertTrue( !createResult.contains( "fatalErrors" ) );
        assertTrue( !createResult.contains( "exception" ) );

        // verify written lab data using SQL 'select' 
        verifyLabRead( patientIdentifier );
    }


    /***
     * Read Lab Chemistry Hematology data from VistA. Validate result against template, and compare result against expected result. 
     * @throws IOException
     */
  //marking all MHV Lab and RDI VISTA reads as broken - we are not reading MHV LAB and RDI from VISTA
    //@Test
    //@Suite( groups = "brokentest" )
    public void testLabChemHemRead1WithDates( )
        throws IOException
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.LAB_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.LAB_CHEM_HEM_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testLab30/expected-labchemhemread1-with-dates.xml" ) ) );

        String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "2" };
        String[][] patientIdentifiers = { vistaPatient578, vistaPatient580 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "LabTestPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "1998-01-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "1998-12-31" );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );

        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertXmlValidation( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
    }


    /***
     * Read Lab Chemistry Hematology data from VistA. Validate result against template, and compare result against expected result. 
     * @throws IOException
     */
  //marking all MHV Lab and RDI VISTA reads as broken - we are not reading MHV LAB and RDI from VISTA
    //@Test
    //@Suite( groups = "brokentest" )
    public void testMHVLabChemHemRead1WithDates( )
        throws IOException
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.LAB_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.MHV_LAB_CHEM_HEM_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testLab30/expected-mhvlabchemhemread1-with-dates.xml" ) ) );

        String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "2" };
        String[][] patientIdentifiers = { vistaPatient578, vistaPatient580 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "LabTestPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "1998-06-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "1998-12-31" );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );

        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertXmlValidation( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
    }

    @Test
    @Suite( groups = "appservertest" )
    public void testHdrMHVLabRead40011( )
        throws IOException
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.LAB_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.MHV_LAB_READ_TEMPLATE_ID;
        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testLab30/expected-mhvLabRead40011.xml" ) ) );
        String expectedReadResultWithDates = StreamUtil.resourceToString( new FileSystemResource( new File(
                "src/test/resources/AbstractClientTest/testLab30/expected-mhvLabRead40011-with-dates.xml" ) ) );

        String[] hdrPatient = { "USVHA", "605", "test_sourceid_519" };
       
        String[][] patientIdentifiers = { hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "LabTestPromise" );
        entryPointFilterMap.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        
        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );

        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertXmlValidation( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
        
        //now read with dates
        entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "LabTestPromise" );
        entryPointFilterMap.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        entryPointFilterMap.put( FilterBuilder.START_DATE_KEY, "2008-06-23" );
        entryPointFilterMap.put( FilterBuilder.END_DATE_KEY, "2008-06-23" );

        entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );

        result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertXmlValidation( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultWithDates, clinicalDataResponse400 ) );
        
    }
    
   /* public void testMHVLabRead40011WithDates( )
            throws IOException
        {
            String requestId = TemplateIdHelper.getUniqueIdentifier();
            String filterId = TemplateIdHelper.LAB_SINGLE_PATIENT_ALL_DATA_FILTER;
            String readTemplateId = TemplateIdHelper.MHV_LAB_READ_TEMPLATE_ID;
            String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                            "src/test/resources/AbstractClientTest/testLab30/expected-mhvLabRead40011-with-dates.xml" ) ) );

            String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
            String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "2" };

            String[][] patientIdentifiers = { vistaPatient578, vistaPatient580 };
            List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

            Map<String, String> entryPointFilterMap = new HashMap<String, String>();
            entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "LabTestPromise" );
            entryPointFilterMap.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
            entryPointFilterMap.put( FilterBuilder.START_DATE_KEY, "1998-06-01" );
            entryPointFilterMap.put( FilterBuilder.END_DATE_KEY, "1998-12-31" );

            List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
            entryPointFilterMaps.add( entryPointFilterMap );

            String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );

            String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
            assertXmlValidation( result, readTemplateId );
            assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                            detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
        }*/


    @Test
    @Suite( groups = "appservertest" )
    public void testTiu( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.TIU_SINGLE_PATIENT_DETAIL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.TIU_DOCUMENT_DETAIL_READ;
        String patientIdentity = "1";
        String assigningAuthority = "USVHA";
        String recordIdentity = "755";
        String recordNamespaceId = "580_8925";
        String recordUniversalId = "";
        String recordUniversalIdType = "";
        String XPATH_CLINICALDOCUMENTEVENT = "//patient/clinicalDocumentEvents/clinicalDocumentEvent";
        String XPATH_DOCUMENTTEXT = "//patient/clinicalDocumentEvents/clinicalDocumentEvent/documentTexts/documentText";
        String XPATH_DOCUMENTUPDATEEVENTS = "//patient/clinicalDocumentEvents/clinicalDocumentEvent/documentUpdateEvents/documentUpdateEvent";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentity };
        String[][] patientIdentifiers = { vistaPatient580 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        // Make a read request with single patient TIU document detail filter
        String expectedReadResultDetail = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testTiu/expectedResultDetail.xml" ) ) );
        String readFilter = dataGenerator.createTiuSinglePatientDetailedDataFilter( filterId, resolvedPatients, recordIdentity, recordNamespaceId,
                        recordUniversalId, recordUniversalIdType );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );
        assertEquals( 1, DocumentHelper.parseText( readResult ).selectNodes( XPATH_CLINICALDOCUMENTEVENT ).size() );
        assertEquals( 9, DocumentHelper.parseText( readResult ).selectNodes( XPATH_DOCUMENTTEXT ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableTIUClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultDetail, configurableTIUClinicalDataResponse ) );

        filterId = TemplateIdHelper.TIU_SINGLE_PATIENT_LIST_DATA_FILTER;
        readTemplateId = TemplateIdHelper.TIU_DOCUMENT_LIST_READ;
        String documentClassValue = "3";
        String[] documentTypeValues = { "4696095", "4696107", "4697146", "4696112", "4696113", "4696119", "4696120", "4696125", "4696444" };

        // Make a read request with single patient list filter - no date range 14 records
        String expectedReadResultList1 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testTiu/expectedResultList1.xml" ) ) );
        readFilter = dataGenerator.createTiuSinglePatientListDataFilter( resolvedPatients, filterId, documentClassValue, null, null, null );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );
        // Was 14 now 6
        assertEquals( 6, DocumentHelper.parseText( readResult ).selectNodes( XPATH_CLINICALDOCUMENTEVENT ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableTIUClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList1, configurableTIUClinicalDataResponse ) );

        // Make a read request with single patient list filter with date range - 6 records (one of which has a null reference_date)
        String expectedReadResultList2 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testTiu/expectedResultList2.xml" ) ) );
        readFilter = dataGenerator.createTiuSinglePatientListDataFilter( resolvedPatients, filterId, documentClassValue, null, "1994-01-01",
                        "1994-12-31" );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        
        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );

        //Was 6 now 1 
        /*assertEquals( String.format( "Read Result: %s", readResult ), 1,
                        DocumentHelper.parseText( readResult ).selectNodes( XPATH_CLINICALDOCUMENTEVENT ).size() );*/
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableTIUClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList2, configurableTIUClinicalDataResponse ) );

        // Make a read request with single patient list filter with documentType and date range - 1 record
        String expectedReadResultList3 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testTiu/expectedResultList3.xml" ) ) );
        readFilter = dataGenerator.createTiuSinglePatientListDataFilter( resolvedPatients, filterId, null, documentTypeValues, "1996-11-08",
                        "1996-11-08" );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        
        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );

        //Was 1 now 2
        /*assertEquals( 1, DocumentHelper.parseText( readResult ).selectNodes( XPATH_CLINICALDOCUMENTEVENT ).size() );*/
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableTIUClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList3, configurableTIUClinicalDataResponse ) );

        // TIU read request for DocumentUpdateEvents
        String expectedReadResultList4 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testTiu/expectedResultList4.xml" ) ) );

        patientIdentity = "711";
        String[] vistaPatient580_1 = { assigningAuthority, Vista_SiteId_580, patientIdentity };
        String[][] patientIdentifiers_1 = { vistaPatient580_1 };
        List<Map<String, String>> resolvedPatients_1 = getResolvedPatients( patientIdentifiers_1 );

        readFilter = dataGenerator.createTiuSinglePatientListDataFilter( resolvedPatients_1, filterId, documentClassValue, null, null, null );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );
        assertEquals( 73, DocumentHelper.parseText( readResult ).selectNodes( XPATH_CLINICALDOCUMENTEVENT ).size() );
        assertEquals( 4, DocumentHelper.parseText( readResult ).selectNodes( XPATH_DOCUMENTUPDATEEVENTS ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableTIUClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList4, configurableTIUClinicalDataResponse ) );
    }


    //@Test
    //@Suite( groups = "brokentest" )
    /*
     * needs to be revisited
     */
    public void testTiuWithBadTemplateId( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.TIU_SINGLE_PATIENT_DETAIL_DATA_FILTER;
        String badTemplateId = "TiuDocumentRead40012";
        String patientIdentity = "117";
        String assigningFacility = Vista_SiteId_580;
        String assigningAuthority = "USVHA";
        String recordIdentity = "17";
        String recordNamespaceId = "580";
        String recordUniversalId = "";

        // Make a good read request with single patient TIU document detail filter using a bad response templateId
        String readFilter = dataGenerator.createTiuSinglePatientDetailedDataFilter( filterId, patientIdentity, assigningFacility, assigningAuthority,
                        recordIdentity, recordNamespaceId, recordUniversalId );
        String readResult = clinicalDataService.readClinicalData( badTemplateId, readFilter, filterId, requestId );
        assertTrue( readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, TemplateIdHelper.CDS_RESPONSE_ID );
        assertTrue( readResult.contains( "<exception>gov.va.med.cds.request.ValidationException</exception>" ) );
        assertTrue( readResult.contains( "<exceptionMessage>CANT_MATCH_TEMPLATE_TO_DELEGATE</exceptionMessage>" ) );
        assertTrue( readResult.contains( "<errorCode>CANT_MATCH_TEMPLATE_TO_DELEGATE</errorCode>" ) );
        assertTrue( readResult
                        .contains( "<displayMessage>Can not match template TiuDocumentRead40012 to available service delegate.</displayMessage>" ) );
    }


    @Test
    @Suite( groups = "appservertest" )
    public void testNonVaMeds( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.NONVA_MEDICATIONS_READ2_TEMPLATE_ID;
        String STATUS_ACTIVE = "ACTIVE";
        String STATUS_DISCONTINUED = "DISCONTINUED";
        String patientIdentityActive = "100839";
        String patientIdentityDiscontinued2 = "25";
        String patientIdentityDiscontinued1 = "69";
        String assigningAuthority = "USVHA";
        String XPATH_NONVAMEDICATIONEVENTS = "//patient/nonVaMedicationEvents/nonVaMedicationEvent";
        String XPATH_STATUS_DISCONTINUED = "//patient/nonVaMedicationEvents/nonVaMedicationEvent/status";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentityActive };
        String[][] patientIdentifiers = { vistaPatient580 };
        List<Map<String, String>> resolvedPatientList = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "NonVaMedicationEvent" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "NonVAMedicationsRead2.NonVAMedication.patient" );
        List<Map<String, String>> entryPointFilterList = new ArrayList<Map<String, String>>();
        entryPointFilterList.add( entryPointFilter );

        String expectedReadResultList1 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testNonVaMed/expectedReadResult1.xml" ) ) );

        String readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, null );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );

        // Expecting 1
        assertEquals( 1, DocumentHelper.parseText( readResult ).selectNodes( XPATH_NONVAMEDICATIONEVENTS ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableNonVAMedsClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList1, configurableNonVAMedsClinicalDataResponse ) );

        // Make a read request with single patient filter - ACTIVE status, no date range
        String expectedReadResultList2 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testNonVaMed/expectedReadResult2.xml" ) ) );
        readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, STATUS_ACTIVE );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );

        // Expecting 1
        assertEquals( 1, DocumentHelper.parseText( readResult ).selectNodes( XPATH_NONVAMEDICATIONEVENTS ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableNonVAMedsClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList2, configurableNonVAMedsClinicalDataResponse ) );

        String[] vistaPatient580_1 = { assigningAuthority, Vista_SiteId_580, patientIdentityDiscontinued2 };
        String[][] patientIdentifiersDiscontinued2 = { vistaPatient580_1 };
        List<Map<String, String>> resolvedPatientList2 = getResolvedPatients( patientIdentifiersDiscontinued2 );

        //No vistA data currently available Nov 15 2012
        /*
        String expectedReadResultList3 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testNonVaMed/expectedResultList3.xml" ) ) );
        readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList2, STATUS_DISCONTINUED );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );

        // Expecting 0
        assertEquals( 0, DocumentHelper.parseText( readResult ).selectNodes( XPATH_STATUS_DISCONTINUED ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableNonVAMedsClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList3, configurableNonVAMedsClinicalDataResponse ) );

        String[] vistaPatient580_11 = { assigningAuthority, Vista_SiteId_580, patientIdentityDiscontinued1 };
        String[][] resolvedPatientDiscontinued1 = { vistaPatient580_11 };
        List<Map<String, String>> resolvedPatientList1 = getResolvedPatients( resolvedPatientDiscontinued1 );

        String expectedReadResultList4 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testNonVaMed/expectedResultList4.xml" ) ) );
        readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList1, STATUS_DISCONTINUED );
        readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !readResult.contains( "<errorSection>" ) );
        XmlValidator.validateXml( readResult, readTemplateId );

        // Expecting 1
        assertEquals( 0, DocumentHelper.parseText( readResult ).selectNodes( XPATH_STATUS_DISCONTINUED ).size() );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableNonVAMedsClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResultList4, configurableNonVAMedsClinicalDataResponse ) );*/
    }


   // @Test
   // @Suite( groups = "brokentest" )
    /*
     * needs to be revisited
     */
    public void testNonVaMedsWithNullParams( )
        throws Exception
    {
        String readResult = clinicalDataService.readClinicalData( null, null, null, null );
        assertTrue( readResult.contains( "<errorSection>" ) );
    }


    @Test
    @Suite( groups = "brokentest" )
    public void testImmunizationEvents( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.IMMUNIZATION_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.IMMUNIZATIONS_READ3_TEMPLATE_ID;

        String assigningAuthority = "USVHA";
        String patientIdentity = "84";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentity };
        String[][] patientIdentifiers = { vistaPatient580 };
        List<Map<String, String>> resolvedPatientList = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "ImmunizationEvent" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "ImmunizationRead2.ImmunizationEvent.immunizationEvents" );

        List<Map<String, String>> entryPointFilterList = new ArrayList<Map<String, String>>();
        entryPointFilterList.add( entryPointFilter );

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testImmunizationEvent/expectedReadResult1.xml" ) ) );

        String readFilter = dataGenerator.createSinglePatientFilter( filterId, entryPointFilterList, resolvedPatientList );

        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertTrue( !readResult.contains( "<errorSection>" ) );

        XmlValidator.validateXml( readResult, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableImmunizationEventClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResult, configurableImmunizationEventClinicalDataResponse ) );
    }


    @Test
    @Suite( groups = "brokentest" )
    public void testSkintestProcedures( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.SKINTEST_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.SKINTEST_READ3_TEMPLATE_ID;

        String assigningAuthority = "USVHA";
        String patientIdentity = "34";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentity };
        String[][] patientIdentifiers = { vistaPatient580 };
        List<Map<String, String>> resolvedPatientList = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "SkinTestProcedure" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "SkintestRead2.SkinTestProcedure.skinTestProcedures" );

        List<Map<String, String>> entryPointFilterList = new ArrayList<Map<String, String>>();
        entryPointFilterList.add( entryPointFilter );

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testSkintestProcedure/expectedReadResult1.xml" ) ) );

        String readFilter = dataGenerator.createSinglePatientFilter( filterId, entryPointFilterList, resolvedPatientList );

        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !readResult.contains( "<errorSection>" ) );

        XmlValidator.validateXml( readResult, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableSkintestProcedureClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResult, configurableSkintestProcedureClinicalDataResponse ) );
    }


    @Test
    @Suite( groups = "appservertest" )
    public void testProblemList( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.PROBLEMLIST_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.PROBLEM_LIST_TEMPLATE_ID;
        String assigningAuthority = "USVHA";
        String patientIdentity = "74";
        String startDate = "1900-01-01";
        String endDate = "2050-12-31";
        String OPTION_PARAM_STATUS = "status";
        String OPTION_PARAM_CONDITION = "condition";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentity };
        String[][] patientIdentifiers = { vistaPatient580 };
        List<Map<String, String>> resolvedPatientList = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "HealthConcern" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "ID" );

        List<Map<String, String>> entryPointFilterList = new ArrayList<Map<String, String>>();
        entryPointFilterList.add( entryPointFilter );

        Map<String, String> optionalParamsMap = new LinkedHashMap<String, String>();
        optionalParamsMap.clear();
        optionalParamsMap.put( OPTION_PARAM_STATUS, "A" );
        optionalParamsMap.put( OPTION_PARAM_CONDITION, "H" );

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testProblemList/expectedReadResult1.xml" ) ) );
        String readFilter = dataGenerator.buildProblemListFilterElementWithResolvedIdentfiers( filterId, entryPointFilterList, resolvedPatientList,
                        startDate, endDate, optionalParamsMap );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertTrue( !readResult.contains( "<errorSection>" ) );

        XmlValidator.validateXml( readResult, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( readResult, configurableHealthConcernClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResult, configurableHealthConcernClinicalDataResponse ) );
    }

   @Test
    @Suite( groups = "appservertest" )
    public void testOutpatientPharmacyRead( )
        throws Exception
    {
        String XPATH_OUTPATIENTMEDICATIONPROMISES = "//patient/outpatientMedicationPromises/outpatientMedicationPromise";
        String XPATH_ACTIVITYLOGS = "//activitiesLog/activityLog";
        String XPATH_REFILLDISPENSES = "//refillDispenses/refillDispense";
        String XPATH_PARTIALDISPENSES = "//partialDispenses/partialDispense";
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.OUTPATIENTPHARMACY_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.PHARMACY_3X_READ_TEMPLATE_ID;

        //String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File("src/test/resources/AbstractClientTest/testOutpatientPharmacy30/expectedReadResult1.xml" ) ) );
        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File("src/test/resources/AbstractClientTest/testOutpatientPharmacy30/expectedReadResult2.xml" ) ) );

        String[] hdrPatient = { "USDOD", "200CH", "test_sourceid_5000" };
        String[][] patientIdentifiers = { hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "2007-01-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "2007-12-31" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );

        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );
        XmlValidator.validateXml( result, readTemplateId );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_OUTPATIENTMEDICATIONPROMISES ).size() > 0 );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_ACTIVITYLOGS ).size() > 0 );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_REFILLDISPENSES ).size() > 0 );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_PARTIALDISPENSES ).size() > 0 );

        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );

    }

    
    @Test
    @Suite( groups = "appservertest" )
    public void testVWOutpatientPharmacyRead( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.OUTPATIENTPHARMACY_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.VW_PHARMACY_3X_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVWOutpatientPharmacyRead1/expectedReadResult1.xml" ) ) );

        String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "1" };
        String[] hdrPatient = { "USDOD", "200CH", "test_sourceid_5000" };
        String[][] patientIdentifiers = { vistaPatient578, vistaPatient580, hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "1998-01-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "2008-12-31" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );
        XmlValidator.validateXml( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
    }


    @Test
    @Suite( groups = "appservertest" )
    public void testVistaPharmacyRead40010CancelDate( )
        throws Exception
    {
        String XPATH_OUTPATIENTMEDICATIONPROMISES = "//patient/outpatientMedicationPromises";
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.PHARMACY_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testPharmacy40010/expectedVistaCancelDateReadResult1.xml" ) ) );

        String[] hdrPatient = { ASSIGNINGAUTHORITY_HDR_DOD, ASSIGNING_FACILITY_HDR_DOD, PATIENTIDENTITY_HDR };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "1" };
        String[][] patientIdentifiers = { hdrPatient, vistaPatient580 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        //start and end date same as cancel date
        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "1995-04-20" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "2050-04-20" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );

        XmlValidator.validateXml( result, readTemplateId );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_OUTPATIENTMEDICATIONPROMISES ).size() > 0 );

        assertXmlSimilar( detachNodesFromReadResult( result, configurableOutpatientMedicationPromiseClinicalDataResponse ),
                      detachNodesFromReadResult( expectedReadResult, configurableOutpatientMedicationPromiseClinicalDataResponse ) );     

    }


    @Test
    @Suite( groups = "appservertest" )
    public void testHdrPharmacyRead40010CancelDate( )
        throws Exception
    {
        String XPATH_OUTPATIENTMEDICATIONPROMISES = "//patient/outpatientMedicationPromises";
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.PHARMACY_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testPharmacy40010/expectedHdrCancelDateReadResult1.xml" ) ) );

        String[] hdrPatient = { ASSIGNINGAUTHORITY_HDR_DOD, ASSIGNING_FACILITY_HDR_DOD, PATIENTIDENTITY_HDR };
        String[][] patientIdentifiers = { hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "2007-01-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "2007-12-29" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );

        XmlValidator.validateXml( result, readTemplateId );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_OUTPATIENTMEDICATIONPROMISES ).size() > 0 );

        assertXmlSimilar( detachNodesFromReadResult( result, configurableOutpatientMedicationPromiseClinicalDataResponse ),
                        detachNodesFromReadResult( expectedReadResult, configurableOutpatientMedicationPromiseClinicalDataResponse ) );
    }


    @Test
    @Suite( groups = "appservertest" )
    public void testVWDetailOutpatientPharmacyRead( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.OUTPATIENTPHARMACY_SINGLE_PATIENT_SINGLE_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.VW_PHARMACY_READ_3X_DETAIL_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVWOutpatientPharmacyDetailRead1/expectedReadResult1.xml" ) ) );

        Map<String, String> assigningFacilityAndPatientIdentityMap = new HashMap<String, String>();
        assigningFacilityAndPatientIdentityMap.put( "200CH", "test_sourceid_5000" );
        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        Map<String, String> entryPointMap = new HashMap<String, String>();
        entryPointMap.put( "ID_1", "OutpatientMedicationPromise" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createOutpatientMedicationPromiseEntryFilterWithAdditionalQueryParameters(
                        assigningFacilityAndPatientIdentityMap, "OutpatientMedicationPromise", "USDOD", filterId, "FILLER8_75138915.8",
                        "FILLER7_78383734.8", "FILLER5_31808233.8", "FILLER17_70798258.8", "60" );

        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        assertTrue( !result.contains( "<errorSection>" ) );
        XmlValidator.validateXml( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );

    }


   // @Test
   // @Suite( groups = "brokentest" )
    public void testVistaPharmacyRead40010( )
        throws Exception
    {
        String XPATH_OUTPATIENTMEDICATIONPROMISES = "//patient/outpatientMedicationPromises";
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.PHARMACY_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testPharmacy40010/expectedReadResult1.xml" ) ) );

        String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "2" };
        String[][] patientIdentifiers = { vistaPatient578, vistaPatient580 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "1998-06-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "1998-12-31" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );

        XmlValidator.validateXml( result, readTemplateId );
        assertTrue( DocumentHelper.parseText( result ).selectNodes( XPATH_OUTPATIENTMEDICATIONPROMISES ).size() > 0 );

       assertXmlSimilar( detachNodesFromReadResult( result, configurableOutpatientMedicationPromiseClinicalDataResponse ),
                     detachNodesFromReadResult( expectedReadResult, configurableOutpatientMedicationPromiseClinicalDataResponse ) );

    }

    @Test
    @Suite( groups = "timeouttest" )
    public void testVistaOutpatientPharmacyQueryTimeout( )
        throws Exception
    {
        String XPATH_OUTPATIENTMEDICATIONPROMISES = "//patient/outpatientMedicationPromises";
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.PHARMACY_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testPharmacy40010/expectedReadResult1.xml" ) ) );

        String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
        String[][] patientIdentifiers = { vistaPatient578 };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "1998-06-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "1998-12-31" );
        entryPointFilter.put( FilterBuilder.QUERY_TIMEOUT_SECONDS, "1" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );        

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiersWithQueryTimeout( filterId, entryPointFilterMaps, resolvedPatients );
                
        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
       
        assertTrue( result.contains( "<errorSection>" ) );
        assertTrue( result.contains( "<errorCode>READ_REQUEST_DATA_SOURCE_TIMEOUT</errorCode>" ) );
        assertTrue( result.contains( "<displayMessage>A query timeout occured during the read request. Assigning Facility is 578. Patient ID is 1. Domain entry point is OutpatientMedicationPromise. Database is VISTA-578-R. The Error reason is : The query timed out with timeout value of: 1000 milliseconds.")); 
    }
    
    @Test
    @Suite( groups = "appservertest" )
    public void testVWPharmacyRead40010( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.VW_PHARMACY_READ_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testPharmacy40010/expectedReadResult2.xml" ) ) );

        String[] vistaPatient578 = { "USVHA", Vista_SiteId_578, "1" };
        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "2" };
        String[] hdrPatient = { "USDOD", "200CH", "test_sourceid_5000" };
        String[][] patientIdentifiers = { vistaPatient578, vistaPatient580, hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        entryPointFilter.put( FilterBuilder.START_DATE_KEY, "2007-01-01" );
        entryPointFilter.put( FilterBuilder.END_DATE_KEY, "2007-12-31" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );
        XmlValidator.validateXml( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
    }


    @Ignore
    //@Test
    @Suite( groups = "appservertest" )
    public void testVWDetailPharmacyRead40010( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_SINGLE_RECORD_FILTER;
        String readTemplateId = TemplateIdHelper.VW_PHARMACY_READ_DETAIL_TEMPLATE_ID;

        String expectedReadResult = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testPharmacy40010/expectedReadResult3.xml" ) ) );

        Map<String, String> assigningFacilityAndPatientIdentityMap = new HashMap<String, String>();
        assigningFacilityAndPatientIdentityMap.put( "200CH", "test_sourceid_5000" );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );

        Map<String, String> entryPointMap = new HashMap<String, String>();
        entryPointMap.put( "ID_1", "OutpatientMedicationPromise" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilter );

        String readFilter = dataGenerator.createOutpatientMedicationPromiseEntryFilterWithAdditionalQueryParameters(
                        assigningFacilityAndPatientIdentityMap, "OutpatientMedicationPromise", "USVHA", filterId, "FILLER8_75138915.8",
                        "FILLER7_78383734.8", "FILLER5_31808233.8", "FILLER17_70798258.8", "60" );

        String result = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !result.contains( "<errorSection>" ) );
        XmlValidator.validateXml( result, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( result, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResult, clinicalDataResponse400 ) );
    }


    @Test
    @Suite( groups = { "smoketest" } )
    public void testProblemListReadAuditLog( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.PROBLEMLIST_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.PROBLEM_LIST_TEMPLATE_ID;
        String assigningAuthority = "USVHA";
        String patientIdentity = "260";
        String clientName = "testClientName";
        String XPATH_HEALTH_CONCERN = "//patients/patient/healthConcerns/healthConcern";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentity };
        String[][] patientIdentifiers = { vistaPatient580 };
        List<Map<String, String>> resolvedPatientList = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilter = new HashMap<String, String>();
        entryPointFilter.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "HealthConcern" );
        entryPointFilter.put( FilterBuilder.QUERY_NAME_KEY, "ID" );

        List<Map<String, String>> entryPointFilterList = new ArrayList<Map<String, String>>();
        entryPointFilterList.add( entryPointFilter );

        // clean up CDS_AUDIT_LOG table
        clearCdsAuditLogTable();

        String readFilter = dataGenerator.buildProblemListFilterElementWithResolvedIdentfiers( filterId, entryPointFilterList, resolvedPatientList,
                        null, null, null );

        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 6000 );

        verifyCdsAuditLogData( readTemplateId, clientName, DocumentHelper.parseText( readResult ).selectNodes( XPATH_HEALTH_CONCERN ).size() );
    }


    @Test
    @Suite( groups = "appservertest" )
    /**
     * Test to create record for AllergyAssessment Domain and read using Allergy assessment filter and template id 
     */
    public void testAllergyAssessmentCreate40060( )
        throws Exception
    {

        String templateId = TemplateIdHelper.ALLERGY_ASSESSMENT_CREATEORUPDATE_TEMPLATE_ID;
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String patientIdentifier = "testId7026";

        doAllergyAssessmentDelete( patientIdentifier );

        String createRequestXml = dataGenerator.createAllergyAssessmentCreateXml( templateId, requestId, patientIdentifier );
        String createResult = clinicalDataService.createClinicalData( createRequestXml, templateId, requestId );

        assertNotNull( createResult );

        // Check for an empty error section
        assertTrue( createResult.contains( "errorSection" ) );
        assertTrue( createResult.contains( requestId ) );
        assertTrue( !createResult.contains( "errors" ) );
        assertTrue( !createResult.contains( "warning" ) );
        assertTrue( !createResult.contains( "fatalErrors" ) );
        assertTrue( !createResult.contains( "exception" ) );

        String filterId = TemplateIdHelper.AA_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.ALLERGY_ASSESSMENT_READ_TEMPLATE_ID;
        requestId = TemplateIdHelper.getUniqueIdentifier();

        String[] hdrPatient = { "USDOD", "200CH", patientIdentifier };
        String[][] patientIdentifiers = { hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "AllergyAssessment" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertNotNull( readResult );

        XmlValidator.validateXml( readResult, TemplateIdHelper.ALLERGY_ASSESSMENT_READ_TEMPLATE_ID );

        Document readResponseDocument = DocumentHelper.parseText( readResult );
        if ( readResponseDocument.getRootElement().element( "templateId" ).asXML().contains( "templateId" ) )
        {
            readResponseDocument.getRootElement().element( "templateId" ).detach();
        }

        assertXmlSimilar( detachNodesFromWriteRequest( createRequestXml ),
                        detachNodesFromReadResult( readResponseDocument.asXML(), clinicalDataResponse400 ) );

        doAllergyAssessmentDelete( patientIdentifier );

    }


    @Test
    @Suite( groups = "appservertest" )
    /**
     * Test to create record for Intolerance Conditions Domain 
     */
    public void testIntoleranceConditionCreate40060( )
        throws Exception
    {

        String templateId = TemplateIdHelper.INTOLERANCE_CONDITION_CREATEORUPDATE_TEMPLATE_ID;
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String patientIdentifier = "test_sourceid_6019";

        doIntoleranceConditionDelete( patientIdentifier );

        String createRequestXml = dataGenerator.createDODIntoleranceConditionXml( templateId, requestId, patientIdentifier );
        String createResult = clinicalDataService.createClinicalData( createRequestXml, templateId, requestId );
        assertNotNull( createResult );

        // Check for an empty error section
        assertTrue( createResult.contains( "errorSection" ) );
        assertTrue( createResult.contains( requestId ) );
        assertTrue( !createResult.contains( "errors" ) );
        assertTrue( !createResult.contains( "warning" ) );
        assertTrue( !createResult.contains( "fatalErrors" ) );
        assertTrue( !createResult.contains( "exception" ) );

        String filterId = TemplateIdHelper.IC_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.INTOLERANCE_CONDITION_READ_TEMPLATE_ID;
        requestId = TemplateIdHelper.getUniqueIdentifier();

        String[] hdrPatient = { "USDOD", "200CH", patientIdentifier };
        String[][] patientIdentifiers = { hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "IntoleranceCondition" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertNotNull( readResult );

        XmlValidator.validateXml( readResult, TemplateIdHelper.INTOLERANCE_CONDITION_READ_TEMPLATE_ID );

        Document readResponseDocument = DocumentHelper.parseText( readResult );
        if ( readResponseDocument.getRootElement().element( "templateId" ).asXML().contains( "templateId" ) )
        {
            readResponseDocument.getRootElement().element( "templateId" ).detach();
        }

        assertXmlSimilar( detachNodesFromWriteRequest( createRequestXml ),
                        detachNodesFromReadResult( readResponseDocument.asXML(), clinicalDataResponse400 ) );

        doIntoleranceConditionDelete( patientIdentifier );

    }


    @Test
    @Suite( groups = { "appservertest" } )
    public void testMHVVitalsignsRead40010( )
        throws Exception
    {
        String readTemplateId = TemplateIdHelper.MHV_VITALSIGNS_READ_TEMPLATE_ID;
        String filterId = TemplateIdHelper.MHV_VITAL_SINGLE_PATIENT_FILTER;

        String expectedReadResultMHVVitalsignsRead40010 = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVitals30/readMHVVitalsExpectedResult.xml" ) ) );
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        String[] hdrPatient = { "USVHA", "605", "test_sourceid_2" };

        String[][] patientIdentifiers = { hdrPatient };

        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterForVitalSignObservationEvent = new HashMap<String, String>();
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "VitalSignObservationEvent" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.X_PATH_KEY, FilterBuilder.VITALS_XPATH );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterForVitalSignObservationEvent );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String resultVitalsignsRead40010 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !resultVitalsignsRead40010.contains( "<status>E</status>" ) );
        assertXmlValidation( resultVitalsignsRead40010, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( resultVitalsignsRead40010, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultMHVVitalsignsRead40010, clinicalDataResponse400 ) );

    }

    @Test
    @Suite( groups = { "appservertest" } )
    //FTP Vitals test
    public void testVitalsignsRead40010( )
        throws Exception
    {
        //all data
        String readTemplateId = TemplateIdHelper.VITALSIGNS_READ_TEMPLATE_ID;
        String filterId = TemplateIdHelper.VITAL_SINGLE_PATIENT_ALL_DATA_FILTER;

        String expectedReadResultVitalsigns = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVitals30/readVitalsHdrExpectedResult1.xml" ) ) );   
        
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        String[] hdrPatient1 = { "USVHA", "605", "test_sourceid_3" };
        String[] hdrPatient2 = { "USVHA", "660", "test_sourceid_11" };
        String[] hdrPatientVista = { "USVHA", "580", "test_sourceid_11" };

        String[][] patientIdentifiers = { hdrPatient1, hdrPatient2, hdrPatientVista };

        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterForVitalSignObservationEvent = new HashMap<String, String>();
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "VitalSignObservationEvent" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.START_DATE_KEY, "2000-03-16" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.END_DATE_KEY, "2017-06-30" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.X_PATH_KEY, FilterBuilder.VITALS_XPATH );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterForVitalSignObservationEvent );
       
        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String resultVitalsignsRead40010 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !resultVitalsignsRead40010.contains( "<status>E</status>" ) );
        assertXmlValidation( resultVitalsignsRead40010, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( resultVitalsignsRead40010, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultVitalsigns, clinicalDataResponse400 ) );
        
        //hth vitals
        readTemplateId = TemplateIdHelper.VITALSIGNS_READ_TEMPLATE_ID;
        filterId = TemplateIdHelper.VITAL_SINGLE_PATIENT_ALL_DATA_FILTER;
        requestId = TemplateIdHelper.getUniqueIdentifier();

        expectedReadResultVitalsigns = StreamUtil.resourceToString( new FileSystemResource( new File("src/test/resources/AbstractClientTest/testVitals30/readVitalsHdrHTHExpectedResult1.xml" ) ) );   
 
        resolvedPatients = getResolvedPatients( patientIdentifiers );
        entryPointFilterForVitalSignObservationEvent.clear();
        
        entryPointFilterMaps.clear();
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "VitalSignObservationEvent" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.START_DATE_KEY, "2000-03-16" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.END_DATE_KEY, "2017-06-30" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.X_PATH_KEY, VITALS_HTH_XPATH );
        Map<String, String> otherQueryParametersMap = new HashMap<String, String>();
        otherQueryParametersMap.put( "vitalSignType", "TEMPERATURE" );
        entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterForVitalSignObservationEvent );
        
        readFilter = dataGenerator.createFilterWithResolvedIdentifiersWithAdditionalParams( filterId, entryPointFilterMaps, resolvedPatients, otherQueryParametersMap, VITALS_HTH_XPATH );
        resultVitalsignsRead40010 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !resultVitalsignsRead40010.contains( "<status>E</status>" ) );
        assertXmlValidation( resultVitalsignsRead40010, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( resultVitalsignsRead40010, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultVitalsigns, clinicalDataResponse400 ) );
        //vista vitals
        readTemplateId = TemplateIdHelper.VITALSIGNS_READ_TEMPLATE_ID;
        filterId = TemplateIdHelper.VITAL_SINGLE_PATIENT_ALL_DATA_FILTER;
        requestId = TemplateIdHelper.getUniqueIdentifier();

        expectedReadResultVitalsigns = StreamUtil.resourceToString( new FileSystemResource( new File(
                        "src/test/resources/AbstractClientTest/testVitals30/readVitalsHdrVistaExpectedResult1.xml" ) ) ); 

        resolvedPatients = getResolvedPatients( patientIdentifiers );
        entryPointFilterForVitalSignObservationEvent.clear();
        otherQueryParametersMap.clear();
        entryPointFilterMaps.clear();
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "VitalSignObservationEvent" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.QUERY_NAME_KEY, "queryName" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.START_DATE_KEY, "2000-03-16" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.END_DATE_KEY, "2017-06-30" );
        entryPointFilterForVitalSignObservationEvent.put( FilterBuilder.X_PATH_KEY, VITALS_VISTA_XPATH );
        otherQueryParametersMap.put( "vitalSignType", "TEMPERATURE" );
        entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterForVitalSignObservationEvent );
        
        readFilter = dataGenerator.createFilterWithResolvedIdentifiersWithAdditionalParams( filterId, entryPointFilterMaps, resolvedPatients, otherQueryParametersMap, VITALS_VISTA_XPATH );
        resultVitalsignsRead40010 = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertTrue( !resultVitalsignsRead40010.contains( "<status>E</status>" ) );
        assertXmlValidation( resultVitalsignsRead40010, readTemplateId );
        assertXmlSimilar( detachNodesFromReadResult( resultVitalsignsRead40010, clinicalDataResponse400 ),
                        detachNodesFromReadResult( expectedReadResultVitalsigns, clinicalDataResponse400 ) );
        

    }

    private void doIntoleranceConditionDelete( String pid )
    {
        hdrJdbcTemplate.update( "DELETE FROM allergy_comment_v WHERE allergy_comment_event_id IN (SELECT allergy_comment_event_id FROM allergy_comment_event_v WHERE allergy_id in (SELECT allergy_id FROM allergy30_v WHERE patient_identity = '"
                        + pid + "'))" );
        hdrJdbcTemplate.update( "DELETE FROM allergy_comment_event_v WHERE allergy_id in (SELECT allergy_id FROM allergy30_v WHERE patient_identity = '"
                        + pid + "')" );
        hdrJdbcTemplate.update( "DELETE FROM drug_ingredient_v WHERE allergy_id in (SELECT allergy_id FROM allergy30_v WHERE patient_identity = '"
                        + pid + "')" );
        ;
        hdrJdbcTemplate.update( "DELETE FROM drug_class_v WHERE allergy_id in (SELECT allergy_id FROM allergy30_v WHERE patient_identity = '" + pid
                        + "')" );
        hdrJdbcTemplate.update( "DELETE FROM allergy_pract_part_v WHERE allergy_id in (SELECT allergy_id FROM allergy30_v WHERE patient_identity = '"
                        + pid + "')" );
        hdrJdbcTemplate.update( "DELETE FROM reaction_v WHERE allergy_id in (SELECT allergy_id FROM allergy30_v WHERE patient_identity = '" + pid
                        + "')" );
        hdrJdbcTemplate.update( "DELETE FROM allergy30_v WHERE patient_identity = '" + pid + "'" );

    }


    private void doAllergyAssessmentDelete( String pid )
    {
        hdrJdbcTemplate.update( "DELETE FROM ALLERGY_ASSESSMENT30_V where patient_identity = '" + pid + "'" );
    }


    @SuppressWarnings( "unchecked" )
    @Test
    @Suite( groups = "appservertest" )
    /**
     * Test to create record for Pharmacy Create Domain
     */
    public void testPharmacyCreateOrUpdate40060( )
        throws Exception
    {
        String templateId = TemplateIdHelper.PHARMACY_CREATEORUPDATE_TEMPLATE_ID;
        String patientIdentifier = "test_sourceid_7777";
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        // Delete old records
        doOutpatientPharmacyDelete( patientIdentifier );

        // Create a record
        String createRequestXml = dataGenerator.createDODOutpatientMedicationPromiseXml( templateId, requestId, patientIdentifier );
        String createResult = clinicalDataService.createClinicalData( createRequestXml, templateId, requestId );
        assertNotNull( createResult );

        // Verify no errors
        assertTrue( createResult.contains( "errorSection" ) );
        assertTrue( createResult.contains( requestId ) );
        assertTrue( !createResult.contains( "errors" ) );
        assertTrue( !createResult.contains( "warning" ) );
        assertTrue( !createResult.contains( "fatalErrors" ) );
        assertTrue( !createResult.contains( "exception" ) );

        // Make a read request with Rx Single Patient All Data Filter
        String filterId = TemplateIdHelper.RX_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.PHARMACY_READ_TEMPLATE_ID;
        requestId = TemplateIdHelper.getUniqueIdentifier();

        String[] hdrPatient = { "USDOD", "200CH", patientIdentifier };
        String[][] patientIdentifiers = { hdrPatient };
        List<Map<String, String>> resolvedPatients = getResolvedPatients( patientIdentifiers );

        Map<String, String> entryPointFilterMap = new HashMap<String, String>();
        entryPointFilterMap.put( FilterBuilder.DOMAIN_ENTRYPOINT_KEY, "OutpatientMedicationPromise" );

        List<Map<String, String>> entryPointFilterMaps = new ArrayList<Map<String, String>>();
        entryPointFilterMaps.add( entryPointFilterMap );

        String readFilter = dataGenerator.createFilterWithResolvedIdentifiers( filterId, entryPointFilterMaps, resolvedPatients );
        String readResult = clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        assertNotNull( readResult );

        XmlValidator.validateXml( readResult, TemplateIdHelper.PHARMACY_READ_TEMPLATE_ID );
        Document readResponseDocument = DocumentHelper.parseText( readResult );

        // Get create recordIdentifier Element
        Document createRequestDocument = DocumentHelper.parseText( createRequestXml );
        List<Element> createRecordIdentiferList = ( List<Element> )createRequestDocument
                        .selectNodes( "//outpatientMedicationPromises/recordIdentifier" );
        assertNotNull( createRequestDocument );
        Element createRecordIdentifier = ( Element )createRecordIdentiferList.get( 0 );

        // Get response recordIdentifer Element
        List<Element> readRecordsList = ( List<Element> )readResponseDocument.selectNodes( "//outpatientMedicationPromises/recordIdentifier" );
        assertNotNull( readRecordsList );
        assert ( readRecordsList.size() == 1 );
        Element readRecordIdentifier = ( Element )readRecordsList.get( 0 );

        assert ( ( createRecordIdentifier.asXML() ).equals( readRecordIdentifier.asXML() ) );

        // Delete old records
        doOutpatientPharmacyDelete( patientIdentifier );
    }


    private void doOutpatientPharmacyDelete( String patientId )
    {
        hdrJdbcTemplate.update( "DELETE FROM activity_log_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM PHARMACY_INSTRUCTION_V WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM OUTPPHARM_TREATMENT_FACTOR_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM MEDICATION_INSTRUCTION_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM dispense_comment_v where OUTPATIENT_MED_DSP_ID in ( select OUTPATIENT_MED_DSP_ID from outpatient_med_dsp_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "'))" );
        hdrJdbcTemplate.update( "DELETE FROM current_provider_comment_v where OUTPATIENT_MED_DSP_ID in ( select OUTPATIENT_MED_DSP_ID from outpatient_med_dsp_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "'))" );
        hdrJdbcTemplate.update( "DELETE FROM outpatient_med_dsp_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM patient_INSTRUCTION_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM expanded_patient_instruction_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM other_patient_instruction_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM cancel_comment_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM outppharm_sig_v WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
        hdrJdbcTemplate.update( "DELETE FROM OUTPATIENT_MED_PRM30_V WHERE OUTPATIENT_MED_PRM_ID IN (SELECT OUTPATIENT_MED_PRM_ID FROM OUTPATIENT_MED_PRM30_V WHERE PATIENT_IDENTITY = '"
                        + patientId + "')" );
    }


    protected void clearCdsAuditLogTable( )
    {
        this.hdrJdbcTemplate.update( "DELETE FROM CDS_AUDIT_LOG3" );
    }


    protected void verifyCdsAuditLogData( String templateId, String clientName, int responseLength )
    {
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM CDS_AUDIT_LOG3 al, TEMPLATE_NAME tn WHERE al.TEMPLATE_NAME_ID = tn.TEMPLATE_NAME_ID AND tn.TEMPLATE_NAME_IDENTIFIER = '" );
        sqlBuilder.append( templateId );
        sqlBuilder.append( "'" );
        sqlBuilder.append( " AND RESPONSE_LENGTH = " );
        sqlBuilder.append( responseLength );
        sqlBuilder.append( " AND CLIENT_IDENTIFIER = '" );
        sqlBuilder.append( clientName );
        sqlBuilder.append( "'" );

        int retVal = hdrJdbcTemplate.queryForObject( sqlBuilder.toString(), Integer.class );

        Assert.assertEquals( 1, retVal );
    }


    protected void verifyLabRead( String patientId )
    {
        assertTrue( hdrJdbcTemplate
                        .queryForObject( "SELECT COUNT(1) FROM CHEMRSLT_COMMENT_V WHERE CHEMRSLT_COMMENT_EVENT_ID IN( SELECT CHEMRSLT_COMMENT_EVENT_ID FROM CHEMRSLT_COMMENT_EVENT_V WHERE CHEMISTRY_RESULT_ID IN ( SELECT CHEMISTRY_RESULT_ID FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN ( SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "'))))", Integer.class ) == 16);
        assertTrue( hdrJdbcTemplate
                        .queryForObject("SELECT COUNT(1) FROM LAB_OBSERVATION_METHOD_V WHERE CHEMISTRY_RESULT_ID IN ( SELECT CHEMISTRY_RESULT_ID FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT  LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "')))", Integer.class ) == 8 );
        assertTrue( hdrJdbcTemplate
                        .queryForObject( "SELECT COUNT(1) FROM CHEMRSLT_COMMENT_EVENT_V WHERE CHEMISTRY_RESULT_ID IN ( SELECT CHEMISTRY_RESULT_ID FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT  LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "')))", Integer.class ) == 8 );
        assertTrue( hdrJdbcTemplate
                        .queryForObject( "SELECT COUNT(1) FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT  LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "'))", Integer.class ) == 4 );
        assertTrue( hdrJdbcTemplate
                        .queryForObject( "SELECT COUNT(1) FROM LAB_COMMENT_V WHERE LAB_COMMENT_EVENT_ID IN (SELECT  LAB_COMMENT_EVENT_ID FROM LAB_COMMENT_EVENT_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "'))", Integer.class ) == 4 );
        assertTrue( hdrJdbcTemplate
                        .queryForObject( "SELECT COUNT(1) FROM LAB_COMMENT_EVENT_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY ='"
                                        + patientId + "')", Integer.class ) == 2 );
        assertTrue( hdrJdbcTemplate
                        .queryForObject( "SELECT COUNT(1) FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "')", Integer.class ) == 2 );
        assertTrue( hdrJdbcTemplate
             .queryForObject( "SELECT COUNT(1) FROM LAB_PATIENT_VISIT_V WHERE LAB_PATIENT_VISIT_ID = (SELECT LAB_PATIENT_VISIT_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                                        + patientId + "')", Integer.class ) == 1 );
        assertTrue( hdrJdbcTemplate.queryForObject( "SELECT COUNT(1) FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '" + patientId + "'", Integer.class ) == 1 );
    }


    protected void doDeleteLabTests( String patientId )
    {
        List<String> labPatientVisitIds = null;
        int recordExists = 0;

        recordExists = hdrJdbcTemplate.queryForObject( "SELECT COUNT(1) FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '" + patientId + "'", Integer.class );

        if ( recordExists > 0 )
        {
            labPatientVisitIds = hdrJdbcTemplate.queryForList( "SELECT LAB_PATIENT_VISIT_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "'", String.class );

            hdrJdbcTemplate.update( "DELETE FROM CHEMRSLT_COMMENT_V WHERE CHEMRSLT_COMMENT_EVENT_ID IN( SELECT CHEMRSLT_COMMENT_EVENT_ID FROM CHEMRSLT_COMMENT_EVENT_V WHERE CHEMISTRY_RESULT_ID IN ( SELECT CHEMISTRY_RESULT_ID FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN ( SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "'))))" );
            hdrJdbcTemplate.update( "DELETE FROM LAB_OBSERVATION_METHOD_V WHERE CHEMISTRY_RESULT_ID IN ( SELECT CHEMISTRY_RESULT_ID FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT  LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "')))" );
            hdrJdbcTemplate.update( "DELETE FROM CHEMRSLT_COMMENT_EVENT_V WHERE CHEMISTRY_RESULT_ID IN ( SELECT CHEMISTRY_RESULT_ID FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT  LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "')))" );
            hdrJdbcTemplate.update( "DELETE FROM CHEMISTRY_RESULT_V WHERE LAB_TEST_ID IN ( SELECT  LAB_TEST_ID FROM LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "'))" );
            //hdrJdbcTemplate.update( "" + patientId + "'))))" );

            hdrJdbcTemplate.update( "DELETE FROM LAB_COMMENT_V WHERE LAB_COMMENT_EVENT_ID IN (SELECT  LAB_COMMENT_EVENT_ID FROM LAB_COMMENT_EVENT_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "'))" );
            hdrJdbcTemplate.update( "DELETE FROM LAB_COMMENT_EVENT_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY ='"
                            + patientId + "')" );
            hdrJdbcTemplate.update( "DELETE LAB_TEST_V WHERE LAB_TEST_PRM_ID IN (SELECT LAB_TEST_PRM_ID FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '"
                            + patientId + "')" );
            hdrJdbcTemplate.update( "DELETE FROM LAB_TEST_PRM_V WHERE PATIENT_IDENTITY = '" + patientId + "'" );

            if ( null != labPatientVisitIds && labPatientVisitIds.size() > 0 )
            {
                for ( String labPatientVisitId : labPatientVisitIds )
                {
                    hdrJdbcTemplate.update( "DELETE FROM LAB_PATIENT_VISIT_V WHERE LAB_PATIENT_VISIT_ID = '" + labPatientVisitId + "'" );
                }
            }
        }
    }


    @After
    @Suite( groups = "smoketest" )
    public void AfterAbstractClient30TestMethodTearDown( )
    {
        clearCdsAuditLogTable();
    }
}
