/*
 * Created on Dec 10, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.va.med.esr.service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import gov.va.med.esr.common.infra.ImpreciseDate;
import gov.va.med.esr.common.infra.ImpreciseDateUtils;
import gov.va.med.esr.common.model.cases.WorkflowCase;
import gov.va.med.esr.common.model.ee.CDCondition;
import gov.va.med.esr.common.model.ee.CatastrophicDisability;
import gov.va.med.esr.common.model.ee.CDDescriptor;
import gov.va.med.esr.common.model.ee.Pension;
import gov.va.med.esr.common.model.ee.IncomingMessageInfo;
import gov.va.med.esr.common.model.ee.MonetaryBenefitAward;
import gov.va.med.esr.common.model.ee.MonetaryBenefit;
import gov.va.med.esr.common.model.CommonEntityKeyFactory;
import gov.va.med.esr.common.model.ee.AgentOrangeExposure;
import gov.va.med.esr.common.model.ee.PurpleHeart;
import gov.va.med.esr.common.model.ee.ReceivedEligibility;
import gov.va.med.esr.common.model.ee.SpecialFactor;
import gov.va.med.esr.common.model.ee.RatedDisability;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.ee.VerificationInfo;
import gov.va.med.esr.common.model.financials.IncomeTest;
import gov.va.med.esr.common.model.financials.IncomeTestStatus;
import gov.va.med.esr.common.model.lookup.ApplicationStatus;
import gov.va.med.esr.common.model.lookup.CDDeterminationMethod;
import gov.va.med.esr.common.model.lookup.Condition;
import gov.va.med.esr.common.model.lookup.DecorationStatus;
import gov.va.med.esr.common.model.lookup.DescriptorType;
import gov.va.med.esr.common.model.lookup.Disability;
import gov.va.med.esr.common.model.lookup.EligibilityStatus;
import gov.va.med.esr.common.model.lookup.EligibilityVerificationSource;
import gov.va.med.esr.common.model.lookup.AACIndicator;
import gov.va.med.esr.common.model.lookup.EligibilityType;
import gov.va.med.esr.common.model.lookup.EnrollmentPriorityGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentStatus;
import gov.va.med.esr.common.model.lookup.IncomeTestType;
import gov.va.med.esr.common.model.lookup.IncomeTestSource;
import gov.va.med.esr.common.model.lookup.MeansTestStatus;
import gov.va.med.esr.common.model.lookup.MessageStatus;
import gov.va.med.esr.common.model.lookup.MessageType;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.lookup.WkfCaseStatusType;
import gov.va.med.esr.common.model.lookup.WkfCaseType;
import gov.va.med.esr.common.model.messaging.MessageLogEntry;
import gov.va.med.esr.common.model.messaging.SiteIdentity;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.id.PersonIdEntityKeyImpl;
import gov.va.med.esr.common.model.workload.WorkflowCaseInfo;
import gov.va.med.esr.common.util.RuleAbstractTestCase;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.service.trigger.TriggerIdentity;
import gov.va.med.esr.common.model.lookup.MonetaryBenefitType;
import gov.va.med.esr.service.ApplicationInProcessService;
import gov.va.med.esr.service.impl.VOAApplicationServiceImpl;
import gov.va.med.esr.service.trigger.PersonTrigger;
import gov.va.med.esr.service.trigger.PersonTriggerEvent;

/**
 * @author Yi He
 *
 */
public class MessagingServiceTest extends RuleAbstractTestCase {
	private static final String CANNED_PERSON_ID = "66512";
	private static final Character VOA_IND_1 = '1';
	private static final Character VOA_IND_2 = '2';
    private MessagingService messagingService = null;
    private ApplicationInProcessService applicationInProcessService = null;
    private Person person;


