package gov.va.med.esr.common.util;

// Java classes
import gov.va.med.esr.common.infra.ImpreciseDate;
import gov.va.med.esr.common.infra.ImpreciseDateUtils;
import gov.va.med.esr.common.infra.TriState;
import gov.va.med.esr.common.model.CommonEntityKeyFactory;
import gov.va.med.esr.common.model.comms.CommsLogEntry;
import gov.va.med.esr.common.model.comms.CommsTemplate;
import gov.va.med.esr.common.model.ee.AgentOrangeExposure;
import gov.va.med.esr.common.model.ee.Application;
import gov.va.med.esr.common.model.ee.CDDescriptor;
import gov.va.med.esr.common.model.ee.CampLejeuneVerification;
//import gov.va.med.esr.common.model.ee.CampLejeuneVerificationMethod;
import gov.va.med.esr.common.model.ee.CancelDecline;
import gov.va.med.esr.common.model.ee.CatastrophicDisability;
import gov.va.med.esr.common.model.ee.CombatEpisode;
import gov.va.med.esr.common.model.ee.ConflictExperience;
import gov.va.med.esr.common.model.ee.EGTProcessStatistic;
import gov.va.med.esr.common.model.ee.EGTSetting;
import gov.va.med.esr.common.model.ee.EGTSiteStatistic;
import gov.va.med.esr.common.model.ee.Eligibility;
import gov.va.med.esr.common.model.ee.EligibilityVerification;
import gov.va.med.esr.common.model.ee.EnrollmentDetermination;
import gov.va.med.esr.common.model.ee.EnvironmentalContaminationExposure;
import gov.va.med.esr.common.model.ee.FeeBasis;
import gov.va.med.esr.common.model.ee.HealthBenefitPlan;
import gov.va.med.esr.common.model.ee.HealthBenefitProfile;
import gov.va.med.esr.common.model.ee.HealthBenefitPlan;
import gov.va.med.esr.common.model.ee.HealthBenefitProfile;
import gov.va.med.esr.common.model.ee.IncompetenceRuling;
import gov.va.med.esr.common.model.ee.IneligibilityFactor;
import gov.va.med.esr.common.model.ee.MedicaidFactor;
import gov.va.med.esr.common.model.ee.MilitaryService;
import gov.va.med.esr.common.model.ee.MilitaryServiceEpisode;
import gov.va.med.esr.common.model.ee.MilitaryServiceSiteRecord;
import gov.va.med.esr.common.model.ee.MilitarySexualTrauma;
import gov.va.med.esr.common.model.ee.MonetaryBenefit;
import gov.va.med.esr.common.model.ee.MonetaryBenefitAward;
import gov.va.med.esr.common.model.ee.NoseThroatRadium;
import gov.va.med.esr.common.model.ee.POWEpisode;
import gov.va.med.esr.common.model.ee.PrisonerOfWar;
import gov.va.med.esr.common.model.ee.PurpleHeart;
import gov.va.med.esr.common.model.ee.PurpleHeartDocument;
import gov.va.med.esr.common.model.ee.RadiationExposure;
import gov.va.med.esr.common.model.ee.RatedDisability;
import gov.va.med.esr.common.model.ee.ReceivedEligibility;
import gov.va.med.esr.common.model.ee.ReceivedEnrollment;
import gov.va.med.esr.common.model.ee.ServiceConnectionAward;
import gov.va.med.esr.common.model.ee.VerificationInfo;
import gov.va.med.esr.common.model.financials.Asset;
import gov.va.med.esr.common.model.financials.BeneficiaryTravel;
import gov.va.med.esr.common.model.financials.Debt;
import gov.va.med.esr.common.model.financials.DependentFinancials;
import gov.va.med.esr.common.model.financials.Expense;
import gov.va.med.esr.common.model.financials.FinancialInformation;
import gov.va.med.esr.common.model.financials.FinancialStatement;
import gov.va.med.esr.common.model.financials.Hardship;
import gov.va.med.esr.common.model.financials.Income;
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.financials.PatientVisitSummary;
import gov.va.med.esr.common.model.financials.SpouseFinancials;
import gov.va.med.esr.common.model.insurance.InsurancePlan;
import gov.va.med.esr.common.model.insurance.Medicare;
import gov.va.med.esr.common.model.insurance.PrivateInsurance;
import gov.va.med.esr.common.model.lookup.AACIndicator;
import gov.va.med.esr.common.model.lookup.AddressType;
import gov.va.med.esr.common.model.lookup.AgentOrangeExposureLocation;
import gov.va.med.esr.common.model.lookup.AlliedCountry;
import gov.va.med.esr.common.model.lookup.AssetType;
import gov.va.med.esr.common.model.lookup.AssociationType;
import gov.va.med.esr.common.model.lookup.CDDeterminationMethod;
import gov.va.med.esr.common.model.lookup.CampLejeuneChangeSource;
import gov.va.med.esr.common.model.lookup.CampLejeuneVerificationType;
import gov.va.med.esr.common.model.lookup.ComLetterType;
import gov.va.med.esr.common.model.lookup.ComMailingStatusType;
import gov.va.med.esr.common.model.lookup.ConflictLocation;
import gov.va.med.esr.common.model.lookup.DecorationStatus;
import gov.va.med.esr.common.model.lookup.Disability;
import gov.va.med.esr.common.model.lookup.DischargeType;
import gov.va.med.esr.common.model.lookup.EGTSettingType;
import gov.va.med.esr.common.model.lookup.EGTStatus;
import gov.va.med.esr.common.model.lookup.EligibilityStatus;
import gov.va.med.esr.common.model.lookup.EligibilityType;
import gov.va.med.esr.common.model.lookup.EligibilityVerificationSource;
import gov.va.med.esr.common.model.lookup.EmailType;
import gov.va.med.esr.common.model.lookup.EnrollmentCategory;
import gov.va.med.esr.common.model.lookup.EnrollmentOverrideReason;
import gov.va.med.esr.common.model.lookup.EnrollmentPriorityGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentPrioritySubGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentSource;
import gov.va.med.esr.common.model.lookup.EnrollmentStatus;
import gov.va.med.esr.common.model.lookup.ExpenseType;
import gov.va.med.esr.common.model.lookup.FederalAgency;
import gov.va.med.esr.common.model.lookup.FeeBasisProgram;
import gov.va.med.esr.common.model.lookup.FeeBasisTreatmentType;
import gov.va.med.esr.common.model.lookup.Gender;
import gov.va.med.esr.common.model.lookup.IncomeTestSource;
import gov.va.med.esr.common.model.lookup.IncomeTestType;
import gov.va.med.esr.common.model.lookup.IncomeType;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.lookup.InsurancePlanType;
import gov.va.med.esr.common.model.lookup.InsuranceReportSource;
import gov.va.med.esr.common.model.lookup.InsuredRelationship;
import gov.va.med.esr.common.model.lookup.MeansTestStatus;
import gov.va.med.esr.common.model.lookup.MilitarySexualTraumaStatus;
import gov.va.med.esr.common.model.lookup.MonetaryBenefitType;
import gov.va.med.esr.common.model.lookup.NTRVerificationMethod;
import gov.va.med.esr.common.model.lookup.NameType;
import gov.va.med.esr.common.model.lookup.PHDocumentType;
import gov.va.med.esr.common.model.lookup.PhoneType;
import gov.va.med.esr.common.model.lookup.PrisonerOfWarLocation;
import gov.va.med.esr.common.model.lookup.RadiationExposureMethod;
import gov.va.med.esr.common.model.lookup.RegistryType;
import gov.va.med.esr.common.model.lookup.Relationship;
import gov.va.med.esr.common.model.lookup.SSNType;
import gov.va.med.esr.common.model.lookup.ServiceBranch;
import gov.va.med.esr.common.model.lookup.ServicePeriod;
import gov.va.med.esr.common.model.lookup.SignatureIndicator;
import gov.va.med.esr.common.model.lookup.SourceDesignation;
import gov.va.med.esr.common.model.lookup.TeamPurpose;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.party.Address;
import gov.va.med.esr.common.model.party.Email;
import gov.va.med.esr.common.model.party.Phone;
import gov.va.med.esr.common.model.party.SimpleAddress;
import gov.va.med.esr.common.model.person.Association;
import gov.va.med.esr.common.model.person.BirthRecord;
import gov.va.med.esr.common.model.person.DeathRecord;
import gov.va.med.esr.common.model.person.Dependent;
import gov.va.med.esr.common.model.person.HealthCareProvider;
import gov.va.med.esr.common.model.person.Name;
import gov.va.med.esr.common.model.person.PatientProviderAssignment;
import gov.va.med.esr.common.model.person.PatientProviderAssignmentLite;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.PreferredFacility;
import gov.va.med.esr.common.model.person.PreferredFacilityLite;
import gov.va.med.esr.common.model.person.PreferredFacilityPerson;
import gov.va.med.esr.common.model.person.SSN;
import gov.va.med.esr.common.model.person.SignatureImage;
import gov.va.med.esr.common.model.person.Spouse;
import gov.va.med.esr.common.model.person.id.PersonEntityKey;
import gov.va.med.esr.common.model.person.id.VPIDEntityKey;
import gov.va.med.esr.common.model.registry.Registry;
import gov.va.med.esr.common.model.registry.RegistryTrait;
import gov.va.med.esr.common.persistent.comms.CommsTemplateDAO;
import gov.va.med.esr.service.AssociationService;
import gov.va.med.esr.service.ClinicalDeterminationService;
import gov.va.med.esr.service.DemographicService;
import gov.va.med.esr.service.EEServiceAdminService;
import gov.va.med.esr.service.EGTService;
import gov.va.med.esr.service.EligibilityEnrollmentService;
import gov.va.med.esr.service.FinancialsService;
import gov.va.med.esr.service.HandBookService;
import gov.va.med.esr.service.InsuranceService;
import gov.va.med.esr.service.LookupService;
import gov.va.med.esr.service.MessagingService;
import gov.va.med.esr.service.MilitaryInfoService;
import gov.va.med.esr.service.PSDelegateService;
import gov.va.med.esr.service.PersonHelperService;
import gov.va.med.esr.service.PersonService;
import gov.va.med.esr.service.UserAdminService;
import gov.va.med.esr.service.VOAApplicationService;
import gov.va.med.esr.service.external.ExternalSummaryFactory;
import gov.va.med.esr.service.impl.IdmWebServiceDelegate;
import gov.va.med.fw.conversion.CopyService;
import gov.va.med.fw.model.lookup.Lookup;
import gov.va.med.fw.persistent.DAOOperations;
import gov.va.med.fw.security.LoginManager;
import gov.va.med.fw.util.AbstractTestCase;
import gov.va.med.fw.util.StringUtils;
import gov.va.med.ps.model.PersonVPID;
import gov.va.med.esr.common.persistent.person.PersonDAO;

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

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.Validate;

/**
 * @author Yi He
 */
public abstract class AbstractCommonTestCase extends AbstractTestCase {

	// path in common.jar
	protected static final String COMMONS_CONTEXT = "commons/applicationContext.xml";

	// path in test_resource.jar
	protected static final String DEFAULT_TEST_CONTEXT = "commons/test_components.xml";

	private Integer INCOME_YEAR = new Integer("2005");

	private DAOOperations dao;

	private LookupService lookupService = null;

	private PersonHelperService personHelperService = null;

	private EligibilityEnrollmentService eligibilityEnrollmentService = null;

    private VOAApplicationService voaApplicationService = null;

	private PersonService personService = null;

	protected LoginManager loginManager;

	private ClinicalDeterminationService clinicalDeterminationService = null;

	private DemographicService demographicService = null;

	private EGTService egtService = null;

	private InsuranceService insuranceService = null;

	private MessagingService messagingService = null;

	private MilitaryInfoService militaryInfoService = null;

	private AssociationService associationService = null;

	private PSDelegateService psDelegateService = null;

	private FinancialsService financialsService = null;

	private HandBookService handBookService = null ;

	private CopyService copyService = null;

	private UserAdminService userAdminService = null;

	private EEServiceAdminService eeServiceAdminService = null;

	private ExternalSummaryFactory externalSummaryFactory = null;

	private PersonDAO personDAO = null;

	private IdmWebServiceDelegate idmServiceDelegate = null;

	// #####################################
	// ### below are used for test drivers in Common
	// #####################################
	// allows subclasses to not have to name testcases
	protected AbstractCommonTestCase() {
		super(new String[] { COMMONS_CONTEXT, DEFAULT_TEST_CONTEXT });
	}

	// preserved for old code
	protected AbstractCommonTestCase(String testName) {
		super(testName, new String[] { COMMONS_CONTEXT, DEFAULT_TEST_CONTEXT });
	}

	// #####################################
	// ### below are used for test drivers in Common clients (eg, UI and
	// Messaging)
	// #####################################
	// allows subclasses to not have to name testcases
	protected AbstractCommonTestCase(String[] configFiles) {
		super(configFiles, new String[] { COMMONS_CONTEXT });
	}

	// preserved for old code
	protected AbstractCommonTestCase(String testName, String[] configFiles) {
		super(testName, configFiles, new String[] { COMMONS_CONTEXT });
	}

	protected void customSetUp() throws Exception {
		if (shouldLoginForTest())
			loginManager.loginAnonymous("JUnit");
	}

	/** Subclasses can override this */
	protected boolean shouldLoginForTest() {
		return true;
	}

	/*
	 * Since Messaging defines a bean of type PersonService also, then autowire
	 * by type will not work (when extended and used by Messaging). Therefore,
	 * we will set this lazily in getter method... public void
	 * setPersonService(PersonService personService) { this.personService =
	 * personService; }
	 */

