diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/CdaMapper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/CdaMapper.java index a3aa4d92b..390cb69d5 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/CdaMapper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/CdaMapper.java @@ -198,7 +198,7 @@ private CdaContainerComp mapParentContainer(POCDMT000040ClinicalDocument1 clinic clinicalDocument.getCode().setDisplayName("Public Health Case Report - PHRI"); clinicalDocument.setTitle(ST.Factory.newInstance()); - clinicalDocument.getTitle().set(cdaMapHelper.mapToStringData("Public Health Case Report - Data from Legacy System to CDA")); + clinicalDocument.getTitle().set(cdaMapHelper.mapToPCData("Public Health Case Report - Data from Legacy System to CDA")); clinicalDocument.setEffectiveTime(TS.Factory.newInstance()); clinicalDocument.getEffectiveTime().setValue(this.cdaMapHelper.getCurrentUtcDateTimeInCdaFormat()); @@ -237,28 +237,28 @@ private void mapCustodian(POCDMT000040ClinicalDocument1 clinicalDocument) throws custodianValue = mapToTranslatedValue("CUS103"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().addNewStreetAddressLine(); - clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getStreetAddressLineArray(k).set(cdaMapHelper.mapToCData(custodianValue)); + clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getStreetAddressLineArray(k).set(cdaMapHelper.mapToPCData(custodianValue)); k = k+1; custodianValue = mapToTranslatedValue("CUS104"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().addNewStreetAddressLine(); - clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getStreetAddressLineArray(k).set(cdaMapHelper.mapToCData(custodianValue)); + clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getStreetAddressLineArray(k).set(cdaMapHelper.mapToPCData(custodianValue)); k = 0; custodianValue = mapToTranslatedValue("CUS105"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().addNewCity(); - clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getCityArray(k).set(cdaMapHelper.mapToCData(custodianValue)); + clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getCityArray(k).set(cdaMapHelper.mapToPCData(custodianValue)); custodianValue = mapToTranslatedValue("CUS106"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().addNewState(); - clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getStateArray(k).set(cdaMapHelper.mapToCData(custodianValue)); + clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getStateArray(k).set(cdaMapHelper.mapToPCData(custodianValue)); custodianValue = mapToTranslatedValue("CUS107"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().addNewPostalCode(); - clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getPostalCodeArray(k).set(cdaMapHelper.mapToCData(custodianValue)); + clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getPostalCodeArray(k).set(cdaMapHelper.mapToPCData(custodianValue)); custodianValue = mapToTranslatedValue("CUS108"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().addNewCountry(); - clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getCountryArray(k).set(cdaMapHelper.mapToCData(custodianValue)); + clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getAddr().getCountryArray(k).set(cdaMapHelper.mapToPCData(custodianValue)); custodianValue = mapToTranslatedValue("CUS109"); clinicalDocument.getCustodian().getAssignedCustodian().getRepresentedCustodianOrganization().getTelecom().setValue(custodianValue); @@ -277,7 +277,7 @@ private void mapAuthor(POCDMT000040ClinicalDocument1 clinicalDocument) throws Ec clinicalDocument.getAuthorArray(0).getAssignedAuthor().addNewAssignedPerson().addNewName(); clinicalDocument.getAuthorArray(0).getAssignedAuthor().getAssignedPerson().getNameArray(0).addNewFamily(); value = mapToTranslatedValue("AUT102"); - clinicalDocument.getAuthorArray(0).getAssignedAuthor().getAssignedPerson().getNameArray(0).getFamilyArray(0).set(cdaMapHelper.mapToCData(value)); + clinicalDocument.getAuthorArray(0).getAssignedAuthor().getAssignedPerson().getNameArray(0).getFamilyArray(0).set(cdaMapHelper.mapToPCData(value)); OffsetDateTime now = OffsetDateTime.now(); String formattedDateTime = formatDateTime(now); @@ -292,21 +292,15 @@ private static String formatDateTime(OffsetDateTime dateTime) { private String convertXmlToString(ClinicalDocumentDocument1 clinicalDocument) { XmlOptions options = new XmlOptions(); - options.setSavePrettyPrint(); - options.setSavePrettyPrintIndent(4); // Set indentation // Use a default namespace instead of a prefixed one (like urn:) options.setUseDefaultNamespace(); - // Set to always use full tags instead of self-closing tags - options.setSaveNoXmlDecl(); - options.setSaveOuter(); - String xmlOutput = clinicalDocument.xmlText(options); xmlOutput = xmlOutput.replaceAll("]*>([^<]+)", "$1");// NOSONAR // remove string tag - xmlOutput = xmlOutput.replaceAll("]*>(.*?)", "$1");// NOSONAR // replace CDATA with real CDATA + xmlOutput = xmlOutput.replaceAll("\\[CDATA\\](.*?)\\[CDATA\\]", "");// NOSONAR // replace CDATA with real CDATA + xmlOutput = xmlOutput.replaceAll("]*>(.*?)", "");// NOSONAR // replace CDATA with real CDATA xmlOutput = xmlOutput.replaceAll("<(\\w+)>", "");// NOSONAR // remove empty - xmlOutput = xmlOutput.replaceAll("<(\\w+)/>", "");// NOSONAR // remove empty xmlOutput = xmlOutput.replaceAll("STUD", "");// NOSONAR // remove STUD tag xmlOutput = xmlOutput.replaceAll("stud", "");// NOSONAR // remove STUD tag xmlOutput = xmlOutput.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");// NOSONAR // remove new line @@ -314,9 +308,18 @@ private String convertXmlToString(ClinicalDocumentDocument1 clinicalDocument) { xmlOutput = xmlOutput.replaceAll("sdtcxmlnamespaceholder=\""+ XML_NAME_SPACE_HOLDER +"\"", "xmlns:sdtcxmlnamespaceholder=\""+XML_NAME_SPACE_HOLDER+"\"");// NOSONAR xmlOutput = xmlOutput.replaceAll("sdt=\"urn:hl7-org:sdtc\"", "xmlns:sdt=\"urn:hl7-org:sdtc\"");// NOSONAR xmlOutput = xmlOutput.replaceAll("xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xmlns:xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xmlns:xmlns", "xmlns");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xmlns:urn=\"urn:hl7-org:v3\"", "");// NOSONAR + xmlOutput = xmlOutput.replaceAll("schemaLocation=\""+ XML_NAME_SPACE_HOLDER +" CDA_SDTC.xsd\"", "xsi:schemaLocation=\""+XML_NAME_SPACE_HOLDER +" CDA_SDTC.xsd\"");// NOSONAR xmlOutput = xmlOutput.replaceAll("
", "
");// NOSONAR - + xmlOutput = xmlOutput.replaceAll("", "");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xmlns=\"\"", "");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xsi:type=\"urn:CE\"", "xsi:type=\"CE\"");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xsi:type=\"urn:ST\"", "xsi:type=\"ST\"");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xsi:type=\"urn:II\"", "xsi:type=\"II\"");// NOSONAR + xmlOutput = xmlOutput.replaceAll("xsi:type=\"urn:TS\"", "xsi:type=\"TS\"");// NOSONAR xmlOutput = xmlOutput.replaceAll("\\^NOT_MAPPED", "");// NOSONAR xmlOutput = xmlOutput.replaceAll("NOT_MAPPED","");// NOSONAR diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaCaseMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaCaseMappingHelper.java index 9f7896d16..05626b7cb 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaCaseMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaCaseMappingHelper.java @@ -13,9 +13,7 @@ import gov.cdc.dataingestion.nbs.repository.model.dto.EcrMsgCaseParticipantDto; import gov.cdc.dataingestion.nbs.repository.model.dto.lookup.PhdcQuestionLookUpDto; import gov.cdc.nedss.phdc.cda.*; -import org.apache.xmlbeans.XmlCursor; -import javax.xml.namespace.QName; import java.util.List; import java.util.Map; @@ -55,7 +53,7 @@ public CdaCaseMapper mapToCaseTop(EcrSelectedRecord input, POCDMT000040ClinicalD clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getCode().setCodeSystem(CODE_SYSTEM); clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getCode().setCodeSystemName(CODE_SYSTEM_NAME); clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getCode().setDisplayName("Clinical Information"); - clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle().set(cdaMapHelper.mapToStringData("CLINICAL INFORMATION")); + clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle().set(cdaMapHelper.mapToPCData("CLINICAL INFORMATION")); componentCounter = c; @@ -528,12 +526,11 @@ private void setMessageAnswerDate(String name, EcrMsgCaseAnswerDto in, POCDMT000 var element = out.getSection().getEntryArray(counter).getObservation().getValueArray(0); - XmlCursor cursor = element.newCursor(); - cursor.toFirstAttribute(); - cursor.insertAttributeWithValue(new QName(NAME_SPACE_URL, "type"), "TS"); + TS ts = TS.Factory.newInstance(); + var ot = cdaMapHelper.mapToTsType(in.getAnswerTxt()).toString(); - cursor.insertAttributeWithValue("value", ot); - cursor.dispose(); + ts.setValue(ot); + element.set(ts); } } @@ -618,7 +615,7 @@ private MultiSelect mapToMultiSelect(EcrMsgCaseAnswerDto in, out.getCode().setCodeSystem(CLINICAL_CODE_SYSTEM); out.getCode().setCodeSystemName(CLINICAL_CODE_SYSTEM_NAME); out.getCode().setDisplayName("Generic Repeating Questions Section"); - out.getTitle().set(cdaMapHelper.mapToStringData("REPEATING QUESTIONS")); + out.getTitle().set(cdaMapHelper.mapToPCData("REPEATING QUESTIONS")); int componentCounter = 0; String dataType="DATE"; int questionGroupSeqNbr = 0; diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaInterviewMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaInterviewMappingHelper.java index 7898d2485..cb9cd0851 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaInterviewMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaInterviewMappingHelper.java @@ -47,7 +47,7 @@ public CdaInterviewMapper mapToInterviewTop(EcrSelectedRecord input, POCDMT00004 if (clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle() == null) { clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().addNewTitle(); } - clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle().set(cdaMapHelper.mapToStringData("INTERVIEW SECTION")); + clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle().set(cdaMapHelper.mapToPCData("INTERVIEW SECTION")); } POCDMT000040Component3 ot = clinicalDocument.getComponent().getStructuredBody().getComponentArray(c); @@ -818,7 +818,7 @@ private void mapToInterviewObservationFieldP2Date(String name, if(name.equals(COL_ANS_TXT) && !in.getAnswerTxt().isEmpty()){ var element = out.getEntryRelationshipArray(counter).getObservation().getValueArray(0); XmlCursor cursor = element.newCursor(); - cursor.setAttributeText(new QName(NAME_SPACE_URL, "type"), "TS"); + cursor.setAttributeText(new QName(NAME_SPACE_URL, "xsi:type"), "TS"); cursor.setAttributeText(new QName("name"), value); // This is an assumption based on the original code if(!in.getAnswerTxt().isEmpty()){ diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaMapHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaMapHelper.java index 4149d3b64..b193a66e5 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaMapHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaMapHelper.java @@ -59,7 +59,7 @@ public OrgPlaceDocCommonField mapOrgPlaceDocCommonField(POCDMT000040Section clin clinicalDocument.getCode().setCodeSystem(CLINICAL_CODE_SYSTEM); clinicalDocument.getCode().setCodeSystemName(CLINICAL_CODE_SYSTEM_NAME); clinicalDocument.getCode().setDisplayName(CODE_DISPLAY_NAME); - clinicalDocument.getTitle().set(mapToStringData(CLINICAL_TITLE)); + clinicalDocument.getTitle().set(mapToPCData(CLINICAL_TITLE)); } var model = mapActParticipantArray(clinicalDocument); @@ -76,13 +76,27 @@ public OrgPlaceDocCommonField mapOrgPlaceDocCommonField(POCDMT000040Section clin public XmlObject mapToCData(String data) throws EcrCdaXmlException { try { - return XmlObject.Factory.parse(""+data+""); + String escapedString = data.replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """) + .replace("'", "'"); + + return XmlObject.Factory.parse(""+escapedString+""); } catch (Exception e) { throw new EcrCdaXmlException(e.getMessage()); } } + public XmlObject mapToPCData(String data) throws EcrCdaXmlException { + try { + return XmlObject.Factory.parse(""+data+""); + } catch (Exception e) { + throw new EcrCdaXmlException(e.getMessage()); + } + } + public ActParticipantArray mapActParticipantArray(POCDMT000040Section section) { int c; if ( section.getEntryArray().length == 0) { @@ -161,16 +175,6 @@ public MapStructure mapToStructureBodyCheck(POCDMT000040ClinicalDocument1 clinic return mapStruct; } - - public XmlObject mapToStringData(String data) throws EcrCdaXmlException { - try { - return XmlObject.Factory.parse(""+data+""); - } catch (Exception e) { - throw new EcrCdaXmlException(e.getMessage()); - } - - } - public XmlObject mapToUsableTSElement(String data, XmlObject output, String name) throws EcrCdaXmlException { XmlCursor cursor = output.newCursor(); cursor.toFirstChild(); // Move to the root element @@ -345,19 +349,24 @@ public PhdcAnswerDao mapToCodedAnswer(String data, String questionCode) throws E public POCDMT000040CustodianOrganization mapToElementValue(String data, POCDMT000040CustodianOrganization output, String name) { XmlCursor cursor = output.newCursor(); - cursor.toFirstChild(); + + // Counter is set to 4 here to move it to the next element of id as the batch requires + // name to be the second element in the representedCustodianOrganization section + int counter = 4; + while (counter > 0) { + cursor.toNextToken(); + counter--; + } cursor.beginElement(name, XML_NAME_SPACE_HOLDER); cursor.insertChars(data); cursor.dispose(); - return output; } - //TODO: Check if we need to fix the Zulu time zone public String getCurrentUtcDateTimeInCdaFormat() { ZonedDateTime utcNow = ZonedDateTime.now(ZoneId.of("UTC")); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssX"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); return utcNow.format(formatter); } @@ -459,16 +468,12 @@ private void mapToObservationDataTypeNotCoded(PhdcQuestionLookUpDto result, observation.addNewCode(); } - ANY any = ANY.Factory.parse(VALUE_TAG); - XmlCursor cursor = any.newCursor(); - cursor.toFirstAttribute(); - cursor.toNextToken(); - cursor.insertAttributeWithValue("type", "II"); + II id = II.Factory.newInstance(); + var val = ecrLookUpService.fetchPhdcQuestionByCriteriaWithColumn("Question_Identifier", defaultQuestionIdentifier); - cursor.insertAttributeWithValue("root", val.getQuesCodeSystemCd()); - cursor.insertAttributeWithValue("extension", data); - cursor.dispose(); - observation.setValueArray(0, any); // THIS + id.setRoot(val.getQuesCodeSystemCd()); + id.setExtension(data); + observation.setValueArray(0, id); // THIS } else if (result.getDataType().equalsIgnoreCase("DATE")) { var ts = mapToTsType(data); @@ -478,14 +483,12 @@ else if (result.getDataType().equalsIgnoreCase("DATE")) { else { observation.addNewValue(); - ANY any = ANY.Factory.parse(VALUE_TAG); - XmlCursor cursor = any.newCursor(); - cursor.toFirstAttribute(); + ST st = ST.Factory.newInstance(); + XmlCursor cursor = st.newCursor(); cursor.toNextToken(); - cursor.insertAttributeWithValue("type", "ST"); - cursor.insertChars(data); + cursor.insertChars(CDATA + data + CDATA); cursor.dispose(); - observation.setValueArray(0, any); + observation.setValueArray(0, st); } } catch (Exception e) { @@ -572,9 +575,9 @@ public XmlObject mapToSTValue(String input, XmlObject output) { XmlCursor cursor = output.newCursor(); if (cursor.toChild(new QName(VALUE_NAME))) { - cursor.insertAttributeWithValue("type", "ST"); + cursor.setAttributeText(new QName(NAME_SPACE_URL, "type"), "ST"); cursor.toNextToken(); - cursor.insertChars(input); + cursor.insertChars(CDATA + input + CDATA); } cursor.dispose(); @@ -582,14 +585,19 @@ public XmlObject mapToSTValue(String input, XmlObject output) { } public XmlObject mapToObservationPlace(String in, XmlObject out) { - XmlCursor cursor = out.newCursor(); - cursor.toFirstChild(); - cursor.setAttributeText(new QName(NAME_SPACE_URL, "type"), "II"); - cursor.setAttributeText(new QName("", "root"), "2.3.3.3.322.23.34"); - cursor.setAttributeText(new QName("", "extension"), in); - cursor.dispose(); - return out; + II id = II.Factory.newInstance(); + id.setRoot("2.3.3.3.322.23.34"); + id.setExtension(in); + +// XmlCursor cursor = out.newCursor(); +// cursor.toFirstChild(); +// cursor.setAttributeText(new QName(NAME_SPACE_URL, "xsi:type"), "II"); +// cursor.setAttributeText(new QName("", "root"), "2.3.3.3.322.23.34"); +// cursor.setAttributeText(new QName("", "extension"), in); +// cursor.dispose(); + + return id; } public POCDMT000040Participant2 mapToPSN(EcrMsgProviderDto in, POCDMT000040Participant2 out) @@ -859,10 +867,11 @@ private void mapToPSNAddress1(String address1, POCDMT000040Participant2 out) th private void mapToPSNSuffix(String suffix, POCDMT000040Participant2 out) throws EcrCdaXmlException { if (out.getParticipantRole() == null) { out.addNewParticipantRole().addNewPlayingEntity().addNewName(); - } else { - out.getParticipantRole().addNewPlayingEntity().addNewName(); } - var mapVal = mapToCData(suffix); +// else { +// out.getParticipantRole().addNewPlayingEntity().addNewName(); +// } + var mapVal = mapToPCData(suffix); EnSuffix enG = EnSuffix.Factory.newInstance(); enG.set(mapVal); out.getParticipantRole().getPlayingEntity().getNameArray(0).addNewSuffix(); @@ -875,10 +884,11 @@ private void mapToPSNSuffix(String suffix, POCDMT000040Participant2 out) throws private void mapToPSNPrefix(String prefix, POCDMT000040Participant2 out) throws EcrCdaXmlException { if (out.getParticipantRole() == null) { out.addNewParticipantRole().addNewPlayingEntity().addNewName(); - } else { - out.getParticipantRole().addNewPlayingEntity().addNewName(); } - var mapVal = mapToCData(prefix); +// else { +// out.getParticipantRole().addNewPlayingEntity().addNewName(); +// } + var mapVal = mapToPCData(prefix); EnPrefix enG = EnPrefix.Factory.newInstance(); enG.set(mapVal); out.getParticipantRole().getPlayingEntity().getNameArray(0).addNewPrefix(); @@ -904,9 +914,10 @@ private void mapToPSNFirstName(String firstName, POCDMT000040Participant2 out) private void mapToPSNLastName(String lastName, POCDMT000040Participant2 out) throws EcrCdaXmlException { if (out.getParticipantRole() == null) { out.addNewParticipantRole().addNewPlayingEntity().addNewName(); - } else { - out.getParticipantRole().addNewPlayingEntity().addNewName(); } +// else { +// out.getParticipantRole().addNewPlayingEntity().addNewName(); +// } var mapVal = mapToCData(lastName); EnFamily enG = EnFamily.Factory.newInstance(); enG.set(mapVal); diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPatientMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPatientMappingHelper.java index 8a46423ce..4bb26552e 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPatientMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPatientMappingHelper.java @@ -294,7 +294,7 @@ else if(field.getName().equals("patBirthCountryCd") && patient.getPatBirthCountr AdxpCounty county = AdxpCounty.Factory.newInstance(); XmlCursor cursor = county.newCursor(); - cursor.setTextValue(CDATA + val + CDATA); + cursor.setTextValue("" + val + ""); cursor.dispose(); AdxpCounty[] countyArr = {county}; @@ -1032,7 +1032,6 @@ private POCDMT000040Component3 mapToPatientNested(int counter, String colName, S component3.getSection().getEntryArray(counter).setObservation(observation); return component3; } - private boolean isFieldValid(String fieldValue) { return fieldValue != null && !fieldValue.isEmpty(); } diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPlaceMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPlaceMappingHelper.java index aa95a2481..af714c57b 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPlaceMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaPlaceMappingHelper.java @@ -352,7 +352,7 @@ private void mapToPlaceFieldCheckP2Census(String censusTract,POCDMT000040Partici out.getParticipantRole().getAddrArray(0).addNewCensusTract(); out.getParticipantRole().getAddrArray(0).setCensusTractArray(0, AdxpCensusTract.Factory.newInstance()); - out.getParticipantRole().getAddrArray(0).getCensusTractArray(0).set(cdaMapHelper.mapToCData(censusTract)); + out.getParticipantRole().getAddrArray(0).getCensusTractArray(0).set(cdaMapHelper.mapToPCData(censusTract)); } private void mapToPlaceFieldCheckP2Country(String country,POCDMT000040Participant2 out ) throws EcrCdaXmlException { @@ -378,7 +378,7 @@ private void mapToPlaceFieldCheckP2Zip(String zip,POCDMT000040Participant2 out ) out.getParticipantRole().getAddrArray(0).addNewPostalCode(); out.getParticipantRole().getAddrArray(0).setPostalCodeArray(0, AdxpPostalCode.Factory.newInstance()); - out.getParticipantRole().getAddrArray(0).getPostalCodeArray(0).set(cdaMapHelper.mapToCData(zip )); + out.getParticipantRole().getAddrArray(0).getPostalCodeArray(0).set(cdaMapHelper.mapToPCData(zip )); } private void mapToPlaceFieldCheckP2County(String county,POCDMT000040Participant2 out ) throws EcrCdaXmlException { diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaProviderMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaProviderMappingHelper.java index aaef0bc08..9752bd7d2 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaProviderMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaProviderMappingHelper.java @@ -98,7 +98,7 @@ private ProviderFieldCheck mapToProviderTopFieldCheck(EcrSelectedRecord input, clinicalDocument.getCode().setCodeSystem(CLINICAL_CODE_SYSTEM); clinicalDocument.getCode().setCodeSystemName(CLINICAL_CODE_SYSTEM_NAME); clinicalDocument.getCode().setDisplayName(CODE_DISPLAY_NAME); - clinicalDocument.getTitle().set(cdaMapHelper.mapToStringData(CLINICAL_TITLE)); + clinicalDocument.getTitle().set(cdaMapHelper.mapToPCData(CLINICAL_TITLE)); } if ( clinicalDocument.getEntryArray().length == 0) { diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaTreatmentMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaTreatmentMappingHelper.java index 19c557866..1fafcd3da 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaTreatmentMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaTreatmentMappingHelper.java @@ -92,7 +92,7 @@ private void mapToTreatmentTopHasNoCounter(POCDMT000040ClinicalDocument1 clinica if (clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle() == null) { clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().addNewTitle(); } - clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle().set(cdaMapHelper.mapToStringData("TREATMENT INFORMATION")); + clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getTitle().set(cdaMapHelper.mapToPCData("TREATMENT INFORMATION")); if (clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().getText() == null) { clinicalDocument.getComponent().getStructuredBody().getComponentArray(c).getSection().addNewText(); diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaXmlAnswerMappingHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaXmlAnswerMappingHelper.java index 2abfcbb0e..d9e4cd228 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaXmlAnswerMappingHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/CdaXmlAnswerMappingHelper.java @@ -7,15 +7,12 @@ import gov.cdc.dataingestion.nbs.repository.model.dto.EcrMsgXmlAnswerDto; import gov.cdc.nedss.phdc.cda.POCDMT000040ClinicalDocument1; import gov.cdc.nedss.phdc.cda.POCDMT000040Component3; +import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; -import org.w3c.dom.Document; +import org.apache.xmlbeans.XmlOptions; import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; public class CdaXmlAnswerMappingHelper implements ICdaXmlAnswerMappingHelper { public CdaXmlAnswerMapper mapToXmlAnswerTop(EcrSelectedRecord input, @@ -65,12 +62,35 @@ private POCDMT000040Component3 mapToExtendedData(EcrMsgXmlAnswerDto in, POCDMT00 factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputStream is = new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)); - Document document = builder.parse(is); + if(xmlContent.contains("sdt:") && xmlContent.contains("xsi:")) { + String wrappedXmlContent = "" + xmlContent + ""; - XmlObject xmlData = XmlObject.Factory.parse(document.getDocumentElement()); - out.set(xmlData); + XmlOptions options = new XmlOptions(); + options.setCompileNoValidation(); + + XmlObject xmlData = XmlObject.Factory.parse(wrappedXmlContent, options); + XmlObject parsedXmlData = extractSection(xmlData); + out.set(parsedXmlData); + } + else if(xmlContent.contains("sdt:")) { + String wrappedXmlContent = "" + xmlContent + ""; + + XmlOptions options = new XmlOptions(); + options.setCompileNoValidation(); + + XmlObject xmlData = XmlObject.Factory.parse(wrappedXmlContent, options); + XmlObject parsedXmlData = extractSection(xmlData); + out.set(parsedXmlData); + } + else { + String wrappedXmlContent = "" + xmlContent + ""; + XmlOptions options = new XmlOptions(); + options.setCompileNoValidation(); + + XmlObject xmlData = XmlObject.Factory.parse(wrappedXmlContent, options); + XmlObject parsedXmlData = extractSection(xmlData); + out.set(parsedXmlData); + } } return out; } catch (Exception e) { @@ -78,4 +98,20 @@ private POCDMT000040Component3 mapToExtendedData(EcrMsgXmlAnswerDto in, POCDMT00 } } + public XmlObject extractSection(XmlObject xmlObject) { + XmlCursor cursor = xmlObject.newCursor(); + + cursor.toStartDoc(); + cursor.selectPath("./*"); + if (cursor.toFirstChild()) { + cursor.selectPath("./wrapper"); + XmlObject section = cursor.getObject().copy(); + cursor.dispose(); + return section; + } + cursor.dispose(); + return null; + } + } + diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/interfaces/ICdaMapHelper.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/interfaces/ICdaMapHelper.java index e238b5a6b..fb753d9b8 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/interfaces/ICdaMapHelper.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/ecr/service/helper/interfaces/ICdaMapHelper.java @@ -23,7 +23,6 @@ OrgPlaceDocCommonField mapOrgPlaceDocCommonField(POCDMT000040Section clinicalDoc int performerComponentCounter) throws EcrCdaXmlException; ActParticipantArray mapActParticipantArray(POCDMT000040Section section); XmlObject mapToCData(String data) throws EcrCdaXmlException; - XmlObject mapToStringData(String data) throws EcrCdaXmlException; XmlObject mapToUsableTSElement(String data, XmlObject output, String name) throws EcrCdaXmlException; TS mapToTsType(String data) throws EcrCdaXmlException; String mapToQuestionId(String data) throws EcrCdaXmlException; @@ -53,4 +52,6 @@ POCDMT000040Participant2 mapToORG(EcrMsgOrganizationDto in, MapStructure mapToStructureBodyCheck(POCDMT000040ClinicalDocument1 clinicalDocument); MapParticipantRole mapToParticipantRoleCheck(POCDMT000040SubstanceAdministration output); ANY mapMultiSelectDateMapXmlElement(ANY element, String value, EcrMsgCaseAnswerDto in) throws EcrCdaXmlException; + + XmlObject mapToPCData(String data) throws EcrCdaXmlException; } diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/repository/model/NbsInterfaceModel.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/repository/model/NbsInterfaceModel.java index f35200f12..438a8a662 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/repository/model/NbsInterfaceModel.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/repository/model/NbsInterfaceModel.java @@ -20,7 +20,7 @@ public class NbsInterfaceModel { @Column(name="nbs_interface_uid") private Integer nbsInterfaceUid; - @Column(name = "payload", length = 2048, nullable = false) + @Column(name = "payload", length = 2048, nullable = true) private String payload; @Column(name = "imp_exp_ind_cd", length = 8, nullable = true) @@ -62,10 +62,10 @@ public class NbsInterfaceModel { @Column(name = "OBSERVATION_UID") private Integer observationUid; - @Column(name = "original_payload_RR") + @Column(name = "original_payload_RR", length = 1024, nullable = true) private String originalPayloadRR; - @Column(name = "original_doc_type_cd_RR") + @Column(name = "original_doc_type_cd_RR", length = 100, nullable = true) private String originalDocTypeCdRR; @Override diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/EcrMsgQueryService.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/EcrMsgQueryService.java index 2be5de31f..4c84196d9 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/EcrMsgQueryService.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/EcrMsgQueryService.java @@ -31,7 +31,7 @@ public EcrSelectedRecord getSelectedEcrRecord() throws EcrCdaXmlException { selectedRecord = new EcrSelectedRecord(); // Commented out for testing right now and will need to be uncommented during the unit tests stage - // this.ecrMsgQueryRepository.updateMatchEcrRecordForProcessing(msgContainer.getMsgContainerUid()); //NOSONAR + this.ecrMsgQueryRepository.updateMatchEcrRecordForProcessing(msgContainer.getMsgContainerUid()); //NOSONAR List msgPatients = this.ecrMsgQueryRepository.fetchMsgPatientForApplicableEcr(msgContainer.getMsgContainerUid()); diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/NbsRepositoryServiceProvider.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/NbsRepositoryServiceProvider.java index 80e3befa2..23073674e 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/NbsRepositoryServiceProvider.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/nbs/services/NbsRepositoryServiceProvider.java @@ -37,11 +37,12 @@ public class NbsRepositoryServiceProvider { public void saveEcrCdaXmlMessage (String nbsInterfaceUid, Integer dataMigrationStatus, String xmlMsg) { - Optional response = nbsInterfaceRepo.getNbsInterfaceByIdAndDocType(Integer.valueOf(nbsInterfaceUid), ECR_DOC_TYPE); + Optional response = nbsInterfaceRepo.getNbsInterfaceByIdAndDocType(Integer.valueOf(nbsInterfaceUid), ECR_DOC_TYPE); var time = getCurrentTimeStamp(); NbsInterfaceModel model = new NbsInterfaceModel(); if (response.isPresent()) { model = response.get(); + model.setRecordStatusCd(STATUS_UNPROCESSED); model.setRecordStatusTime(time); model.setPayload(xmlMsg); nbsInterfaceRepo.save(model); diff --git a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsController.java b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsController.java index acc165ad8..645a95aa0 100644 --- a/data-ingestion-service/src/main/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsController.java +++ b/data-ingestion-service/src/main/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsController.java @@ -50,7 +50,7 @@ public EcrReportsController(NbsRepositoryServiceProvider nbsRepositoryServicePro public ResponseEntity saveIncomingEcr(@RequestBody final String payload, @RequestHeader("systemNm") String systemNm, @RequestHeader("origDocTypeEicr") String origDocTypeEicr, - @RequestHeader("origDocTypeRR, required = false") String origDocTypeRR) { + @RequestHeader(value = "origDocTypeRR", required = false) String origDocTypeRR) { try { String eicrXml = extractXmlContent(payload, "", ""); String rrXml = extractXmlContent(payload, "", ""); @@ -70,9 +70,9 @@ public ResponseEntity saveIncomingEcr(@RequestBody final String payload private String extractXmlContent(String textInput, String startTag, String endTag) { int startIndex = textInput.indexOf(startTag) + startTag.length(); - int endIndex = textInput.indexOf(endTag); + int endIndex = textInput.indexOf(endTag, startIndex); if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex) { - throw new IllegalArgumentException("XML tags not found or malformed input"); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Malformed XML content: missing or incorrect tags"); } return textInput.substring(startIndex, endIndex).trim(); } diff --git a/data-ingestion-service/src/test/java/gov/cdc/dataingestion/ecr/service/EcrMessagePollServiceTest.java b/data-ingestion-service/src/test/java/gov/cdc/dataingestion/ecr/service/EcrMessagePollServiceTest.java new file mode 100644 index 000000000..0009a8fc5 --- /dev/null +++ b/data-ingestion-service/src/test/java/gov/cdc/dataingestion/ecr/service/EcrMessagePollServiceTest.java @@ -0,0 +1,77 @@ +package gov.cdc.dataingestion.ecr.service; + +import gov.cdc.dataingestion.exception.EcrCdaXmlException; +import gov.cdc.dataingestion.nbs.ecr.service.EcrMessagePollService; +import gov.cdc.dataingestion.nbs.ecr.service.interfaces.ICdaMapper; +import gov.cdc.dataingestion.nbs.repository.model.dao.EcrSelectedRecord; +import gov.cdc.dataingestion.nbs.repository.model.dto.EcrMsgContainerDto; +import gov.cdc.dataingestion.nbs.services.EcrMsgQueryService; +import gov.cdc.dataingestion.nbs.services.NbsRepositoryServiceProvider; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + +class EcrMessagePollServiceTest { + + @Mock + private EcrMsgQueryService ecrMsgQueryService; + + @Mock + private ICdaMapper cdaMapper; + + @Mock + private NbsRepositoryServiceProvider nbsRepositoryServiceProvider; + + @Mock + EcrMsgContainerDto ecrMsgContainerDto = mock(EcrMsgContainerDto.class); + + @InjectMocks + private EcrMessagePollService ecrMessagePollService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void fetchMessageContainerData_WithValidResult_ShouldProcessAndSave() throws EcrCdaXmlException { + EcrSelectedRecord mockRecord = mock(EcrSelectedRecord.class); + when(mockRecord.getMsgContainer()).thenReturn(ecrMsgContainerDto); + when(mockRecord.getMsgContainer().getNbsInterfaceUid()).thenReturn(123456); + when(mockRecord.getMsgContainer().getDataMigrationStatus()).thenReturn(-2); + when(ecrMsgQueryService.getSelectedEcrRecord()).thenReturn(mockRecord); + when(cdaMapper.tranformSelectedEcrToCDAXml(mockRecord)).thenReturn("result"); + + ecrMessagePollService.fetchMessageContainerData(); + + verify(nbsRepositoryServiceProvider, times(1)) + .saveEcrCdaXmlMessage("123456", -2, "result"); + } + + @Test + void fetchMessageContainerData_WithNullResult_ShouldNotProcess() throws EcrCdaXmlException { + when(ecrMsgQueryService.getSelectedEcrRecord()).thenReturn(null); + + ecrMessagePollService.fetchMessageContainerData(); + + verify(cdaMapper, never()).tranformSelectedEcrToCDAXml(any()); + verify(nbsRepositoryServiceProvider, never()).saveEcrCdaXmlMessage(anyString(), anyInt(), anyString()); + } + + @Test + void fetchMessageContainerData_WithEcrCdaXmlException_ShouldThrow() throws EcrCdaXmlException { + EcrSelectedRecord mockRecord = mock(EcrSelectedRecord.class); + when(mockRecord.getMsgContainer()).thenReturn(ecrMsgContainerDto); + when(mockRecord.getMsgContainer().getNbsInterfaceUid()).thenReturn(123456); + when(mockRecord.getMsgContainer().getDataMigrationStatus()).thenReturn(-2); + when(ecrMsgQueryService.getSelectedEcrRecord()).thenReturn(mockRecord); + when(cdaMapper.tranformSelectedEcrToCDAXml(mockRecord)).thenThrow(new EcrCdaXmlException("Error during transformation")); + + assertThrows(EcrCdaXmlException.class, () -> ecrMessagePollService.fetchMessageContainerData()); + } +} diff --git a/data-ingestion-service/src/test/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsControllerTest.java b/data-ingestion-service/src/test/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsControllerTest.java index 25ca49ee2..31500593a 100644 --- a/data-ingestion-service/src/test/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsControllerTest.java +++ b/data-ingestion-service/src/test/java/gov/cdc/dataingestion/rawmessage/controller/EcrReportsControllerTest.java @@ -1,11 +1,6 @@ package gov.cdc.dataingestion.rawmessage.controller; -import gov.cdc.dataingestion.nbs.ecr.service.CdaMapper; -import gov.cdc.dataingestion.nbs.repository.model.dao.EcrSelectedCase; -import gov.cdc.dataingestion.nbs.repository.model.dao.EcrSelectedRecord; -import gov.cdc.dataingestion.nbs.repository.model.dto.EcrMsgContainerDto; -import gov.cdc.dataingestion.nbs.repository.model.dto.EcrMsgPatientDto; -import gov.cdc.dataingestion.nbs.services.EcrMsgQueryService; +import gov.cdc.dataingestion.nbs.repository.model.NbsInterfaceModel; import gov.cdc.dataingestion.nbs.services.NbsRepositoryServiceProvider; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,10 +13,8 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.util.Collections; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; @WebMvcTest(EcrReportsController.class) @ActiveProfiles("test") @@ -31,61 +24,64 @@ class EcrReportsControllerTest { private MockMvc mockMvc; @MockBean - private EcrMsgQueryService ecrMsgQueryService; + private NbsRepositoryServiceProvider nbsRepositoryServiceProvider; - @MockBean - private CdaMapper cdaMapper; + @Test + void testSaveIncomingEcr_WithRR() throws Exception { + String payload = "eicrContentrrContent"; + NbsInterfaceModel mockModel = new NbsInterfaceModel(); + mockModel.setNbsInterfaceUid(123456); - @MockBean - private NbsRepositoryServiceProvider nbsRepositoryServiceProvider; + when(nbsRepositoryServiceProvider.saveIncomingEcrMessageWithRR(anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(mockModel); + + mockMvc.perform(MockMvcRequestBuilders.post("/api/ecrs") + .contentType(MediaType.TEXT_PLAIN) + .content(payload) + .header("systemNm", "testSystem") + .header("origDocTypeEicr", "EICR") + .header("origDocTypeRR", "RR") + .with(SecurityMockMvcRequestPostProcessors.jwt())) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("123456")); + + verify(nbsRepositoryServiceProvider).saveIncomingEcrMessageWithRR("eicrContent", "testSystem", "EICR", "rrContent", "RR"); + } @Test - void testSaveEcrMessagePHC236() throws Exception { - String documentTypeCode = "PHC236"; - String payload = "dummyPayload"; - - EcrSelectedRecord resultDto = new EcrSelectedRecord(); - EcrMsgContainerDto ecrMsgContainerDto = new EcrMsgContainerDto(); - ecrMsgContainerDto.setMsgContainerUid(1); - ecrMsgContainerDto.setNbsInterfaceUid(1234); - resultDto.setMsgContainer(ecrMsgContainerDto); - resultDto.setMsgCases(Collections.singletonList(new EcrSelectedCase())); - resultDto.setMsgPatients(Collections.singletonList(new EcrMsgPatientDto())); - - when(ecrMsgQueryService.getSelectedEcrRecord()).thenReturn(resultDto); - when(cdaMapper.tranformSelectedEcrToCDAXml(resultDto)).thenReturn("transformedXml"); - - mockMvc.perform(MockMvcRequestBuilders.post("/api/ecrs/{document-type-code}", documentTypeCode) + void testSaveIncomingEcr_WithoutRR() throws Exception { + String payload = "eicrContentnull"; + NbsInterfaceModel mockModel = new NbsInterfaceModel(); + mockModel.setNbsInterfaceUid(123456); + + when(nbsRepositoryServiceProvider.saveIncomingEcrMessageWithoutRR(anyString(), anyString(), anyString())) + .thenReturn(mockModel); + + mockMvc.perform(MockMvcRequestBuilders.post("/api/ecrs") .contentType(MediaType.TEXT_PLAIN) .content(payload) + .header("systemNm", "testSystem") + .header("origDocTypeEicr", "EICR") .with(SecurityMockMvcRequestPostProcessors.jwt())) .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string("transformedXml")); + .andExpect(MockMvcResultMatchers.content().string("123456")); - verify(ecrMsgQueryService).getSelectedEcrRecord(); - verify(cdaMapper).tranformSelectedEcrToCDAXml(resultDto); + verify(nbsRepositoryServiceProvider).saveIncomingEcrMessageWithoutRR("eicrContent", "testSystem", "EICR"); } @Test - void testSaveEcrMessageNonPHC236() throws Exception { - String documentTypeCode = "notPHC236"; - String payload = "dummyPayload"; - - EcrSelectedRecord resultDto = new EcrSelectedRecord(); - EcrMsgContainerDto ecrMsgContainerDto = new EcrMsgContainerDto(); - ecrMsgContainerDto.setMsgContainerUid(1); - ecrMsgContainerDto.setNbsInterfaceUid(1234); - resultDto.setMsgContainer(ecrMsgContainerDto); - resultDto.setMsgCases(Collections.singletonList(new EcrSelectedCase())); - resultDto.setMsgPatients(Collections.singletonList(new EcrMsgPatientDto())); - - when(ecrMsgQueryService.getSelectedEcrRecord()).thenReturn(resultDto); - when(cdaMapper.tranformSelectedEcrToCDAXml(resultDto)).thenReturn("transformedXml"); - - mockMvc.perform(MockMvcRequestBuilders.post("/api/ecrs/{document-type-code}", documentTypeCode) + void testSaveIncomingEcr_WithMalformedXml_ShouldReturnInternalServerError() throws Exception { + String payload = "invalidXmlContent"; + + mockMvc.perform(MockMvcRequestBuilders.post("/api/ecrs") .contentType(MediaType.TEXT_PLAIN) .content(payload) + .header("systemNm", "testSystem") + .header("origDocTypeEicr", "EICR") .with(SecurityMockMvcRequestPostProcessors.jwt())) .andExpect(MockMvcResultMatchers.status().isInternalServerError()); + + verify(nbsRepositoryServiceProvider, never()).saveIncomingEcrMessageWithRR(anyString(), anyString(), anyString(), anyString(), anyString()); + verify(nbsRepositoryServiceProvider, never()).saveIncomingEcrMessageWithoutRR(anyString(), anyString(), anyString()); } -} \ No newline at end of file +}