    /**
	 * Setup the test data. Create test data in the database
	 */
	protected final void customSetUp() throws Exception {
		super.customSetUp();
	    // use an available person
	    person = this.getPersonService().getPerson(new PersonIdEntityKeyImpl(new BigDecimal(CANNED_PERSON_ID)));
	}
	
	
	public Person getPerson() {
		return person;
	}
    
	
	public void testCDDescriptorsFromZ07() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_AUTOMATED_RECORD_REVIEW.getCode(), "TESTER");        
        onFile.setCatastrophicDisability(cd);
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_QUADRIPLEGIA.getCode()));		
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_DEAFNESS.getCode()));		
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_PERSISTENT_VEGETATIVE_STATE.getCode()));	    
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_PARAPLEGIA.getCode()));		
        Person incoming = this.savePerson(onFile);
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode()));
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode()));
		// Add a duplicate
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));	   		
        
        VAFacility va = this.getRandomVAFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+7+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 7);
	}
	public void testCDDescriptorsFromZ07ExistingCDStub() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = new CatastrophicDisability();
        onFile.setCatastrophicDisability(cd);
        Person incoming = this.savePerson(onFile);
        CatastrophicDisability newCD = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_PHYSICAL_EXAMINATION.getCode(), "TESTER");
        incoming.removeAllClinicalDeterminations();
        incoming.setCatastrophicDisability(newCD);
        incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
        
        VAFacility va = newCD.getDeterminationFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
	    assertNotNull( newCD.getDeterminedBy());
	    assertNotNull( newCD.getDeterminationMethod());  	    
	    assertNotNull( newCD.getDeterminationFacility());	    
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+1+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 1);
        assertNotNull( cdResult.getDeterminedBy());
        assertNotNull( cdResult.getDeterminationMethod());
	    assertNotNull( cdResult.getDeterminationFacility());        
	}
	public void testCDDescriptorsFromZ07ExistingCD_CatDisabledFalse_SameSite() throws Exception {
        CatastrophicDisability newCD = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_PHYSICAL_EXAMINATION.getCode(), "TESTER");
		
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = new CatastrophicDisability();
        cd.setCatastrophicallyDisabled(Boolean.FALSE);
        cd.setDeterminationFacility(newCD.getDeterminationFacility());
        onFile.setCatastrophicDisability(cd);
        Person incoming = this.savePerson(onFile);
        
        incoming.removeAllClinicalDeterminations();
        incoming.setCatastrophicDisability(newCD);
        incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
        
        VAFacility va = newCD.getDeterminationFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
	    assertNotNull( newCD.getDeterminedBy());
	    assertNotNull( newCD.getDeterminationMethod());  	    
	    assertNotNull( newCD.getDeterminationFacility());	    
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+1+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 1);
        assertNotNull( cdResult.getDeterminedBy());
        assertNotNull( cdResult.getDeterminationMethod());
	    assertNotNull( cdResult.getDeterminationFacility());        
	}	
	
	public void testCDDescriptorsFromZ07ExistingCD_CatDisabledFalse_DifferentSite() throws Exception {
        CatastrophicDisability newCD = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_PHYSICAL_EXAMINATION.getCode(), "TESTER");
		
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = new CatastrophicDisability();
        cd.setCatastrophicallyDisabled(Boolean.FALSE);
        cd.setDeterminationFacility(newCD.getDeterminationFacility());
        onFile.setCatastrophicDisability(cd);
        Person incoming = this.savePerson(onFile);
        
        incoming.removeAllClinicalDeterminations();
        incoming.setCatastrophicDisability(newCD);
        incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
        
        VAFacility va = getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
	    assertNotNull( newCD.getDeterminedBy());
	    assertNotNull( newCD.getDeterminationMethod());  	    
	    assertNotNull( newCD.getDeterminationFacility());	    
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+1+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 1);
        assertNotNull( cdResult.getDeterminedBy());
        assertNotNull( cdResult.getDeterminationMethod());
	    assertNotNull( cdResult.getDeterminationFacility());        
	}		
	/*
	 * 3. Conversation/Narrative A new CD record will be created/updated in ES
	 * when ANY of the following occurs and the Sending Site = Facility Making
	 * Determination. (the "ANY of" will be added 7/28/14)
	 * 
	 * -The on file Determination Method is “Medical Record Review” and ES
	 * receives “Physical Exam”
	 * 
	 * -Change to Catastrophic Disability Indicator (yes to no, no to yes)
	 * 
	 * -Change to Evaluation Requested Date
	 * 
	 * -Change to Decision Date
	 * 
	 * -A new CD Descriptor is received that is not on file
	 * 
	 * If the sending site is not the Facility Making Determination and a CD
	 * Descriptor that is not already on file in ES is sent, ES will accept only
	 * the Descriptor. The following fields will remain unchanged:
	 * 
	 * -Determination Method
	 * 
	 * -Facility Making Determination
	 * 
	 * -Catastrophically Disabled - Y/N
	 * 
	 * -Decided by
	 * 
	 * -Evaluation Requested Date
	 * 
	 * -Decision Date
	 * 
	 * The originating site (i.e. Facility Making Determination) will remain the
	 * owner.
	 */
	public void testCDDescriptorsFromZ07OtherSite() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_AUTOMATED_RECORD_REVIEW.getCode(), "TESTER");        
        onFile.setCatastrophicDisability(cd);
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_QUADRIPLEGIA.getCode()));		
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_DEAFNESS.getCode()));		
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_PERSISTENT_VEGETATIVE_STATE.getCode()));	    
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_PARAPLEGIA.getCode()));		
        Person incoming = this.savePerson(onFile);
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode()));
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode()));
		// Add a duplicate
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));	   		
        
        VAFacility va = getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+7+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 7);
	}
	
	
	public void testCDDescriptorsFromZ07WithNoIncomingDescriptorsSameSite() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_AUTOMATED_RECORD_REVIEW.getCode(), "TESTER");        
        onFile.setCatastrophicDisability(cd);
		Condition type = this.getLookupService().getConditionByCode(Condition.CODE_FIM.getCode());
		CDCondition c = new CDCondition(); 
		c.setCondition(type);
		cd.addCondition(c);        
        Person incoming = this.savePerson(onFile);
        
        VAFacility va = cd.getDeterminationFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+1+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 1);
	}	
	
	public void testCDDescriptorsFromZ07ExistingCPDSameFacility() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_AUTOMATED_RECORD_REVIEW.getCode(), "TESTER");        
        onFile.setCatastrophicDisability(cd);
		Condition type = this.getLookupService().getConditionByCode(Condition.CODE_FIM.getCode());
		CDCondition c = new CDCondition(); 
		c.setCondition(type);
		cd.addCondition(c);
		cd.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_PARAPLEGIA.getCode()));		
        Person incoming = this.savePerson(onFile);
        incoming.getCatastrophicDisability().removeAllConditions();
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode()));
		incoming.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode()));
        
        VAFacility va = cd.getDeterminationFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+2+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 3);
        assertTrue(cdResult.getConditions().size()==1);
	}	
	
	public void testCDDescriptorsFromZ07WithNoExistingCD() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_AUTOMATED_RECORD_REVIEW.getCode(), "TESTER");        
        onFile.setCatastrophicDisability(cd);
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_QUADRIPLEGIA.getCode()));		
        Person incoming = this.savePerson(onFile);
        CatastrophicDisability incomingCD = incoming.getCatastrophicDisability();
        incomingCD.removeAllCDDescriptors();
		incomingCD.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode()));
		incomingCD.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode()));
		incomingCD.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_DEAFNESS.getCode()));	   		
        
        VAFacility va = incomingCD.getDeterminationFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+3+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 3);
        assertTrue(containsDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode(), cdResult.getCDDescriptors() ));
        assertTrue(containsDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode(), cdResult.getCDDescriptors() ));
        assertTrue(containsDescriptor(DescriptorType.CODE_DEAFNESS.getCode(), cdResult.getCDDescriptors() ));
        assertFalse(containsDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode(), cdResult.getCDDescriptors() ));
        assertFalse(containsDescriptor(DescriptorType.CODE_QUADRIPLEGIA.getCode(), cdResult.getCDDescriptors() ));        
	}		

	public void testCDDescriptorsFromZ07NoExistingCDAndNoIncomingCD() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = new CatastrophicDisability();        
        onFile.setCatastrophicDisability(cd);
        Person incoming = this.savePerson(onFile);
        
        VAFacility va = getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+0+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 0);
	}
	public void testCDDescriptorsFromZ07ExistingCDStubAndNoIncomingCD() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = new CatastrophicDisability();        
        onFile.setCatastrophicDisability(cd);
        Person incoming = this.savePerson(onFile);
        
        VAFacility va = getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+0+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 0);
	}			
	public void testCDDescriptorsFromZ07NoExistingCDStubAndNoIncomingCD() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        Person incoming = this.savePerson(onFile);
        
        VAFacility va = getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertNull(cdResult);
	}				
	
	
	public void testCDDescriptorsFromZ07WithDeletes() throws Exception {
	    Person onFile = buildSimplePerson();
	    this.attachVerifiedEnrollment(onFile);
        CatastrophicDisability cd = createCatastrophicDisability(
				new Date(), new Date(), CDDeterminationMethod.CODE_AUTOMATED_RECORD_REVIEW.getCode(), "TESTER");        
        onFile.setCatastrophicDisability(cd);
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode()));        
		onFile.getCatastrophicDisability().addCDDescriptor(this.createCDDescriptor(DescriptorType.CODE_QUADRIPLEGIA.getCode()));		
        Person incoming = this.savePerson(onFile);
        CatastrophicDisability incomingCD = incoming.getCatastrophicDisability();
        incomingCD.removeAllCDDescriptors();
		incomingCD.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode()));
		incomingCD.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode()));
		incomingCD.addCDDescriptor(createCDDescriptor(DescriptorType.CODE_DEAFNESS.getCode()));	   		
        
        VAFacility va = incomingCD.getDeterminationFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);
        CatastrophicDisability cdResult = result.getCatastrophicDisability();
        assertTrue("expected="+3+" but was "+cdResult.getCDDescriptors().size(), cdResult.getCDDescriptors().size() == 3);
        assertTrue(containsDescriptor(DescriptorType.CODE_AMPUTATION_DISARTICULATION_DETACHMENT.getCode(), cdResult.getCDDescriptors() ));
        assertTrue(containsDescriptor(DescriptorType.CODE_DEFICIENCIES_OF_PHYSICAL_OR_MENTAL_FUNCTION.getCode(), cdResult.getCDDescriptors() ));
        assertTrue(containsDescriptor(DescriptorType.CODE_DEAFNESS.getCode(), cdResult.getCDDescriptors() ));
        assertFalse(containsDescriptor(DescriptorType.CODE_LEGAL_BLINDNESS.getCode(), cdResult.getCDDescriptors() ));
        assertFalse(containsDescriptor(DescriptorType.CODE_QUADRIPLEGIA.getCode(), cdResult.getCDDescriptors() ));        
	}	
	private boolean containsDescriptor(String typeCode, Set<CDDescriptor> descriptors ) {
		for (CDDescriptor descriptor : descriptors) {
			if (descriptor.getDescriptorType().getCode().equals(typeCode)) {
				return true;
			}
		}
		return false;
	}
	
	public void testLogMessage() throws Exception{
        //getDAO().removeObject(message.getEntityKey());
	}	
	
	public void testCCR13095NonQueryZ11_1() throws Exception {
		// Test VBA callback with VOAindicator = 2; isTriggerEnrollmentProcess() = true; enrollmentStatus = PENDING;
        
        // Get start time for this unit test
        Date startTime = new Date();
		
		Person onFile = this.getPerson("377323380");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");			
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);

		// Assert bypass Vista
		//assertFalse("Vista Events not removed.", hasVistaEvents());
		// Assert VOA Indicator still = 2
		assertTrue("VOA Indicator not set to '2'.", VOA_IND_2.equals(result.getVOAIndicator()));
        // Assert workflow item created
        WorkflowCase wfc = getWorkflowService().getMostRecentWorkflowItem(result);
        assertTrue("No workflow items found.", wfc != null);
        assertTrue("Most recent workflow item found does not have a type = 'VOA'", getLookupService().getWkfCaseTypeByCode(WkfCaseType.CODE_VETERANS_ONLINE_APPLICATION.getCode()).equals(wfc.getCaseType()));
        assertTrue("Most recent workflow item found does not have a status = 'New'.", getLookupService().getWkfCaseStatusTypeByCode(WkfCaseStatusType.NEW.getName()).equals(wfc.getStatus().getStatusValue()));
        assertTrue("Most recent workflow item found is too old.", wfc.getCreatedOn().after(startTime));
        assertTrue("Most recent workflow item found has wrong error msg.", "VOA Submission with Determined Enrollment Status of PENDING".equalsIgnoreCase(wfc.getErrorMessage()));
		
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR13095NonQueryZ11_2() throws Exception {
		// Test VBA callback with VOAindicator = 2; isTriggerEnrollmentProcess() = false; enrollmentStatus = PENDING;
        
        // Get start time for this unit test
        Date startTime = new Date();
		
		Person onFile = this.getPerson("377323380");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");
		vi.setTriggerEnrollmentProcess(false);
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);

		// Assert bypass Vista
		//assertFalse("Vista Events not removed.", hasVistaEvents());
		// Assert VOA Indicator still = 2
		assertTrue("VOA Indicator not set to '2'.", VOA_IND_2.equals(result.getVOAIndicator()));
        // Assert workflow item created
        WorkflowCase wfc = getWorkflowService().getMostRecentWorkflowItem(result);
        assertTrue("No workflow items found.", wfc != null);
        assertTrue("Most recent workflow item found does not have a type = 'VOA'", getLookupService().getWkfCaseTypeByCode(WkfCaseType.CODE_VETERANS_ONLINE_APPLICATION.getCode()).equals(wfc.getCaseType()));
        assertTrue("Most recent workflow item found does not have a status = 'New'.", getLookupService().getWkfCaseStatusTypeByCode(WkfCaseStatusType.NEW.getName()).equals(wfc.getStatus().getStatusValue()));
        assertTrue("Most recent workflow item found is too old.", wfc.getCreatedOn().after(startTime));
        assertTrue("Most recent workflow item found has wrong error msg.", "VOA Submission with Determined Enrollment Status of PENDING".equalsIgnoreCase(wfc.getErrorMessage()));
		
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR13095NonQueryZ11_3() throws Exception {
		// Test VBA callback with VOAindicator = 2; isTriggerEnrollmentProcess() = true; enrollmentStatus != PENDING;
        
        // Get start time for this unit test
        Date startTime = new Date();
		
		Person onFile = this.getPerson("377326248");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);

		// Assert messages added to trigger Vista update
		//assertTrue("Vista Events not found.", hasVistaEvents());
		// Assert VOA Indicator updated to 1
		assertTrue("VOA Indicator not set to '1'.", VOA_IND_1.equals(result.getVOAIndicator()));
        // Assert NO workflow items created
        WorkflowCase wfc = getWorkflowService().getMostRecentWorkflowItem(result);
        assertTrue("Unexpected workflow item added.", wfc == null || wfc.getCreatedOn().before(startTime));
		
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR13095NonQueryZ11_4() throws Exception {
		// Test VBA callback with VOAindicator = 2; isTriggerEnrollmentProcess() = false;  enrollmentStatus != PENDING;
        
        // Get start time for this unit test
        Date startTime = new Date();
		
		Person onFile = this.getPerson("377318219");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);

		// Assert messages added to trigger Vista update
		//assertTrue("Vista Events not found.", hasVistaEvents());
		// Assert VOA Indicator updated to 1
		assertTrue("VOA Indicator not set to '1'.", VOA_IND_1.equals(result.getVOAIndicator()));
        // Assert NO workflow items created
        WorkflowCase wfc = getWorkflowService().getMostRecentWorkflowItem(result);
        assertTrue("Unexpected workflow item added.", wfc == null || wfc.getCreatedOn().before(startTime));
		
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR13095NonQueryZ11_5() throws Exception {
		// Test VBA callback with VOAindicator = null; isTriggerEnrollmentProcess() = false;  enrollmentStatus != **IRRELEVANT**;
        
        // Get start time for this unit test
        Date startTime = new Date();
		
		Person onFile = this.getPerson("375124624");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);

		// Assert bypass Vista
		//assertFalse("Vista Events not removed.", hasVistaEvents());
		// Assert VOA Indicator still = null
		assertTrue("VOA Indicator not set to 'null'.", result.getVOAIndicator() == null);
        // Assert NO workflow items created
        WorkflowCase wfc = getWorkflowService().getMostRecentWorkflowItem(result);
        assertTrue("Unexpected workflow item added.", wfc == null || wfc.getCreatedOn().before(startTime));
		
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR13095NonQueryZ11_6() throws Exception {
		// Test VBA callback with VOAindicator = 1; isTriggerEnrollmentProcess() = true;  enrollmentStatus != **IRRELEVANT**;
        
        // Get start time for this unit test
        Date startTime = new Date();
		
		Person onFile = this.getPerson("377459275");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);

		// Assert sharing with Vista
		//assertTrue("Vista Events not added.", hasVistaEvents());
		// Assert VOA Indicator still = 1
		assertTrue("VOA Indicator not set to '1'.", VOA_IND_1.equals(result.getVOAIndicator()));
        // Assert NO workflow items created
        WorkflowCase wfc = getWorkflowService().getMostRecentWorkflowItem(result);
        assertTrue("Unexpected workflow item added.", wfc == null || wfc.getCreatedOn().before(startTime));
		
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR11457() throws Exception {
		//Person onFile = this.getPerson("375124624");
		//373971922
		Person onFile = this.getPerson("375124624");
		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", "No Data on File");			
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_NO_DATA.getCode()));
		
		Person result = this.getMessagingService().processNonQueryZ11(onFile,vi);
		//this.setComplete();
		System.out.println("verification record ="+result.getEligibilityVerification());
	}
	
	public void testCCR11457GetCompletePerson() throws Exception {
		//Person onFile = this.getPerson("375124624");
		//373971922
		Person onFile = this.getPerson("375124624");
		Person result = this.getApplicationInProcessService().getCompletedPersonByIcn(onFile.getVPIDEntityKey().getShortVPID());
		//  this.setComplete();
		System.out.println("id ="+result.getEntityKey().getKeyValueAsString());
	}
	//39764
	public void testCCR11457GetCompletePersonNegative() throws Exception {
		Person onFile = this.getPerson("375137257");
		Person result = this.getApplicationInProcessService().getCompletedPersonByIcn(onFile.getVPIDEntityKey().getShortVPID());
		assertNull(result);
	}
	
	public void testCCR11486AAP() throws Exception {
		Person onFile = this.getPerson("375137257");
		Person result = this.getApplicationInProcessService().getInProcessPersonByIcn(onFile.getVPIDEntityKey().getShortVPID());
		Person incoming = result;//this.getPersonService().save(result, true);	
		String stationNumber = "200ESR";
		VAFacility sendingFacility = this.getLookupService().getVaFacilityByStationNumber(stationNumber);		
		
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(sendingFacility.getCode());
		Person updated = this.getMessagingService().processAddPerson(incoming,sendingFacility, vi);
		System.out.println("Person id="	+ updated.getPersonEntityKey().getKeyValueAsString());		
	}		
	public void testCCR11457UpdateCompletePerson() throws Exception {
		//Person onFile = this.getPerson("375124624");
		//373971922
		Person onFile = this.getPerson("375124624");
		Person result = this.getApplicationInProcessService().getCompletedPersonByIcn(onFile.getVPIDEntityKey().getShortVPID());
		this.setEligibilityStatusToVerified(result);
		result.getEligibilityVerification().setEligibilityStatusDate(ImpreciseDateUtils.createImpreciseDate(2011,6,1));
		this.getApplicationInProcessService().savePersonInProcess(result, 
				this.getLookupService().getApplicationStatusByCode(ApplicationStatus.COMPLETE.getCode()));
		//this.setComplete();
		System.out.println("id ="+result.getEntityKey().getKeyValueAsString());
	}		
	public void testORFZ11forAAP11457() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEnrollmentStatus(this.getLookupService().getEnrollmentStatusByCode(
						EnrollmentStatus.CODE_PENDING.getName()));
		this.setEligibilityStatusToPendingVerification(onFile);
		VerificationInfo vi = createVerificationInfoFromORFZ11();
		onFile.getEligibilityVerification().setAacIndicator(this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_NO_DATA.getCode()));
		Person incoming = this.savePerson(onFile);
		Person result = this.getMessagingService().processNonQueryZ11(incoming,vi);
		//  this.setComplete();
		System.out.println("id ="+result.getEntityKey().getKeyValueAsString());
	}
	/*
	 * SUC103.11.31 - [6483] Scenario 14 In scenario 14, ESR receives VBA Data
	 * in which the Entitlement Code = “0L”, Total Check Amount > $0, Rated
	 * Disabilities are present, and SC % > 0%.
	 * 
	 * SUC103.11.31.1 - [6484] If the incoming message is a query response
	 * (ORF~Z11) Set VBA Query Status = VBA Data Auto Uploaded
	 * 
	 * Eligibility Status = Verified Eligibility 
	 * Status Date = Current Date
	 * Verification Source = “CEV” 
	 * Verification Method = “VBA”
	 */
	public void testORFZ11for11752Scenario14() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEnrollmentStatus(this.getLookupService().getEnrollmentStatusByCode(
						EnrollmentStatus.CODE_PENDING.getName()));
		this.setEligibilityStatusToPendingVerification(onFile);		
		Person incoming = this.savePerson(onFile);
		incoming.getEligibilityVerification().setAacIndicator(this.getLookupService().getAACIndicatorByCode(
				AACIndicator.CODE_DATA_RECEIVED.getCode()));
		this.attachServiceConnectionAward(incoming, new Integer(1));
	    this.attachMonetaryBenefitAward(incoming);
        incoming.getMonetaryBenefitAward().setCheckAmount(new BigDecimal(100));		

		VerificationInfo vi = new VerificationInfo("0L","ORFZ11-E", null);
		
		Person result = this.getMessagingService().processNonQueryZ11(incoming,vi);
		System.out.println("verification="+result.getEligibilityVerification());		
		assertTrue("expected verified",result.getEligibilityVerification().getEligibilityStatus().getCode().equals(
				EligibilityStatus.CODE_VERIFIED.getName()));
		assertTrue("expected VBA",result.getEligibilityVerification().getVerificationMethod().equals("VBA"));
		assertTrue("expected source",result.getEligibilityVerification().getVerificationSource().getCode().equals(
				EligibilityVerificationSource.CODE_CEV.getCode()));
		assertNotNull("expected date",result.getEligibilityVerification().getEligibilityStatusDate());
		
		
	}   		
	
	/*
	 * 
	 * SUC103.11.32 - [6486] Scenario 15 In scenario 15, ESR receives VBA Data
	 * in which the Entitlement Code = “01” or NULL, Total Check Amount = $0 or
	 * NULL, Rated Disabilities are present, and SC % > 0%
	 * 
	 * SUC103.11.32.1 - [6487] If the incoming message is a query response
	 * (ORF~Z11) Set VBA Query Status to VBA Data Auto Uploaded
	 * 
	 * Eligibility Status = Verified Eligibility 
	 * Status Date = Current Date
	 * Verification Source = “CEV” 
	 * Verification Method = “VBA”
	 */
	public void testORFZ11for11752Scenario15() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEnrollmentStatus(this.getLookupService().getEnrollmentStatusByCode(
						EnrollmentStatus.CODE_PENDING.getName()));
		this.setEligibilityStatusToPendingVerification(onFile);		
		Person incoming = this.savePerson(onFile);
		incoming.getEligibilityVerification().setAacIndicator(this.getLookupService().getAACIndicatorByCode(
				AACIndicator.CODE_DATA_RECEIVED.getCode()));
		this.attachServiceConnectionAward(incoming, new Integer(1));

		VerificationInfo vi = new VerificationInfo("01","ORFZ11-E", null);
		
		Person result = this.getMessagingService().processNonQueryZ11(incoming,vi);
		assertTrue("expected verified",result.getEligibilityVerification().getEligibilityStatus().getCode().equals(
				EligibilityStatus.CODE_VERIFIED.getName()));
		assertTrue("expected VBA",result.getEligibilityVerification().getVerificationMethod().equals("VBA"));
		assertTrue("expected source",result.getEligibilityVerification().getVerificationSource().getCode().equals(
				EligibilityVerificationSource.CODE_CEV.getCode()));
		assertNotNull("expected date",result.getEligibilityVerification().getEligibilityStatusDate());		
	}   		
	public void testRetrieveAAPpersonCCR11457() throws Exception {
		Person onFile = this.getPerson("375124624");
		
		List list = this.getApplicationInProcessService().getApplicationStatusesByIcn(onFile.getVPIDEntityKey().getShortVPID());
		//  this.setComplete();
		System.out.println("id =");
	}   		
	public void testGetSites() throws Exception {
		Set sites = messagingService.findSitesOfRecord(getPerson());
        for (Iterator iterator = sites.iterator(); iterator.hasNext();)
        {
            SiteIdentity siteIdentity = (SiteIdentity)iterator.next();
            System.out.println("Found site of record: " + siteIdentity);
        }
	}
	
	
	public void testGetMessageLogEntry() throws Exception{
		MessageLogEntry message = null;
        try {  
        	// create test message
            message = logMessage();
            
            MessageLogEntry foundMessage = messagingService.getMessageLogEntry(message.getControlIdentifier());
      		if(foundMessage != null && message.getEntityKey().equals(foundMessage.getEntityKey()))
      		    logger.fatal("MessageLogEntry found. id = " + message.getEntityKey());
      		else {
      			logger.fatal("Fail to getMessageLogEntry");
      			fail("Fail to getMessageLogEntry");
      		}
      		
        }
        catch( Exception e ) {
            logger.info( "Failed in getMessageLogEntry", e );
            throw e;
	    }
        finally {
      		// cleanup
           // getDAO().removeObject(message.getEntityKey());        	
        }
	}	
		

		
	private MessageLogEntry logMessage() throws Exception {
		try {
			MessageLogEntry message = new MessageLogEntry();
			VAFacility facility = getLookupService().getVaFacilityByStationNumber("650GA");
			message.setVaFacility(facility);
			message.setPersonId(
			        (getPerson().getEntityKey() == null) ? null :
			            (BigDecimal)getPerson().getEntityKey().getKeyValue());
			
			MessageStatus status = getLookupService().getMessageStatusByCode(MessageStatus.COMPLETE);
			message.setStatus(status);
			
			MessageType type = getLookupService().getMessageTypeByCode("ORUZ07-E");
			message.setType(type);
			
			message.setControlIdentifier(messagingService.generateControlIdentifier());
			message.setRetransmissionCount(0);
			message.setBody("test msg body");
			
			messagingService.logMessage(message);
			logger.info("Logged MessageLogEntry with id = " + message.getEntityKey());
			return message;
		}
		catch( Exception e ) {
			logger.fatal( "Failed in logMessageEntry", e );
			throw e;		
		}
	}
	
	public void testAddSecondaryPRISONER_OF_WAR() {
	    
	    try {
	        Person onFile = buildSimplePerson(); // bare-bones person
	        this.attachServiceConnectionAward(onFile, new Integer(75));
	        this.attachPOW(onFile);
            this.attachMilitaryService(onFile);	        
	        Person incoming = this.getPersonService().save(onFile);            
           
            Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());            

	        this.assessIfHasSecondaryRanking(
	                EligibilityType.PRISONER_OF_WAR.getName(), updated);
	        
	        updated.setServiceConnectionAward(null);
            Person updated2 = this.getMessagingService().processZ07(updated, this.getRandomVAFacility(), new VerificationInfo());
            
	        this.assessIfHasPrimaryRanking(
	                EligibilityType.PRISONER_OF_WAR.getName(), updated2);            
	        logger.info("Completed adding Secondary Test");
	    } catch (Exception e) {
	        fail("test failed due to exception: " + e);
	    }
	}            
    public void testProcessORUZ07SendORUZ11() throws Exception {
        testORUZ11Trigger(AACIndicator.CODE_DATA_ACCEPTED.getName());
    }
    
    public void testProcessORUZ07DoNotSendORUZ11() throws Exception {
        testORUZ11Trigger(AACIndicator.CODE_AAC_QUERIED_PENDING.getName());
    }    
    
    public void testDefect3613() throws Exception {
        String aac = AACIndicator.CODE_DATA_INCONCLUSIVE.getName();
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        this.setEligibilityStatusToPendingVerification(onFile);
        onFile.getEligibilityVerification().setAacIndicator(this.getLookupService().getAACIndicatorByCode(aac));
        this.attachVerifiedEnrollment(onFile);
        onFile.getEnrollmentDetermination().setEnrollmentStatus(this.getLookupService().getEnrollmentStatusByCode("9"));
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertTrue(result.getEligibilityVerification().getEligibilityStatus()
                .getCode().equals(EligibilityStatus.CODE_PENDING_VERIFICATION.getName()));
    }    
    
    private void testORUZ11Trigger(String aac) throws Exception {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        this.setEligibilityStatusToPendingVerification(onFile);
        onFile.getEligibilityVerification().setAacIndicator(this.getLookupService().getAACIndicatorByCode(aac));
        this.attachVerifiedEnrollment(onFile);  
        Person incoming = this.getPersonService().save(onFile);
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertTrue(updated.getEligibilityVerification().getEligibilityStatus()
                .getCode().equals(EligibilityStatus.CODE_PENDING_VERIFICATION.getName()));
    }
    
    public void testReceivedEnrollment() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        Person incoming = this.getPersonService().save(onFile);
        this.attachReceivedEnrollment(incoming);  
        incoming.getReceivedEnrollment().setFacilityReceived(this.getRandomVAFacility());        
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertNotNull(updated.getReceivedEnrollment().getFacilityReceived());
    }
    
    public void testPreferredFac() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        onFile.setMostRecentPreferredFacility(this.getLookupService().getVaFacilityByCode("722"));
        Person incoming = this.getPersonService().save(onFile);
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        incoming.setMostRecentPreferredFacility(null);
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertNotNull(updated.getMostRecentPreferredFacility());
        
        
        onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        incoming = this.getPersonService().save(onFile);
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        incoming.setMostRecentPreferredFacility(this.getLookupService().getVaFacilityByCode("742"));
        updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertNotNull(updated.getMostRecentPreferredFacility());
        
        onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        onFile.setMostRecentPreferredFacility(this.getLookupService().getVaFacilityByCode("722"));        
        incoming = this.getPersonService().save(onFile);
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        incoming.setMostRecentPreferredFacility(this.getLookupService().getVaFacilityByCode("742"));
        updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertTrue(updated.getMostRecentPreferredFacility().getCode().equals(incoming.getMostRecentPreferredFacility().getCode()));             
    }             
    
    public void testProcessORUZ07WithAOE() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person incoming = this.getPersonService().save(onFile);
        this.attachAgentOrangeExposure(incoming);        
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        SpecialFactor sf = updated.getSpecialFactorByType(AgentOrangeExposure.class);
        assertNotNull(sf);
    }
    
    public void testProcessORUZ07WithNonVet() throws Exception {
        Person onFile = buildSimpleNonVeteran();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person incoming = this.getPersonService().save(onFile);
        this.attachEmployee(incoming);        
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertNotNull(updated.isVeteran());
        assertFalse(updated.isVeteran().booleanValue());
    }
    
    public void testDefect3859() throws Exception {
        Person onFile = buildSimpleNonVeteran();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        this.attachAlliedVeteranAsPrimary(incoming);        
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertFalse(result.isVeteran().booleanValue());
        this.assessIfHasPrimaryRanking( EligibilityType.ALLIED_VETERAN.getName(), result);        
    }
    
    public void testDefect3886() throws Exception {
        Person onFile = buildSimpleNonVeteran();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        this.attachOtherFederalAgencyAsPrimary(incoming);        
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertFalse(result.isVeteran().booleanValue());
        this.assessIfHasPrimaryRanking( EligibilityType.OTHER_FEDERAL_AGENCY.getName(), result);
        
    }    
    
    public void testDefect3989() throws Exception {
        PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("654131"));        
        Person updated = this.getPersonService().getPerson(personKey);
        Person incoming = (Person)updated.clone();
        IncomingMessageInfo imi = new IncomingMessageInfo();
        imi.setQueryDateTime(new Date());
        imi.setReferenceMessageId("1234");
        imi.setSendingFacility(this.getRandomVAFacility());        
        this.getMessagingService().processQRYZ11(incoming, imi);  
  
        logger.info("Completed Test");
    }        
    /**
     * description While preparing for other testing, I sent a veteran to ESR
     * with no income test (the test was done in a previous income year). After
     * the update from MVR was received, an enrollment record with Pending;
     * Means Test Required was created. I added a new Means Test in VistA and
     * transmitted it to ESR. The Means Test was uploaded and stored, but the
     * enrollment remains Pending; Means Test Required. According to the
     * Enrollment History, it does appear a new enrollment was created, but it
     * did not use the new means test on file.
     * 
     * I have tested this previously by adding a Means Test via the application
     * and it worked OK. This time I added the Means Test via messaging and it
     * failed.
     * 
     */
    public void testDefect2218() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingVerification(onFile);  
        this.attachMilitaryService(onFile);
        onFile.setFinancialStatement(new Integer(2005), this.createFinancialStatement());
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        this.attachMeansTestWithMtCopayRequired(incoming, new BigDecimal(1), new BigDecimal(1));
        VAFacility va = this.getRandomVAFacility();
        IncomeTest it = incoming.getIncomeTest(new Integer(2005));
        it.setSource(this.getLookupService().getIncomeTestSourceByCode(IncomeTestSource.CODE_VAMC.getCode()));
        it.setSiteConductingTest(va);
        Person result = this.getMessagingService().processZ07(incoming, va, new VerificationInfo());;
        assertNotNull(result);        
        assertNotNull(result.getIncomeTest(new Integer(2005)));        
    }      
    /*

SUC2031.3.4.2 
For a new person with an eligibility status not verified and the HL7 contains an 
Ineligible Date and Ineligible Reason ESR will not query the MSDS Broker.

If the HL7 does not contain an Ineligible Date and Ineligible Reason ESR will query the 
MSDS Broker whether a site MSE is received or not.
 
     */
    public void testDefect11614() throws Exception {
        Person onFile = buildSimplePerson();
        Person incoming = this.savePerson(onFile);
        this.attachIneligibleFactorFromSite(incoming);
        VAFacility va = this.getRandomVAFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);;
        assertNotNull(result);        
         
    }
    public void testDefect11614_neg() throws Exception {
        Person onFile = buildSimplePerson();
        Person incoming = this.savePerson(onFile);
        VAFacility va = this.getRandomVAFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);;
        assertNotNull(result);        
         
    }
    public void testDefect11614_neg2() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        Person incoming = this.savePerson(onFile);
        this.attachMilitaryServiceEpisode(incoming);
        this.attachIneligibleFactorFromSite(incoming);        
        VAFacility va = this.getRandomVAFacility();
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(va.getCode());        
        Person result = this.getMessagingService().processZ07(incoming, va, vi);;
        assertNotNull(result);        
         
    }         
    /**
     * description
     * Processed an ORFZ11 from MVR that contained a date of death. In ESR the
     * vet was NSC VA Pension with a VA check amount, eligibility was
     * unverified. ORFZ11's data was ignored (Date of death was not uploaded),
     * the HEC Notification of need for Site to Verify Veteran was triggered
     * appropriately.
     * 
     * however the VBA Query Status was set to Unsolicited DOD - and per emails
     * from Barry and Monica that status should not be assigned. Per the BR the
     * status of VBA Data Inconclusive should have been assigned. (ORFZ11
     * attached)
     * 
     * BR 4017 in the ELSE section states the following
     * 
     * ELSE Keep Eligibility Status of Pending Verification Set Eligibility
     * Status Date = NULL VBA Query Status = VBA Data Inconclusive Set
     * Eligibility Status = Pending Verification Set Eligibility Verification
     * Source = NULL Set Eligibility Verification Method = NULL Send HEC
     * Notification of Need for Site to Verifiy Veteran
     * 
     * Execute the Determine Eligibility use case EXIT
     * 
     */
    public void testDefect3444() throws Exception {
        Person onFile = buildSimpleNonVeteran();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        
        Person result = this.getMessagingService().processNonQueryZ11(incoming,  new VerificationInfo());

        
    }    
    
    
    /**
     * DEFECT: I encountered a problem while trying to test BR 5072 in Process
     * Person Information -> Process VBA Related Site Eligibility Data. That BR
     * says that if ESR shows a person to be a veteran (Veteran Indicator = Yes)
     * with Eligibility Status = Pending Reverification/Verification and a Z07
     * comes in with the Veteran Indicator = No and Eligibility Status =
     * Verified to accept the site data. I converted an NSC veteran (DFN 1812 in
     * DAYT20) to a non-veteran. The guy is deceased, but for my test case that
     * doesn't matter. The Z07 transmits to ESR, but ESR gives me a: "Failed to
     * invoke rule flow ProcessVBAFromZ07" error message. Digging through the
     * stack trace shows this error: "A veteran must not be null." Everything
     * appears to be correct and populated. I have attached the original Z07
     * (the one that put the NSC veteran into ESR), the second Z07 (with the
     * non-veteran set), and the entire stack trace.
     */
    public void testDefect3800() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        incoming.setVeteran(Boolean.FALSE);
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertFalse(result.isVeteran().booleanValue());
    }       
    
    public void testProcessORUZ07WithPH() throws Exception {
        Person onFile = buildSimplePerson();
//        this.setEligibilityStatusToVerified(onFile);  
        this.attachMilitaryService(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone(); 
        this.attachPurpleHeartWithPHStatusPending(incoming);
        incoming.getPurpleHeart().addDocument(this.createPHDocument());
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());

        assertTrue(result.getPurpleHeart().getPhIndicator().booleanValue());
    }
    /*
    public void testDefect2221() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        this.setEligibilityStatusToPendingVerification(onFile);
        this.attachMilitaryService(onFile);
        this.attachServiceConnectionAward(onFile, new Integer(10));
        this.attachMeansTestWithNoLongerRequired(onFile);
        onFile.getServiceConnectionAward().setServiceConnectedPercentage(
                new Integer(0));
        
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person) updated.clone();
        
        incoming.setMonetaryBenefitAward(new MonetaryBenefitAward() );
        this.attachPension(incoming);
        VerificationInfo vi = createVerificationInfoFromORFZ11();
        
        Person result = this.getMessagingService().processNonQueryZ11(incoming,vi);
        assertTrue(result.getServiceConnectionAward()
                .getServiceConnectedPercentage().equals(new Integer(0)));
        IncomeTest it = this.getPersonHelperService().getCurrentIncomeTest(result);
        assertNull(result.getEnrollmentDetermination().getPriorityGroup());        
    }
    private void attachPension(Person person) throws Exception {
    	MonetaryBenefit ben = new MonetaryBenefit();
		ben.setType(this.getLookupService().getMonetaryBenefitTypeByCode(MonetaryBenefitType.CODE_VA_PENSION.getCode()));
		ben.setMonetaryBenefitIndicator(this.getLookupService().getIndicatorByCode(Indicator.YES));
		person.getMonetaryBenefitAward().addMonetaryBenefit(ben);
		Pension pension = ben.getPension();
		if (pension == null) {
			pension = new Pension();
			pension.setMonetaryBenefit(ben);
			ben.setPension(pension);
		}
		pension.setEffectiveDate(this.getDate(2009, 1, 1));
		pension.setTerminationDate(null);
		
		pension.setAwardReasonCode( this.getLookupService().getPensionReasonByCode("04"));
    }
    */
    public void testDefect11156Verified() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        this.setEligibilityStatusToVerified(onFile);        
        Person result = testORFZ11(onFile);
        assertTrue(result.getServiceConnectionAward()
                .getServiceConnectedPercentage().equals(new Integer(0)));
        MonetaryBenefitAward award = result.getMonetaryBenefitAward();
        assertNotNull("award should not be null", award);
        MonetaryBenefit mb = award.getVAPension();
        assertNotNull("monetary benefit should not be null", mb);        
        assertNotNull("pension should not be null",mb.getPension());        
    }
    
    public void testDefect11156Pending() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        this.setEligibilityStatusToVerified(onFile);        
        Person result = testORFZ11(onFile);
        assertTrue(result.getServiceConnectionAward()
                .getServiceConnectedPercentage().equals(new Integer(0)));
        MonetaryBenefitAward award = result.getMonetaryBenefitAward();
        assertNotNull("award should not be null", award);
        MonetaryBenefit mb = award.getVAPension();
        assertNotNull("monetary benefit should not be null", mb);        
        assertNotNull("pension should not be null",mb.getPension());        
    }    
    /*
     * Innis:
	 * CCR 10969 was supposed to implement a change in ESR to not allow null
	 * dates from VBA to overwrite ESR data for rated disabilities (the two
	 * effective dates).
	 * 
	 * Messages from VBA that have null values for the two effective dates is
	 * overwriting HEC-entered effective dates. From looking at the history
	 * table in the database, ESR deletes the HEC-entered rated disabilities and
	 * then inserts new RD records with the null dates from VBA.
	 * 
	 * This is the requirement that is not working: SUC103.10.6 – Do Not Upload
	 * ‘Null’ Date Values If the value is “null” for either the Rated Disability
	 * Original Date, or for the Rating Disability Current Effective Date, do
	 * not upload the date.
	 * 
	 * 
	 * VPID used in Pre-Prod: 1002334326V388891
	 * 
	 * Here is the RD data sent from VBA: 
	 * ZRD^1^8599^10^1^^^^^^^^^^
	 * ZRD^2^5299^0^1^^^^^^^^^^ 
	 * ZRD^3^8599^0^1^^^^^^^^^^
	 * ZRD^4^8100^10^1^^^^^^^^^^ 
	 * ZRD^5^5299^20^1^^^^^^^^^^
	 * ZRD^6^7101^0^1^^^^^^^^^^
	 * 
	 * The two 8599 ones were the ones where a HEC user entered the two
	 * effective dates. Upon receipt of the VBA message, ESR deleted those two
	 * 8599 entries and inserted two new 8599 records with the null dates from
	 * VBA. I have attached a screenshot showing the two new 8599 records with
	 * null dates from VBA.
	 */
    public void testDefect11415FixFor10969() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        this.setEligibilityStatusToVerified(onFile);       
    //    this.setEligibilityStatusToPendingVerification(onFile);
        this.attachMilitaryService(onFile);
        this.attachServiceConnectionAward(onFile, new Integer(10));
        this.attachMeansTestWithNoLongerRequired(onFile);
        
        
        Disability d8599 = this.getLookupService().getDisabilityByCode("8599");
        onFile.getServiceConnectionAward().setServiceConnectedPercentage(new Integer(0));
        onFile.getServiceConnectionAward().removeAllRatedDisability();
        RatedDisability rd1 = this.createRatedDisability(d8599, 10, ImpreciseDateUtils.createImpreciseDate(2001,1,1), ImpreciseDateUtils.createImpreciseDate(2001,1,1));
        RatedDisability rd2 = this.createRatedDisability(d8599, 0, ImpreciseDateUtils.createImpreciseDate(2002,2,1), ImpreciseDateUtils.createImpreciseDate(2002,2,1));
        
        //onfileRd2.setDiagnosticExtremity((DiagnosticExtremity)this.getLookupService().getByCode(DiagnosticExtremity.class, "RU"));
        onFile.getServiceConnectionAward().addRatedDisability(rd1);     
        onFile.getServiceConnectionAward().addRatedDisability(rd2);        
          
       	Set original = new HashSet();
       	// Save the original set for testing later
    	for (Iterator iterator = onFile.getServiceConnectionAward().getRatedDisabilities().iterator(); iterator.hasNext();) {
    		RatedDisability rd = (RatedDisability)iterator.next();
    		RatedDisability cloneRd = (RatedDisability)rd.clone();
    		original.add(cloneRd);
    	}        
        Person updated = this.getPersonService().save(onFile);
       
        Person incoming = (Person) updated.clone();
        VerificationInfo vi = createVerificationInfoFromORUZ11();
        incoming.getServiceConnectionAward().removeAllRatedDisability();
        Disability d5299 = this.getLookupService().getDisabilityByCode("5299");        
        Disability d8100 = this.getLookupService().getDisabilityByCode("8100");        
        Disability d7101 = this.getLookupService().getDisabilityByCode("7100");        
        /*
         * ZRD^1^8599^10^1^^^^^^^^^^
         * ZRD^2^5299^0^1^^^^^^^^^^ 
         * ZRD^3^8599^0^1^^^^^^^^^^
         * ZRD^4^8100^10^1^^^^^^^^^^ 
         * ZRD^5^5299^20^1^^^^^^^^^^
         * ZRD^6^7101^0^1^^^^^^^^^^
         */
        RatedDisability inRd1 = this.createRatedDisability(d8599, 10, null,null);
        RatedDisability inRd2 = this.createRatedDisability(d5299, 0, null,null);
        RatedDisability inRd3 = this.createRatedDisability(d8599, 0, null,null);
        RatedDisability inRd4 = this.createRatedDisability(d8100, 10, null,null);
        RatedDisability inRd5 = this.createRatedDisability(d5299, 20, null,null);
        RatedDisability inRd6 = this.createRatedDisability(d7101, 0, null,null);
        
        incoming.getServiceConnectionAward().addRatedDisability(inRd1);
        incoming.getServiceConnectionAward().addRatedDisability(inRd2);        
        incoming.getServiceConnectionAward().addRatedDisability(inRd3);
        incoming.getServiceConnectionAward().addRatedDisability(inRd4);
        incoming.getServiceConnectionAward().addRatedDisability(inRd5);
        incoming.getServiceConnectionAward().addRatedDisability(inRd6);
        
        Person result = this.getMessagingService().processNonQueryZ11(incoming,vi);     
        
        assertTrue(result.getServiceConnectionAward().getServiceConnectedPercentage().equals(new Integer(0)));
        assertTrue(result.getServiceConnectionAward().getRatedDisabilities().size() > 1);        
        for (Iterator i = original.iterator(); i.hasNext();){
        	 RatedDisability rd = (RatedDisability)i.next();
        	 RatedDisability match = (RatedDisability)this.getMergeRuleService().getMatchRuleService().findMatchingElement(
        			 rd, result.getServiceConnectionAward().getRatedDisabilities());
        	 if (match != null) {
        		 System.out.println("***MATCH****");        		 
        		 System.out.println("match  dates="+match.getRatingDate() + " and "+match.getOriginalEffectiveRatingDate() + " %=" + match.getPercentage());        		 
        		 System.out.println("onfile dates="+rd.getRatingDate() + " and "+ rd.getOriginalEffectiveRatingDate() + " %=" + rd.getPercentage());        		 
        		 if (rd.getDiagnosticExtremity() != null) {
                     assertNotNull("extremity should not be null", match.getDiagnosticExtremity());        			 
        		 }
        		 if (rd.getOriginalEffectiveRatingDate() != null) {
                     assertNotNull("eff date should not be null", match.getOriginalEffectiveRatingDate());        			 
        		 }
        		 if (rd.getRatingDate()!= null) {
                     assertNotNull("rating date should not be null", match.getRatingDate());        			 
        		 }
        	 }
        	 else {
        		 System.out.println("***NO MATCH****");
        	 }
        }
        System.out.println("count="+result.getServiceConnectionAward().getRatedDisabilities().size());
        for (Iterator i = result.getServiceConnectionAward().getRatedDisabilities().iterator(); i.hasNext();){
        	RatedDisability rd = (RatedDisability)i.next();
   		 	System.out.println("type="+rd.getDisability().getCode()+ 
   		 			"  result dates="+rd.getRatingDate() + 
   		 			" and "+ rd.getOriginalEffectiveRatingDate() + 
   		 			" %=" + rd.getPercentage());
        }
    }
    protected RatedDisability createRatedDisability(Disability type,
			Integer percent, ImpreciseDate origEffRatingDt, ImpreciseDate effRatingDt) throws Exception {
		RatedDisability ratedDisability = new RatedDisability();
		ratedDisability.setPercentage(percent);
		ratedDisability.setServiceConnected(Boolean.TRUE);
		ratedDisability.setDisability(type);
		ratedDisability.setOriginalEffectiveRatingDate(origEffRatingDt);
		ratedDisability.setRatingDate(effRatingDt);
		return ratedDisability;
	}    
    
    public void testDefect10969noOnfile() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        this.setEligibilityStatusToVerified(onFile);        
        this.attachMilitaryService(onFile);
        this.attachMeansTestWithNoLongerRequired(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person) updated.clone();
        VerificationInfo vi = createVerificationInfoFromORUZ11();
        this.attachServiceConnectionAward(incoming);
        RatedDisability dupRd = this.createRatedDisability();
        RatedDisability dupRd2 = this.createRatedDisability();
        incoming.getServiceConnectionAward().addRatedDisability(dupRd);        
        incoming.getServiceConnectionAward().addRatedDisability(dupRd2);
        
        Person result = this.getMessagingService().processNonQueryZ11(incoming,vi);
        assertTrue(result.getServiceConnectionAward().getRatedDisabilities().size() > 2);     
        System.out.println("data="+result.getServiceConnectionAward().getRatedDisabilities());
    }   
    protected Person testORFZ11(Person onFile) throws Exception {
        this.attachMilitaryService(onFile);
        this.attachServiceConnectionAward(onFile, new Integer(10));
        this.attachMeansTestWithNoLongerRequired(onFile);
        onFile.getServiceConnectionAward().setServiceConnectedPercentage(
                new Integer(0));
        
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person) updated.clone();
        
        incoming.setMonetaryBenefitAward(new MonetaryBenefitAward() );
        this.attachPension(incoming);
        VerificationInfo vi = createVerificationInfoFromORFZ11();
        
        return this.getMessagingService().processNonQueryZ11(incoming,vi);
    }    
    

    private void attachPension(Person person) throws Exception {
    	MonetaryBenefit ben = new MonetaryBenefit();
		ben.setType(this.getLookupService().getMonetaryBenefitTypeByCode(MonetaryBenefitType.CODE_VA_PENSION.getCode()));
		ben.setMonetaryBenefitIndicator(this.getLookupService().getIndicatorByCode(Indicator.YES));
		person.getMonetaryBenefitAward().addMonetaryBenefit(ben);
		Pension pension = ben.getPension();
		if (pension == null) {
			pension = new Pension();
			pension.setMonetaryBenefit(ben);
			ben.setPension(pension);
		}
		pension.setEffectiveDate(this.getDate(2009, 1, 1));
		pension.setTerminationDate(null);
		
		pension.setAwardReasonCode( this.getLookupService().getPensionReasonByCode("04"));
    }    
    public void testProcessORUZ07WithPHReject() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToVerified(onFile);  
        this.attachMilitaryService(onFile);
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone(); 
        this.attachPurpleHeartWithPHStatusPending(incoming);
