

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


import gov.va.med.cds.client.functional.AbstractDataGeneratorValidatorTest;
import gov.va.med.cds.junit.runners.BeforeTestsOnce;
import gov.va.med.cds.junit.runners.Suite;
import gov.va.med.cds.junit.runners.SuiteAwareSpringRunner;
import gov.va.med.cds.testharness.sql.OracleSqlPlusConnectionStringBuilder;
import gov.va.med.cds.testharness.sql.SqlPlusRunner;
import gov.va.med.cds.testharness.vhim400.TemplateIdHelper;
import gov.va.med.cds.testharness.vhim400.builders.FilterBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;


/**
 * This test is to verify the application logging using SOAP client
 * 
 * @author DNS   thummp
 *
 */
@RunWith( SuiteAwareSpringRunner.class )
@ContextConfiguration( locations = { "classpath:gov/va/med/cds/client/functional/vhim400/soapClientTestContext.xml",
                "classpath:gov/va/med/cds/config/nonWeblogicHdr2DataSourceContext.xml",
                "classpath:gov/va/med/cds/client/functional/testDataGeneratorContext.xml",
                "classpath:gov/va/med/cds/config/appNamesContext.xml",
                "classpath:gov/va/med/cds/config/staticPropertiesContext.xml",
                "classpath:gov/va/med/cds/client/functional/logging/testAuditLoggerContext.xml" } )
