FixMissingOpenmrsIdentifiers extends AbstractChore { @Override public void perform(PrintWriter output) { Location defaultLocation = kenyaEmrService.getDefaultLocation(); if (defaultLocation == null) { return; } PatientIdentifierType openmrsIdType = MetadataUtils.existing(PatientIdentifierType.class, CommonMetadata._PatientIdentifierType.OPENMRS_ID); IdentifierSource openmrsIdSource = idgenService.getAutoGenerationOption(openmrsIdType).getSource(); List<Patient> allPatients = patientService.getAllPatients(); Map<Patient, PatientIdentifier> patientsWithOpenmrsID = new HashMap<Patient, PatientIdentifier>(); for (Patient patient : allPatients) { PatientIdentifier openmrsID = patient.getPatientIdentifier(openmrsIdType); if (openmrsID != null) { patientsWithOpenmrsID.put(patient, patient.getPatientIdentifier(openmrsIdType)); } } int missingOpenmrsIDs = allPatients.size() - patientsWithOpenmrsID.size(); List<String> generatedIds = idgenService.generateIdentifiers(openmrsIdSource, missingOpenmrsIDs, FixMissingOpenmrsIdentifiers.class.getSimpleName()); int fixedMissing = 0, fixedNoPreferred = 0; for (Patient patient : allPatients) { PatientIdentifier openmrsID = patientsWithOpenmrsID.get(patient); boolean needsSaved = false; if (openmrsID == null) { String generated = generatedIds.get(fixedMissing); openmrsID = new PatientIdentifier(generated, openmrsIdType, defaultLocation); patient.addIdentifier(openmrsID); fixedMissing++; needsSaved = true; } if (!patientHasPreferredId(patient)) { openmrsID.setPreferred(true); fixedNoPreferred++; needsSaved = true; } if (needsSaved) { patientService.savePatientIdentifier(openmrsID); } } output.println("Fixed " + fixedMissing + " missing OpenMRS IDs"); output.println("Fixed " + fixedNoPreferred + " patients with no preferred ID"); }  @Override void perform(PrintWriter output);  }
@Test public void perform() throws Exception { PatientIdentifierType openmrsIdType = MetadataUtils.existing(PatientIdentifierType.class, CommonMetadata._PatientIdentifierType.OPENMRS_ID); chore.perform(new PrintWriter(System.out)); for (Patient patient : patientService.getAllPatients()) { PatientIdentifier openmrsId = patient.getPatientIdentifier(); Assert.assertThat(openmrsId.getIdentifierType(), is(openmrsIdType)); Assert.assertThat(openmrsId.isPreferred(), is(true)); } }