Search in sources :

Example 1 with DiagnosticReport

use of ca.uhn.fhir.model.dstu2.resource.DiagnosticReport in project synthea by synthetichealth.

the class FhirDstu2 method report.

/**
 * Map the given Report to a FHIR DiagnosticReport resource, and add it to the given Bundle.
 *
 * @param rand
 *          Source of randomness to use when generating ids etc
 * @param personEntry
 *          The Entry for the Person
 * @param bundle
 *          Bundle to add the Report to
 * @param encounterEntry
 *          Current Encounter entry
 * @param report
 *          The Report
 * @return The added Entry
 */
private static Entry report(RandomNumberGenerator rand, Entry personEntry, Bundle bundle, Entry encounterEntry, Report report) {
    DiagnosticReport reportResource = new DiagnosticReport();
    reportResource.setStatus(DiagnosticReportStatusEnum.FINAL);
    /*
     * Technically, the CodeableConcept system should be "http://hl7.org/fhir/v2/0074"
     * But the official Argonauts profiles incorrectly list the category pattern as
     * the ValueSet (which contains the above system) as
     * "http://hl7.org/fhir/ValueSet/diagnostic-service-sections", so we repeat the
     * error here.
     */
    CodeableConceptDt category = new CodeableConceptDt("http://hl7.org/fhir/ValueSet/diagnostic-service-sections", "LAB");
    reportResource.setCategory(category);
    reportResource.setCode(mapCodeToCodeableConcept(report.codes.get(0), LOINC_URI));
    reportResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
    reportResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
    reportResource.setEffective(convertFhirDateTime(report.start, true));
    reportResource.setIssued(new InstantDt(new Date(report.start)));
    ca.uhn.fhir.model.dstu2.resource.Encounter encounter = (ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry.getResource();
    reportResource.setPerformer(encounter.getServiceProvider());
    for (Observation observation : report.observations) {
        ResourceReferenceDt reference = new ResourceReferenceDt(observation.fullUrl);
        reference.setDisplay(observation.codes.get(0).display);
        List<ResourceReferenceDt> result = new ArrayList<ResourceReferenceDt>();
        result.add(reference);
        reportResource.setResult(result);
    }
    return newEntry(rand, bundle, reportResource);
}
Also used : CodeableConceptDt(ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt) ResourceReferenceDt(ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt) ArrayList(java.util.ArrayList) DiagnosticReport(ca.uhn.fhir.model.dstu2.resource.DiagnosticReport) Date(java.util.Date) Observation(org.mitre.synthea.world.concepts.HealthRecord.Observation) Encounter(org.mitre.synthea.world.concepts.HealthRecord.Encounter) InstantDt(ca.uhn.fhir.model.primitive.InstantDt)

Example 2 with DiagnosticReport

use of ca.uhn.fhir.model.dstu2.resource.DiagnosticReport in project synthea by synthetichealth.

the class FHIRDSTU2ExporterTest method testFHIRDSTU2Export.

@Test
public void testFHIRDSTU2Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirDstu2.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    FhirValidator validator = ctx.newValidator();
    validator.setValidateAgainstStandardSchema(true);
    validator.setValidateAgainstStandardSchematron(true);
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        Config.set("exporter.fhir_dstu2.export", "true");
        FhirDstu2.TRANSACTION_BUNDLE = person.randBoolean();
        String fhirJson = FhirDstu2.convertToFHIRJson(person, System.currentTimeMillis());
        // (these should have been converted into URIs)
        if (fhirJson.contains("SNOMED-CT")) {
            validationErrors.add("JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
        }
        // let's crack open the Bundle and validate
        // each individual entry.resource to get context-sensitive error
        // messages...
        Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
        for (Entry entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateWithResult(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    if (emessage.getMessage().contains("start SHALL have a lower value than end")) {
                        continue;
                    }
                    System.out.println(parser.encodeResourceToString(entry.getResource()));
                    System.out.println("ERROR: " + emessage.getMessage());
                    validationErrors.add(emessage.getMessage());
                }
            }
            if (entry.getResource() instanceof DiagnosticReport) {
                DiagnosticReport report = (DiagnosticReport) entry.getResource();
                if (report.getPerformer().isEmpty()) {
                    validationErrors.add("Performer is a required field on DiagnosticReport!");
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            Exporter.export(person, System.currentTimeMillis());
        }
        return validationErrors;
    });
    assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) Entry(ca.uhn.fhir.model.dstu2.resource.Bundle.Entry) SingleValidationMessage(ca.uhn.fhir.validation.SingleValidationMessage) Bundle(ca.uhn.fhir.model.dstu2.resource.Bundle) ArrayList(java.util.ArrayList) DiagnosticReport(org.hl7.fhir.dstu3.model.DiagnosticReport) FhirValidator(ca.uhn.fhir.validation.FhirValidator) ValidationResult(ca.uhn.fhir.validation.ValidationResult) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 3 with DiagnosticReport