//        PurpleHeartDocument purpleHeartDocument = this.createPHDocument();
//        purpleHeartDocument.setAcceptable(Boolean.FALSE);
//        purpleHeartDocument.setUnacceptableRemarks("bad");
//        incoming.getPurpleHeart().addDocument(purpleHeartDocument);
        incoming.getPurpleHeart().setPhIndicator(Boolean.FALSE);        
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());

        assertFalse(result.getPurpleHeart().getPhIndicator().booleanValue());
    }        
    
    public void testProcessORUZ07WithMBW() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingReverification(onFile);  
        
        this.attachMilitaryService(onFile);
        Person incoming = this.getPersonService().save(onFile);
//        this.attachAlliedVeteran(onFile);
        ReceivedEligibility re = this.createReceivedEligibility(EligibilityType.MEXICAN_BORDER_WAR);
        incoming.addReceivedSecondaryEligibility(re);
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        updated.getBirthRecord().getBirthDate();
        this.assessIfHasPrimaryRanking(EligibilityType.MEXICAN_BORDER_WAR.getName(), updated);
        ReceivedEligibility r = (ReceivedEligibility)updated.getReceivedSecondaryEligibilities().iterator().next();
        updated.removeReceivedSecondaryEligibility(r);
        updated.setReceivedPrimaryEligiblity(null);
        Person updated2 = this.getMessagingService().processZ07(updated, this.getRandomVAFacility(), new VerificationInfo());
        assertTrue(updated2.getReceivedSecondaryEligibilities().size() == 0);
        assertFalse(this.hasPrimaryEligibility(EligibilityType.MEXICAN_BORDER_WAR.getName(), updated2));
    }        
    
    public void testProcessORUZ07WithVet() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person incoming = this.getPersonService().save(onFile);
        this.attachEmployee(incoming);        
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertNotNull(updated.isVeteran());
        assertTrue(updated.isVeteran().booleanValue());
    }
    
    public void testProcessORUZ07WithIT() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        Person incoming = this.getPersonService().save(onFile);
        this.attachMeansTestWithMtStatusPendingAdjudication(incoming, new BigDecimal(1), new BigDecimal(1));        
        IncomeTest it = incoming.getIncomeTest(new Integer(2005));
        it.setSiteConductingTest(this.getRandomVAFacility());
        
        incoming.setFinancialStatement(new Integer(2005), this.createFinancialStatement());
        this.attachEmployee(incoming);        
        Person updated = this.getMessagingService().processZ07(incoming,it.getSiteConductingTest(), new VerificationInfo());
        assertTrue(updated.isVeteran().booleanValue());
    }      
    
    public void testProcessORUZ07WithCFNandCFL() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        onFile.setClaimFolderLocation(this.getRandomVAFacility());
        onFile.setClaimFolderNumber("12345");
        Person incoming = this.getPersonService().save(onFile);
        incoming.setClaimFolderLocation(this.getRandomVAFacility());        
        incoming.setClaimFolderNumber("678");
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertFalse(updated.getClaimFolderNumber().equals(incoming.getClaimFolderNumber()));
        assertFalse(updated.getClaimFolderLocation().equals(incoming.getClaimFolderLocation()));        
        
        onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        incoming = this.getPersonService().save(onFile);
        incoming.setClaimFolderNumber("678");
        incoming.setClaimFolderLocation(this.getRandomVAFacility());        
        updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertTrue(updated.getClaimFolderNumber().equals(incoming.getClaimFolderNumber()));        
        assertTrue(updated.getClaimFolderLocation().equals(incoming.getClaimFolderLocation()));        
    }    
    
    public void testprocessZ07DeleteAOE() throws Exception {
        Person onFile = buildSimplePerson();
        this.setEligibilityStatusToPendingReverification(onFile);  
        this.attachMilitaryService(onFile);
        this.attachAgentOrangeExposure(onFile);        
        Person incoming = this.getPersonService().save(onFile);
        incoming.removeAllSpecialFactors();
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        SpecialFactor sf = updated.getSpecialFactorByType(AgentOrangeExposure.class);
        assertNull(sf);
        assertTrue(updated.getSpecialFactors().size() == 0);
    }       
    
    public void testProcessORUZ07WithIneligibility() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        this.setEligibilityStatusToPendingVerification(onFile);        
        Person incoming = this.getPersonService().save(onFile);
        this.addPermanentAddress(incoming, Calendar.getInstance()
                .getTime(), null); 
        this.attachReceivedEnrollment(incoming);
        this.attachIneligibleFactorFromSite(incoming);
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        assertTrue(updated.getEligibilityVerification().getEligibilityStatus()
                .getCode().equals(EligibilityStatus.CODE_PENDING_VERIFICATION.getName()));
        assertNotNull(updated.getReceivedEnrollment().getEnrollmentStatus());
        
        assertNotNull(updated.getIneligibilityFactor());        
    }    
    
    public void testProcessORUZ07WithWorkload() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);
        this.setEligibilityStatusToPendingVerification(onFile);
        this.attachAidAndAttendance(onFile);

        this.attachVerifiedEnrollment(onFile); // to make existing person
        Person incoming = this.getPersonService().save(onFile);     
        this.attachIneligibleFactorFromSite(incoming);
        this.attachHousebound(incoming);
       
        VerificationInfo vi = new VerificationInfo();
        WorkflowCaseInfo workflowCaseInfo = new WorkflowCaseInfo();
        workflowCaseInfo.setErrorMessage("test");
        workflowCaseInfo.setMessageID("fsdf");
        vi.setWorkflowCaseInfo(workflowCaseInfo);
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), vi);

        assertNull( updated.getIneligibilityFactor() );                     
    }    
    
    public void testProcessORUZ07Defect835() throws Exception {
        Person onFile = buildSimplePerson();
        Person incoming = this.getPersonService().save(onFile);
        this.setEligibilityStatusToVerified(incoming);
        // FIXME
        /*
        this.attachPOW(incoming);
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility());
        assertTrue(updated.getPrisonerOfWarRecords().size() == 0);
        */
    }    
    
    public void testProcessORUZ07EligibilityUnverified() throws Exception {
        Person onFile = buildSimplePerson();
        Person updated = this.getPersonService().save(onFile);
        Person incoming = (Person)updated.clone();
        this.attachMilitaryService(incoming);
        // Person would be P1 except that eligibility status will get set to Pending since
        // person is new and need to verify eligibility with VBA
        this.attachServiceConnectionAward(incoming, new Integer(75));
        //this.setEligibilityStatusToVerified(incoming);
        Person result = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), null);
        assertNull(result.getEnrollmentDetermination().getPriorityGroup());
        assertTrue(result.getEnrollmentDetermination().getEnrollmentStatus().getCode().equals(EnrollmentStatus.CODE_PENDING_ELIGIBILITY_STATUS_IS_UNVERIFIED.getName()));        
    }    
    
    public void testProcessORUZ05() throws Exception {
        Person person  = this.buildPerson();
        this.getPersonService().save(person);
        this.addPermanentAddress(person, Calendar.getInstance()
                .getTime(), null);
        this.getMessagingService().processORUZ05(person);
    }
    
    public void testDefect2220() throws Exception {
        Person onFile = this.buildSimplePerson();
        // Attach a means test to the person
        this.setEligibilityStatusToVerified(onFile);
        this.attachMeansTestWithNoLongerRequired(onFile);
        this.attachServiceConnectionAward(onFile, new Integer(0));        
        this.attachVerifiedEnrollment(onFile);
        this.attachMilitaryService(onFile);        
        Person incoming = this.getPersonService().save(onFile);        
        this.attachServiceConnectionAward(incoming, new Integer(0));
        incoming.getServiceConnectionAward().addRatedDisability(this.createRatedDisability());
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), null);
        IncomeTest it =  this.getPersonHelperService().getCurrentIncomeTest(updated);
        IncomeTestStatus its =  it.getIncomeTestStatusOfType(IncomeTestType.CODE_MEANS_TEST);
        
        assertTrue(MeansTestStatus.MT_STATUS_REQUIRED.getName().equals(its.getStatus().getCode()));
   
        }     
    
    public void testPurpleHeartIsYESFromSite() throws Exception 
    {
        Person onFile = buildSimplePerson();
        // Set the incoming with PH equal No
        this.attachPurpleHeartWithPHStatusPending(onFile);
        attachFacilityToPurpleHeart(onFile,VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER.getName());
        
        // Set the purple heart status to NO
        this.setPurpleHeartToNo(onFile);              
        this.attachMilitaryService(onFile);        
        Person incoming = this.getPersonService().save(onFile);       
        PurpleHeart incomingPurpleHeart = this.getPersonHelperService().getPurpleHeart(incoming);
        incomingPurpleHeart.setPhIndicator(Boolean.TRUE);
        incomingPurpleHeart.setRejectionRemark(null);
        
        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());

        assertEquals(1, updated.getDecorations().size());
        PurpleHeart resultPurpleHeart = this.getPersonHelperService().getPurpleHeart(updated);
        assertNotNull(resultPurpleHeart);
        
        Boolean PHIndicator = resultPurpleHeart.getPhIndicator();
        assertTrue("Indicator is set to false.",PHIndicator.booleanValue());
        String purpleHeartStatus = resultPurpleHeart.getStatus().getCode();
        assertEquals(DecorationStatus.CODE_PENDING.getName(), purpleHeartStatus);
        String facility = resultPurpleHeart.getFacility().getCode();
        assertEquals(facility,VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER.getName());
        
        // The incoming PH had no remark text so processing should reset text 
        assertNull(resultPurpleHeart.getRejectionRemark());        
    }    
    
    public void testPurpleHeartIsNOFromSite() throws Exception 
    {
        Person onFile = buildSimplePerson();
        this.attachMilitaryService(onFile);        
        Person incoming = this.getPersonService().save(onFile);            
     
        // Set the incoming with PH equal No
        this.attachPurpleHeartWithPHStatusPending(incoming);
        attachFacilityToPurpleHeart(incoming,VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER.getName());
        
        // Set the purple heart status to NO
        this.setPurpleHeartToNo(incoming);      

        Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
        
        assertEquals(1, onFile.getDecorations().size());
        PurpleHeart resultPurpleHeart = this.getPersonHelperService().getPurpleHeart(updated);
        assertNotNull(resultPurpleHeart);
        
        Boolean PHIndicator = resultPurpleHeart.getPhIndicator();
        assertFalse("Indicator is set to true.",PHIndicator.booleanValue());
        // The incoming PH had rejection text 
        assertNotNull(resultPurpleHeart.getRejectionRemark());     
    }    
    
    public void testIsEnrollmentPriorityEqualTo5PartOne() throws Exception {
        try {
            Person onFile = buildSimplePerson(); // bare-bones person
            this.attachMexicanBorderWar(onFile);
            this.attachMilitaryService(onFile);            
            this.setEligibilityStatusToVerified(onFile);
            this.attachVerifiedEnrollment(onFile);
            
            Person incoming = this.getPersonService().save(onFile);

            incoming.setFinancialStatement(new Integer(2005), this.createFinancialStatement());
            this.attachMeansTestWithMtCopayExempt(onFile);

            Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
            assessPriorityResult(updated, EnrollmentPriorityGroup.GROUP_5);
            System.out.println("Person id=" + updated.getPersonEntityKey().getKeyValueAsString());

            logger.info("Completed testIsEnrollmentPriorityEqualto5");
        } catch (Exception e) {
            fail("failed due to exception " + e);
        }
    }
    
    public void testIsEnrollmentPriorityEqualTo5PartTwo() throws Exception {
        try {
            PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("230045"));
            Person incoming = this.getPersonService().getPerson(personKey);
            
            Person updated = this.getMessagingService().processZ07(incoming, this.getRandomVAFacility(), new VerificationInfo());
            this.setComplete();
            System.out.println("Person id=" + incoming.getPersonEntityKey().getKeyValueAsString());
            if (updated.getEnrollmentDetermination().getPriorityGroup() != null) {
                assertFalse(updated.getEnrollmentDetermination().getPriorityGroup().getCode().equals(EnrollmentPriorityGroup.GROUP_5.getName()));
            }

            logger.info("Completed testIsEnrollmentPriorityEqualto5");
        } catch (Exception e) {
            fail("failed due to exception " + e);
        }
    }                
    
    public void testPocessORUZ04() {
        
    }
    
    public void testProcessQRYZ10() throws Exception {
        Person onFile = buildSimplePerson();

        this.attachMeansTestWithMtCopayExempt(onFile);
        IncomeTest current = this.getPersonHelperService().getCurrentIncomeTest(onFile);
        current.setIncomeYear(new Integer(2002));
        
        Person incoming = this.getPersonService().save(onFile);       

        IncomingMessageInfo imi = new IncomingMessageInfo();
        imi.setQueryDateTime(new Date());
        imi.setReferenceMessageId("1234");
        imi.setSendingFacility(this.getRandomVAFacility());
        this.getMessagingService().processQRYZ10(incoming, new Integer(2005), imi);        
    }
        
    public void testProcessQRYZ11() throws Exception {
        Person onFile = buildSimplePerson();
        Person incoming = this.getPersonService().save(onFile);       
        IncomingMessageInfo imi = new IncomingMessageInfo();
        imi.setQueryDateTime(new Date());
        imi.setReferenceMessageId("1234");
        imi.setSendingFacility(this.getRandomVAFacility());        
        this.getMessagingService().processQRYZ11(incoming, imi);        
    }    
    
    public void testProcessORUZ12() throws Exception {
        Person incoming = setupZ12Z13();       
        this.getMessagingService().processORUZ12(incoming, this.getRandomVAFacility());               
    }
    
    
    public void testProcessORUZ13() throws Exception {
        Person incoming = setupZ12Z13();
        incoming.setDeathRecord(null);
        this.getMessagingService().processORUZ13(incoming, this.getRandomVAFacility());               
    }
    
    public void testProcessORFZ11() {
        
    }
    
    public void triggerQRYZ07() 
    {
    }
    
    public void testTriggerRetransmission() throws ServiceException
    {
        this.getMessagingService().triggerRetransmission(new BigDecimal(245097));
    }

    
    public void testFindSiteLastTransmittedMsg() throws Exception {
        
        VAFacility facility = this.getMessagingService().findSiteLastTransmittedMsg(
                CommonEntityKeyFactory.createPersonIdEntityKey("73009"));
        
        assertNotNull("last Transmitted Site is null", facility);
    }


    /**
     * @return Returns the messagingService.
     */
    public MessagingService getMessagingService() {
        return messagingService;
    }


    /**
     * @param messagingService The messagingService to set.
     */
    public void setMessagingService(MessagingService messagingService) {
        this.messagingService = messagingService;
    }
    
    private Person setupZ12Z13() throws Exception {
        Person onFile = buildSimplePerson();
        this.attachVerifiedEnrollment(onFile);
        this.attachDeathRecordFromSite(onFile);
                
        return this.getPersonService().save(onFile);        
    }


   public void testCCR7443() throws Exception
   {
	   String msg = "MSH^~|\\&^VAMC 552^552^ESR^200ESR^20030904121212-0500^^ORU~Z07^99990000-1^T^2.1^^^AL^AL^USA\n" +
	   "PID^1^1000913833V082573^5520676~~~USVHA&&0363~PI~VA FACILITY ID&552&L^^ESRPATIENT~FNAME~X~~~^^19270101^M^^^557 OREGONS~\"\"~LITTLE FALLS~NY~13333-1633~USA~VACAE~STE 322~~~~20020125&20060125|3400 EDS DRIVE~\"\"~HERNDON~VA~20171-1633~USA~P~STE 322~~~~20020125&20060125^^(999)123-0001~PRN~PH|(999)123-0002~WPN~PH|(999)123-0003~ORN~CP|(999)123-0004~BPN~BP|~NET~INTERNET~EMAIL@FOO.COM^(999)123-0005X3464^^^^^134673732\n" +
	   "PD1^^^DAYTON~~552\n"+ 
	   "ZPD^1^^^^^^^0^\"\"^^0^0^199109030832-0500^^^^U^^0^^^^^^^^^^^^\"\"^\"\"^\"\"^^CIV SER^^^^^\"\"\n" +
	   "ZTA^1^1^20050321^20050416^64 NEW ENGLAND~\"\"~BIG FALLS~NY~13333-1633~USA~~STE 153^043^(800)934-7534^20041019164937-0400^552\n" +
	   "ZIE^1^\"\"^\"\"^^\n" +
	   "ZEL^1^3^^^\"\"^10000007^552^1^^V^20000129^^VIVA^0^0^0^1^0^1^0^3876^2^N^20030422151958-0400^552^^^^\"\"^^^^^20050000^554^^0^\"\"^\"\"^\"\"\n" +
	   "ZEN^1^19981029^1^1^\"\"^\"\"^552^552^\"\"^20060308^19981029^\"\"^\"\"\n" +
	   "ZCD^1^20041109^DR SMITH^552^20041109^3~PHYSICAL EXAMINATION~VA0041^369.4~Blindness~ICD DIAGNOSIS^\"\"^\"\"^\"\"^\"\"^Y^\"\"^20040920^20041020^20041120\n" +
	   "ZCD^2^20041109^DR SMITH^552^20041109^3~PHYSICAL EXAMINATION~VA0041^780.03~Persistent Vegetative State~ICD DIAGNOSIS^\"\"^\"\"^\"\"^\"\"^Y^\"\"\n" +
	   "ZCD^3^20041109^DR SMITH^552^20041109^3~PHYSICAL EXAMINATION~VA0041^\"\"^84.17~Above Knee Amputation~ICD OPERATION/PROCEDURE^2~RLE~VA0042^\"\"^\"\"^Y^\"\"\n" +
	   "ZCD^4^20041109^DR SMITH^552^20041109^3~PHYSICAL EXAMINATION~VA0041^\"\"^84.17~Above Knee Amputation~ICD OPERATION/PROCEDURE^4~LLE~VA0042^\"\"^\"\"^Y^\"\"\n" +
	   "ZCD^5^20041109^DR SMITH^552^20041109^3~PHYSICAL EXAMINATION~VA0041^\"\"^\"\"^\"\"^2~FOLS~VA0043^10^Y^1~PERMANENT~VA0045\n" +
	   "ZCD^6^20041109^DR SMITH^552^20041109^3~PHYSICAL EXAMINATION~VA0041^\"\"^\"\"^\"\"^1~KATZ~VA0043^4^Y^2~NOT PERMANENT~VA0045\n" +
	   "ZMH^1^SL^ARMY~00552455~HONORABLE^19620216~19720131^R\n" +
	   "ZMH^2^SNL^ARMY~17235361~HONORABLE^19440316~19460826^R\n" +
	   "ZMH^2^POW^Y~\"\"^\"\"~\"\"^\"\"\n" +
	   "ZMH^3^COMB^Y~WORLD WAR II - EUROPE^\"\"\n" +
	   "ZMH^4^LEBA^Y^19831010~19831110^\"\"\n" +
	   "ZMH^5^GREN^N^\"\"~\"\"^\"\"\n" +
	   "ZMH^6^PANA^N^\"\"~\"\"^\"\"\n" +
	   "ZMH^7^GULF^Y^\"\"\n" +
	   "ZMH^8^SOMA^N^\"\"~\"\"^\"\"\n" +
	   "ZMH^9^PH^Y~1~1^\"\"^\"\"\n" +
	   "ZRD^1^7913~DIABETES MELLITUS^40^1\n" +
	   "ZRD^2^7017~CORONARY ARTERY BYPASS^30^1\n" +
	   "ZRD^3^8520~PARALYSIS OF SCIATIC NERVE^20^1\n" +
	   "ZRD^4^8520~PARALYSIS OF SCIATIC NERVE^20^1\n" +
	   "ZRD^5^5284~RESIDUALS OF FOOT INJURY^20^1\n" +
	   "ZRD^6^6079~IMPAIRED VISION^0^1\n" +
	   "ZCT^1^1^ESRWIFE~FNAME~~~~~L^WIFE^PO BOX 1534~112 ELM STREET~HEBRON~OH~430251534^(666)666-5296^\"\"^^^20060823132750-0400\n" +
	   "ZEM^1^1^5^^^^^\n" +
	   "ZEM^2^2^3^^^^^\n" +
	   "ZGD^1^1^PVA^\"\"^\"\"^133 HOLLAND~~ALBANY~NY~12208^(518)225-2210^20051010\n" +
	   "ZGD^2^2^\"\"^\"\"^\"\"^\"\"^\"\"^\"\"\n" +
	   "ZIC^1^20050000^\"\"^^^^^^\"\"^^^\"\"^\"\"^\"\"^\"\"^\"\"^^\"\"^\"\"^\n" +
	   "ZIR^\n" +
	   "ZDP^1^MARTINEZ~SUZIE^F^19500815^189440133^2^76035^JONES,SUZIE^19831215^\"\"\n" +
	   "ZIC^1^20050000^\"\"^^^^^^\"\"^^^\"\"^^^^\"\"^^\"\"^\"\"^\n" +
	   "ZIR^1^\"\"^\"\"^^^^^^^^^^^\n" +
	   "ZDP^1^MARTINEZ~JOE^M^19910915^388104010^3^76036^^19910915^\"\"\n" +
	   "ZIC^1^20050000^\"\"^^^^^^\"\"^^^\"\"^^^\"\"^\"\"^^\"\"^\"\"^\n" +
	   "ZIR^1^\"\"^1^^^0^\"\"^0^\"\"^^^^^N\n" +
	   "ZDP^1^MARTINEZ~FRED^M^19840915^380114910^3^76037^^19840923^\"\"^19840923\n" +
	   "ZIO^1^0^0^20000403^\"\"^\"\"\n" +
	   "NTE^1^^:A MEANS TEST was edited on Oct 19, 2004 4:49:37 pm with data inconsistencies.\n" +
	   "NTE^2^^: MT Copay Exempt veteran-Agree to Pay Deductible should be null\n" +
	   "IN1^1^^^ALLMERICAN FINANCIALs^334 PIERCE ROAD SUITE 310~~ITASCA~IL~60150~USA^^(800)431-5197^25186-012^BENGA INDUSTRY^^^19951119^\"\"^^40^FOOTE,RONALD A^v^^^^^^^^^^^1^^^^^^^^370585261\n" +
	   "IN1^1^^^MEDICARE (WNR)^\"\"^^(877)591-1587^\"\"^PART A^^^20010501^\"\"^^33^INSURANCE,JOE^v^^^^^^^^^^^0^^^^^^^^368739846A\n" +
	   "IN1^2^^^MEDICARE (WNR)^\"\"^^(877)591-1587^\"\"^PART B^^^20011201^\"\"^^33^INSURANCE,JOE^v^^^^^^^^^^^0^^^^^^^^368739846B\n" +
	   "ZMT^1^20060101^C^31800^0^\"\"^1^23688^0^20060101000001-0400^\"\"^0^0^\"\"^\"\"^\"\"^1^1^^^\"\"^552^^^20030124071207-0400^C^^0^^0\n" +
	   "ZMT^2^20060831^E^469^\"\"^\"\"^\"\"^^0^200608311351-0400^^1^^^\"\"^\"\"^2^1^^^\"\"^987^^^20060831135159-0400^E\n" +
	   "ZMT^4^^^^^^^^^^^^^^^^^^^^^\n" +
	   "ZBT^1\n" +
	   "ZSP^1^1^80^0^Y^0^1^\"\"^^\"\"\n" +
	   "OBX^1^CE^38.1~SECURITY LOG^^Y~YES~HL70136^^^^^^R^^^200606031704-0400^^\"\"^\n" +
	   "OBX^2^CE^VISTA~28.11^^5~No NTR Trmt~VA0053^^^^^^F^\"\"^^20040510120149-0400^554^\"\"^\"\"\n" +
	   "RF1^^^SAD^^^552~USVAMC^20060309101714-0500^^^\n" +
	   "RF1^^^CPH^^^552~USVAMC^20060627111830-0400^^^\n" +
	   "RF1^^^PNO^^^552~USVAMC^20060627111845-0400^^^\n" +
	   "RF1^^^EAD^^^552~USVAMC^20060627111952-0400^^^";
	   
	   String[] fields= msg.split("\\^", 5);
        
		System.out.println("0=" + fields[0] +"    1=" + fields[1] +"    2=" + fields[2] +"    3=" + fields[3] );
	   PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("230045"));
	   
	   java.util.List list = this.messagingService .findVoaAaAckLogEntryByPersonId(personKey);
	   
	   assertTrue(list.size()==0);
	   
	   personKey = new PersonIdEntityKeyImpl(new BigDecimal("1515"));
	   list  = this.messagingService .findVoaAaAckLogEntryByPersonId(personKey);
	   assertTrue(list.size()==1);
	   
	   personKey = new PersonIdEntityKeyImpl(new BigDecimal("106"));
	   list  = this.messagingService .findVoaAaAckLogEntryByPersonId(personKey);
	   assertTrue(list.size()==9);

	   
	   
   }

	/**
	 * Checks for the existence of any Vista events
	 */
	private boolean hasVistaEvents() {
		
		if (getTriggerEventCacheManager().getTriggerEvents() == null || getTriggerEventCacheManager().getTriggerEvents().size() == 0)
			return false;

		Iterator iter = getTriggerEventCacheManager().getTriggerEvents().iterator();

		while (iter.hasNext()) {
			Object item = iter.next();
			if (item instanceof PersonTriggerEvent) {
				TriggerIdentity tid = ((PersonTriggerEvent) item).getTriggerIdentity();
				if (PersonTrigger.DestinationType.MESSAGING.getName().equals(
						tid.getDestinationType().getName())
						&& PersonTrigger.TargetType.VISTA.getName().equals(
								tid.getTargetType().getName())) {
					return true;
				}
			}
		}
		return false;
	}

   public ApplicationInProcessService getApplicationInProcessService() {
	   return applicationInProcessService;
   }

   public void setApplicationInProcessService(
		   ApplicationInProcessService applicationInProcessService) {
	   this.applicationInProcessService = applicationInProcessService;
   }
}