public class CdsApplicationLoggingTest
    extends
        AbstractDataGeneratorValidatorTest
{
    private static final String Vista_SiteId_580 = "580";
    private static final int THREAD_SLEEP_TIME = 3000;
    private static final String INVALID_ASSIGNING_FACILITY_IN_FILTER_REQUEST_X1 = "X1";
    private static final String CDS_APP_NAME = "CDS 3.3";

    @Autowired
    private JdbcTemplate hdrJdbcTemplate;

    @Autowired
    private OracleSqlPlusConnectionStringBuilder loggerSchemaOracleSqlPlusConnectionStringBuilder;

    @Autowired
    private SqlPlusRunner sqlPlusRunner;

    @Autowired
    private String hdrSchemaName;


    @BeforeTestsOnce
    @Suite( groups = { "smoketest" } )
    public void beforeCdsApplicationLoggingTestSetUp( )
        throws Exception
    {
        sqlPlusRunner.execute( loggerSchemaOracleSqlPlusConnectionStringBuilder.getConnectionString(),
                        "src/test/resources/sql/grant_insert_permission_cds_audit_log_to_hdr.sql", hdrSchemaName );

        clearCdsAuditLogTable();
        clearHAAuditClobStrTable();
        clearHaCdsAuditLogTable();
        clearCdsApplicationLogTable();
    }


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

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test to create, read and delete record for Intolerance Conditions Domain via 3.0
     */
    public void testIntoleranceConditions30_withNullFilter( )
        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();

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testAllAllergies30_withNullFilter( )
        throws Exception
    {
        String filterId = TemplateIdHelper.ALLERGY_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.ALLERGIES_READ_TEMPLATE_ID;
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    /***
     * testRDI30 tests a multi domain read across CDS 3.X and CDS 2.X. The pharmacy read call is delegated to CDS 2.X while the allergies read
     * call is handled by CDS 3.X
     */
    public void testRdi30_withNullFilter( )
        throws Exception
    {

        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RDI_IC_RX_CANNED_FILTER_ID;
        String readTemplateId = TemplateIdHelper.RDI_INTOLERANCE_CONDITION_PHARMACY_READ_TEMPLATE_ID;

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    /***
     * Read Vita signs from both VistA & HDR. Validate result against template, and compare result against expected result. 
     * @throws IOException
     */
    @Test
    @Suite( groups = "brokentest" )
    public void testVitalRead30_withNullFilter( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.VITAL_SINGLE_PATIENT_ALL_DATA_FILTER;
        String filterIdVW = TemplateIdHelper.VW_VITAL_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.VITALSIGNS_READ_TEMPLATE_ID;
        String readTemplateIdVW = TemplateIdHelper.VW_VITALSIGNS_READ_TEMPLATE_ID;

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateIdVW, null, filterIdVW, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateIdVW, null, filterIdVW, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    public void testTiu_withNullFilter( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.TIU_SINGLE_PATIENT_DETAIL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.TIU_DOCUMENT_DETAIL_READ;

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );

        filterId = TemplateIdHelper.TIU_SINGLE_PATIENT_LIST_DATA_FILTER;
        readTemplateId = TemplateIdHelper.TIU_DOCUMENT_LIST_READ;

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    public void testNonVaMeds_withNullFilter( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.NONVA_MEDICATIONS_READ2_TEMPLATE_ID;

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyCdsAuditLogData( requestId );
    }


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

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


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

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = { "brokentest" } )
    public void testProblemListReadCdsApplicationLog_withNullFilter( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.PROBLEMLIST_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.PROBLEM_LIST_TEMPLATE_ID;

        clearCdsApplicationLogTable();
        clinicalDataService.readClinicalData( readTemplateId, null, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = { "brokentest" } )
    public void testProblemListReadCdsApplicationLog_withNullTemplateId( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.PROBLEMLIST_SINGLE_PATIENT_FILTER;
        String readTemplateId = null;

        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "260" };
        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_APPLICATION_LOG table
        clearCdsApplicationLogTable();
        String readFilter = dataGenerator.buildProblemListFilterElementWithResolvedIdentfiers( filterId, entryPointFilterList, resolvedPatientList,
                        null, null, null );
        // read request with 'null' read filter
        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
    }


    @Test
    @Suite( groups = { "smoketest" } )
    public void testProblemListReadCdsApplicationLogWithInvalidFilterXml( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.PROBLEMLIST_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.PROBLEM_LIST_TEMPLATE_ID;

        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "260" };
        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_APPLICATION_LOG table
        clearCdsApplicationLogTable();

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

        readFilter = readFilter.replaceAll( "<", "*" );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 3000 );

        verifyCdsApplicationLogData( requestId, "Invalid filterId" );
    }


    @Test
    @Suite( groups = { "smoketest" } )
    public void testProblemListReadWithNoAuditLog( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.PROBLEMLIST_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.PROBLEM_LIST_TEMPLATE_ID;

        String[] vistaPatient580 = { "USVHA", Vista_SiteId_580, "260" };
        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 );

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

        // clean up CDS_AUDIT_LOG table
        clearCdsAuditLogTable();
        clearCdsApplicationLogTable();
        clearPathwaysApplicationLogTable();
        Assert.assertEquals( 0, getCdsAuditLog() );
        Assert.assertEquals( 0, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );

        // grant insert permission on CDS_AUDIT_LOG to HDR
        sqlPlusRunner.execute( loggerSchemaOracleSqlPlusConnectionStringBuilder.getConnectionString(),
                        "src/test/resources/sql/grant_insert_permission_cds_audit_log_to_hdr.sql", hdrSchemaName );
        // revoke insert permission on CDS_AUDIT_LOG from HDR
        sqlPlusRunner.execute( loggerSchemaOracleSqlPlusConnectionStringBuilder.getConnectionString(),
                        "src/test/resources/sql/revoke_insert_permission_cds_audit_log_from_hdr.sql", hdrSchemaName );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 3000 );

        // grant insert permission on CDS_AUDIT_LOG to HDR2
        sqlPlusRunner.execute( loggerSchemaOracleSqlPlusConnectionStringBuilder.getConnectionString(),
                        "src/test/resources/sql/grant_insert_permission_cds_audit_log_to_hdr.sql", hdrSchemaName );

        Assert.assertEquals( 0, getCdsAuditLog() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );
        verifyCdsApllicationLogMessageData( "Error auditing READ message", "org.hibernate.exception.SQLGrammarException" );
    }


    @Test
    @Suite( groups = "smoketest" )
    public void testClinicalPathWithInvalidNValidVistaSites( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.NONVA_MEDICATIONS_READ2_TEMPLATE_ID;
        String patientIdentityActive = "100839";
        String assigningAuthority = "USVHA";

        String[] vistaPatient580 = { assigningAuthority, Vista_SiteId_580, patientIdentityActive };
        String[] vistaPatientX1 = { assigningAuthority, INVALID_ASSIGNING_FACILITY_IN_FILTER_REQUEST_X1, "patient_1" };
        String[][] patientIdentifiers = { vistaPatient580, vistaPatientX1 };
        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 readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, null );

        // clean up application log tables
        clearCdsApplicationLogTable();
        clearPathwaysApplicationLogTable();
        Assert.assertEquals( 0, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 3000 );

        Assert.assertEquals( 1, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );
    }


    @Test
    @Suite( groups = "smoketest" )
    public void testClinicalPathWithAllInvalidVistaSites( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.NONVA_MEDICATIONS_READ2_TEMPLATE_ID;
        //String patientIdentityActive = "100839";
        String assigningAuthority = "USVHA";

        String[] vistaPatientX1 = { assigningAuthority, INVALID_ASSIGNING_FACILITY_IN_FILTER_REQUEST_X1, "100600" };
        String[][] patientIdentifiers = { vistaPatientX1 };
        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 readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, null );

        // clean up application log tables
        clearCdsApplicationLogTable();
        clearPathwaysApplicationLogTable();
        Assert.assertEquals( 0, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 10000 );

        verifyCdsApplicationLogData( requestId, "All the Assigning Facilities mentioned in the Filter are invalid and they are" );
        
        verifyPathwaysApplicationLogForNoData( requestId, "All the Assigning Facilities mentioned in the Filter are invalid and they are" );
    }

    @Test
    @Suite( groups = "smoketest" )
    public void testClinicalPathWithInvalidVistaSiteNDFN( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.NONVA_MEDICATIONS_READ2_TEMPLATE_ID;
        //String patientIdentityActive = "100839";
        String assigningAuthority = "USVHA";

        String[] vistaPatientX1 = { assigningAuthority, INVALID_ASSIGNING_FACILITY_IN_FILTER_REQUEST_X1, "PID" };
        String[][] patientIdentifiers = { vistaPatientX1 };
        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 readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, null );

        // clean up application log tables
        clearCdsApplicationLogTable();
        clearPathwaysApplicationLogTable();
        Assert.assertEquals( 0, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 10000 );

        verifyCdsApplicationLogData( requestId, "All the Assigning Facilities mentioned in the Filter are invalid and they are" );
        
        verifyPathwaysApplicationLogForNoData( requestId, "All the Assigning Facilities mentioned in the Filter are invalid and they are" );
    }

    @Test
    @Suite( groups = "smoketest" )
    public void testClinicalPathWithInvalidTemplateId( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = "XYZ";
        //String patientIdentityActive = "100839";
        String assigningAuthority = "USVHA";

        String[] vistaPatientX1 = { assigningAuthority, "580", "123456" };
        String[][] patientIdentifiers = { vistaPatientX1 };
        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 readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, null );

        // clean up application log tables
        clearCdsApplicationLogTable();
        clearPathwaysApplicationLogTable();
        Assert.assertEquals( 0, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 10000 );

        verifyCdsApplicationLogData( requestId, "Invalid template" );
        
        verifyPathwaysApplicationLogForNoData( requestId, "Invalid template" );
    }
    
    @Test
    @Suite( groups = "smoketest" )
    public void testClinicalPathWithInvalidDFN( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.NONVAMED_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.NONVA_MEDICATIONS_READ2_TEMPLATE_ID;
        String assigningAuthority = "USVHA";

        String[] vistaPatientX1 = { assigningAuthority, "580", "pid" };
        String[][] patientIdentifiers = { vistaPatientX1 };
        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 readFilter = dataGenerator.createNonVAMedsSinglePatientDataFilter( filterId, entryPointFilterList, resolvedPatientList, null );

        // clean up application log tables
        clearCdsApplicationLogTable();
        clearPathwaysApplicationLogTable();
        Assert.assertEquals( 0, getCdsApllicationLogTableCount() );
        Assert.assertEquals( 0, getPathwaysApplicationLogTableCount() );

        clinicalDataService.readClinicalData( readTemplateId, readFilter, filterId, requestId );

        Thread.sleep( 10000 );

        verifyCdsApplicationLogData( requestId, "All datasources failed.  Unable to get data from applicable datasource(s) due to the following reason" );
        
        verifyPathwaysApplicationLogForNoData( requestId, "All datasources failed.  Unable to get data from applicable datasource(s) due to the following reason" );
    }

    @SuppressWarnings( "unused" )
    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testHAWrite( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHAAuditClobStrTable();
        String createResult = clinicalDataService.createClinicalData( "xml", TemplateIdHelper.HEALTH_ADAPTER_CREATE1_TEMPLATE_ID, null );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyHAWriteAuditLogData( requestId );
    }


    @SuppressWarnings( "unused" )
    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testHAWriteWithNullXml( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHAAuditClobStrTable();
        String createResult = clinicalDataService.createClinicalData( "", TemplateIdHelper.HEALTH_ADAPTER_CREATE1_TEMPLATE_ID, "request_id" );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyHAWriteAuditLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testHARead( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHaCdsAuditLogTable();
        clinicalDataService.readClinicalData( TemplateIdHelper.HEALTH_ADAPTER_READ1_TEMPLATE_ID, "xml", "filterId", requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyHAAuditLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for HA assessement dtl template id to check it has been inserted in HA read audit log table
     */
    public void testHAAssessmentDtlRead( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHaCdsAuditLogTable();

        String readFilterXml = "<filter:filter xmlns:filter=\"Filter\" vhimVersion=\"Vhim_4_00\"><filterId>HEALTH_ADAPTER_ASSESSMENT_DOCUMENT_DETAIL_FILTER</filterId><clientName>testClientName</clientName><clientRequestInitiationTime>2011-06-06T12:01:01Z</clientRequestInitiationTime><entryPointFilter queryName=\"queryName\" isPatientCentric=\"false\"><domainEntryPoint>AssessmentDocument</domainEntryPoint><recordIdentifiers><identity>2246</identity></recordIdentifiers></entryPointFilter></filter:filter>";
        clinicalDataService.readClinicalData( TemplateIdHelper.HEALTH_ADAPTER_ASSESSMENT_DOCUMENT_DETAIL_READ1_TEMPLATE, readFilterXml,
                        TemplateIdHelper.HEALTH_ADAPTER_ASSESSMENT_DOCUMENT_DETAIL_FILTER, requestId );

        Thread.sleep( THREAD_SLEEP_TIME );
        verifyHAAuditLogData( requestId );
    }


    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for HA journal dtl template id to check it has been inserted in HA read audit log table
     */
    public void testHAJournalDtlRead( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHaCdsAuditLogTable();

        String readFilterXml = "<filter:filter xmlns:filter=\"Filter\" vhimVersion=\"Vhim_4_00\" xsi:schemaLocation=\"Filter Health_Adapter_Journal_Detail_Filter.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><filterId>HEALTH_ADAPTER_JOURNAL_DETAIL_FILTER</filterId><clientName>testClientName</clientName><clientRequestInitiationTime>2001-12-17T09:30:47Z</clientRequestInitiationTime><entryPointFilter queryName=\"ID_1\" isPatientCentric=\"false\"><domainEntryPoint>PatientEnteredDietJournalEntry</domainEntryPoint><recordIdentifiers><identity>2246</identity></recordIdentifiers><otherQueryParameters><attachmentName>filename_44911967</attachmentName></otherQueryParameters></entryPointFilter></filter:filter>";
        clinicalDataService.readClinicalData( TemplateIdHelper.HEALTH_ADAPTER_JOURNAL_DETAIL_READ1_TEMPLATE_ID, readFilterXml,
                        TemplateIdHelper.HEALTH_ADAPTER_JOURNAL_DETAIL_FILTER, requestId );

        Thread.sleep( THREAD_SLEEP_TIME );
        verifyHAAuditLogData( requestId );
    }

    @Test
    @Suite( groups = "smoketest" )
    public void testWithJunkClientName( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.GENERIC_VISTA_LIST_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.VISTA_GENERIC_OBSERVATION_TEMPLATE_ID;
        
        String readFilterXml = "<filter:filter xmlns:filter=\"Filter\" vhimVersion=\"Vhim_4_00\" xsi:schemaLocation=\"Filter100.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><filterId>GENERIC_VISTA_LIST_DATA_FILTER</filterId><clientName>testClientName</clientName><clientRequestInitiationTime>2001-12-17T09:30:47Z</clientRequestInitiationTime><entryPointFilter queryName=\"ID_1\"><domainEntryPoint>GenericObservation</domainEntryPoint></entryPointFilter></filter:filter>";
    
        clearCdsAuditLogTable();
        clinicalDataService.readClinicalData( readTemplateId, readFilterXml, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        
        verifyCdsAuditLogNullClientMapping( requestId );
    }

    @Test
    @Suite( groups = "smoketest" )
    public void testWithValidClientName( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.VITAL_SINGLE_PATIENT_ALL_DATA_FILTER;
        String readTemplateId = TemplateIdHelper.VITALSIGNS_READ_TEMPLATE_ID;
        
        String readFilterXml = "<filter:filter xmlns:filter=\"Filter\" vhimVersion=\"Vhim_4_00\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><filterId>VITAL_SINGLE_PATIENT_ALL_DATA_FILTER</filterId><clientName>Fix The Phones</clientName><clientRequestInitiationTime>2001-12-17T09:30:47Z</clientRequestInitiationTime><patients><NationalId>1008523096V381537</NationalId></patients><entryPointFilter queryName=\"ID_1\"><domainEntryPoint>VitalSignObservationEvent</domainEntryPoint></entryPointFilter></filter:filter>";
        
        clearCdsAuditLogTable();
        clinicalDataService.readClinicalData( readTemplateId, readFilterXml, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        
        verifyCdsAuditLogClientMapping( requestId );
    }
  
    @Test
    @Suite( groups = "smoketest" )
    public void testWithNoClientName( )
        throws Exception
    {
        String requestId = "580RDI" + TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.RDI_ALLERGY_RX_FILTER_ID;
        String readTemplateId = TemplateIdHelper.RDI_ALLERGIES_PHARMACY_READ_TEMPLATE_ID_40013;
        
        String readFilterXml = "<filter:filter xmlns:filter=\"Filter\" vhimVersion=\"Vhim_4_00\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><filterId>RDI_ALLERGY_RX_SINGLE_PATIENT_FILTER</filterId><patients><resolvedIdentifiers><assigningAuthority>USVHA</assigningAuthority><assigningFacility>992</assigningFacility><identity>7</identity></resolvedIdentifiers></patients><entryPointFilter queryName=\"ID_1\"><domainEntryPoint>IntoleranceCondition</domainEntryPoint></entryPointFilter></filter:filter>";
        
        clearCdsAuditLogTable();
        clinicalDataService.readClinicalData( readTemplateId, readFilterXml, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        
        verifyCdsAuditLogClientMapping( requestId );
    }

    @Test
    @Suite( groups = "smoketest" )
    public void testCHDRWithNoClientName( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();
        String filterId = TemplateIdHelper.CHDR_ALLERGY_SINGLE_PATIENT_FILTER;
        String readTemplateId = TemplateIdHelper.INTOLERANCE_CONDITION_READ_TEMPLATE_ID;
        
        String readFilterXml = "<filter:filter xmlns:filter=\"Filter\" vhimVersion=\"Vhim_4_00\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><filterId>CHDR_ALLERGY_SINGLE_PATIENT_FILTER</filterId><patients><NationalId>1008523096V381537</NationalId><excludeIdentifiers><assigningAuthority>USDOD</assigningAuthority><assigningFacility>200HD</assigningFacility></excludeIdentifiers></patients><entryPointFilter queryName=\"ID_1\"><domainEntryPoint>IntoleranceCondition</domainEntryPoint></entryPointFilter></filter:filter>";
        
        //clearCdsAuditLogTable();
        clinicalDataService.readClinicalData( readTemplateId, readFilterXml, filterId, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        
        verifyCdsAuditLogClientMapping( requestId );
    }
    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testHAReadWithNullFilter( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHaCdsAuditLogTable();
        clinicalDataService.readClinicalData( TemplateIdHelper.HEALTH_ADAPTER_READ1_TEMPLATE_ID, "", "filterId", requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyHAAuditLogData( requestId );
    }


    @SuppressWarnings( "unused" )
    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testHAUpdate( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHAAuditClobStrTable();
        String createResult = clinicalDataService.createClinicalData( "XML", TemplateIdHelper.HEALTH_ADAPTER_UPDATE1_TEMPLATE_ID, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyHAWriteAuditLogData( requestId );
    }


    @SuppressWarnings( "unused" )
    @Test
    @Suite( groups = "brokentest" )
    /**
     * Test read record for All Allergies: Intolerance Conditions & Allergy Assessment via 3.0
     */
    public void testHADelete( )
        throws Exception
    {
        String requestId = TemplateIdHelper.getUniqueIdentifier();

        clearCdsApplicationLogTable();
        clearHAAuditClobStrTable();
        String createResult = clinicalDataService.createClinicalData( "XML", TemplateIdHelper.HEALTH_ADAPTER_DELETE1_TEMPLATE_ID, requestId );
        Thread.sleep( THREAD_SLEEP_TIME );
        verifyCdsApplicationLogData( requestId );
        verifyHAWriteAuditLogData( requestId );
    }


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


    private void clearHaCdsAuditLogTable( )
    {
        this.hdrJdbcTemplate.update( "DELETE FROM HA_CDS_AUDIT_LOG" );
    }


    private void clearHAAuditClobStrTable( )
    {
        this.hdrJdbcTemplate.update( "DELETE FROM HA_AUDIT_CLOB_STR" );
    }


    private void verifyCdsApplicationLogData( String requestId, String errorMsg )
    {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append( "SELECT COUNT(*) FROM CDS_APPLICATION_LOG " );
        sqlBuilder.append( "WHERE DBMS_LOB.INSTR(MESSAGE, '" );
        sqlBuilder.append( errorMsg );
        sqlBuilder.append( "', 1, 1) > 0" );
        sqlBuilder.append( " AND REQUEST_ID = '" );
        sqlBuilder.append( requestId );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }


    protected void verifyPathwaysApplicationLogForNoData( String requestId, String errorMsg )
    {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append( "SELECT COUNT(*) FROM PATHWAYS_APPLICATION_LOG " );
        sqlBuilder.append( "WHERE DBMS_LOB.INSTR(MESSAGE, '" );
        sqlBuilder.append( errorMsg );
        sqlBuilder.append( "', 1, 1) > 0" );
        sqlBuilder.append( " AND REQUEST_ID = '" );
        sqlBuilder.append( requestId );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 0 );
    }

    

    private void verifyCdsApllicationLogMessageData( String searchString1, String searchString2 )
    {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append( "select count(*) from cds_application_log where dbms_lob.instr(message,'" );
        sqlBuilder.append( searchString1 );
        sqlBuilder.append( "', 1, 1) = 0" );
        sqlBuilder.append( " and dbms_lob.instr(message,'" );
        sqlBuilder.append( searchString2 );
        sqlBuilder.append( "', 1, 1) > 0" );

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

        Assert.assertEquals( 1, retVal );
    }


    private void clearCdsApplicationLogTable( )
    {
        this.hdrJdbcTemplate.update( "DELETE FROM CDS_APPLICATION_LOG" );
    }


    private void clearPathwaysApplicationLogTable( )
    {
        this.hdrJdbcTemplate.update( "DELETE FROM PATHWAYS_APPLICATION_LOG" );
    }


    private int getCdsAuditLog( )
    {
        return hdrJdbcTemplate.queryForObject( "SELECT COUNT(*) FROM CDS_AUDIT_LOG3", Integer.class );
    }


    private int getCdsApllicationLogTableCount( )
    {
        return hdrJdbcTemplate.queryForObject( "SELECT COUNT(*) FROM CDS_APPLICATION_LOG", Integer.class );
    }


    private int getPathwaysApplicationLogTableCount( )
    {
        return hdrJdbcTemplate.queryForObject( "SELECT COUNT(*) FROM PATHWAYS_APPLICATION_LOG", Integer.class );
    }


    private void verifyCdsApplicationLogData( String requestId )
    {
        String jmsQueueAppender = "JmsQueueAppender";
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM CDS_APPLICATION_LOG " );
        sqlBuilder.append( " WHERE DBMS_LOB.INSTR(MESSAGE, '" );
        sqlBuilder.append( requestId );
        sqlBuilder.append( "', 1, 1) > 0" );
        sqlBuilder.append( " AND DBMS_LOB.INSTR(MESSAGE, '" );
        sqlBuilder.append( jmsQueueAppender );
        sqlBuilder.append( "', 1, 1) = 0" );
        sqlBuilder.append( " AND REQUEST_ID = '" );
        sqlBuilder.append( requestId );
        sqlBuilder.append( "'" );
        sqlBuilder.append( " AND APP_NAME = '" );
        sqlBuilder.append( cdsAppName );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }


    private void verifyCdsAuditLogData( String domain )
    {
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM CDS_AUDIT_LOG3 " );
        sqlBuilder.append( " WHERE MACHINE IS NOT NULL " );
        sqlBuilder.append( " AND REQUEST_IDENTIFIER = '" );
        sqlBuilder.append( domain );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }

    private void verifyCdsAuditLogNullClientMapping( String reqId )
    {
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM CDS_AUDIT_LOG3 " );
        sqlBuilder.append( " WHERE MACHINE IS NOT NULL " );
        sqlBuilder.append( " AND CLIENT_MAPPING_ID IS NULL " );
        sqlBuilder.append( " AND REQUEST_IDENTIFIER = '" );
        sqlBuilder.append( reqId );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }

    private void verifyCdsAuditLogClientMapping( String reqId )
    {
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM CDS_AUDIT_LOG3 " );
        sqlBuilder.append( " WHERE MACHINE IS NOT NULL " );
        sqlBuilder.append( " AND CLIENT_MAPPING_ID IS NOT NULL " );
        sqlBuilder.append( " AND CLIENT_IDENTIFIER IS NOT NULL " );
        sqlBuilder.append( " AND REQUEST_IDENTIFIER = '" );
        sqlBuilder.append( reqId );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }

    private void verifyHAAuditLogData( String domain )
    {
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM HA_CDS_AUDIT_LOG " );
        sqlBuilder.append( " WHERE MACHINE IS NOT NULL " );
        sqlBuilder.append( " AND REQUEST_IDENTIFIER = '" );
        sqlBuilder.append( domain );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }


    private void verifyHAWriteAuditLogData( String reqId )
    {
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append( "SELECT COUNT(*) FROM HA_AUDIT_CLOB_STR " );
        sqlBuilder.append( " WHERE REQUEST_ID = '" );
        sqlBuilder.append( reqId );
        sqlBuilder.append( "'" );

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

        Assert.assertTrue( retVal == 1 );
    }


    @After
    @Suite( groups = "smoketest" )
    public void AfterCdsApplicationLoggingTestMethodTearDown( )
        throws Exception
    {
        sqlPlusRunner.execute( loggerSchemaOracleSqlPlusConnectionStringBuilder.getConnectionString(),
                        "src/test/resources/sql/grant_insert_permission_cds_audit_log_to_hdr.sql", hdrSchemaName );

        clearCdsAuditLogTable();
        clearHAAuditClobStrTable();
        clearHaCdsAuditLogTable();
        clearCdsApplicationLogTable();
    }

}