use of ca.uhn.fhir.model.dstu2.resource.DiagnosticReport in project eCRNow by drajer-health.

the class Dstu2CdaEicrGenerator method convertDstu2FhirBundletoCdaEicr.

public static String convertDstu2FhirBundletoCdaEicr(Dstu2FhirData data, LaunchDetails details, Eicr ecr) {
    StringBuilder eICR = new StringBuilder();
    if (data != null) {
        Bundle bundle = data.getData();
        if (bundle != null) {
            List<Entry> entries = bundle.getEntry();
            for (Entry ent : entries) {
                // Populate data ..this can be moved to the APIs where the bundle is getting created.
                if (ent.getResource() instanceof Patient) {
                    logger.info(" Bundle contains Patient ");
                    data.setPatient((Patient) ent.getResource());
                } else if (ent.getResource() instanceof Practitioner) {
                    logger.info(" Bundle contains Practitioner ");
                    data.setPractitioner((Practitioner) ent.getResource());
                } else if (ent.getResource() instanceof Encounter) {
                    logger.info(" Bundle contains Encounter ");
                    data.setEncounter((Encounter) ent.getResource());
                } else if (ent.getResource() instanceof Location) {
                    logger.info(" Bundle contains Location ");
                    data.setLocation((Location) ent.getResource());
                } else if (ent.getResource() instanceof Organization) {
                    logger.info(" Bundle contains Organization ");
                    data.setOrganization((Organization) ent.getResource());
                } else if (ent.getResource() instanceof Condition) {
                    logger.info(" Bundle contains Condition ");
                    data.getConditions().add((Condition) ent.getResource());
                } else if (ent.getResource() instanceof Observation) {
                    Observation obs = (Observation) ent.getResource();
                    if (obs.getCategory() != null && obs.getCategory().getCodingFirstRep() != null && obs.getCategory().getCodingFirstRep().getCode() != null && obs.getCategory().getCodingFirstRep().getCode().contentEquals(CdaGeneratorConstants.FHIR_LAB_RESULT_CATEGORY)) {
                        logger.info(" Bundle contains Lab Results ");
                        data.getLabResults().add((Observation) ent.getResource());
                    } else if (obs.getCategory() != null && obs.getCategory().getCodingFirstRep() != null && obs.getCategory().getCodingFirstRep().getCode() != null) {
                        logger.info("Code for Observation Category =  " + obs.getCategory().getCodingFirstRep().getCode());
                    }
                // Compare Code for Travel Obs
                // Compare Codes for Pregnancy Obs and sort it out.
                } else if (ent.getResource() instanceof DiagnosticReport) {
                    logger.info(" Bundle contains Diagnostic Report ");
                    data.getDiagReports().add((DiagnosticReport) ent.getResource());
                } else if (ent.getResource() instanceof DiagnosticOrder) {
                    logger.info(" Bundle contains Diagnostic Order ");
                    data.getDiagOrders().add((DiagnosticOrder) ent.getResource());
                } else if (ent.getResource() instanceof MedicationStatement) {
                    logger.info(" Bundle contains MedicationStatement ");
                    data.getMedications().add((MedicationStatement) ent.getResource());
                } else if (ent.getResource() instanceof Immunization) {
                    logger.info(" Bundle contains Immunization ");
                    data.getImmunizations().add((Immunization) ent.getResource());
                }
            }
            eICR.append(Dstu2CdaHeaderGenerator.createCdaHeader(data, details));
            eICR.append(Dstu2CdaBodyGenerator.generateCdaBody(data, details));
            eICR.append(CdaGeneratorUtils.getEndXMLHeaderForCdaDocument());
        }
    } else {
        logger.error(" No Fhir Bundle Available to create CDA Documents ");
    }
    return eICR.toString();
}
Also used : Condition(ca.uhn.fhir.model.dstu2.resource.Condition) Immunization(ca.uhn.fhir.model.dstu2.resource.Immunization) Organization(ca.uhn.fhir.model.dstu2.resource.Organization) Bundle(ca.uhn.fhir.model.dstu2.resource.Bundle) Patient(ca.uhn.fhir.model.dstu2.resource.Patient) DiagnosticReport(ca.uhn.fhir.model.dstu2.resource.DiagnosticReport) DiagnosticOrder(ca.uhn.fhir.model.dstu2.resource.DiagnosticOrder) Practitioner(ca.uhn.fhir.model.dstu2.resource.Practitioner) Entry(ca.uhn.fhir.model.dstu2.resource.Bundle.Entry) Observation(ca.uhn.fhir.model.dstu2.resource.Observation) Encounter(ca.uhn.fhir.model.dstu2.resource.Encounter) MedicationStatement(ca.uhn.fhir.model.dstu2.resource.MedicationStatement) Location(ca.uhn.fhir.model.dstu2.resource.Location)