	protected PersonService getPersonService() throws Exception {
		if (personService == null)
			personService = (PersonService) this.applicationContext
					.getBean("personService");
		return personService;
	}

	protected PersonDAO getPersonDAO() throws Exception {
		if (personDAO == null)
			personDAO = (PersonDAO) this.applicationContext
					.getBean("personDAO");
		return personDAO;
	}

	protected PSDelegateService getPsDelegateService() throws Exception {
		if (psDelegateService == null)
			psDelegateService = (PSDelegateService) this.applicationContext
					.getBean("psDelegateService");
		return psDelegateService;
	}

	protected  IdmWebServiceDelegate getIdmWebServiceDelegate() throws Exception {
		if (idmServiceDelegate == null)
			idmServiceDelegate = (IdmWebServiceDelegate) this.applicationContext
					.getBean("idmServiceDelegate");
		return idmServiceDelegate;

	}



	protected ServiceConnectionAward createServiceConnectionAward(
			int percentage, boolean includeRatedDisability) throws Exception {
		ServiceConnectionAward serviceConnectionAward = new ServiceConnectionAward();
		serviceConnectionAward.setServiceConnectedPercentage(new Integer(
				percentage));
		serviceConnectionAward.setUnemployable(Boolean.FALSE);
		if (includeRatedDisability) {
			serviceConnectionAward.addRatedDisability(this
					.createRatedDisability(
							Disability.CODE_RESPIRATORY_CONDITION_GENERAL
									.getName(), new Integer(percentage)));
		}
		return serviceConnectionAward;
	}

	/**
	 * Builds a basic person with some default settings.
	 *
	 * @return
	 * @throws Exception
	 */
	protected Person buildPerson() throws Exception {
		Person person = this.buildSimplePerson();

		ServiceConnectionAward serviceConnectionAward = createServiceConnectionAward(
				60, true);
		serviceConnectionAward.addRatedDisability(this.createRatedDisability(
				Disability.CODE_RESPIRATORY_CONDITION_GENERAL.getName(),
				new Integer(60)));
		person.setServiceConnectionAward(serviceConnectionAward);

		// Birth record
		person.setBirthRecord(this.createBirthRecord(ImpreciseDateUtils
				.createImpreciseDate(1969, 1, 1)));

		// Add some income test information
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_REQUIRED, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);

		// Monetary Benefit Award
		MonetaryBenefitAward mba = new MonetaryBenefitAward();
		mba.setCheckAmount(new BigDecimal(20));
		mba.addMonetaryBenefit(this
				.createMonetaryBenefit(MonetaryBenefitType.CODE_HOUSEBOUND));
		person.setMonetaryBenefitAward(mba);

		// Special Factor
		person.addSpecialFactor(this.createAgentOrange());