Example 4 with DiagnosticReport

use of ca.uhn.fhir.model.dstu2.resource.DiagnosticReport in project eCRNow by drajer-health.

the class LoadingQueryDstu2Bundle method createDSTU2Bundle.

public Bundle createDSTU2Bundle(LaunchDetails launchDetails, Dstu2FhirData dstu2FhirData, Date start, Date end) {
    Bundle bundle = new Bundle();
    logger.info("Initializing FHIR Context for Version:::: {}", launchDetails.getFhirVersion());
    FhirContext context = fhirContextInitializer.getFhirContext(launchDetails.getFhirVersion());
    logger.info("Initializing Client");
    IGenericClient client = fhirContextInitializer.createClient(context, launchDetails);
    // GET Patient Details and Add to Bundle
    try {
        logger.info("Get Patient Data");
        Patient patient = (Patient) fhirContextInitializer.getResouceById(launchDetails, client, context, "Patient", launchDetails.getLaunchPatientId());
        Entry patientEntry = new Entry();
        patientEntry.setResource(patient);
        bundle.addEntry(patientEntry);
    } catch (Exception e) {
        logger.error("Error in getting Patient Data", e);
    }
    // Step 1: Get Encounters for Patient based on encId. (Create a method to get
    // encounters)
    // If encId is null, find encounters for patient within the start and end time
    // provided.
    // Add to the bundle.
    // As you are adding to the bundle within Fhir Data, add the codeable concept
    // also to the list of encounterCodes.
    Encounter encounter = null;
    try {
        logger.info("Get Encounter Data");
        encounter = dstu2ResourcesData.getEncounterData(context, client, launchDetails, dstu2FhirData, start, end);
        if (encounter.getParticipant() != null) {
            List<Participant> participants = encounter.getParticipant();
            for (Participant participant : participants) {
                if (participant.getIndividual() != null) {
                    ResourceReferenceDt practitionerReference = participant.getIndividual();
                    Practitioner practitioner = (Practitioner) fhirContextInitializer.getResouceById(launchDetails, client, context, "Practitioner", practitionerReference.getReference().getIdPart());
                    Entry practitionerEntry = new Entry().setResource(practitioner);
                    bundle.addEntry(practitionerEntry);
                }
            }
        }
        if (encounter.getServiceProvider() != null) {
            ResourceReferenceDt organizationReference = encounter.getServiceProvider();
            Organization organization = (Organization) fhirContextInitializer.getResouceById(launchDetails, client, context, "Organization", organizationReference.getReference().getIdPart());
            Entry organizationEntry = new Entry().setResource(organization);
            bundle.addEntry(organizationEntry);
        }
        if (encounter.getLocation() != null) {
            List<Location> enocunterLocations = encounter.getLocation();
            for (Location location : enocunterLocations) {
                if (location.getLocation() != null) {
                    ResourceReferenceDt locationReference = location.getLocation();
                    ca.uhn.fhir.model.dstu2.resource.Location locationResource = (ca.uhn.fhir.model.dstu2.resource.Location) fhirContextInitializer.getResouceById(launchDetails, client, context, "Location", locationReference.getReference().getIdPart());
                    Entry locationEntry = new Entry().setResource(locationResource);
                    bundle.addEntry(locationEntry);
                }
            }
        }
        Entry encounterEntry = new Entry().setResource(encounter);
        bundle.addEntry(encounterEntry);
    } catch (Exception e) {
        logger.error("Error in getting Encounter Data", e);
    }
    // also to the list of ConditionCodes.
    try {
        logger.info("Get Condition Data");
        List<Condition> conditionsList = dstu2ResourcesData.getConditionData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered ConditionsList----> {}", conditionsList.size());
        dstu2FhirData.setConditions(conditionsList);
        for (Condition condition : conditionsList) {
            Entry conditionsEntry = new Entry().setResource(condition);
            bundle.addEntry(conditionsEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting Condition Data", e);
    }
    // also to the list of labResultCodes.
    try {
        logger.info("Get Observation Data");
        List<Observation> observationList = dstu2ResourcesData.getObservationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered Observations----> {}", observationList.size());
        dstu2FhirData.setLabResults(observationList);
        for (Observation observation : observationList) {
            Entry observationsEntry = new Entry().setResource(observation);
            bundle.addEntry(observationsEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting Observation Data", e);
    }
    // Get Pregnancy Observations
    try {
        logger.info("Get Pregnancy Observation Data");
        List<Observation> observationList = dstu2ResourcesData.getPregnancyObservationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered Observations----> {}", observationList.size());
        dstu2FhirData.setPregnancyObs(observationList);
        for (Observation observation : observationList) {
            Entry observationsEntry = new Entry().setResource(observation);
            bundle.addEntry(observationsEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting Pregnancy Observation Data", e);
    }
    // Get Travel Observations
    try {
        logger.info("Get Travel Observation Data");
        List<Observation> observationList = dstu2ResourcesData.getTravelObservationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered Observations----> {}", observationList.size());
        dstu2FhirData.setTravelObs(observationList);
        for (Observation observation : observationList) {
            Entry observationsEntry = new Entry().setResource(observation);
            bundle.addEntry(observationsEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting Travel Observation Data", e);
    }
    // also to the list of medicationCodes.
    try {
        logger.info("Get MedicationAdministration Data");
        List<MedicationAdministration> medAdministrationsList = dstu2ResourcesData.getMedicationAdministrationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered MedicationAdministration-----------> {}", medAdministrationsList.size());
        dstu2FhirData.setMedicationAdministrations(medAdministrationsList);
        for (MedicationAdministration medAdministration : medAdministrationsList) {
            if (medAdministration.getMedication() != null && !medAdministration.getMedication().isEmpty() && medAdministration.getMedication() instanceof ResourceReferenceDt) {
                BaseResourceReferenceDt medRef = (BaseResourceReferenceDt) medAdministration.getMedication();
                String medReference = medRef.getReference().getValue();
                if (medReference.startsWith("#")) {
                    BaseContainedDt medAdministrationContained = medAdministration.getContained();
                    List<Medication> containedResources = (List<Medication>) medAdministrationContained.getContainedResources();
                    if (containedResources.stream().anyMatch(resource -> resource.getIdElement().getValue().equals(medReference))) {
                        logger.info("Medication Resource exists in MedicationAdministration.contained. So no need to add again in Bundle.");
                    }
                } else {
                    logger.info("Medication Reference Found=============>");
                    Medication medication = dstu2ResourcesData.getMedicationData(context, client, launchDetails, dstu2FhirData, medReference);
                    Entry medicationEntry = new Entry().setResource(medication);
                    bundle.addEntry(medicationEntry);
                    if (medication != null) {
                        List<Medication> medicationList = new ArrayList<>();
                        medicationList.add(medication);
                        dstu2FhirData.setMedicationList(medicationList);
                    }
                }
            }
            Entry medAdministrationEntry = new Entry().setResource(medAdministration);
            bundle.addEntry(medAdministrationEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the MedicationAdministration Data", e);
    }
    try {
        logger.info("Get MedicationStatement Data");
        List<MedicationStatement> medStatementsList = dstu2ResourcesData.getMedicationStatementData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered MedicationStatement-----------> {}", medStatementsList.size());
        for (MedicationStatement medStatement : medStatementsList) {
            Entry medStatementEntry = new Entry().setResource(medStatement);
            bundle.addEntry(medStatementEntry);
        }
        dstu2FhirData.setMedications(medStatementsList);
    } catch (Exception e) {
        logger.error("Error in getting the MedicationStatement Data", e);
    }
    try {
        logger.info("Get DiagnosticOrder Data");
        List<DiagnosticOrder> diagnosticOrdersList = dstu2ResourcesData.getDiagnosticOrderData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered DiagnosticOrders-----------> {}", diagnosticOrdersList.size());
        dstu2FhirData.setDiagOrders(diagnosticOrdersList);
        for (DiagnosticOrder diagnosticOrder : diagnosticOrdersList) {
            Entry diagnosticOrderEntry = new Entry().setResource(diagnosticOrder);
            bundle.addEntry(diagnosticOrderEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the DiagnosticOrder Data", e);
    }
    // Add to the bundle
    try {
        List<Immunization> immunizationsList = dstu2ResourcesData.getImmunizationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered Immunizations-----------> {}", immunizationsList.size());
        dstu2FhirData.setImmunizations(immunizationsList);
        for (Immunization immunization : immunizationsList) {
            Entry immunizationEntry = new Entry().setResource(immunization);
            bundle.addEntry(immunizationEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the Immunization Data", e);
    }
    // Add to the bundle
    try {
        List<DiagnosticReport> diagnosticReportList = dstu2ResourcesData.getDiagnosticReportData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered DiagnosticReports-----------> {}", diagnosticReportList.size());
        dstu2FhirData.setDiagReports(diagnosticReportList);
        for (DiagnosticReport diagnosticReport : diagnosticReportList) {
            Entry diagnosticReportEntry = new Entry().setResource(diagnosticReport);
            bundle.addEntry(diagnosticReportEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the DiagnosticReport Data", e);
    }
    // Setting bundle to FHIR Data
    logger.info("------------------------------CodeableConcept Codes------------------------------");
    logger.info("Encounter Codes Size=====> {}", dstu2FhirData.getEncounterCodes().size());
    logger.info("Conditions Codes Size=====> {}", dstu2FhirData.getConditionCodes().size());
    logger.info("Observation Codes Size=====> {}", dstu2FhirData.getLabResultCodes().size());
    logger.info("Medication Codes Size=====> {}", dstu2FhirData.getMedicationCodes().size());
    logger.info("Immunization Codes Size=====> {}", dstu2FhirData.getImmuniationCodes().size());
    logger.info("DiagnosticReport Codes Size=====> {}", dstu2FhirData.getDiagnosticReportCodes().size());
    String fileName = ActionRepo.getInstance().getLogFileDirectory() + "/LoadingQueryDSTU2Bundle-" + launchDetails.getLaunchPatientId() + ".json";
    ApplicationUtils.saveDataToFile(context.newJsonParser().encodeResourceToString(bundle), fileName);
    return bundle;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) ResourceReferenceDt(ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt) BaseResourceReferenceDt(ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt) Organization(ca.uhn.fhir.model.dstu2.resource.Organization) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ArrayList(java.util.ArrayList) DiagnosticReport(ca.uhn.fhir.model.dstu2.resource.DiagnosticReport) Entry(ca.uhn.fhir.model.dstu2.resource.Bundle.Entry) Medication(ca.uhn.fhir.model.dstu2.resource.Medication) Encounter(ca.uhn.fhir.model.dstu2.resource.Encounter) ArrayList(java.util.ArrayList) List(java.util.List) Condition(ca.uhn.fhir.model.dstu2.resource.Condition) Immunization(ca.uhn.fhir.model.dstu2.resource.Immunization) BaseContainedDt(ca.uhn.fhir.model.base.composite.BaseContainedDt) Bundle(ca.uhn.fhir.model.dstu2.resource.Bundle) Patient(ca.uhn.fhir.model.dstu2.resource.Patient) DiagnosticOrder(ca.uhn.fhir.model.dstu2.resource.DiagnosticOrder) BaseResourceReferenceDt(ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt) Practitioner(ca.uhn.fhir.model.dstu2.resource.Practitioner) Participant(ca.uhn.fhir.model.dstu2.resource.Encounter.Participant) Observation(ca.uhn.fhir.model.dstu2.resource.Observation) MedicationAdministration(ca.uhn.fhir.model.dstu2.resource.MedicationAdministration) MedicationStatement(ca.uhn.fhir.model.dstu2.resource.MedicationStatement) Location(ca.uhn.fhir.model.dstu2.resource.Encounter.Location)

Example 5 with DiagnosticReport

use of ca.uhn.fhir.model.dstu2.resource.DiagnosticReport in project eCRNow by drajer-health.

the class TriggerQueryDstu2Bundle method createDSTU2Bundle.

public Bundle createDSTU2Bundle(LaunchDetails launchDetails, Dstu2FhirData dstu2FhirData, Date start, Date end) {
    Bundle bundle = new Bundle();
    logger.info("Initializing FHIR Context for Version:::: {}", launchDetails.getFhirVersion());
    FhirContext context = fhirContextInitializer.getFhirContext(launchDetails.getFhirVersion());
    logger.info("Initializing Client");
    IGenericClient client = fhirContextInitializer.createClient(context, launchDetails);
    // GET Patient Details and Add to Bundle
    try {
        logger.info("Get Patient Data");
        Patient patient = (Patient) fhirContextInitializer.getResouceById(launchDetails, client, context, "Patient", launchDetails.getLaunchPatientId());
        Entry patientEntry = new Entry();
        patientEntry.setResource(patient);
        bundle.addEntry(patientEntry);
    } catch (Exception e) {
        logger.error("Error in getting Patient Data", e);
    }
    // Step 1: Get Encounters for Patient based on encId. (Create a method to get
    // encounters)
    // If encId is null, find encounters for patient within the start and end time
    // provided.
    // Add to the bundle.
    // As you are adding to the bundle within Fhir Data, add the codeable concept
    // also to the list of encounterCodes.
    Encounter encounter = null;
    try {
        logger.info("Get Encounter Data");
        encounter = dstu2ResourcesData.getEncounterData(context, client, launchDetails, dstu2FhirData, start, end);
        if (encounter.getParticipant() != null) {
            List<Participant> participants = encounter.getParticipant();
            for (Participant participant : participants) {
                if (participant.getIndividual() != null) {
                    ResourceReferenceDt practitionerReference = participant.getIndividual();
                    Practitioner practitioner = (Practitioner) fhirContextInitializer.getResouceById(launchDetails, client, context, "Practitioner", practitionerReference.getReference().getIdPart());
                    Entry practitionerEntry = new Entry().setResource(practitioner);
                    bundle.addEntry(practitionerEntry);
                }
            }
        }
        if (encounter.getServiceProvider() != null) {
            ResourceReferenceDt organizationReference = encounter.getServiceProvider();
            Organization organization = (Organization) fhirContextInitializer.getResouceById(launchDetails, client, context, "Organization", organizationReference.getReference().getIdPart());
            Entry organizationEntry = new Entry().setResource(organization);
            bundle.addEntry(organizationEntry);
        }
        if (encounter.getLocation() != null) {
            List<Location> enocunterLocations = encounter.getLocation();
            for (Location location : enocunterLocations) {
                if (location.getLocation() != null) {
                    ResourceReferenceDt locationReference = location.getLocation();
                    ca.uhn.fhir.model.dstu2.resource.Location locationResource = (ca.uhn.fhir.model.dstu2.resource.Location) fhirContextInitializer.getResouceById(launchDetails, client, context, "Location", locationReference.getReference().getIdPart());
                    Entry locationEntry = new Entry().setResource(locationResource);
                    bundle.addEntry(locationEntry);
                }
            }
        }
        Entry encounterEntry = new Entry().setResource(encounter);
        bundle.addEntry(encounterEntry);
    } catch (Exception e) {
        logger.error("Error in getting Encounter Data", e);
    }
    // also to the list of ConditionCodes.
    try {
        logger.info("Get Condition Data");
        List<Condition> conditionsList = dstu2ResourcesData.getConditionData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered ConditionsList----> {}", conditionsList.size());
        dstu2FhirData.setConditions(conditionsList);
        for (Condition condition : conditionsList) {
            Entry conditionsEntry = new Entry().setResource(condition);
            bundle.addEntry(conditionsEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting Condition Data", e);
    }
    // also to the list of labResultCodes.
    try {
        logger.info("Get Observation Data");
        List<Observation> observationList = dstu2ResourcesData.getObservationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered Observations----> {}", observationList.size());
        dstu2FhirData.setLabResults(observationList);
        for (Observation observation : observationList) {
            Entry observationsEntry = new Entry().setResource(observation);
            bundle.addEntry(observationsEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting Observation Data", e);
    }
    // also to the list of medicationCodes.
    try {
        logger.info("Get MedicationAdministration Data");
        List<MedicationAdministration> medAdministrationsList = dstu2ResourcesData.getMedicationAdministrationData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered MedicationAdministration-----------> {}", medAdministrationsList.size());
        dstu2FhirData.setMedicationAdministrations(medAdministrationsList);
        for (MedicationAdministration medAdministration : medAdministrationsList) {
            if (!medAdministration.getMedication().isEmpty() && medAdministration.getMedication() != null) {
                if (medAdministration.getMedication() instanceof ResourceReferenceDt) {
                    BaseResourceReferenceDt medRef = (BaseResourceReferenceDt) medAdministration.getMedication();
                    String medReference = medRef.getReference().getValue();
                    if (medReference.startsWith("#")) {
                        BaseContainedDt medAdministrationContained = medAdministration.getContained();
                        List<Medication> containedResources = (List<Medication>) medAdministrationContained.getContainedResources();
                        if (containedResources.stream().anyMatch(resource -> resource.getIdElement().getValue().equals(medReference))) {
                            logger.info("Medication Resource exists in MedicationAdministration.contained. So no need to add again in Bundle.");
                        }
                    } else {
                        logger.info("Medication Reference Found=============>");
                        Medication medication = dstu2ResourcesData.getMedicationData(context, client, launchDetails, dstu2FhirData, medReference);
                        Entry medicationEntry = new Entry().setResource(medication);
                        bundle.addEntry(medicationEntry);
                        if (medication != null) {
                            List<Medication> medicationList = new ArrayList<>();
                            medicationList.add(medication);
                            dstu2FhirData.setMedicationList(medicationList);
                        }
                    }
                }
            }
            Entry medAdministrationEntry = new Entry().setResource(medAdministration);
            bundle.addEntry(medAdministrationEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the MedicationAdministration Data", e);
    }
    try {
        logger.info("Get DiagnosticOrder Data");
        List<DiagnosticOrder> diagnosticOrdersList = dstu2ResourcesData.getDiagnosticOrderData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered DiagnosticOrders-----------> {}", diagnosticOrdersList.size());
        dstu2FhirData.setDiagOrders(diagnosticOrdersList);
        for (DiagnosticOrder diagnosticOrder : diagnosticOrdersList) {
            Entry diagnosticOrderEntry = new Entry().setResource(diagnosticOrder);
            bundle.addEntry(diagnosticOrderEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the DiagnosticOrder Data", e);
    }
    try {
        List<DiagnosticReport> diagnosticReportList = dstu2ResourcesData.getDiagnosticReportData(context, client, launchDetails, dstu2FhirData, encounter, start, end);
        logger.info("Filtered DiagnosticReports-----------> {}", diagnosticReportList.size());
        dstu2FhirData.setDiagReports(diagnosticReportList);
        for (DiagnosticReport diagnosticReport : diagnosticReportList) {
            Entry diagnosticReportEntry = new Entry().setResource(diagnosticReport);
            bundle.addEntry(diagnosticReportEntry);
        }
    } catch (Exception e) {
        logger.error("Error in getting the DiagnosticReport Data", e);
    }
    // Setting bundle to FHIR Data
    logger.info("------------------------------CodeableConcept Codes------------------------------");
    logger.info("Encounter Codes Size=====> {}", dstu2FhirData.getEncounterCodes().size());
    logger.info("Conditions Codes Size=====> {}", dstu2FhirData.getConditionCodes().size());
    logger.info("Observation Codes Size=====> {}", dstu2FhirData.getLabResultCodes().size());
    logger.info("Medication Codes Size=====> {}", dstu2FhirData.getMedicationCodes().size());
    logger.info("DiagnosticReport Codes Size=====> {}", dstu2FhirData.getDiagnosticReportCodes().size());
    logger.info("DiagnosticOrders Codes Size=====> {}", dstu2FhirData.getDiagnosticOrderCodes().size());
    String fileName = ActionRepo.getInstance().getLogFileDirectory() + "/TriggerQueryDSTU2Bundle-" + launchDetails.getLaunchPatientId() + ".json";
    ApplicationUtils.saveDataToFile(context.newJsonParser().encodeResourceToString(bundle), fileName);
    return bundle;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) ResourceReferenceDt(ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt) BaseResourceReferenceDt(ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt) Organization(ca.uhn.fhir.model.dstu2.resource.Organization) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ArrayList(java.util.ArrayList) DiagnosticReport(ca.uhn.fhir.model.dstu2.resource.DiagnosticReport) Entry(ca.uhn.fhir.model.dstu2.resource.Bundle.Entry) Medication(ca.uhn.fhir.model.dstu2.resource.Medication) Encounter(ca.uhn.fhir.model.dstu2.resource.Encounter) ArrayList(java.util.ArrayList) List(java.util.List) Condition(ca.uhn.fhir.model.dstu2.resource.Condition) BaseContainedDt(ca.uhn.fhir.model.base.composite.BaseContainedDt) Bundle(ca.uhn.fhir.model.dstu2.resource.Bundle) Patient(ca.uhn.fhir.model.dstu2.resource.Patient) DiagnosticOrder(ca.uhn.fhir.model.dstu2.resource.DiagnosticOrder) BaseResourceReferenceDt(ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt) Practitioner(ca.uhn.fhir.model.dstu2.resource.Practitioner) Participant(ca.uhn.fhir.model.dstu2.resource.Encounter.Participant) Observation(ca.uhn.fhir.model.dstu2.resource.Observation) MedicationAdministration(ca.uhn.fhir.model.dstu2.resource.MedicationAdministration) Location(ca.uhn.fhir.model.dstu2.resource.Encounter.Location)

Aggregations

Bundle (ca.uhn.fhir.model.dstu2.resource.Bundle)5 Entry (ca.uhn.fhir.model.dstu2.resource.Bundle.Entry)5 DiagnosticReport (ca.uhn.fhir.model.dstu2.resource.DiagnosticReport)5 ArrayList (java.util.ArrayList)5 FhirContext (ca.uhn.fhir.context.FhirContext)3 ResourceReferenceDt (ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt)3 Condition (ca.uhn.fhir.model.dstu2.resource.Condition)3 DiagnosticOrder (ca.uhn.fhir.model.dstu2.resource.DiagnosticOrder)3 Encounter (ca.uhn.fhir.model.dstu2.resource.Encounter)3 Observation (ca.uhn.fhir.model.dstu2.resource.Observation)3 Organization (ca.uhn.fhir.model.dstu2.resource.Organization)3 Patient (ca.uhn.fhir.model.dstu2.resource.Patient)3 Practitioner (ca.uhn.fhir.model.dstu2.resource.Practitioner)3 BaseContainedDt (ca.uhn.fhir.model.base.composite.BaseContainedDt)2 BaseResourceReferenceDt (ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt)2 CodeableConceptDt (ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt)2 Location (ca.uhn.fhir.model.dstu2.resource.Encounter.Location)2 Participant (ca.uhn.fhir.model.dstu2.resource.Encounter.Participant)2 Immunization (ca.uhn.fhir.model.dstu2.resource.Immunization)2 Medication (ca.uhn.fhir.model.dstu2.resource.Medication)2