		return person;
	}

	protected Person buildSeededPerson(String vpidValue) throws Exception {
		return doBuildSimplePerson(false, vpidValue, null);
	}

	protected Person buildSeededPerson(String vpidValue,
			String claimFolderNumber) throws Exception {
		return doBuildSimplePerson(false, vpidValue, claimFolderNumber);
	}

	// Build a "bare-bones" dead person
	protected Person buildDeadPerson() throws Exception {
		Person p = buildSimplePerson();
		DeathRecord death = new DeathRecord();
		death.setDeathReportDate(new Date());
		death.setLazarusDate(new ImpreciseDate(new Date()));
		death.setDeathDate(new ImpreciseDate(new Date()));
		p.setDeathRecord(death);
		return p;
	}

	// Build a "bare-bones" person without any Identity Trait information
	protected Person buildSimplePersonWithNoIdentityTraits() throws Exception {
		return doBuildSimplePerson(false, null, null);
	}

	// The Simple Person needs to remain "simple." Please don't add an E&E
	// factors such
	// as POW or PH.
	protected Person doBuildSimplePerson(boolean includeIdentityTraits,
			String vpidValue, String claimFolderNumber) throws Exception {

		VPIDEntityKey personKey = CommonEntityKeyFactory.createVPIDEntityKey(PersonVPID.DEFAULT_TESTING_VPID);

		Person person = this.getPersonService().getPersonWithoutIdentityTraits(personKey);

		// these are marked as private since application should never set
		if (vpidValue == null)
			vpidValue = PersonVPID.DEFAULT_TESTING_VPID;
		PersonVPID vpid = new PersonVPID(vpidValue);
		vpid.attach(person);

		person.setSensitiveRecord(Boolean.FALSE);
		// Needs to be true otherwise most e&e rules would fail
		person.setVeteran(Boolean.TRUE);

		if (claimFolderNumber == null)
			person.setClaimFolderNumber(RandomStringUtils.randomNumeric(9));
		else
			person.setClaimFolderNumber(claimFolderNumber);

		if (includeIdentityTraits) {
			person.addName(createName("TEST", "PERSON",
					NameType.LEGAL_NAME.getName()));
			person.setBirthRecord(this.createBirthRecord(ImpreciseDateUtils
					.createImpreciseDate(1950, 1, 1)));
			person.setGender(lookupService.getGenderByCode(Gender.MALE
					.getName()));
		}
		return person;
	}

	// Build a "bare-bones" person
	protected Person buildSimplePerson() throws Exception {
		return doBuildSimplePerson(true, null, null);
	}

	protected Person buildSimpleNonVeteran() throws Exception {
		Person person = doBuildSimplePerson(true, null, null);
		person.setVeteran(Boolean.FALSE);
		return person;
	}

	protected SSN createSSN() throws Exception {
		String str = Long.toString(System.currentTimeMillis());
		String ssn = str.substring(str.length() - 9);
		return createSSN(ssn);
	}

	protected SSN createSSN(String text) throws Exception {
		SSN ssn = new SSN();
		ssn.setSsnText(text);
		ssn.setType(this.getLookupService().getSSNTypeByCode(
				SSNType.CODE_ACTIVE.getCode()));
		return ssn;
	}

	protected IncomeTest createIncomeTest(IncomeTestType.Code testType,
			MeansTestStatus.Code status, Integer incomeYear) throws Exception {
		IncomeTest incomeTest = new IncomeTest();
		incomeTest.setEffectiveDate(new Date());

		IncomeTestStatus incomeTestStatus = new IncomeTestStatus();

		incomeTest.setIncomeYear(incomeYear);
		incomeTest.setType(lookupService.getIncomeTestTypeByCode(testType
				.getName()));
		incomeTestStatus.setStatus(lookupService
				.getMeansTestStatusByCode(status.getName()));
		incomeTestStatus.setType(lookupService.getIncomeTestTypeByCode(testType
				.getName()));
		incomeTestStatus
				.setDeterminedStatus(lookupService
						.getMeansTestStatusByCode(MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED
								.getName()));
		incomeTestStatus.setCompletedDate(new Date());
		incomeTest.addStatus(incomeTestStatus);
		incomeTest.setGmtAddress(this.createAddress());
		incomeTest.setSiteConductingTest(this.getRandomVAFacility());

		return incomeTest;
	}

	protected IncomeTest createIncomeTest(Integer incomeYear,
			IncomeTestType testType, IncomeTestSource testSource,
			MeansTestStatus status, VAFacility facility) throws Exception {
		IncomeTest incomeTest = new IncomeTest();
		incomeTest.setIncomeYear(incomeYear);
		setIncomeTestProps(incomeTest, testType, testSource, status, facility);

		incomeTest.setAdjudicationDate(new Date());
		incomeTest.setAgreesToPayDeductible(Boolean.FALSE);
		incomeTest.setCadAdjusted(Boolean.FALSE);
		incomeTest.setComments("IncomeTest created from TestCase ");
		incomeTest.setDiscloseFinancialInformation(Boolean.TRUE);
		incomeTest.setGmtAddress(createSimpleAddress());
		incomeTest.setIncomeVerificationStatus(getLookupService()
				.getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_REQUIRED.getName()));
		incomeTest.setNetWorth(new BigDecimal(666423.33));
		incomeTest.setRefusedToSign(Boolean.TRUE);
		incomeTest.setTotalNumberOfDependents(new Integer(5));
		incomeTest.setDeductibleExpenses(new BigDecimal(55000));

		return incomeTest;
	}

	protected void setIncomeTestProps(IncomeTest incomeTest,
			IncomeTestType testType, IncomeTestSource testSource,
			MeansTestStatus status, VAFacility facility) throws Exception {
		Date time = getPastTime().getTime();
		setIncomeTestProps(incomeTest, testType, testSource, status, facility,
				time, time, time);
	}

	protected Calendar getPastTime() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR, -1);
		return cal;
	}

	protected void setIncomeTestProps(IncomeTest incomeTest,
			IncomeTestType testType, IncomeTestSource testSource,
			MeansTestStatus status, VAFacility facility, Date completedDate,
			Date lastEditTime, Date effectiveDate) throws Exception {

		incomeTest.setType(testType);
		incomeTest.setSource(testSource);
		incomeTest.setSiteConductingTest(facility);

		IncomeTestStatus incomeTestStatus = setIncomeTestStatusProps(
				incomeTest, testType, status);
		incomeTestStatus.setDeterminedStatus(status);

		incomeTest.setCompletedDate(completedDate);
		incomeTest.setEffectiveDate(effectiveDate);
		incomeTest.setLastEditedDate(lastEditTime);
	}

	protected IncomeTestStatus setIncomeTestStatusProps(IncomeTest incomeTest,
			IncomeTestType testType, MeansTestStatus status) {
		IncomeTestStatus incomeTestStatus = incomeTest
				.getIncomeTestStatus(testType);
		if (incomeTestStatus == null) {
			incomeTestStatus = new IncomeTestStatus();
			incomeTestStatus.setType(testType);
			incomeTest.addStatus(incomeTestStatus);
		}
		incomeTestStatus.setStatus(status);
		return incomeTestStatus;
	}

	protected ReceivedEligibility createReceivedEligibility(
			EligibilityType.Code type) throws Exception {
		ReceivedEligibility receivedEligibility = new ReceivedEligibility();
		receivedEligibility.setType(lookupService.getEligibilityTypeByCode(type
				.getName()));
		return receivedEligibility;
	}

	protected ReceivedEligibility createReceivedEligibility() throws Exception {
		ReceivedEligibility receivedEligibility = new ReceivedEligibility();
		receivedEligibility.setType(getRandomEligibilityType());
		receivedEligibility.setReportSite(getRandomVAFacility());
		return receivedEligibility;
	}

	protected void setServiceConnectedPercentage(Integer percentage,
			Person person) throws Exception {
		ServiceConnectionAward scw = person.getServiceConnectionAward();
		if (scw == null) {
			this.attachServiceConnectionAward(person, percentage);
		} else {
			scw.setServiceConnectedPercentage(percentage);
		}
	}

	protected MonetaryBenefit createMonetaryBenefit(
			MonetaryBenefitType.Code type) throws Exception {

		MonetaryBenefit monetaryBenefit = new MonetaryBenefit();
		monetaryBenefit.setType(lookupService.getMonetaryBenefitTypeByCode(type
				.getName()));
		monetaryBenefit.setMonetaryBenefitIndicator(this.getLookupService()
				.getIndicatorByCode(Indicator.YES));
		return monetaryBenefit;
	}

	protected CatastrophicDisability createCatastrophicDisability(
			Date reviewDate, Date determinationDate,
			String cdDeterminationType, String determineBy) throws Exception {
		CatastrophicDisability catastrophicDisability = new CatastrophicDisability();

		// FIXME replace with its own date
		// catastrophicDisability.setDeterminationDate(determinationDate);
		catastrophicDisability.setReviewDate(reviewDate);
		catastrophicDisability.setDeterminedBy(determineBy);
		catastrophicDisability.setCatastrophicallyDisabled(Boolean.TRUE);
		CDDeterminationMethod cdDeterminationMethod = lookupService
				.getCdDeterminationMethodByCode(cdDeterminationType);
		catastrophicDisability.setDeterminationMethod(cdDeterminationMethod);
		catastrophicDisability
				.setDeterminationFacility(getVaFacility(VAFacility.CODE_NEW_BEDFORD_CBOC));
		return catastrophicDisability;
	}

	protected CDDescriptor createCDDescriptor(String code) throws Exception {
		CDDescriptor cdd = new CDDescriptor();
		cdd.setDescriptorType(this.getLookupService().getDescriptorTypeByCode(code));
		return cdd;
	}

	protected Name createName() throws Exception {
		String str = Long.toString(System.currentTimeMillis());
		String familyName = "FirstNm_" + str.substring(str.length() - 10);
		String givenName = "LastNm_" + str.substring(str.length() - 10);
		NameType nameType = getRandomNameType();
		return createName(familyName, givenName, nameType);
	}

	protected Name createName(String familyName, String givenName, String type)
			throws Exception {
		NameType nameType = lookupService.getNameTypeByCode(type);
		return createName(familyName, givenName, nameType);
	}

	protected Name createName(String familyName, String givenName,
			NameType nameType) throws Exception {
		Name name = new Name();
		name.setPrefix("Prefix");
		name.setFamilyName(familyName);
		name.setGivenName(givenName);
		name.setType(nameType);
		return name;
	}

	protected PrivateInsurance createPrivateInsurance() throws Exception {
		String str = Long.toString(System.currentTimeMillis());
		PrivateInsurance privateInsurance = new PrivateInsurance();
		privateInsurance.setCompanyName("Company"
				+ str.substring(str.length() - 7));
		privateInsurance.setGroupName("GrpName_"
				+ str.substring(str.length() - 7));
		privateInsurance.setGroupNumber("GrpNo_"
				+ str.substring(str.length() - 7));
		return privateInsurance;
	}

	protected Medicare createMedicareInsurance() {
		String str = Long.toString(System.currentTimeMillis());
		Medicare medicare = new Medicare();
		medicare.setGroupName("GrpName_" + str.substring(str.length() - 7));
		medicare.setGroupNumber("GrpNo_" + str.substring(str.length() - 7));
		medicare.setMedicareClaimNumber("MC_ClaimNo_"
				+ str.substring(str.length() - 7));
		medicare.setNameOnMedicareCard("MC_NameOnCard_"
				+ str.substring(str.length() - 7));
		medicare.setEnrolledInPartB(Boolean.FALSE);
		medicare.setEnrolledInPartA(Boolean.FALSE);
		return medicare;
	}

	protected InsurancePlan createInsurancePlan() throws Exception {
		InsurancePlan plan = new InsurancePlan();
		plan.setPlanType(getRandomInsurancePlanType());
		plan.setPrecertificationRequired(Boolean.TRUE);
		return plan;
	}

	protected Association createAssociation(String organization,
			String relationShip) throws Exception {
		Association association = new Association();
		association.setRepresentativeName(createName());
		association.setOrganizationName(organization);
		association.setType(getRandomAssociationType());
		association.setRelationship(relationShip);

		association.setAddress(createSimpleAddress());
		association.setPrimaryPhone("703-555-5555");
		association.setAlternatePhone("703-555-5555");
		return association;
	}

	protected Association createOrganizationAssociation(String organization,
			String relationShip) throws Exception {
		Association association = new Association();
		association.setOrganizationName(organization);
		association.setRepresentativeName(createName());
		// Need to set organization type
		association.setType(this.getLookupService().getAssociationTypeByCode(
				AssociationType.CODE_GUARDIAN_CIVIL.getName()));
		association.setRelationship(relationShip);
		association.setAddress(createOrganizationAddress());
		association.setPrimaryPhone("703-555-5555");
		association.setAlternatePhone("703-555-5555");
		return association;
	}

	protected Address createOrganizationAddress() throws Exception {
		return this.createAddress(this.getLookupService().getAddressTypeByCode(
				AddressType.CODE_BUSINESS_ADDRESS.getName()));
	}

	protected Association createPersonAssociation(String name,
			String relationShip, String type) throws Exception {
		Association association = new Association();
		association.setRepresentativeName(createName());
		AssociationType associationType = (AssociationType) this
				.getLookupService().getAssociationTypeByCode(type);
		association.setType(associationType);
		association.setRelationship(relationShip);
		association.setOrganizationName(name);
		association.setAddress((Address) createSimpleAddress());
		association.setPrimaryPhone("703-555-5555");
		association.setAlternatePhone("703-555-5555");
		return association;
	}

	protected Phone createPhone() throws Exception {
		PhoneType type = getRandomPhoneType();
		return createPhone(type);
	}

	protected Phone createPhone(PhoneType.Code code) throws Exception {
		PhoneType type = getLookupService().getPhoneTypeByCode(code.getName());
		return createPhone(type);
	}

	protected Phone createPhone(PhoneType type) throws Exception {
		String timeStr = Long.toString(System.currentTimeMillis());
		Phone phone = new Phone();
		phone.setType(type);
		phone.setPhoneNumber(timeStr.substring(timeStr.length() - 10));
		phone.setSiteOfChange(this.getLookupService()
				.getVaFacilityByCode("742"));
		return phone;
	}

	protected Email createEmail() throws Exception {
		EmailType type = getRandomEmailType();
		return createEmail(type);
	}

	protected Email createEmail(EmailType.Code code) throws Exception {
		EmailType type = getLookupService().getEmailTypeByCode(code.getName());
		return createEmail(type);
	}

	protected Email createEmail(EmailType type) throws Exception {
		String timeStr = Long.toString(System.currentTimeMillis());
		Email email = new Email();
		email.setType(type);
		email.setAddress(timeStr.substring(timeStr.length() - 10));
		return email;
	}

	protected Address createSimpleAddress() throws Exception {
		AddressType type = getRandomAddressType();
		return createSimpleAddress(type);
	}

	protected Address createSimpleAddress(AddressType type) throws Exception {
		Address address = new Address();
		String timeStr = Long.toString(System.currentTimeMillis());
		address.setLine1(timeStr.substring(timeStr.length() - 6) + " EDS Drive");
		address.setCity("City" + timeStr.substring(timeStr.length() - 6));
		address.setState("VA");
		address.setCountry("USA");
		address.setZipCode("20172");
		address.setType(type);
		return address;
	}

	protected Address createAddress(String city, String line1,
			String stateCode, String zipCode, Date updatedDate,
			String addressTypeCode) throws Exception {
		Address address = new Address();
		AddressType addressType = (AddressType) this.getLookupService()
				.getAddressTypeByCode(addressTypeCode);
		address.setType(addressType);
		address.setCity(city);
		address.setLine1(line1);
		address.setState(stateCode);
		address.setZipCode(zipCode);
		address.setChangeDate(updatedDate);
		return address;
	}

	protected void updateAddress(Address address, String city, String line1,
			String stateCode, String zipCode, Date updatedDate,
			String addressTypeCode) throws Exception {
		AddressType addressType = (AddressType) this.getLookupService()
				.getAddressTypeByCode(addressTypeCode);
		address.setType(addressType);
		address.setCity(city);
		address.setLine1(line1);
		address.setState(stateCode);
		address.setZipCode(zipCode);
		address.setChangeDate(updatedDate);
	}

	protected void addPermanentAddress(Person person, Date updatedDate,
			ImpreciseDate endDate) throws Exception {
		this.addSpecificAddressType(
				AddressType.CODE_PERMANENT_ADDRESS.getName(), person,
				updatedDate, endDate);
	}

	protected void addGuardianAddress(Person person, Date updatedDate,
			ImpreciseDate endDate) throws Exception {
		Association associate = this.createOrganizationAssociation("Test Org",
				"Guardian");
		person.addAssociation(associate);
	}

	protected void addSpecificAddressType(String type, Person person,
			Date updatedDate, ImpreciseDate endDate) throws Exception {
		Address found = Address.getAddressOfType(person.getAddresses(), type);
		if (found == null) {
			found = createAddress("Atlanta", "Clairmont Dr", "GA", "30305",
					updatedDate, AddressType.CODE_PERMANENT_ADDRESS.getName());
			found.setEndDate(endDate);
			person.addAddress(found);
		} else {
			updateAddress(found, "Atlanta", "Clairmont Dr", "GA", "30305",
					updatedDate, type);
		}
	}

	protected void addAssociationAddress(String type, Association associate,
			Date updatedDate, ImpreciseDate endDate) throws Exception {
		Address found = this.findMatchingAddress(type, associate.getAddress());
		if (found == null) {
			found = createAddress("Atlanta", "Association Dr", "GA", "30305",
					updatedDate, AddressType.CODE_PERMANENT_ADDRESS.getName());
			found.setEndDate(endDate);
			associate.setAddress(found);
		} else {
			updateAddress(found, "Atlanta", "Association Dr", "GA", "30305",
					updatedDate, type);
		}
	}

	protected Address findMatchingAddress(String code, Address address) {
		Validate.notNull(code, "Address type's code must not be null");
		// NOTE the current set of addresses might be empty
		Validate.notNull(address, "The address must not be null");

		Address found = null;
		// Make sure not expired
		if (code.equals(address.getType().getCode())
				&& address.getEndDate() == null) {
			found = address;
		}

		return found;
	}

	protected void addTwoAddresses(Person person, Date updatedDate)
			throws Exception {

		Address address = createAddress("Cobb Parkway", "Windy Hill", "GA",
				"30338", updatedDate,
				AddressType.CODE_PRIMARY_RESIDENCE.getName());
		Address secondAddress = createAddress("Coca Cola Museum",
				"Five points", "GA", "30339", updatedDate,
				AddressType.CODE_PERMANENT_ADDRESS.getName());
		person.addAddress(address);
		person.addAddress(secondAddress);
	}

	protected Address createAddress() throws Exception {
		return createAddress(createSimpleAddress());
	}

	protected Address createAddress(AddressType type) throws Exception {
		return createAddress(createSimpleAddress(type));
	}

	private Address createAddress(Address simpleAddress) {
		Address address = new Address();
		address.setLine1(simpleAddress.getLine1());
		address.setLine2(simpleAddress.getLine2());
		address.setLine3(simpleAddress.getLine3());
		address.setCity(simpleAddress.getCity());
		address.setState(simpleAddress.getState());
		address.setCounty(simpleAddress.getCounty());
		address.setCountry(simpleAddress.getCountry());
		address.setZipCode(simpleAddress.getZipCode());
		address.setZipPlus4(simpleAddress.getZipPlus4());
		address.setPostalCode(simpleAddress.getPostalCode());
		address.setProvince(simpleAddress.getProvince());
		address.setType(simpleAddress.getType());
		return address;
	}

	protected EGTSetting createSimpleEGTSetting() throws Exception {
		EGTSetting egt = new EGTSetting();
		egt.setType(getRandomEGTSettingType());
		return egt;
	}

	protected EGTSetting createEGTSetting() throws Exception {
		EGTSetting egt = createSimpleEGTSetting();
		egt.setFederalRegisterDate(new Date());
		egt.setDisable(Boolean.FALSE);
		egt.setPriorityGroup(getRandomEnrollmentPriorityGroup());
		egt.setPrioritySubGroup(getRandomEnrollmentPrioritySubGroup());
		egt.setEffectiveDate(new Date());
		egt.setComments("Comments ");
		return egt;
	}

	protected EGTProcessStatistic createEGTProcessStatistic() throws Exception {
		EGTProcessStatistic egtStat = new EGTProcessStatistic();
		egtStat.setBeneficiaryNotEnrolledCount(new Integer(200));
		egtStat.setBeneficiaryProcessedCount(new Integer(2000));
		egtStat.setEgtProcessStatus(getRandomEGTProcessStatus());
		egtStat.setProcessStartDate(new Date());
		egtStat.setProcessEndDate(new Date());
		return egtStat;
	}

	protected EGTStatus getRandomEGTProcessStatus() throws Exception {
		List types = getLookupService().getAllEGTStatuss();
		return (EGTStatus) selectRandomly(types);
	}

	protected EnrollmentDetermination createEnrollmentDetermination()
			throws Exception {
		EnrollmentDetermination edt = new EnrollmentDetermination();
		edt.setCalculationSource(getRandomEnrollmentSource());
		edt.setEffectiveDate(new Date());
		edt.setEnrollmentDate(new Date());
		edt.setFacilityReceived(getRandomVAFacility());
		edt.setPriorityGroup(getRandomEnrollmentPriorityGroup());
		edt.setPrioritySubGroup(getRandomEnrollmentPrioritySubGroup());

		EGTSetting egt = this.getEgtService().getCurrentEGTSetting();

		edt.setEgtSetting(egt);
		return edt;
	}

	protected Spouse createSpouse() throws Exception {
		Spouse spouse = new Spouse();
		spouse.setName(createName());
		spouse.addSsn(createSSN());
		spouse.addSsn(createSSN());
		spouse.setRelationship(getLookupService().getRelationshipByCode(
				Relationship.CODE_SPOUSE.getName()));
		return spouse;
	}

	protected Dependent createDependent() throws Exception {
		Dependent dependent = new Dependent();
		dependent.setName(createName());
		dependent.setRelationship(getRandomRelationship());
		dependent.addSsn(createSSN());
		dependent.addSsn(createSSN());
		dependent.setDob(ImpreciseDateUtils.createImpreciseDate(1980, 1, 1));
		return dependent;

	}

	protected SpouseFinancials createSpouseFinancials() throws Exception {
		return createSpouseFinancials(createSpouse());
	}

	protected SpouseFinancials createSpouseFinancials(Spouse spouse)
			throws Exception {
		return createSpouseFinancials(spouse, getRandomAssetType(),
				getRandomIncomeType(), getRandomExpenseType());
	}

	protected SpouseFinancials createSpouseFinancials(Spouse spouse,
			AssetType assetType, IncomeType incomeType, ExpenseType expType)
			throws Exception {
		SpouseFinancials spouseFinancials = new SpouseFinancials();
		spouseFinancials.setReportedOn(spouse);
		spouseFinancials.setLivedWithPatient(Boolean.FALSE);
		createFinancialInformation(spouseFinancials, assetType, incomeType,
				expType);
		spouseFinancials.setDebt(new Debt(new BigDecimal(77.33)));
		return spouseFinancials;
	}

	protected DependentFinancials createDependentFinancials() throws Exception {
		return createDependentFinancials(createDependent());
	}

	protected DependentFinancials createDependentFinancials(Dependent dependent)
			throws Exception {
		return createDependentFinancials(dependent, getRandomAssetType(),
				getRandomIncomeType(), getRandomExpenseType());
	}

	protected DependentFinancials createDependentFinancials(
			Dependent dependent, AssetType assetType, IncomeType incomeType,
			ExpenseType expType) throws Exception {
		DependentFinancials dependentFinancials = new DependentFinancials();
		dependentFinancials.setReportedOn(dependent);
		dependentFinancials.setLivedWithPatient(Boolean.FALSE);
		createFinancialInformation(dependentFinancials, assetType, incomeType,
				expType);
		dependentFinancials.setDebt(new Debt(new BigDecimal(88.77)));
		dependentFinancials.setAttendedSchool(Boolean.FALSE);
		dependentFinancials.setContributedToSupport(Boolean.FALSE);
		dependentFinancials.setHasIncome(Boolean.FALSE);
		dependentFinancials.setIncapableOfSelfSupport(Boolean.FALSE);
		dependentFinancials.setIncomeAvailableToPatient(Boolean.FALSE);
		return dependentFinancials;
	}

	private void createFinancialInformation(
			FinancialInformation financialInformation, AssetType assetType,
			IncomeType incomeType, ExpenseType expType) {
		if (assetType != null) {
			financialInformation.setAsset(assetType, createAsset(123.33));
		}
		if (incomeType != null) {
			financialInformation.setIncome(incomeType, createIncome(789.33));
		}
		if (expType != null) {
			financialInformation.setExpense(expType, createExpense(134.33));
		}
	}

	protected void setExpense(FinancialInformation finInfo, double amount,
			ExpenseType.Code typeCode) throws Exception {
		ExpenseType type = getLookupService().getExpenseTypeByCode(
				typeCode.getName());
		Expense expense = new Expense(new BigDecimal(amount));
		finInfo.setExpense(type, expense);
	}

	protected void createIncome(FinancialInformation finInfo, double amount,
			IncomeType.Code typeCode) throws Exception {
		IncomeType type = getLookupService().getIncomeTypeByCode(
				typeCode.getName());
		Income income = new Income(new BigDecimal(amount));
		finInfo.setIncome(type, income);
	}

	protected void createAsset(FinancialInformation finInfo, double amount,
			AssetType.Code typeCode) throws Exception {
		Asset asset = new Asset(new BigDecimal(amount));
		AssetType type = getLookupService().getAssetTypeByCode(
				typeCode.getName());
		finInfo.setAsset(type, asset);
	}

	protected Expense createExpense(double amount) {
		Expense expense = new Expense(new BigDecimal(amount));
		return expense;
	}

	protected Income createIncome(double amount) {
		Income income = new Income(new BigDecimal(amount));
		return income;
	}

	protected Asset createAsset(double amount) {
		Asset asset = new Asset(new BigDecimal(amount));
		return asset;
	}

	protected FinancialStatement createFinancialStatement() throws Exception {
		return createFinancialStatement(getRandomAssetType(),
				getRandomIncomeType(), getRandomExpenseType());
	}

	protected FinancialStatement createFinancialStatement(AssetType assetType,
			IncomeType incomeType, ExpenseType expType) throws Exception {
		FinancialStatement stmt = new FinancialStatement();
		stmt.setIsPost2005Format(Boolean.FALSE);
		createFinancialInformation(stmt, assetType, incomeType, expType);
		stmt.setDebt(createDebt(1234.33));
		stmt.setContributionToSpouse(new BigDecimal(2342.44));
		stmt.setMarriedLastCalendarYear(Boolean.FALSE);
		stmt.setNumberOfDependentChildren(new Integer(3));
		return stmt;
	}

	protected Debt createDebt(double amount) {
		return new Debt(new BigDecimal(amount));
	}

	protected EligibilityType getRandomEligibilityType() throws Exception {
		List types = getLookupService().getAllEligibilityTypes();
		return (EligibilityType) selectRandomly(types);
	}

	protected VAFacility getRandomVAFacility() throws Exception {
		List types = getLookupService().getAllVaFacilitys();
		return (VAFacility) selectRandomly(types);
	}

	protected ServiceBranch getRandomServiceBranch() throws Exception {
		List types = getLookupService().getAllServiceBranchs();
		return (ServiceBranch) selectRandomly(types);
	}

	protected ServicePeriod getRandomServicePeriod() throws Exception {
		List types = getLookupService().getAllServicePeriods();
		return (ServicePeriod) selectRandomly(types);
	}

	protected ConflictLocation getRandomConflictLocation() throws Exception {
		List types = getLookupService().getAllConflicts();
		return (ConflictLocation) selectRandomly(types);
	}

	protected DischargeType getRandomDischargeType() throws Exception {
		List types = getLookupService().getAllDischargeTypes();
		return (DischargeType) selectRandomly(types);
	}

	protected ConflictLocation getConflictLocation(ConflictLocation.Code code)
			throws Exception {
		return this.getLookupService().getConflictByCode(code.getName());
	}

	protected ServiceBranch getServiceBranch(ServiceBranch.Code code)
			throws Exception {
		return this.getLookupService().getServiceBranchByCode(code.getName());
	}

	protected DischargeType getDischargeType(DischargeType.Code code)
			throws Exception {
		return this.getLookupService().getDischargeTypeByCode(code.getName());
	}

	protected EnrollmentSource getRandomEnrollmentSource() throws Exception {
		List types = getLookupService().getAllEnrollmentSources();
		return (EnrollmentSource) selectRandomly(types);
	}

	protected EGTSettingType getRandomEGTSettingType() throws Exception {
		List types = getLookupService().getAllEgtSettingTypes();
		return (EGTSettingType) selectRandomly(types);
	}

	protected EnrollmentPriorityGroup getRandomEnrollmentPriorityGroup()
			throws Exception {
		List types = getLookupService().getAllEnrollmentPriorityGroups();
		return (EnrollmentPriorityGroup) selectRandomly(types);
	}

	protected EnrollmentPrioritySubGroup getRandomEnrollmentPrioritySubGroup()
			throws Exception {
		List types = getLookupService().getAllEnrollmentPrioritySubGroups();
		return (EnrollmentPrioritySubGroup) selectRandomly(types);
	}

	protected InsuredRelationship getRandomInsuredRelationship()
			throws Exception {
		List types = getLookupService().getAllInsuredRelationships();
		return (InsuredRelationship) selectRandomly(types);
	}

	protected InsuranceReportSource getRandomReportSource() throws Exception {
		List types = getLookupService().getAllInsuranceReportSources();
		return (InsuranceReportSource) selectRandomly(types);
	}

	protected InsurancePlanType getRandomInsurancePlanType() throws Exception {
		List types = getLookupService().getAllInsurancePlanTypes();
		return (InsurancePlanType) selectRandomly(types);
	}

	protected AssociationType getRandomAssociationType() throws Exception {
		List types = getLookupService().getAllAssociationTypes();
		return (AssociationType) selectRandomly(types);
	}

	protected PhoneType getRandomPhoneType() throws Exception {
		List types = getLookupService().getAllPhoneTypes();
		return (PhoneType) selectRandomly(types);
	}

	protected EmailType getRandomEmailType() throws Exception {
		List types = getLookupService().getAllEmailTypes();
		return (EmailType) selectRandomly(types);
	}

	protected AddressType getRandomAddressType() throws Exception {
		List types = getLookupService().getAllAddressTypes();
		return (AddressType) selectRandomly(types);
	}

	protected AddressType getAddressType(AddressType.Code code)
			throws Exception {
		return getLookupService().getAddressTypeByCode(code.getName());
	}

	protected SSNType getRandomSSNType() throws Exception {
		List types = getLookupService().getAllSSNTypes();
		return (SSNType) selectRandomly(types);
	}

	protected NameType getRandomNameType() throws Exception {
		List types = getLookupService().getAllNameTypes();
		return (NameType) selectRandomly(types);
	}

	protected Relationship getRandomRelationship() throws Exception {
		List types = getLookupService().getAllRelationships();
		return (Relationship) selectRandomly(types);
	}

	protected Disability getRandomDisabilityType() throws Exception {
		List types = getLookupService().getAllDisabilitys();
		return (Disability) selectRandomly(types);
	}

	protected EnrollmentOverrideReason getRandomEnrollmentOverrideReason()
			throws Exception {
		List reasons = getLookupService().getAllEnrollmentOverrideReasons();
		return (EnrollmentOverrideReason) selectRandomly(reasons);
	}

	protected AssetType getRandomAssetType() throws Exception {
		List types = getLookupService().getAllAssetTypes();
		return (AssetType) selectRandomly(types);
	}

	protected ExpenseType getRandomExpenseType() throws Exception {
		List types = getLookupService().getAllExpenseTypes();
		return (ExpenseType) selectRandomly(types);
	}

	protected IncomeType getRandomIncomeType() throws Exception {
		List types = getLookupService().getAllIncomeTypes();
		return (IncomeType) selectRandomly(types);
	}

	protected AACIndicator getRandomAACIndicator() throws Exception {
		List types = getLookupService().getAllAACIndicators();
		return (AACIndicator) selectRandomly(types);
	}

	protected EligibilityStatus getRandomEligibilityStatus() throws Exception {
		List types = getLookupService().getAllEligibilityStatuss();
		return (EligibilityStatus) selectRandomly(types);
	}

	protected EligibilityVerificationSource getRandomEligibilityVerificationSource()
			throws Exception {
		List types = getLookupService().getAllEligibilityVerificationSources();
		return (EligibilityVerificationSource) selectRandomly(types);
	}

	protected EGTStatus getRandomEGTStatus() throws Exception {
		List types = getLookupService().getAllEGTStatuss();
		return (EGTStatus) selectRandomly(types);
	}

	protected IncomeTestType getRandomIncomeTestType() throws Exception {
		List types = getLookupService().getAllIncomeTestTypes();
		return (IncomeTestType) selectRandomly(types);
	}

	protected MeansTestStatus getRandomMeansTestStatus() throws Exception {
		List types = getLookupService().getAllMeansTestStatuss();
		return (MeansTestStatus) selectRandomly(types);
	}

	protected FeeBasisProgram getRandomFeeBasisProgram() throws Exception {
		List types = getLookupService().getAllFeeBasisPrograms();
		return (FeeBasisProgram) selectRandomly(types);
	}

	protected FeeBasisTreatmentType getRandomFeeBasisTreatmentType()
			throws Exception {
		List types = getLookupService().getAllFeeBasisTreatmentTypes();
		return (FeeBasisTreatmentType) selectRandomly(types);
	}

	protected Lookup selectRandomly(List types) {
		//Random random = new Random();
		SecureRandom secureRandom = new SecureRandom();
		int index = secureRandom.nextInt(types.size());
		return (Lookup) types.get(index);
	}

	protected RatedDisability createRatedDisability() throws Exception {
		return createRatedDisability(getRandomDisabilityType(), new Integer(55));
	}

	protected RatedDisability createRatedDisability(String type, Integer percent)
			throws Exception {
		return createRatedDisability(lookupService.getDisabilityByCode(type),
				percent);
	}

	protected RatedDisability createRatedDisability(Disability type,
			Integer percent) throws Exception {
		RatedDisability ratedDisability = new RatedDisability();
		ratedDisability.setPercentage(percent);
		ratedDisability.setServiceConnected(Boolean.TRUE);
		ratedDisability.setDisability(type);
		ratedDisability.setOriginalEffectiveRatingDate(new ImpreciseDate(
				new Date()));
		ratedDisability.setRatingDate(new ImpreciseDate(new Date()));
		return ratedDisability;
	}

	protected BirthRecord createBirthRecord(ImpreciseDate date) {
		BirthRecord birthRecord = new BirthRecord();
		ImpreciseDate ibd = date;
		birthRecord.setBirthDate(ibd);
		return birthRecord;
	}

	protected AgentOrangeExposure createAgentOrange() throws Exception {
		AgentOrangeExposure agentOrangeExposure = new AgentOrangeExposure();
		agentOrangeExposure
				.setLocation(lookupService
						.getAgentOrangeExposureLocationByCode(AgentOrangeExposureLocation.CODE_VIETNAM
								.getName()));
		agentOrangeExposure.setAgentOrangeExposureIndicator(this
				.getLookupService().getIndicatorByCode(Indicator.YES));

		return agentOrangeExposure;
	}

	protected CampLejeuneVerification createCampLejeuneVerification() throws Exception {
		CampLejeuneVerification campLejeuneVerification = new CampLejeuneVerification();
		campLejeuneVerification.setSpecialFactorIndicator(getLookupService().getIndicatorByCode(Indicator.YES));

		return campLejeuneVerification;
	}


	protected EnvironmentalContaminationExposure createEnvironmentalContaminationExposure()
			throws Exception {
		EnvironmentalContaminationExposure ece = new EnvironmentalContaminationExposure();
		ece.setEnvironmentalContaminationExposureIndicator(this
				.getLookupService().getIndicatorByCode(Indicator.YES));
		return ece;
	}

	protected RadiationExposure createRadiationExposure() throws Exception {
		RadiationExposure radiationExposure = new RadiationExposure();
		radiationExposure
				.setExposureMethod(lookupService
						.getRadiationExposureMethodByCode(RadiationExposureMethod.CODE_ATMOSPHERIC_NUCLEAR_TESTING
								.getName()));
		radiationExposure.setRadiationExposureIndicator(this.getLookupService()
				.getIndicatorByCode(Indicator.YES));
		return radiationExposure;
	}

	protected void setAACIndicator(String code, Person person) throws Exception {
		this.personHelperService.setAACIndicator(code, person);
	}

	protected void setEligibilityStatus(EligibilityStatus.Code status,
			Person person) throws Exception {
		this.personHelperService.setEligibilityStatus(status.getName(), person);
		person.getEligibilityVerification()
				.setVerificationMethod("test method");
	}

	protected void setEligibilityStatusToVerified(Person person)
			throws Exception {
		setEligibilityStatus(EligibilityStatus.CODE_VERIFIED, person);
	}

	protected void setEligibilityStatusToPendingVerification(Person person)
			throws Exception {
		setEligibilityStatus(EligibilityStatus.CODE_PENDING_VERIFICATION,
				person);
	}

	protected void setEligibilityStatusToPendingReverification(Person person)
			throws Exception {
		setEligibilityStatus(EligibilityStatus.CODE_PENDING_REVERIFICATION,
				person);
	}

	protected String getEligibilityStatusCode(Person person) throws Exception {
		EligibilityStatus status = this.personHelperService
				.getEligibilityStatus(person);
		return status != null ? status.getCode() : null;
	}

	protected void setEnrollmentStatus(String status, Person person)
			throws Exception {
		this.personHelperService.setEnrollmentStatus(status, person);
	}

	protected String getEnrollmentCategoryCode(Person person) throws Exception {
		EnrollmentCategory status = this.personHelperService
				.getEnrollmentCategory(person);
		return (status != null) ? status.getCode() : null;
	}

	protected String getEnrollmentStatusCode(Person person) throws Exception {
		EnrollmentStatus status = this.personHelperService
				.getEnrollmentStatus(person);
		return (status != null) ? status.getCode() : null;
	}

	protected void setPurpleHeartStatus(DecorationStatus.Code status,
			Person person) throws Exception {
		this.personHelperService.setPurpleHeartStatus(status.getName(), person);
	}

	protected String getPurpleHeartStatusCode(Person person) throws Exception {
		DecorationStatus decorationStatus = this.personHelperService
				.getPurpleHeartStatus(person);
		return (decorationStatus != null) ? decorationStatus.getCode() : null;
	}

	protected void assessIfHasPrimaryRanking(String type, Person person) {

		assertTrue(this.hasPrimaryEligibility(type, person));
		assertFalse(this.hasSecondaryEligibility(type, person));
		assertFalse(this.hasOtherEligibility(type, person));
	}

	protected void assessIfHasOtherRanking(String type, Person person) {

		assertFalse(this.hasPrimaryEligibility(type, person));
		assertFalse(this.hasSecondaryEligibility(type, person));
		assertTrue(this.hasOtherEligibility(type, person));
	}

	protected void assessIfHasSecondaryRanking(String type, Person person) {

		assertFalse(this.hasPrimaryEligibility(type, person));
		assertTrue(this.hasSecondaryEligibility(type, person));
		assertFalse(this.hasOtherEligibility(type, person));
	}

	protected void attachMeansTestWithMtCopayRequired(Person person,
			BigDecimal gmtThresholdAmount, BigDecimal thresholdA)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED, INCOME_YEAR);
		incomeTest.setGmtThresholdAmount(gmtThresholdAmount);
		incomeTest.setThresholdA(thresholdA);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachMeansTestWithNoLongerRequired(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_NO_LONGER_REQUIRED, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachMeansTestWithRequired(Person person) throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_REQUIRED, INCOME_YEAR);
		incomeTest.setHardship(this.createHardship("test"));
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachPrimaryMeansTest(Person person) throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_REQUIRED, INCOME_YEAR);
		incomeTest.setPrimaryIncomeTest(Boolean.TRUE);
		incomeTest
				.setSiteConductingTest(lookupService
						.getVaFacilityByCode(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER
								.getName()));
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachMeansTestWithMtCopayExempt(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachPharmacyCopayTestWithRXCopayExempt(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_CO_PAY_EXEMPTION_TEST,
				MeansTestStatus.MT_STATUS_EXEMPT, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachPharmacyCopayTestWithNonExempt(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_CO_PAY_EXEMPTION_TEST,
				MeansTestStatus.MT_STATUS_NON_EXEMPT, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachPharmacyCopayTestWithNoLongerApplicable(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_CO_PAY_EXEMPTION_TEST,
				MeansTestStatus.MT_STATUS_NP_LONGER_APPLICABLE_RX_COPAY_ONLY,
				INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachLongTermCareTestWithExempt(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_LTC_CO_PAY_EXEMPTION_TEST,
				MeansTestStatus.MT_STATUS_EXEMPT, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachLongTermCareTestWithNonExempt(Person person)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_LTC_CO_PAY_TEST,
				MeansTestStatus.MT_STATUS_NON_EXEMPT, INCOME_YEAR);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachMeansTestWithGmtCopayRequired(Person person,
			BigDecimal gmtThresholdAmount, BigDecimal thresholdA)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_GMT_COPAY_REQUIRED, INCOME_YEAR);
		incomeTest.setGmtThresholdAmount(gmtThresholdAmount);
		incomeTest.setThresholdA(thresholdA);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachMeansTestWithHardship(Person person) throws Exception {

		IncomeTest incomeTest = person.getIncomeTest(INCOME_YEAR);
		if (incomeTest == null) {
			incomeTest = this.createIncomeTest(IncomeTestType.CODE_MEANS_TEST,
					MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED, INCOME_YEAR);
			person.setIncomeTest(INCOME_YEAR, incomeTest);
		}
		Hardship hardship = new Hardship();
		hardship.setEffectiveDate(new Date());
		hardship.setHardshipGranted(Boolean.TRUE);
		incomeTest.setHardship(hardship);
	}

	protected void attachMeansTestWithMtStatusPendingAdjudication(
			Person person, BigDecimal gmtThresholdAmount, BigDecimal thresholdA)
			throws Exception {
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_PENDING_ADJUDICATION, INCOME_YEAR);
		incomeTest.setGmtThresholdAmount(gmtThresholdAmount);
		incomeTest.setThresholdA(thresholdA);
		person.setIncomeTest(INCOME_YEAR, incomeTest);
	}

	protected void attachServiceConnectionAward(Person person, Integer percent)
			throws Exception {
		this.attachServiceConnectionAward(person);
		person.getServiceConnectionAward().setServiceConnectedPercentage(
				percent);
	}

	protected ServiceConnectionAward attachServiceConnectionAward(Person person)
			throws Exception {
		ServiceConnectionAward serviceConnectionAward = person
				.getServiceConnectionAward();
		if (serviceConnectionAward == null) {
			serviceConnectionAward = new ServiceConnectionAward();
			person.setServiceConnectionAward(serviceConnectionAward);
		}
		serviceConnectionAward.setUnemployable(Boolean.FALSE);
		serviceConnectionAward.addRatedDisability(this.createRatedDisability());

		if (serviceConnectionAward.getServiceConnectedPercentage() == null) {
			// Assume SC with minimum
			serviceConnectionAward
					.setServiceConnectedPercentage(new Integer(0));
		}
		serviceConnectionAward.setServiceConnectedIndicator(Boolean.TRUE);
		return serviceConnectionAward;
	}

	protected void attachNoseThroatRadium(Person person) throws Exception {
		NoseThroatRadium noseThroatRadium = createNoseThroatRadium(new Date(),
				VAFacility.CODE_CONNECTICUT_HCS, "M");
		person.addClinicalDetermination(noseThroatRadium);
	}

	protected void attachVaDisabilityCompensation(Person person)
			throws Exception {
		MonetaryBenefit monetaryBenefit = createMonetaryBenefit(MonetaryBenefitType.CODE_DISABILITY_COMPENSATION);
		this.attachMonetaryBenefitAward(person);
		person.getMonetaryBenefitAward().addMonetaryBenefit(monetaryBenefit);
	}

	protected void attachVaPension(Person person) throws Exception {
		MonetaryBenefit monetaryBenefit = createMonetaryBenefit(MonetaryBenefitType.CODE_VA_PENSION);
		this.attachMonetaryBenefitAward(person);
		person.getMonetaryBenefitAward().addMonetaryBenefit(monetaryBenefit);
	}

	protected void attachHousebound(Person person) throws Exception {
		MonetaryBenefit monetaryBenefit = createMonetaryBenefit(MonetaryBenefitType.CODE_HOUSEBOUND);
		this.attachMonetaryBenefitAward(person);
		person.getMonetaryBenefitAward().addMonetaryBenefit(monetaryBenefit);
	}

	protected void attachAidAndAttendance(Person person) throws Exception {
		MonetaryBenefit monetaryBenefit = createMonetaryBenefit(MonetaryBenefitType.CODE_AID_AND_ATTENDANCE);
		this.attachMonetaryBenefitAward(person);
		person.getMonetaryBenefitAward().addMonetaryBenefit(monetaryBenefit);
	}

	protected void attachTotalAnnualCheckAmount(Person person) throws Exception {
		MonetaryBenefit monetaryBenefit = createMonetaryBenefit(MonetaryBenefitType.CODE_VA_PENSION);
		this.attachMonetaryBenefitAward(person);
		person.getMonetaryBenefitAward().addMonetaryBenefit(monetaryBenefit);
	}

	protected MonetaryBenefitAward attachMonetaryBenefitAward(Person person)
			throws Exception {
		MonetaryBenefitAward monetaryBenefitAward = person
				.getMonetaryBenefitAward();
		if (monetaryBenefitAward == null) {
			monetaryBenefitAward = new MonetaryBenefitAward();
			person.setMonetaryBenefitAward(monetaryBenefitAward);
		}
		return monetaryBenefitAward;
	}

	protected void attachDischargeDueToDisability(Person person) {
		attachMilitaryService(person);
		person.getMilitaryService().setDischargeDueToDisability(Boolean.TRUE);
	}

	protected void attachMilitaryRetirementInLieuOfVaCompensation(Person person)
			throws Exception {
		this.attachMilitaryServiceEpisode(person);
		person.getMilitaryService().setDisabilityRetirementIndicator(
				Boolean.TRUE);
	}

	protected MilitaryService attachMilitaryService(Person person) {
		MilitaryService militaryService = person.getMilitaryService();
		if (militaryService == null) {
			militaryService = new MilitaryService();
			person.setMilitaryService(militaryService);
		}
		return militaryService;
	}

	protected MilitaryServiceEpisode attachMilitaryServiceEpisode(Person person)
			throws Exception {

		return this.attachMilitaryServiceEpisode(person,
				this.getRandomServiceBranch());
	}

	protected MilitaryServiceEpisode attachMilitaryServiceEpisode(
			Person person, ServiceBranch branch) throws Exception {

		MilitaryService ms = this.attachMilitaryService(person);

		MilitaryServiceSiteRecord mssr = this.createMilitaryServiceSireRecord();

		mssr.setServicePeriod(this.getLookupService().getServicePeriodByCode(
				ServicePeriod.CODE_WORLD_WAR_II.getCode()));
		mssr.setSite(this.getLookupService().getVaFacilityByStationNumber(
				VAFacility.CODE_HEC.getName()));
		// Create mse
		MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
		mse.setServiceBranch(branch);
		mse.setDischargeType(this.getLookupService().getDischargeTypeByCode(
				DischargeType.CODE_HONORABLE.getCode()));
		mse.setStartDate(ImpreciseDateUtils.createImpreciseDate(1940, 1, 1));
		mse.setEndDate(ImpreciseDateUtils.createImpreciseDate(1946, 1, 1));
		mse.setServiceNumber("12345");
		mssr.addMilitaryServiceEpisode(mse);
		ms.addMilitaryServiceSiteRecord(mssr);

		CombatEpisode ce = new CombatEpisode();
		ce.setConflictLocation(this.getLookupService().getConflictByCode(
				ConflictLocation.CODE_WORLD_WAR_II_EUROPE.getCode()));
		ce.setStartDate(ImpreciseDateUtils.createImpreciseDate(1942, 2, 1));
		ce.setEndDate(ImpreciseDateUtils.createImpreciseDate(1945, 1, 1));
		ms.addCombatEpisode(ce);
		return mse;
	}

	protected void attachReceivingMilitaryRetirement(Person person)
			throws Exception {

		attachMilitaryService(person);

		person.getMilitaryService().setDisabilityRetirementIndicator(
				Boolean.TRUE);
	}

	protected void attachPermanentAndTotal(Person person) throws Exception {
		this.attachServiceConnectionAward(person);
		person.getServiceConnectionAward().setPermanentAndTotal(Boolean.TRUE);
	}

	protected void attachUnemployable(Person person) throws Exception {
		this.attachServiceConnectionAward(person);
		person.getServiceConnectionAward().setUnemployable(Boolean.TRUE);
	}

	protected void attachAgentOrangeExposure(Person person) throws Exception {
		person.addSpecialFactor(this.createAgentOrange());
	}

	protected void attachCampLejeuneVerification(Person person) throws Exception {
		person.addSpecialFactor(this.createCampLejeuneVerification());
	}

	protected void attachEnvironmentalContaminationExposure(Person person)
			throws Exception {
		person.addSpecialFactor(this.createEnvironmentalContaminationExposure());
	}

	protected void attachRadiationExposure(Person person) throws Exception {
		person.addSpecialFactor(this.createRadiationExposure());
	}

	protected void attachEmployee(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.EMPLOYEE));
	}

	protected void attachEmployeeAsPrimary(Person person) throws Exception {
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.EMPLOYEE));
	}

	protected void attachMexicanBorderWar(Person person) throws Exception {
		person.setBirthRecord(createBirthRecord(ImpreciseDateUtils
				.createImpreciseDate(1906, 12, 31)));
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.MEXICAN_BORDER_WAR));
	}

	protected void attachMexicanBorderWarAsPrimary(Person person)
			throws Exception {
		person.setBirthRecord(createBirthRecord(ImpreciseDateUtils
				.createImpreciseDate(1906, 12, 31)));
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.MEXICAN_BORDER_WAR));
	}

	protected void attachAlliedVeteran(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createAlliedVeteran());
	}

	protected ReceivedEligibility createAlliedVeteran() throws Exception {
		ReceivedEligibility re = createReceivedEligibility(EligibilityType.ALLIED_VETERAN);
		re.setAlliedCountry((AlliedCountry) this.getLookupService().getByCode(
				AlliedCountry.class, AlliedCountry.CODE_CANADA));
		return re;
	}

	protected void attachAlliedVeteranAsPrimary(Person person) throws Exception {
		person.setReceivedPrimaryEligiblity(createAlliedVeteran());
	}

	protected void attachWWI(Person person) throws Exception {
		person.setBirthRecord(createBirthRecord(ImpreciseDateUtils
				.createImpreciseDate(1907, 12, 31)));
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.WORLD_WAR_I));
	}

	protected void attachWWIAsPrimary(Person person) throws Exception {
		person.setBirthRecord(createBirthRecord(ImpreciseDateUtils
				.createImpreciseDate(1907, 12, 31)));
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.WORLD_WAR_I));
	}

	protected void attachTriCare(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.TRICARE_CHAMPUS));
	}

	protected void attachTriCareAsPrimary(Person person) throws Exception {
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.TRICARE_CHAMPUS));
	}

	protected void attachSharingAgreement(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.SHARING_AGREEMENT));
	}

	protected void attachSharingAgreementAsPrimary(Person person)
			throws Exception {
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.SHARING_AGREEMENT));
	}

	protected void attachVerifiedEnrollment(Person person) throws Exception {
		if (person.getEnrollmentDetermination() == null) {
			person.setEnrollmentDetermination(this
					.createEnrollmentDetermination());
		}
		person.getEnrollmentDetermination().setEgtSetting(
				this.getEgtService().getCurrentEGTSetting());
		person.getEnrollmentDetermination().setEffectiveDate(
				this.getDate(2005, 1, 1));
		person.getEnrollmentDetermination().setEnrollmentStatus(
				this.getLookupService().getEnrollmentStatusByCode(
						EnrollmentStatus.CODE_VERIFIED.getName()));
	}

	protected void attachChampVA(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.CHAMPVA));
	}

	protected void attachChampVAAsPrimary(Person person) throws Exception {
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.CHAMPVA));
	}

	protected void attachCollateralOfVeteran(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createReceivedEligibility(EligibilityType.COLLATERAL_OF_VETERAN));
	}

	protected void attachCollateralOfVeteranAsPrimary(Person person)
			throws Exception {
		person.setReceivedPrimaryEligiblity(createReceivedEligibility(EligibilityType.COLLATERAL_OF_VETERAN));
	}

	protected void attachOtherFederalAgency(Person person) throws Exception {
		person.addReceivedSecondaryEligibility(createOtherFederalAgency());
	}

	protected void attachOtherFederalAgencyAsPrimary(Person person)
			throws Exception {
		person.setReceivedPrimaryEligiblity(createOtherFederalAgency());
	}

	protected ReceivedEligibility createOtherFederalAgency() throws Exception {
		ReceivedEligibility re = createReceivedEligibility(EligibilityType.OTHER_FEDERAL_AGENCY);
		re.setOtherFederalAgency((FederalAgency) this.getLookupService()
				.getByCode(FederalAgency.class,
						FederalAgency.CODE_DEPARTMENT_OF_DEFENSE));
		return re;
	}

	protected void attachIneligibleFactor(Person person) throws Exception {
		person.setIneligibilityFactor(createIneligibilityFactor());
	}

	protected void attachIneligibleFactorFromSite(Person person)
			throws Exception {
		person.setIneligibilityFactor(createIneligibilityFactor());
		person.getIneligibilityFactor().setFacilityReceived(
				getVaFacility(VAFacility.CODE_NEW_BEDFORD_CBOC));
	}

	protected IneligibilityFactor createIneligibilityFactor() throws Exception {
		Calendar calendar = Calendar.getInstance();
		calendar.set(1999, 5, 23);
		IneligibilityFactor ineligibilityFactor = new IneligibilityFactor();
		ineligibilityFactor.setIneligibleDate(calendar.getTime());
		ineligibilityFactor.setReason("this person is ineligible");
		ineligibilityFactor
				.setFacilityReceived(getVaFacility(VAFacility.CODE_HEC));
		return ineligibilityFactor;
	}

	protected void attachCatastrophicDisability(Person person) throws Exception {
		Calendar calendar = Calendar.getInstance();
		calendar.set(1983, 5, 15);
		Date reviewDate = calendar.getTime();
		calendar.set(1983, 7, 25);
		Date dateDecision = calendar.getTime();

		CatastrophicDisability catastrophicDisability = createCatastrophicDisability(
				reviewDate, dateDecision, "1", "test reason");

		person.addClinicalDetermination(catastrophicDisability);
	}

	// protected void attachSHAD(Person person) throws Exception {
	// person.addSpecialFactor(new SHAD());
	// }

	protected void attachMedicaidFactor(Person person) {
		person.setMedicaidFactor(this.createMedicaidFactor());
	}

	protected MedicaidFactor createMedicaidFactor() {
		Calendar calendar = Calendar.getInstance();
		MedicaidFactor medicaidFactor = new MedicaidFactor();
		medicaidFactor.setEligibleForMedicaid(Boolean.TRUE);
		calendar.set(2004, 3, 23);
		medicaidFactor.setLastUpdateDate(calendar.getTime());

		return medicaidFactor;
	}

	protected MilitarySexualTrauma createMilitarySexualTrauma()
			throws Exception {
		Calendar calendar = Calendar.getInstance();
		calendar.set(2005, 1, 12);
		Date statusChangeDate = calendar.getTime();

		MilitarySexualTraumaStatus militarySexualTraumaStatus = lookupService
				.getMilitarySexualTraumaStatusByCode("Y");

		MilitarySexualTrauma militarySexualTrauma = new MilitarySexualTrauma();
		militarySexualTrauma.setStatus(militarySexualTraumaStatus);
		militarySexualTrauma
				.setDeterminationFacility(getVaFacility(VAFacility.CODE_CONNECTICUT_HCS));
		calendar.set(1986, 3, 24);
		militarySexualTrauma.setStatusChangeDate(statusChangeDate);
		return militarySexualTrauma;
	}

	protected MilitarySexualTrauma createMilitarySexualTrauma(String status)
			throws Exception {
		MilitarySexualTrauma militarySexualTrauma = createMilitarySexualTrauma();
		militarySexualTrauma.setStatus(lookupService
				.getMilitarySexualTraumaStatusByCode("Y"));
		return militarySexualTrauma;
	}

	protected void attachMilitarySexualTrauma(Person person) throws Exception {
		person.addClinicalDetermination(this.createMilitarySexualTrauma());
	}

	protected ReceivedEnrollment createReceivedEnrollment() throws Exception {
		Calendar calendar = Calendar.getInstance();
		ReceivedEnrollment receivedEnrollment = new ReceivedEnrollment();
		EnrollmentSource enrollmentSource = lookupService
				.getEnrollmentSourceByCode(EnrollmentSource.CODE_VAMC.getName());
		receivedEnrollment.setCalculationSource(enrollmentSource);
		EnrollmentStatus enrollmentStatus = lookupService
				.getEnrollmentStatusByCode(EnrollmentStatus.CODE_UNVERIFIED
						.getName());
		receivedEnrollment.setEnrollmentStatus(enrollmentStatus);
		calendar.set(1986, 1, 1);
		receivedEnrollment.setEnrollmentDate(calendar.getTime());
		receivedEnrollment.setEffectiveDate(calendar.getTime());
		calendar.set(1987, 1, 1);
		receivedEnrollment.setEndDate(calendar.getTime());
		EnrollmentPriorityGroup enrollmentPriorityGroup = lookupService
				.getEnrollmentPriorityGroupByCode(EnrollmentPriorityGroup.GROUP_1
						.getName());
		receivedEnrollment.setPriorityGroup(enrollmentPriorityGroup);
		receivedEnrollment.setPrioritySubGroup(null);
		receivedEnrollment
				.setFacilityReceived(getVaFacility(VAFacility.CODE_CONNECTICUT_HCS));
		return receivedEnrollment;
	}

	protected void attachReceivedEnrollment(Person person) throws Exception {
		person.setReceivedEnrollment(this.createReceivedEnrollment());
	}

	protected void attachPreferredFacility(Person person) throws Exception {
		person.setMostRecentPreferredFacility(getVaFacility(VAFacility.CODE_CONNECTICUT_HCS));
	}

	protected CancelDecline createCancelDecline() {
		CancelDecline cancelDecline = new CancelDecline();
		cancelDecline.setEffectiveDate(new Date());
		cancelDecline.setCancelDeclineIndicator(Boolean.TRUE);
		cancelDecline.setRemarks("test cancel decline remarks");
		return cancelDecline;
	}

	protected void attachCancelDecline(Person person) {
		person.setCancelDecline(this.createCancelDecline());
	}

	protected IncompetenceRuling createIncompetenceRuling() {
		IncompetenceRuling incompetenceRuling = new IncompetenceRuling();
		ImpreciseDate rd = ImpreciseDateUtils.createImpreciseDate(1999, 1, 1);
		incompetenceRuling.setCivilRulingDate(rd);
		incompetenceRuling.setIncompetent(Boolean.TRUE);
		return incompetenceRuling;
	}

	protected ConflictExperience attachConflictExperience(Person person)
			throws Exception {
		return this.attachConflictExperience(person,
				this.getRandomConflictLocation());
	}

	protected ConflictExperience attachConflictExperience(Person person,
			Date date) throws Exception {
		ConflictExperience ce = this.attachConflictExperience(person,
				this.getRandomConflictLocation());
		ce.getMilitaryServiceSiteRecord().getMilitaryService()
				.setCombatVeteranEligibilityEndDate(date);
		return ce;
	}

	protected ConflictExperience attachConflictExperience(Person person,
			ConflictLocation location) throws Exception {

		MilitaryService ms = this.attachMilitaryService(person);
		MilitaryServiceSiteRecord mssr = this.createMilitaryServiceSireRecord();
		mssr.setSite(this.getRandomVAFacility());
		// Create mse
		ConflictExperience ce = new ConflictExperience();
		ce.setConflictLocation(location);

		mssr.addConflictExperience(ce);
		ms.addMilitaryServiceSiteRecord(mssr);

		return ce;
	}

	/**
	 * MilitaryService ms = this.attachMilitaryService( person );
	 * MilitaryServiceSiteRecord mssr = this.createMilitaryServiceSireRecord();
	 *
	 * // Create mse MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
	 * mse.setServiceBranch( branch );
	 *
	 * mssr.addMilitaryServiceEpisode( mse ); ms.addMilitaryServiceSiteRecord(
	 * mssr );
	 *
	 * return mse;
	 */

	protected MilitaryServiceSiteRecord createMilitaryServiceSireRecord() {
		return new MilitaryServiceSiteRecord();
	}

	protected void attachIncompetenceRuling(Person person) {
		person.setIncompetenceRuling(this.createIncompetenceRuling());
	}

	protected void attachMedicare(Person person) throws Exception {
		Medicare policy = this.createMedicareInsurance();
		policy.setCreatedBy(person.getCreatedBy());
		policy.setInsurancePlan(this.createInsurancePlan());
		policy.setReportSite(this.getRandomVAFacility());
		policy.setReportSource(this.getRandomReportSource());

		person.addInsurance(policy);
	}

	protected void attachPrivateInsurance(Person person) throws Exception {
		PrivateInsurance policy = this.createPrivateInsurance();
		policy.setCreatedBy(person.getCreatedBy());
		policy.setInsurancePlan(this.createInsurancePlan());
		policy.setReportSite(this.getRandomVAFacility());
		policy.setReportSource(this.getRandomReportSource());

		person.addInsurance(policy);
	}

	protected void attachRatedIncompetent(Person person) {
		if (person.getIncompetenceRuling() == null)
			this.attachIncompetenceRuling(person);
		person.getIncompetenceRuling().setIncompetent(Boolean.TRUE);
	}

	protected void attachDeathRecord(Person person) throws Exception {
		person.setDeathRecord(this.createDeathRecord());
	}

	protected void attachDeathRecordFromSite(Person person) throws Exception {
		person.setDeathRecord(this.createDeathRecord());
		person.getDeathRecord().setFacilityReceived(
				getVaFacility(VAFacility.CODE_NEW_BEDFORD_CBOC));
	}

	protected DeathRecord createDeathRecord() throws Exception {
		DeathRecord deathRecord = new DeathRecord();
		deathRecord.setDeathDate(ImpreciseDateUtils.createImpreciseDate(2000,
				1, 1));
		deathRecord.setFacilityReceived(getVaFacility(VAFacility.CODE_HEC));
		deathRecord.setDeathReportDate(new Date());
		return deathRecord;
	}

	protected Application createApplication() {
		Application application = new Application();
		application.setApplicationDate(new Date());
		return application;
	}

	protected void attachApplication(Person person) {
		person.setApplication(this.createApplication());
	}

	protected EnrollmentDetermination getEnrollmentDetermination(Person person) {
		return this.getPersonHelperService().getEnrollmentDetermination(person);
	}

	protected VerificationInfo createVerificationInfoFromORFZ11() {
		VerificationInfo verificationInfo = new VerificationInfo("0L",
				"ORFZ11-E", null);
		return verificationInfo;
	}

	protected VerificationInfo createVerificationInfoFromORUZ11() {
		VerificationInfo verificationInfo = new VerificationInfo("0L",
				"ORUZ11-E", null);
		return verificationInfo;
	}

	protected void assessPriorityResult(Person person,
			EnrollmentPriorityGroup.Code priority) {
		EnrollmentDetermination ed = getEnrollmentDetermination(person);
		assertNotNull("enrollment determination s/b non-null", ed);
		assertNotNull("enrollment priority group s/b non-null",
				ed.getPriorityGroup());
		assertEquals(ed.getPriorityGroup().getCode(), priority.getName());
	}

	protected void assessPrioritySubGroupResult(Person person,
			EnrollmentPrioritySubGroup.Code subPriority) {
		EnrollmentDetermination ed = getEnrollmentDetermination(person);
		assertNotNull("enrollment determination s/b non-null", ed);
		assertNotNull("enrollment priority group s/b non-null",
				ed.getPrioritySubGroup());
		assertEquals(ed.getPrioritySubGroup().getCode(), subPriority.getName());
	}

	protected void assessEnrollmentStatusResult(Person person,
			EnrollmentStatus.Code status) throws Exception {
		EnrollmentStatus enrollmentStatus = this.personHelperService
				.getEnrollmentStatus(person);
		assertNotNull(enrollmentStatus);
		assertEquals(status.getName(), enrollmentStatus.getCode());
	}

	protected ReceivedEnrollment createReceivedEnrollment(
			EnrollmentStatus.Code status) throws Exception {
		ReceivedEnrollment receivedEnrollment = this.createReceivedEnrollment();
		receivedEnrollment.setEnrollmentStatus(lookupService
				.getEnrollmentStatusByCode(status.getName()));
		return receivedEnrollment;
	}

	protected VAFacility getVaFacility(VAFacility.Code stationNumber)
			throws Exception {
		return this.getLookupService().getVaFacilityByStationNumber(
				stationNumber.getName());
	}

	protected NoseThroatRadium createNoseThroatRadium(Date determinationDate,
			VAFacility.Code stationNumber, String verificationMethodCode)
			throws Exception {
		NoseThroatRadium noseThroatRadium = new NoseThroatRadium();

		noseThroatRadium.setDeterminationFacility(getVaFacility(stationNumber));
		noseThroatRadium.setVerificationFacility(getVaFacility(stationNumber));
		noseThroatRadium.setVerificationDate(determinationDate);
		NTRVerificationMethod verficationMethod = lookupService
				.getNTRVerificationMethodByCode(verificationMethodCode);

		noseThroatRadium.setVerificationMethod(verficationMethod);

		noseThroatRadium.setFromAviatorServiceBefore1955(new Boolean(true));
		noseThroatRadium.setFromSubmarinerServiceBefore1965(new Boolean(true));
		noseThroatRadium.setReceivingTreatment(TriState.TRUE);

		return noseThroatRadium;
	}

	protected boolean hasOtherEligibility(String type, Person person) {
		boolean contained = false;
		EnrollmentDetermination enrollmentDetermination = getEnrollmentDetermination(person);
		Set others = (enrollmentDetermination != null) ? enrollmentDetermination
				.getOtherEligibilities() : null;
		if (others != null && others.size() > 0) {

			Iterator iter = others.iterator();

			while (iter.hasNext()) {
				Eligibility eligibility = (Eligibility) iter.next();
				if (type.equals(eligibility.getFactor().getCode())) {
					contained = true;
					break;
				}
			}
		}

		return contained;
	}

	protected boolean hasSecondaryEligibility(String type, Person person) {
		EnrollmentDetermination enrollmentDetermination = getEnrollmentDetermination(person);
		boolean contained = false;
		Set secondaries = (enrollmentDetermination != null) ? enrollmentDetermination
				.getSecondaryEligibilities() : null;
		if (secondaries != null && secondaries.size() > 0) {

			Iterator iter = secondaries.iterator();

			while (iter.hasNext()) {
				Eligibility eligibility = (Eligibility) iter.next();
				if (type.equals(eligibility.getType().getCode())) {
					contained = true;
					break;
				}
			}
		}

		return contained;
	}

	protected boolean hasPrimaryEligibility(String type, Person person) {
		EnrollmentDetermination enrollmentDetermination = getEnrollmentDetermination(person);
		boolean contained = false;
		Eligibility primary = (enrollmentDetermination != null) ? enrollmentDetermination
				.getPrimaryEligibility() : null;
		if (primary != null) {

			if (type.equals(primary.getType().getCode())) {
				contained = true;
			}
		}

		return contained;
	}

	protected void attachPurpleHeartWithPHStatusPending(Person person)
			throws Exception {
		PurpleHeart purpleHeart = new PurpleHeart();
		purpleHeart.setPhIndicator(Boolean.TRUE);
		person.addDecoration(purpleHeart);
		this.setPurpleHeartStatus(DecorationStatus.CODE_PENDING, person);
	}

	protected void attachPOW(Person person) throws Exception {
		this.attachPrisonerOfWar(person,
				ImpreciseDateUtils.createImpreciseDate(1943, 1, 1),
				ImpreciseDateUtils.createImpreciseDate(1944, 1, 1));
	}

	protected void attachEligibilityVerification(Person person, String source)
			throws Exception {
		EligibilityVerification eligibilityVerification = new EligibilityVerification();
		eligibilityVerification.setEligibilityStatusDate(null);
		eligibilityVerification.setVerificationMethod("1");

		eligibilityVerification.setVerificationSource(lookupService
				.getEligibilityVerificationSourceByCode(source));
		eligibilityVerification.setVerificationFacility(null);
		person.setEligibilityVerification(eligibilityVerification);
	}

	protected MonetaryBenefit getMonetaryBenefit(String type, Person person)
			throws Exception {

		MonetaryBenefit mb = null;
		MonetaryBenefitType mbt = null;
		MonetaryBenefitAward mba = person.getMonetaryBenefitAward();

		if (mba != null) {
			mbt = lookupService.getMonetaryBenefitTypeByCode(type);
			mb = getMonetaryBenefit(mbt, person);
		}

		return mb;
	}

	protected Date getDate(int year, int month, int day) {
		// Note that month starts at 0.
	    Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(year, month, day);
        return calendar.getTime();
	}

	protected FinancialStatement getFinancialStatement(Person person) {
		// input person has one financial statement.
		if (person.getFinancialStatements() != null
				&& !person.getFinancialStatements().isEmpty()) {
			return (FinancialStatement) person.getFinancialStatements()
					.values().iterator().next();
		}
		return null;
	}

	protected MonetaryBenefit getMonetaryBenefit(
			MonetaryBenefitType monetaryBenefitType, Person person) {
		MonetaryBenefitAward mba = person.getMonetaryBenefitAward();
		MonetaryBenefit mb = null;
		Set monBens = (mba != null) ? mba.getMonetaryBenefits() : null;

		if (mba != null && monBens != null && monBens.size() > 0) {
			Iterator iterMonBens = monBens.iterator();

			while (iterMonBens.hasNext()) {
				MonetaryBenefit mbTemp = (MonetaryBenefit) iterMonBens.next();
				if (mbTemp != null && mbTemp.getType() != null) {
					if (mbTemp.getType().getCode()
							.equals(monetaryBenefitType.getCode())) {
						mb = mbTemp;
						break;
					}
				}
			}
		}

		return mb;
	}

	protected void assessPermanentAddressUpdateResults(Person incomingPerson,
			Person onFilePerson) {
		this.assessAddressResults(AddressType.CODE_PERMANENT_ADDRESS.getName(),
				incomingPerson, onFilePerson);
	}

	protected void assessGuardianAddressUpdateResults(Person incomingPerson,
			Person onFilePerson) {

		SimpleAddress incoming = null;
		SimpleAddress result = null;

		Association incomingAssociation = this.getAssociation(
				AssociationType.CODE_GUARDIAN_CIVIL.getName(), incomingPerson);
		Association onFileAssociation = this.getAssociation(
				AssociationType.CODE_GUARDIAN_CIVIL.getName(), onFilePerson);

		incoming = incomingAssociation.getAddress();
		result = onFileAssociation.getAddress();
		assertEquals(incoming.getType().getCode(), result.getType().getCode());
		assertEquals(incoming.getLine1(), result.getLine1());
		assertEquals(incoming.getCity(), result.getCity());
	}

	protected Association getAssociation(String type, Person person) {
		Iterator iter = person.getAssociations().iterator();
		while (iter.hasNext()) {
			Association association = (Association) iter.next();
			if (association.getType().getCode().equals(type)) {
				return association;
			}
		}
		return null;
	}

	protected void assessAddressResults(String type, Person incomingPerson,
			Person onFilePerson) {
		Address input = Address.getAddressOfType(incomingPerson.getAddresses(),
				type);
		Address result = Address.getAddressOfType(onFilePerson.getAddresses(),
				type);
		assessCommonAddressResults(input, result);
	}

	protected void assessExpiredAddressResults(String type,
			Person incomingPerson, Person onFilePerson) {
		Address input = Address.getAddressOfType(incomingPerson.getAddresses(),
				type);
		Address result = Address.getAddressOfType(onFilePerson.getAddresses(),
				type);
		assessCommonAddressResults(input, result);
		assertNotNull(input.getEndDate());
	}

	private void assessCommonAddressResults(Address input, Address result) {
		assertEquals(input.getType().getCode(), result.getType().getCode());
		assertEquals(input.getLine1(), result.getLine1());
		assertEquals(input.getCity(), result.getCity());
	}

	/**
	 * @return Returns the personHelperService.
	 */
	public PersonHelperService getPersonHelperService() {
		return personHelperService;
	}

	/**
	 * @param personHelperService
	 *            The personHelperService to set.
	 */
	public void setPersonHelperService(PersonHelperService personHelperService) {
		this.personHelperService = personHelperService;
	}

	/**
	 * @return Returns the lookupService.
	 */
	public LookupService getLookupService() {
		return lookupService;
	}

	/**
	 * @param lookupService
	 *            The lookupService to set.
	 */
	public void setLookupService(LookupService lookupService) {
		this.lookupService = lookupService;
	}

	/**
	 * @return Returns the eligibilityEnrollmentService.
	 */
	public EligibilityEnrollmentService getEligibilityEnrollmentService() {
		return this.eligibilityEnrollmentService;
	}

	/**
	 * @param eligibilityEnrollmentService
	 *            The eligibilityEnrollmentService to set.
	 */
	public void setEligibilityEnrollmentService(
			EligibilityEnrollmentService eligibilityEnrollmentService) {
		this.eligibilityEnrollmentService = eligibilityEnrollmentService;
	}

	/**
	 * @return Returns the clinicalDeterminationService.
	 */
	public ClinicalDeterminationService getClinicalDeterminationService() {
		return clinicalDeterminationService;
	}

	/**
	 * @param clinicalDeterminationService
	 *            The clinicalDeterminationService to set.
	 */
	public void setClinicalDeterminationService(
			ClinicalDeterminationService clinicalDeterminationService) {
		this.clinicalDeterminationService = clinicalDeterminationService;
	}

	/**
	 * @return Returns the demographicService.
	 */
	public DemographicService getDemographicService() {
		return demographicService;
	}

	/**
	 * @param demographicService
	 *            The demographicService to set.
	 */
	public void setDemographicService(DemographicService demographicService) {
		this.demographicService = demographicService;
	}

	public FinancialsService getFinancialsService() {
		return financialsService;
	}

	public void setFinancialsService(FinancialsService financialsService) {
		this.financialsService = financialsService;
	}

	/**
	 * @return Returns the egtService.
	 */
	public EGTService getEgtService() {
		return egtService;
	}

	/**
	 * @param egtService
	 *            The egtService to set.
	 */
	public void setEgtService(EGTService egtService) {
		this.egtService = egtService;
	}

	/**
	 * @return Returns the insuranceService.
	 */
	public InsuranceService getInsuranceService() {
		return insuranceService;
	}

	/**
	 * @param insuranceService
	 *            The insuranceService to set.
	 */
	public void setInsuranceService(InsuranceService insuranceService) {
		this.insuranceService = insuranceService;
	}

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

	/**
	 * @param messagingService
	 *            The messagingService to set.
	 */
	public void setMessagingService(MessagingService messagingService) {
		this.messagingService = messagingService;
	}

	/**
	 * @return Returns the militaryInfoService.
	 */
	public MilitaryInfoService getMilitaryInfoService() {
		return militaryInfoService;
	}

	/**
	 * @param militaryInfoService
	 *            The militaryInfoService to set.
	 */
	public void setMilitaryInfoService(MilitaryInfoService militaryInfoService) {
		this.militaryInfoService = militaryInfoService;
	}

	/**
	 * @return Returns the loginManager.
	 */
	public LoginManager getLoginManager() {
		return loginManager;
	}

	/**
	 * @param loginManager
	 *            The loginManager to set.
	 */
	public void setLoginManager(LoginManager loginManager) {
		this.loginManager = loginManager;
	}

	protected HandBookService getHandBookService() throws Exception {
		if (handBookService == null )
			handBookService= (HandBookService)this.applicationContext
			.getBean("handBookService");
		return handBookService;
	}

	public void setHandBookService(HandBookService handBookService) {
		this.handBookService = handBookService;
	}

	/**
	 * @return Returns the dao.
	 */
	public DAOOperations getDAO() {
		if (dao == null) {
			dao = (DAOOperations) applicationContext.getBean("genericDAO");
		}
		return dao;
	}

	/**
	 * @return Returns the associationService.
	 */
	public AssociationService getAssociationService() {
		return associationService;
	}

	/**
	 * @param associationService
	 *            The associationService to set.
	 */
	public void setAssociationService(AssociationService associationService) {
		this.associationService = associationService;
	}

	protected EligibilityVerification createEligibilityVerification()
			throws Exception {
		EligibilityVerification ev = new EligibilityVerification();
		ev.setAacIndicator(getRandomAACIndicator());
		ev.setEligibilityStatus(getRandomEligibilityStatus());
		ev.setEligibilityStatusDate(ImpreciseDateUtils.createImpreciseDate(
				2006, 1, 1));
		ev.setVerificationFacility(getRandomVAFacility());
		ev.setVerificationSource(getRandomEligibilityVerificationSource());
		ev.setVerificationMethod("VerificationMethod");
		return ev;
	}

	protected EGTSiteStatistic createEGTSiteStatistic(
			Integer beneficiaryNotEnrolledCount) throws Exception {
		EGTSiteStatistic siteStatistic = new EGTSiteStatistic();
		siteStatistic
				.setBeneficiaryNotEnrolledCount(beneficiaryNotEnrolledCount);
		siteStatistic.setFacility(getRandomVAFacility());
		return siteStatistic;
	}

	protected EGTSiteStatistic createEGTSiteStatistic() throws Exception {
		return createEGTSiteStatistic(new Integer("2342"));
	}

	protected PatientVisitSummary createPatientVisitSummary() throws Exception {
		String now = System.currentTimeMillis() + "";
		return createPatientVisitSummary(new Integer(
				now.substring(now.length() - 4)));
	}

	protected PatientVisitSummary createPatientVisitSummary(Integer incomeYear)
			throws Exception {
		PatientVisitSummary visitSummary = new PatientVisitSummary();
		String now = System.currentTimeMillis() + "";
		visitSummary.setIncomeYear(incomeYear);
		visitSummary.setLastVisitDate(new Date());
		visitSummary.setInpatientDays(new Integer(
				now.substring(now.length() - 2)));
		visitSummary.setOutpatientDays(new Integer(
				now.substring(now.length() - 1)));
		visitSummary.setFacilityVisited(this.getRandomVAFacility());
		return visitSummary;
	}

	protected BeneficiaryTravel createBeneficiaryTravel() throws Exception {
		return createBeneficiaryTravel(new Integer(2005), getRandomVAFacility());
	}

	protected BeneficiaryTravel createBeneficiaryTravel(Integer incomeYear,
			VAFacility siteVisited) throws Exception {
		BeneficiaryTravel beneTravel = new BeneficiaryTravel();
		beneTravel.setYear(incomeYear);
		beneTravel.setFacilityVisited(siteVisited);
		beneTravel.setEligible(Boolean.FALSE);
		beneTravel.setClaimDate(new Date());
		return beneTravel;
	}

	protected FeeBasis createFeeBasis() throws Exception {
		FeeBasis feeBasis = new FeeBasis();
		feeBasis.setAuthorizationFromDate(new Date());
		feeBasis.setAuthorizationToDate(new Date());
		feeBasis.setProgram(getRandomFeeBasisProgram());
		feeBasis.setTreatmentType(getRandomFeeBasisTreatmentType());
		feeBasis.setReportDate(new Date());
		feeBasis.setReportSite(getRandomVAFacility());
		return feeBasis;
	}

	protected Hardship createHardship(String reason) {
		Hardship hardship = new Hardship();
		hardship.setReason(reason);
		hardship.setEffectiveDate(new Date());
		hardship.setHardshipGranted(Boolean.FALSE);
		return hardship;
	}

	protected void attachFacilityToPurpleHeart(Person person,
			String stationNumber) throws Exception {
		PurpleHeart purpleHeart = this.getPersonHelperService().getPurpleHeart(
				person);
		if (purpleHeart == null) {
			this.attachPurpleHeartWithPHStatusPending(person);
			purpleHeart = this.getPersonHelperService().getPurpleHeart(person);
		}
		if (purpleHeart != null && StringUtils.isNotEmpty(stationNumber)) {
			VAFacility facility = (VAFacility) this.getLookupService()
					.getByCode(VAFacility.class, stationNumber);
			purpleHeart.setFacility(facility);
		}
	}

	protected void attachSignatureImage(Person person) throws Exception {
		SignatureImage signatureImage = new SignatureImage();
		signatureImage.setDateIndex(new Date());
		String str = Long.toString(System.currentTimeMillis());
		String id = str.substring(str.length() - 9);
		signatureImage.setImageIdNumber(id);
		signatureImage.setSiteSubmittingImage(this.getRandomVAFacility());
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		signatureImage.setSignatureIndicator((SignatureIndicator) this
				.getLookupService().getByCode(SignatureIndicator.class,
						SignatureIndicator.CODE_YES.getCode()));
		signatureImage.setIncomeYear(new Integer(cal.get(Calendar.YEAR)));
		person.addSignatureImage(signatureImage);
	}

	protected void setPurpleHeartToNo(Person person) throws Exception {
		PurpleHeart purpleHeart = this.getPersonHelperService().getPurpleHeart(
				person);
		purpleHeart.setPhIndicator(Boolean.FALSE);
		this.getPersonHelperService().setRejectionRemark("6", purpleHeart);
	}

	protected void attachPrisonerOfWar(Person person, ImpreciseDate capture,
			ImpreciseDate release) throws Exception {
		PrisonerOfWar pow = person.getPrisonerOfWar();
		if (pow == null) {
			pow = new PrisonerOfWar();
			POWEpisode powe = new POWEpisode();
			powe.setConfinementLocation(getRandomPrisonerOfWarLocation());
			powe.setCaptureDate(capture);
			powe.setReleaseDate(release);
			pow.addEpisode(powe);
			pow.setPowIndicator((Indicator) this.getLookupService().getByCode(
					Indicator.class, Indicator.YES.getCode()));
			person.setPrisonerOfWar(pow);
		}
	}

	protected PrisonerOfWarLocation getRandomPrisonerOfWarLocation()
			throws Exception {
		List types = getLookupService().getAllPrisonerOfWarLocations();
		return (PrisonerOfWarLocation) selectRandomly(types);
	}

	protected CommsLogEntry createCommsLogEntry(Person person, String form)
			throws Exception {
		CommsTemplateDAO dao = ((CommsTemplateDAO) this.applicationContext
				.getBean("commsTemplateDAO"));
		List list = dao.findTemplateListByFormNumber(form);
		CommsTemplate commsTemplate = (list != null && list.size() > 0) ? (CommsTemplate) list
				.get(0) : null;
		if (commsTemplate == null) {
			fail("commsTemplate not found for form " + form);
		}
		CommsLogEntry commsLogEntry = new CommsLogEntry();
		Address address = (Address) person.getAddresses().iterator().next();
		if (address == null) {
			fail("address required");
		}
		this.getLoginManager().loginAnonymous();
		commsLogEntry.setLogXML("This is logXML");
		commsLogEntry.setRecipient(CommsLogEntry.RECIPIENT_VETERAN);
		commsLogEntry
				.setLetterType(this.getLookupService().getComLetterTypeByCode(
						ComLetterType.CODE_ENROLLMENT.getCode()));
		ComMailingStatusType status = this.getLookupService()
				.getComMailingStatusTypeByCode("0");
		commsLogEntry.addMailingStatus(status);
		commsLogEntry.setPersonId(new BigDecimal(person.getPersonEntityKey()
				.getKeyValueAsString()));
		Address mailingAddress = new Address();
		this.getCopyService().copy(address, mailingAddress);
		commsLogEntry.setAddress(mailingAddress);
		commsLogEntry.setTemplate(commsTemplate);
		return commsLogEntry;
	}

	protected PurpleHeartDocument createPHDocument() throws Exception {
		PurpleHeartDocument purpleHeartDocument = new PurpleHeartDocument();
		purpleHeartDocument.setAcceptable(Boolean.TRUE);
		purpleHeartDocument.setDocumentType((PHDocumentType) this
				.getLookupService().getByCode(PHDocumentType.class, "1"));
		purpleHeartDocument.setReceivedDate(this.getDate(2005, 1, 1));
		return purpleHeartDocument;
	}

	protected Registry createPHRegistry(Person person) throws Exception {
		PurpleHeart purpleHeart = new PurpleHeart();
		purpleHeart.setPhIndicator(Boolean.TRUE);
		purpleHeart.addDocument(this.createPHDocument());
		person.addDecoration(purpleHeart);
		this.setPurpleHeartStatus(DecorationStatus.CODE_PENDING, person);
		Registry reg = purpleHeart;
		RegistryTrait trait = new RegistryTrait();
		trait.setRegistryType((RegistryType) this.getLookupService().getByCode(
				RegistryType.class, RegistryType.CODE_PH_REGISTRY.getCode()));
		if (person.getOfficialSsn() != null)
			trait.setSsn(person.getOfficialSsn().getSsnText());
		reg.setRegistryTrait(trait);
		return reg;
	}

	/*
	 * Since there are multiple beans that implement CopyService autowire by
	 * type will not work. Therefore, service component is retrived in the
	 * getter method.
	 */
	/**
	 * @return Returns the copyService.
	 */
	public CopyService getCopyService() throws Exception {
		if (copyService == null)
			copyService = (CopyService) this.applicationContext
					.getBean("copyService");
		return copyService;
	}

	public UserAdminService getUserAdminService() {
		return this.userAdminService;
	}

	public void setUserAdminService(UserAdminService userAdminService) {
		this.userAdminService = userAdminService;
	}

	public EEServiceAdminService getEeServiceAdminService() {
		return eeServiceAdminService;
	}

	public void setEeServiceAdminService(
			EEServiceAdminService eeServiceAdminService) {
		this.eeServiceAdminService = eeServiceAdminService;
	}

	public ExternalSummaryFactory getExternalSummaryFactory() {
		return externalSummaryFactory;
	}

	public void setExternalSummaryFactory(
			ExternalSummaryFactory externalSummaryFactory) {
		this.externalSummaryFactory = externalSummaryFactory;
	}

	protected void logPersonKeys(Person person) {
		logPersonKeys("Target", person);
	}

	protected void logPersonKeys(String action, Person person) {
		System.out.println(action + " Person with ClaimFolderNumber["
				+ person.getClaimFolderNumber() + "] and VPID["
				+ person.getVPIDEntityKey().getVPID() + "] and EntityKey: "
				+ person.getEntityKey());
	}

	/**
	 * Builds a basic PreferredFacilityPerson with some default settings.
	 *
	 * @return
	 * @throws Exception
	 */
	protected PreferredFacilityPerson buildPFPerson() throws Exception {
		PreferredFacilityPerson pfPerson = new PreferredFacilityPerson();

		//PersonVPID vpid = new PersonVPID(PersonVPID.DEFAULT_TESTING_VPID);
		//vpid.attach(person);

		// PreferredFacility
		pfPerson.addPreferredFacility(this.createPreferredFacility());

		// PatientProviderAssignment
		pfPerson.addProviderAssignment(this.createProviderAssignment());
		return pfPerson;
	}

	protected PreferredFacility createPreferredFacility() throws Exception {
		PreferredFacility pf = new PreferredFacility();
		pf.setAssignmentDate(new Date());
		pf.setFacility(this.getRandomVAFacility());
		pf.setSourceDesignation(lookupService.getSourceDesignationByCode(SourceDesignation.CODE_PCP_ACTIVE.getName()));
		pf.setUnassignmentDate(new Date());
		return pf;
	}

	protected PatientProviderAssignment createProviderAssignment() throws Exception {
		PatientProviderAssignment providerAssignment = new PatientProviderAssignment();
		providerAssignment.setAssignmentDate(new Date());
		providerAssignment.setFacility(this.getRandomVAFacility());
		providerAssignment.setTeamName("TeamID");
		providerAssignment.setTeamPurpose(lookupService.getTeamPurposeByCode("INPATIENT"));
		providerAssignment.setTeamName("TeamName");

		return providerAssignment;
	}

	protected PreferredFacilityLite createPreferredFacilityLite() throws Exception {
		PreferredFacilityLite pf = new PreferredFacilityLite();
		pf.setAssignmentDate(new Date());
		pf.setFacility(this.getRandomVAFacility());
		pf.setSourceDesignation(lookupService.getSourceDesignationByCode(SourceDesignation.CODE_PCP_ACTIVE.getName()));
		pf.setUnassignmentDate(new Date());
		return pf;
	}

	protected PatientProviderAssignmentLite createProviderAssignmentLite() throws Exception {
		PatientProviderAssignmentLite providerAssignment = new PatientProviderAssignmentLite();
		providerAssignment.setAssignmentDate(new Date());
		providerAssignment.setFacility(this.getRandomVAFacility());
		providerAssignment.setTeamName("TeamID");
		providerAssignment.setTeamPurpose(lookupService.getTeamPurposeByCode("INPATIENT"));
		providerAssignment.setTeamName("TeamName");

		return providerAssignment;
	}


	protected HealthCareProvider createHealthCareProvider() throws Exception {

		HealthCareProvider provider = new HealthCareProvider();
		provider.setName(this.createName());
		provider.setPractitionerId("349223");
		return provider;
	}

	public VOAApplicationService getVoaApplicationService() {
		return voaApplicationService;
	}

	public void setVoaApplicationService(VOAApplicationService voaApplicationService) {
		this.voaApplicationService = voaApplicationService;
	}

	protected HealthBenefitPlan createHealthBenefitPlan() throws Exception {
		HealthBenefitPlan hbp = new HealthBenefitPlan();
		hbp.setPlanType(lookupService.getHealthBenefitPlanTypeByCode("101"));
		hbp.setChangeSource(lookupService.getDataChangeSourceByCode("V"));
		hbp.setChangeSite(lookupService.getVaFacilityByCode("553"));
		hbp.setChangeDate(new Date());

		return hbp;
	}
}