From 0479a48a416ef18fb5a7f1c3faf368fc1f5b3e12 Mon Sep 17 00:00:00 2001 From: jamesagnew Date: Fri, 12 Jun 2015 08:27:03 -0400 Subject: [PATCH] Correctly handle Bundle.entry.base --- .../java/ca/uhn/fhir/parser/BaseParser.java | 14 +- .../java/ca/uhn/fhir/parser/ParserState.java | 28 +- .../uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java | 3 +- .../fhir/jpa/dao/FhirSystemDaoDstu2Test.java | 672 +++--- .../uhn/fhir/parser/XmlParserDstu2Test.java | 1960 +++++++++-------- src/changes/changes.xml | 5 + 6 files changed, 1421 insertions(+), 1261 deletions(-) diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java index 43697b77e55..53c993899fe 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java @@ -328,7 +328,19 @@ public abstract class BaseParser implements IParser { versionIdPart = ResourceMetadataKeyEnum.VERSION.get((IResource) res); } - res.setId(new IdDt(baseType.getValueAsString(), resDef.getName(), res.getIdElement().getIdPart(), versionIdPart)); + String baseUrl = baseType.getValueAsString(); + String idPart = res.getIdElement().getIdPart(); + + String resourceName = resDef.getName(); + if (!baseUrl.startsWith("cid:") && !baseUrl.startsWith("urn:")) { + res.setId(new IdDt(baseUrl, resourceName, idPart, versionIdPart)); + } else { + if (baseUrl.endsWith(":")) { + res.setId(new IdDt(baseUrl + idPart)); + } else { + res.setId(new IdDt(baseUrl + ':' + idPart)); + } + } } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java index ee8822253a2..3f41442f169 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java @@ -1059,8 +1059,6 @@ class ParserState { } else { throw new DataFormatException("Unexpected element in entry: " + theLocalPart); } - - // TODO: handle category } protected BundleEntry getEntry() { @@ -1317,10 +1315,20 @@ class ParserState { String resourceName = myContext.getResourceDefinition(nextResource).getName(); String bundleIdPart = nextResource.getId().getIdPart(); if (isNotBlank(bundleIdPart)) { + String baseUrl; if (isNotBlank(entryBaseUrl)) { - nextResource.setId(new IdDt(entryBaseUrl, resourceName, bundleIdPart, version)); + baseUrl = entryBaseUrl; } else { - nextResource.setId(new IdDt(bundleBaseUrl, resourceName, bundleIdPart, version)); + baseUrl = bundleBaseUrl; + } + if (!baseUrl.startsWith("cid:") && !baseUrl.startsWith("urn:")) { + nextResource.setId(new IdDt(baseUrl, resourceName, bundleIdPart, version)); + } else { + if (baseUrl.endsWith(":")) { + nextResource.setId(new IdDt(baseUrl + bundleIdPart)); + } else { + nextResource.setId(new IdDt(baseUrl + ':' + bundleIdPart)); + } } } } @@ -1535,9 +1543,9 @@ class ParserState { try { child = myDefinition.getChildByNameOrThrowDataFormatException(theChildName); } catch (DataFormatException e) { - /* This means we've found an element that doesn't exist on the structure. - * If the error handler doesn't throw an exception, swallow the element silently along - * with any child elements + /* + * This means we've found an element that doesn't exist on the structure. If the error handler doesn't + * throw an exception, swallow the element silently along with any child elements */ myErrorHandler.unknownElement(null, theChildName); push(new SwallowChildrenWholeState(getPreResourceState())); @@ -2093,7 +2101,7 @@ class ParserState { } } } - }else if (theElement instanceof IBaseReference) { + } else if (theElement instanceof IBaseReference) { IBaseReference nextRef = (IBaseReference) theElement; String ref = nextRef.getReferenceElement().getValue(); if (isNotBlank(ref)) { @@ -2589,7 +2597,7 @@ class ParserState { @Override public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException { - // IGNORE - don't handle this as an error, we process these as XML events + // IGNORE - don't handle this as an error, we process these as XML events } @Override @@ -2598,7 +2606,7 @@ class ParserState { myDt.setValueAsString(theValue); return; } else { - // IGNORE - don't handle this as an error, we process these as XML events + // IGNORE - don't handle this as an error, we process these as XML events } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java index bef3c5027d5..9e2771490d3 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java @@ -25,6 +25,7 @@ import static org.apache.commons.lang3.StringUtils.*; import java.util.Date; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -128,7 +129,7 @@ public class FhirSystemDaoDstu2 extends BaseFhirSystemDao { ourLog.info("Beginning transaction with {} resources", theResources.getEntry().size()); long start = System.currentTimeMillis(); - Set allIds = new HashSet(); + Set allIds = new LinkedHashSet(); Map idSubstitutions = new HashMap(); Map idToPersistedOutcome = new HashMap(); diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2Test.java index 66038650bcb..84c560451ee 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2Test.java @@ -50,9 +50,103 @@ public class FhirSystemDaoDstu2Test { private static ClassPathXmlApplicationContext ourCtx; private static FhirContext ourFhirContext; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirSystemDaoDstu2Test.class); + private static IFhirResourceDao ourObservationDao; private static IFhirResourceDao ourPatientDao; private static IFhirSystemDao ourSystemDao; - private static IFhirResourceDao ourObservationDao; + + private void deleteEverything() { + FhirSystemDaoDstu2Test.doDeleteEverything(ourSystemDao); + } + + @Test + public void testSystemMetaOperation() { + deleteEverything(); + + MetaDt meta = ourSystemDao.metaGetOperation(); + List published = meta.getTag(); + assertEquals(0, published.size()); + + String methodName = "testSystemMetaOperation"; + IdDt id1; + { + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:system").setValue(methodName); + patient.addName().addFamily("Tester").addGiven("Joe"); + TagList tagList = new TagList(); + tagList.addTag(null, "Dog", "Puppies"); + ResourceMetadataKeyEnum.TAG_LIST.put(patient, tagList); + + List securityLabels = new ArrayList(); + securityLabels.add(new CodingDt().setSystem("seclabel:sys:1").setCode("seclabel:code:1").setDisplay("seclabel:dis:1")); + ResourceMetadataKeyEnum.SECURITY_LABELS.put(patient, securityLabels); + + ArrayList profiles = new ArrayList(); + profiles.add(new IdDt("http://profile/1")); + ResourceMetadataKeyEnum.PROFILES.put(patient, profiles); + + id1 = ourPatientDao.create(patient).getId(); + } + { + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:system").setValue(methodName); + patient.addName().addFamily("Tester").addGiven("Joe"); + TagList tagList = new TagList(); + tagList.addTag("http://foo", "Cat", "Kittens"); + ResourceMetadataKeyEnum.TAG_LIST.put(patient, tagList); + + List securityLabels = new ArrayList(); + securityLabels.add(new CodingDt().setSystem("seclabel:sys:2").setCode("seclabel:code:2").setDisplay("seclabel:dis:2")); + ResourceMetadataKeyEnum.SECURITY_LABELS.put(patient, securityLabels); + + ArrayList profiles = new ArrayList(); + profiles.add(new IdDt("http://profile/2")); + ResourceMetadataKeyEnum.PROFILES.put(patient, profiles); + + ourPatientDao.create(patient); + } + + meta = ourSystemDao.metaGetOperation(); + published = meta.getTag(); + assertEquals(2, published.size()); + assertEquals(null, published.get(0).getSystem()); + assertEquals("Dog", published.get(0).getCode()); + assertEquals("Puppies", published.get(0).getDisplay()); + assertEquals("http://foo", published.get(1).getSystem()); + assertEquals("Cat", published.get(1).getCode()); + assertEquals("Kittens", published.get(1).getDisplay()); + List secLabels = meta.getSecurity(); + assertEquals(2, secLabels.size()); + assertEquals("seclabel:sys:1", secLabels.get(0).getSystemElement().getValue()); + assertEquals("seclabel:code:1", secLabels.get(0).getCodeElement().getValue()); + assertEquals("seclabel:dis:1", secLabels.get(0).getDisplayElement().getValue()); + assertEquals("seclabel:sys:2", secLabels.get(1).getSystemElement().getValue()); + assertEquals("seclabel:code:2", secLabels.get(1).getCodeElement().getValue()); + assertEquals("seclabel:dis:2", secLabels.get(1).getDisplayElement().getValue()); + List profiles = meta.getProfile(); + assertEquals(2, profiles.size()); + assertEquals("http://profile/1", profiles.get(0).getValue()); + assertEquals("http://profile/2", profiles.get(1).getValue()); + + ourPatientDao.removeTag(id1, TagTypeEnum.TAG, null, "Dog"); + ourPatientDao.removeTag(id1, TagTypeEnum.SECURITY_LABEL, "seclabel:sys:1", "seclabel:code:1"); + ourPatientDao.removeTag(id1, TagTypeEnum.PROFILE, BaseFhirDao.NS_JPA_PROFILE, "http://profile/1"); + + meta = ourSystemDao.metaGetOperation(); + published = meta.getTag(); + assertEquals(1, published.size()); + assertEquals("http://foo", published.get(0).getSystem()); + assertEquals("Cat", published.get(0).getCode()); + assertEquals("Kittens", published.get(0).getDisplay()); + secLabels = meta.getSecurity(); + assertEquals(1, secLabels.size()); + assertEquals("seclabel:sys:2", secLabels.get(0).getSystemElement().getValue()); + assertEquals("seclabel:code:2", secLabels.get(0).getCodeElement().getValue()); + assertEquals("seclabel:dis:2", secLabels.get(0).getDisplayElement().getValue()); + profiles = meta.getProfile(); + assertEquals(1, profiles.size()); + assertEquals("http://profile/2", profiles.get(0).getValue()); + + } @Test public void testTransactionCreateMatchUrlWithOneMatch() { @@ -96,109 +190,6 @@ public class FhirSystemDaoDstu2Test { } - @Test - public void testTransactionCreateWithInvalidReferenceNumeric() { - String methodName = "testTransactionCreateWithInvalidReferenceNumeric"; - Bundle request = new Bundle(); - - Patient p = new Patient(); - p.addIdentifier().setSystem("urn:system").setValue(methodName); - p.addName().addFamily("Hello"); - p.getManagingOrganization().setReference("Organization/9999999999999999"); - request.addEntry().setResource(p).getTransaction().setMethod(HTTPVerbEnum.POST); - - try { - ourSystemDao.transaction(request); - fail(); - } catch (InvalidRequestException e) { - assertThat(e.getMessage(), containsString("Resource Organization/9999999999999999 not found, specified in path: Patient.managingOrganization")); - } - } - - @Test - public void testTransactionCreateWithInvalidReferenceTextual() { - String methodName = "testTransactionCreateWithInvalidReferenceTextual"; - Bundle request = new Bundle(); - - Patient p = new Patient(); - p.addIdentifier().setSystem("urn:system").setValue(methodName); - p.addName().addFamily("Hello"); - p.getManagingOrganization().setReference("Organization/" + methodName); - request.addEntry().setResource(p).getTransaction().setMethod(HTTPVerbEnum.POST); - - try { - ourSystemDao.transaction(request); - fail(); - } catch (InvalidRequestException e) { - assertThat(e.getMessage(), containsString("Resource Organization/" + methodName + " not found, specified in path: Patient.managingOrganization")); - } - } - - @Test - public void testTransactionFromBundle() throws Exception { - - InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/transaction_link_patient_eve.xml"); - String bundleStr = IOUtils.toString(bundleRes); - Bundle bundle = ourFhirContext.newXmlParser().parseResource(Bundle.class, bundleStr); - - Bundle resp = ourSystemDao.transaction(bundle); - - ourLog.info(ourFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(resp)); - - OperationOutcome oo = (OperationOutcome) resp.getEntry().get(0).getResource(); - assertThat(oo.getIssue().get(0).getDetailsElement().getValue(), containsString("Transaction completed")); - - assertThat(resp.getEntry().get(1).getTransactionResponse().getLocation(), startsWith("Patient/a555-44-4444/_history/")); - assertThat(resp.getEntry().get(2).getTransactionResponse().getLocation(), startsWith("Patient/temp6789/_history/")); - assertThat(resp.getEntry().get(3).getTransactionResponse().getLocation(), startsWith("Organization/GHH/_history/")); - - Patient p = ourPatientDao.read(new IdDt("Patient/a555-44-4444/_history/1")); - assertEquals("Patient/temp6789", p.getLink().get(0).getOther().getReference().getValue()); - } - - @Test - public void testTransactionReadAndSearch() { - String methodName = "testTransactionReadAndSearch"; - - Patient p = new Patient(); - p.addIdentifier().setSystem("urn:system").setValue(methodName); - p.setId("Patient/" + methodName); - IdDt idv1 = ourPatientDao.update(p).getId(); - ourLog.info("Created patient, got id: {}", idv1); - - p = new Patient(); - p.addIdentifier().setSystem("urn:system").setValue(methodName); - p.addName().addFamily("Family Name"); - p.setId("Patient/" + methodName); - IdDt idv2 = ourPatientDao.update(p).getId(); - ourLog.info("Updated patient, got id: {}", idv2); - - Bundle request = new Bundle(); - request.addEntry().getTransaction().setMethod(HTTPVerbEnum.GET).setUrl(idv1.toUnqualifiedVersionless().getValue()); - request.addEntry().getTransaction().setMethod(HTTPVerbEnum.GET).setUrl(idv1.toUnqualified().getValue()); - request.addEntry().getTransaction().setMethod(HTTPVerbEnum.GET).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); - - Bundle resp = ourSystemDao.transaction(request); - - assertEquals(4, resp.getEntry().size()); - - Entry nextEntry; - - nextEntry = resp.getEntry().get(1); - assertEquals(Patient.class, nextEntry.getResource().getClass()); - assertEquals(idv2.toUnqualified(), nextEntry.getResource().getId().toUnqualified()); - - nextEntry = resp.getEntry().get(2); - assertEquals(Patient.class, nextEntry.getResource().getClass()); - assertEquals(idv1.toUnqualified(), nextEntry.getResource().getId().toUnqualified()); - - nextEntry = resp.getEntry().get(3); - assertEquals(Bundle.class, nextEntry.getResource().getClass()); - - Bundle respBundle = (Bundle) nextEntry.getResource(); - assertEquals(1, respBundle.getTotal().intValue()); - } - @Test public void testTransactionCreateMatchUrlWithTwoMatch() { String methodName = "testTransactionCreateMatchUrlWithTwoMatch"; @@ -289,6 +280,89 @@ public class FhirSystemDaoDstu2Test { assertThat(patientId, not(containsString("test"))); } + @Test + public void testTransactionCreateWithInvalidReferenceNumeric() { + String methodName = "testTransactionCreateWithInvalidReferenceNumeric"; + Bundle request = new Bundle(); + + Patient p = new Patient(); + p.addIdentifier().setSystem("urn:system").setValue(methodName); + p.addName().addFamily("Hello"); + p.getManagingOrganization().setReference("Organization/9999999999999999"); + request.addEntry().setResource(p).getTransaction().setMethod(HTTPVerbEnum.POST); + + try { + ourSystemDao.transaction(request); + fail(); + } catch (InvalidRequestException e) { + assertThat(e.getMessage(), containsString("Resource Organization/9999999999999999 not found, specified in path: Patient.managingOrganization")); + } + } + + @Test + public void testTransactionCreateWithInvalidReferenceTextual() { + String methodName = "testTransactionCreateWithInvalidReferenceTextual"; + Bundle request = new Bundle(); + + Patient p = new Patient(); + p.addIdentifier().setSystem("urn:system").setValue(methodName); + p.addName().addFamily("Hello"); + p.getManagingOrganization().setReference("Organization/" + methodName); + request.addEntry().setResource(p).getTransaction().setMethod(HTTPVerbEnum.POST); + + try { + ourSystemDao.transaction(request); + fail(); + } catch (InvalidRequestException e) { + assertThat(e.getMessage(), containsString("Resource Organization/" + methodName + " not found, specified in path: Patient.managingOrganization")); + } + } + + @Test + public void testTransactionDeleteByResourceId() { + String methodName = "testTransactionDeleteByResourceId"; + + Patient p1 = new Patient(); + p1.addIdentifier().setSystem("urn:system").setValue(methodName); + IdDt id1 = ourPatientDao.create(p1).getId(); + ourLog.info("Created patient, got it: {}", id1); + + Patient p2 = new Patient(); + p2.addIdentifier().setSystem("urn:system").setValue(methodName); + p2.setId("Patient/" + methodName); + IdDt id2 = ourPatientDao.update(p2).getId(); + ourLog.info("Created patient, got it: {}", id2); + + Bundle request = new Bundle(); + + request.addEntry().getTransaction().setMethod(HTTPVerbEnum.DELETE).setUrl("Patient/" + id1.getIdPart()); + request.addEntry().getTransaction().setMethod(HTTPVerbEnum.DELETE).setUrl("Patient/" + id2.getIdPart()); + + ourPatientDao.read(id1.toVersionless()); + ourPatientDao.read(id2.toVersionless()); + + Bundle resp = ourSystemDao.transaction(request); + + assertEquals(3, resp.getEntry().size()); + assertEquals("204", resp.getEntry().get(1).getTransactionResponse().getStatus()); + assertEquals("204", resp.getEntry().get(2).getTransactionResponse().getStatus()); + + try { + ourPatientDao.read(id1.toVersionless()); + fail(); + } catch (ResourceGoneException e) { + // good + } + + try { + ourPatientDao.read(id2.toVersionless()); + fail(); + } catch (ResourceGoneException e) { + // good + } + + } + @Test public void testTransactionDeleteMatchUrlWithOneMatch() { String methodName = "testTransactionDeleteMatchUrlWithOneMatch"; @@ -360,51 +434,6 @@ public class FhirSystemDaoDstu2Test { } } - @Test - public void testTransactionDeleteByResourceId() { - String methodName = "testTransactionDeleteByResourceId"; - - Patient p1 = new Patient(); - p1.addIdentifier().setSystem("urn:system").setValue(methodName); - IdDt id1 = ourPatientDao.create(p1).getId(); - ourLog.info("Created patient, got it: {}", id1); - - Patient p2 = new Patient(); - p2.addIdentifier().setSystem("urn:system").setValue(methodName); - p2.setId("Patient/" + methodName); - IdDt id2 = ourPatientDao.update(p2).getId(); - ourLog.info("Created patient, got it: {}", id2); - - Bundle request = new Bundle(); - - request.addEntry().getTransaction().setMethod(HTTPVerbEnum.DELETE).setUrl("Patient/" + id1.getIdPart()); - request.addEntry().getTransaction().setMethod(HTTPVerbEnum.DELETE).setUrl("Patient/" + id2.getIdPart()); - - ourPatientDao.read(id1.toVersionless()); - ourPatientDao.read(id2.toVersionless()); - - Bundle resp = ourSystemDao.transaction(request); - - assertEquals(3, resp.getEntry().size()); - assertEquals("204", resp.getEntry().get(1).getTransactionResponse().getStatus()); - assertEquals("204", resp.getEntry().get(2).getTransactionResponse().getStatus()); - - try { - ourPatientDao.read(id1.toVersionless()); - fail(); - } catch (ResourceGoneException e) { - // good - } - - try { - ourPatientDao.read(id2.toVersionless()); - fail(); - } catch (ResourceGoneException e) { - // good - } - - } - @Test public void testTransactionDeleteMatchUrlWithZeroMatch() { String methodName = "testTransactionDeleteMatchUrlWithZeroMatch"; @@ -463,6 +492,71 @@ public class FhirSystemDaoDstu2Test { ourSystemDao.transaction(request); } + @Test + public void testTransactionFromBundle() throws Exception { + + InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/transaction_link_patient_eve.xml"); + String bundleStr = IOUtils.toString(bundleRes); + Bundle bundle = ourFhirContext.newXmlParser().parseResource(Bundle.class, bundleStr); + + Bundle resp = ourSystemDao.transaction(bundle); + + ourLog.info(ourFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(resp)); + + OperationOutcome oo = (OperationOutcome) resp.getEntry().get(0).getResource(); + assertThat(oo.getIssue().get(0).getDetailsElement().getValue(), containsString("Transaction completed")); + + assertThat(resp.getEntry().get(1).getTransactionResponse().getLocation(), startsWith("Patient/a555-44-4444/_history/")); + assertThat(resp.getEntry().get(2).getTransactionResponse().getLocation(), startsWith("Patient/temp6789/_history/")); + assertThat(resp.getEntry().get(3).getTransactionResponse().getLocation(), startsWith("Organization/GHH/_history/")); + + Patient p = ourPatientDao.read(new IdDt("Patient/a555-44-4444/_history/1")); + assertEquals("Patient/temp6789", p.getLink().get(0).getOther().getReference().getValue()); + } + + @Test + public void testTransactionReadAndSearch() { + String methodName = "testTransactionReadAndSearch"; + + Patient p = new Patient(); + p.addIdentifier().setSystem("urn:system").setValue(methodName); + p.setId("Patient/" + methodName); + IdDt idv1 = ourPatientDao.update(p).getId(); + ourLog.info("Created patient, got id: {}", idv1); + + p = new Patient(); + p.addIdentifier().setSystem("urn:system").setValue(methodName); + p.addName().addFamily("Family Name"); + p.setId("Patient/" + methodName); + IdDt idv2 = ourPatientDao.update(p).getId(); + ourLog.info("Updated patient, got id: {}", idv2); + + Bundle request = new Bundle(); + request.addEntry().getTransaction().setMethod(HTTPVerbEnum.GET).setUrl(idv1.toUnqualifiedVersionless().getValue()); + request.addEntry().getTransaction().setMethod(HTTPVerbEnum.GET).setUrl(idv1.toUnqualified().getValue()); + request.addEntry().getTransaction().setMethod(HTTPVerbEnum.GET).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); + + Bundle resp = ourSystemDao.transaction(request); + + assertEquals(4, resp.getEntry().size()); + + Entry nextEntry; + + nextEntry = resp.getEntry().get(1); + assertEquals(Patient.class, nextEntry.getResource().getClass()); + assertEquals(idv2.toUnqualified(), nextEntry.getResource().getId().toUnqualified()); + + nextEntry = resp.getEntry().get(2); + assertEquals(Patient.class, nextEntry.getResource().getClass()); + assertEquals(idv1.toUnqualified(), nextEntry.getResource().getId().toUnqualified()); + + nextEntry = resp.getEntry().get(3); + assertEquals(Bundle.class, nextEntry.getResource().getClass()); + + Bundle respBundle = (Bundle) nextEntry.getResource(); + assertEquals(1, respBundle.getTotal().intValue()); + } + @Test public void testTransactionUpdateMatchUrlWithOneMatch() { String methodName = "testTransactionUpdateMatchUrlWithOneMatch"; @@ -617,99 +711,6 @@ public class FhirSystemDaoDstu2Test { } - @Test - public void testTransactionWithRelativeOidIds() throws Exception { - Bundle res = new Bundle(); - res.setType(BundleTypeEnum.TRANSACTION); - - Patient p1 = new Patient(); - p1.setId("urn:oid:0.1.2.3"); - p1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds01"); - res.addEntry().setResource(p1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Patient"); - - Observation o1 = new Observation(); - o1.setId("cid:observation1"); - o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); - o1.setSubject(new ResourceReferenceDt("urn:oid:0.1.2.3")); - res.addEntry().setResource(o1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); - - Observation o2 = new Observation(); - o2.setId("cid:observation2"); - o2.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds03"); - o2.setSubject(new ResourceReferenceDt("urn:oid:0.1.2.3")); - res.addEntry().setResource(o2).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); - - Bundle resp = ourSystemDao.transaction(res); - - ourLog.info(ourFhirContext.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); - - assertEquals(BundleTypeEnum.TRANSACTION_RESPONSE, resp.getTypeElement().getValueAsEnum()); - assertEquals(4, resp.getEntry().size()); - - assertEquals(OperationOutcome.class, resp.getEntry().get(0).getResource().getClass()); - - OperationOutcome outcome = (OperationOutcome) resp.getEntry().get(0).getResource(); - assertThat(outcome.getIssue().get(1).getDetails(), containsString("Placeholder resource ID \"Patient/urn:oid:0.1.2.3\" was replaced with permanent ID \"Patient/")); - - assertTrue(resp.getEntry().get(1).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(1).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); - assertTrue(resp.getEntry().get(2).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); - assertTrue(resp.getEntry().get(3).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); - - o1 = ourObservationDao.read(new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation())); - o2 = ourObservationDao.read(new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation())); - assertThat(o1.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); - assertThat(o2.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); - - } - - /** - * This is not the correct way to do it, but we'll allow it to be lenient - */ - @Test - public void testTransactionWithRelativeOidIdsQualified() throws Exception { - Bundle res = new Bundle(); - res.setType(BundleTypeEnum.TRANSACTION); - - Patient p1 = new Patient(); - p1.setId("urn:oid:0.1.2.3"); - p1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds01"); - res.addEntry().setResource(p1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Patient"); - - Observation o1 = new Observation(); - o1.setId("cid:observation1"); - o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); - o1.setSubject(new ResourceReferenceDt("Patient/urn:oid:0.1.2.3")); - res.addEntry().setResource(o1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); - - Observation o2 = new Observation(); - o2.setId("cid:observation2"); - o2.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds03"); - o2.setSubject(new ResourceReferenceDt("Patient/urn:oid:0.1.2.3")); - res.addEntry().setResource(o2).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); - - Bundle resp = ourSystemDao.transaction(res); - - ourLog.info(ourFhirContext.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); - - assertEquals(BundleTypeEnum.TRANSACTION_RESPONSE, resp.getTypeElement().getValueAsEnum()); - assertEquals(4, resp.getEntry().size()); - - assertEquals(OperationOutcome.class, resp.getEntry().get(0).getResource().getClass()); - - OperationOutcome outcome = (OperationOutcome) resp.getEntry().get(0).getResource(); - assertThat(outcome.getIssue().get(1).getDetails(), containsString("Placeholder resource ID \"Patient/urn:oid:0.1.2.3\" was replaced with permanent ID \"Patient/")); - - assertTrue(resp.getEntry().get(1).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(1).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); - assertTrue(resp.getEntry().get(2).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); - assertTrue(resp.getEntry().get(3).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); - - o1 = ourObservationDao.read(new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation())); - o2 = ourObservationDao.read(new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation())); - assertThat(o1.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); - assertThat(o2.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); - - } - // // // /** @@ -812,6 +813,99 @@ public class FhirSystemDaoDstu2Test { // // } + @Test + public void testTransactionWithRelativeOidIds() throws Exception { + Bundle res = new Bundle(); + res.setType(BundleTypeEnum.TRANSACTION); + + Patient p1 = new Patient(); + p1.setId("urn:oid:0.1.2.3"); + p1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds01"); + res.addEntry().setResource(p1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Patient"); + + Observation o1 = new Observation(); + o1.setId("cid:observation1"); + o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); + o1.setSubject(new ResourceReferenceDt("urn:oid:0.1.2.3")); + res.addEntry().setResource(o1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); + + Observation o2 = new Observation(); + o2.setId("cid:observation2"); + o2.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds03"); + o2.setSubject(new ResourceReferenceDt("urn:oid:0.1.2.3")); + res.addEntry().setResource(o2).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); + + Bundle resp = ourSystemDao.transaction(res); + + ourLog.info(ourFhirContext.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); + + assertEquals(BundleTypeEnum.TRANSACTION_RESPONSE, resp.getTypeElement().getValueAsEnum()); + assertEquals(4, resp.getEntry().size()); + + assertEquals(OperationOutcome.class, resp.getEntry().get(0).getResource().getClass()); + + OperationOutcome outcome = (OperationOutcome) resp.getEntry().get(0).getResource(); + assertThat(outcome.getIssue().get(1).getDetails(), containsString("Placeholder resource ID \"Patient/urn:oid:0.1.2.3\" was replaced with permanent ID \"Patient/")); + + assertTrue(resp.getEntry().get(1).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(1).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); + assertTrue(resp.getEntry().get(2).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); + assertTrue(resp.getEntry().get(3).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); + + o1 = ourObservationDao.read(new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation())); + o2 = ourObservationDao.read(new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation())); + assertThat(o1.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); + assertThat(o2.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); + + } + + /** + * This is not the correct way to do it, but we'll allow it to be lenient + */ + @Test + public void testTransactionWithRelativeOidIdsQualified() throws Exception { + Bundle res = new Bundle(); + res.setType(BundleTypeEnum.TRANSACTION); + + Patient p1 = new Patient(); + p1.setId("urn:oid:0.1.2.3"); + p1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds01"); + res.addEntry().setResource(p1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Patient"); + + Observation o1 = new Observation(); + o1.setId("cid:observation1"); + o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); + o1.setSubject(new ResourceReferenceDt("Patient/urn:oid:0.1.2.3")); + res.addEntry().setResource(o1).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); + + Observation o2 = new Observation(); + o2.setId("cid:observation2"); + o2.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds03"); + o2.setSubject(new ResourceReferenceDt("Patient/urn:oid:0.1.2.3")); + res.addEntry().setResource(o2).getTransaction().setMethod(HTTPVerbEnum.POST).setUrl("Observation"); + + Bundle resp = ourSystemDao.transaction(res); + + ourLog.info(ourFhirContext.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); + + assertEquals(BundleTypeEnum.TRANSACTION_RESPONSE, resp.getTypeElement().getValueAsEnum()); + assertEquals(4, resp.getEntry().size()); + + assertEquals(OperationOutcome.class, resp.getEntry().get(0).getResource().getClass()); + + OperationOutcome outcome = (OperationOutcome) resp.getEntry().get(0).getResource(); + assertThat(outcome.getIssue().get(1).getDetails(), containsString("Placeholder resource ID \"Patient/urn:oid:0.1.2.3\" was replaced with permanent ID \"Patient/")); + + assertTrue(resp.getEntry().get(1).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(1).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); + assertTrue(resp.getEntry().get(2).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); + assertTrue(resp.getEntry().get(3).getTransactionResponse().getLocation(), new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation()).getIdPart().matches("^[0-9]+$")); + + o1 = ourObservationDao.read(new IdDt(resp.getEntry().get(2).getTransactionResponse().getLocation())); + o2 = ourObservationDao.read(new IdDt(resp.getEntry().get(3).getTransactionResponse().getLocation())); + assertThat(o1.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); + assertThat(o2.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); + + } + @AfterClass public static void afterClass() { ourCtx.close(); @@ -828,100 +922,6 @@ public class FhirSystemDaoDstu2Test { ourSystemDao = ourCtx.getBean("mySystemDaoDstu2", IFhirSystemDao.class); } - @Test - public void testSystemMetaOperation() { - deleteEverything(); - - MetaDt meta = ourSystemDao.metaGetOperation(); - List published = meta.getTag(); - assertEquals(0, published.size()); - - String methodName = "testSystemMetaOperation"; - IdDt id1; - { - Patient patient = new Patient(); - patient.addIdentifier().setSystem("urn:system").setValue(methodName); - patient.addName().addFamily("Tester").addGiven("Joe"); - TagList tagList = new TagList(); - tagList.addTag(null, "Dog", "Puppies"); - ResourceMetadataKeyEnum.TAG_LIST.put(patient, tagList); - - List securityLabels = new ArrayList(); - securityLabels.add(new CodingDt().setSystem("seclabel:sys:1").setCode("seclabel:code:1").setDisplay("seclabel:dis:1")); - ResourceMetadataKeyEnum.SECURITY_LABELS.put(patient, securityLabels); - - ArrayList profiles = new ArrayList(); - profiles.add(new IdDt("http://profile/1")); - ResourceMetadataKeyEnum.PROFILES.put(patient, profiles); - - id1 = ourPatientDao.create(patient).getId(); - } - { - Patient patient = new Patient(); - patient.addIdentifier().setSystem("urn:system").setValue(methodName); - patient.addName().addFamily("Tester").addGiven("Joe"); - TagList tagList = new TagList(); - tagList.addTag("http://foo", "Cat", "Kittens"); - ResourceMetadataKeyEnum.TAG_LIST.put(patient, tagList); - - List securityLabels = new ArrayList(); - securityLabels.add(new CodingDt().setSystem("seclabel:sys:2").setCode("seclabel:code:2").setDisplay("seclabel:dis:2")); - ResourceMetadataKeyEnum.SECURITY_LABELS.put(patient, securityLabels); - - ArrayList profiles = new ArrayList(); - profiles.add(new IdDt("http://profile/2")); - ResourceMetadataKeyEnum.PROFILES.put(patient, profiles); - - ourPatientDao.create(patient); - } - - meta = ourSystemDao.metaGetOperation(); - published = meta.getTag(); - assertEquals(2, published.size()); - assertEquals(null, published.get(0).getSystem()); - assertEquals("Dog", published.get(0).getCode()); - assertEquals("Puppies", published.get(0).getDisplay()); - assertEquals("http://foo", published.get(1).getSystem()); - assertEquals("Cat", published.get(1).getCode()); - assertEquals("Kittens", published.get(1).getDisplay()); - List secLabels = meta.getSecurity(); - assertEquals(2, secLabels.size()); - assertEquals("seclabel:sys:1", secLabels.get(0).getSystemElement().getValue()); - assertEquals("seclabel:code:1", secLabels.get(0).getCodeElement().getValue()); - assertEquals("seclabel:dis:1", secLabels.get(0).getDisplayElement().getValue()); - assertEquals("seclabel:sys:2", secLabels.get(1).getSystemElement().getValue()); - assertEquals("seclabel:code:2", secLabels.get(1).getCodeElement().getValue()); - assertEquals("seclabel:dis:2", secLabels.get(1).getDisplayElement().getValue()); - List profiles = meta.getProfile(); - assertEquals(2, profiles.size()); - assertEquals("http://profile/1", profiles.get(0).getValue()); - assertEquals("http://profile/2", profiles.get(1).getValue()); - - ourPatientDao.removeTag(id1, TagTypeEnum.TAG, null, "Dog"); - ourPatientDao.removeTag(id1, TagTypeEnum.SECURITY_LABEL, "seclabel:sys:1", "seclabel:code:1"); - ourPatientDao.removeTag(id1, TagTypeEnum.PROFILE, BaseFhirDao.NS_JPA_PROFILE, "http://profile/1"); - - meta = ourSystemDao.metaGetOperation(); - published = meta.getTag(); - assertEquals(1, published.size()); - assertEquals("http://foo", published.get(0).getSystem()); - assertEquals("Cat", published.get(0).getCode()); - assertEquals("Kittens", published.get(0).getDisplay()); - secLabels = meta.getSecurity(); - assertEquals(1, secLabels.size()); - assertEquals("seclabel:sys:2", secLabels.get(0).getSystemElement().getValue()); - assertEquals("seclabel:code:2", secLabels.get(0).getCodeElement().getValue()); - assertEquals("seclabel:dis:2", secLabels.get(0).getDisplayElement().getValue()); - profiles = meta.getProfile(); - assertEquals(1, profiles.size()); - assertEquals("http://profile/2", profiles.get(0).getValue()); - - } - - private void deleteEverything() { - FhirSystemDaoDstu2Test.doDeleteEverything(ourSystemDao); - } - static void doDeleteEverything(IFhirSystemDao systemDao) { IBundleProvider all = systemDao.history(null); List allRes = all.getResources(0, all.size()); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java index 6d051c4bb52..7af67ce9fb5 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java @@ -57,47 +57,39 @@ import ca.uhn.fhir.model.primitive.InstantDt; import ca.uhn.fhir.model.primitive.StringDt; public class XmlParserDstu2Test { - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(XmlParserDstu2Test.class); private static final FhirContext ourCtx = FhirContext.forDstu2(); - - @BeforeClass - public static void beforeClass() { - XMLUnit.setIgnoreAttributeOrder(true); - XMLUnit.setIgnoreComments(true); - XMLUnit.setIgnoreWhitespace(true); - } + private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(XmlParserDstu2Test.class); @Test - public void testOmitResourceId() { - Patient p = new Patient(); - p.setId("123"); - p.addName().addFamily("ABC"); + public void testBundleWithBinary() { + //@formatter:off + String bundle = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + //@formatter:on + + Bundle b = ourCtx.newXmlParser().parseBundle(bundle); + assertEquals(1, b.getEntries().size()); + + Binary bin = (Binary) b.getEntries().get(0).getResource(); + assertArrayEquals(new byte[] {1,2,3,4}, bin.getContent()); - assertThat(ourCtx.newXmlParser().encodeResourceToString(p), stringContainsInOrder("123", "ABC")); - assertThat(ourCtx.newXmlParser().setOmitResourceId(true).encodeResourceToString(p), containsString("ABC")); - assertThat(ourCtx.newXmlParser().setOmitResourceId(true).encodeResourceToString(p), not(containsString("123"))); - } - - - @Test - public void testEncodeExtensionWithResourceContent() { - IParser parser = ourCtx.newXmlParser(); - - Patient patient = new Patient(); - patient.addAddress().setUse(AddressUseEnum.HOME); - patient.addUndeclaredExtension(false, "urn:foo", new ResourceReferenceDt("Organization/123")); - - String val = parser.encodeResourceToString(patient); - ourLog.info(val); - assertThat(val, StringContains.containsString("")); - - Patient actual = parser.parseResource(Patient.class, val); - assertEquals(AddressUseEnum.HOME.getCode(), patient.getAddress().get(0).getUse()); - List ext = actual.getUndeclaredExtensions(); - assertEquals(1, ext.size()); - ResourceReferenceDt ref = (ResourceReferenceDt) ext.get(0).getValue(); - assertEquals("Organization/123", ref.getReference().getValue()); - } @Test @@ -121,7 +113,104 @@ public class XmlParserDstu2Test { o = (Organization) rr.getResource(); assertEquals("ORG", o.getName()); } + + @Test + public void testDuration() { + Encounter enc = new Encounter(); + DurationDt duration = new DurationDt(); + duration.setUnits("day").setValue(123L); + enc.setLength(duration); + + String str = ourCtx.newXmlParser().encodeResourceToString(enc); + ourLog.info(str); + + assertThat(str, not(containsString("meta"))); + assertThat(str, containsString("")); + } + @Test + public void testEncodeAndParseBundleWithoutResourceIds() { + Organization org = new Organization(); + org.addIdentifier().setSystem("urn:system").setValue("someval"); + + Bundle bundle = Bundle.withSingleResource(org); + String str = ourCtx.newXmlParser().encodeBundleToString(bundle); + ourLog.info(str); + + Bundle parsed = ourCtx.newXmlParser().parseBundle(str); + assertThat(parsed.getEntries().get(0).getResource().getId().getValue(), emptyOrNullString()); + assertTrue(parsed.getEntries().get(0).getResource().getId().isEmpty()); + } + + @Test + public void testEncodeAndParseContained() { + IParser xmlParser = ourCtx.newXmlParser().setPrettyPrint(true); + + // Create an organization, note that the organization does not have an ID + Organization org = new Organization(); + org.getNameElement().setValue("Contained Test Organization"); + + // Create a patient + Patient patient = new Patient(); + patient.setId("Patient/1333"); + patient.addIdentifier().setSystem("urn:mrns").setValue("253345"); + + // Put the organization as a reference in the patient resource + patient.getManagingOrganization().setResource(org); + + String encoded = xmlParser.encodeResourceToString(patient); + ourLog.info(encoded); + assertThat(encoded, containsString("")); + assertThat(encoded, containsString("")); + + // Create a bundle with just the patient resource + ca.uhn.fhir.model.dstu2.resource.Bundle b = new ca.uhn.fhir.model.dstu2.resource.Bundle(); + b.addEntry().setResource(patient); + + // Encode the bundle + encoded = xmlParser.encodeResourceToString(b); + ourLog.info(encoded); + assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", ""))); + assertThat(encoded, containsString("")); + assertThat(encoded, stringContainsInOrder(Arrays.asList("", ""))); + assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "", "")))); + + // Re-parse the bundle + patient = (Patient) xmlParser.parseResource(xmlParser.encodeResourceToString(patient)); + assertEquals("#1", patient.getManagingOrganization().getReference().getValue()); + + assertNotNull(patient.getManagingOrganization().getResource()); + org = (Organization) patient.getManagingOrganization().getResource(); + assertEquals("#1", org.getId().getValue()); + assertEquals("Contained Test Organization", org.getName()); + + // And re-encode a second time + encoded = xmlParser.encodeResourceToString(patient); + ourLog.info(encoded); + assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", "", ""))); + assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "")))); + assertThat(encoded, containsString("")); + + // And re-encode once more, with the references cleared + patient.getContained().getContainedResources().clear(); + patient.getManagingOrganization().setReference((String)null); + encoded = xmlParser.encodeResourceToString(patient); + ourLog.info(encoded); + assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", "", ""))); + assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "")))); + assertThat(encoded, containsString("")); + + // And re-encode once more, with the references cleared and a manually set local ID + patient.getContained().getContainedResources().clear(); + patient.getManagingOrganization().setReference((String)null); + patient.getManagingOrganization().getResource().setId(("#333")); + encoded = xmlParser.encodeResourceToString(patient); + ourLog.info(encoded); + assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", "", ""))); + assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "")))); + + } + @Test public void testEncodeAndParseExtensionOnResourceReference() { DataElement de = new DataElement(); @@ -147,6 +236,705 @@ public class XmlParserDstu2Test { } + @Test + public void testEncodeAndParseExtensions() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135"); + + ExtensionDt ext = new ExtensionDt(); + ext.setUrl("http://example.com/extensions#someext"); + ext.setValue(new DateTimeDt("2011-01-02T11:13:15")); + patient.addUndeclaredExtension(ext); + + ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent"); + patient.addUndeclaredExtension(parent); + ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1")); + parent.addUndeclaredExtension(child1); + ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value2")); + parent.addUndeclaredExtension(child2); + + ExtensionDt modExt = new ExtensionDt(); + modExt.setUrl("http://example.com/extensions#modext"); + modExt.setValue(new DateDt("1995-01-02")); + modExt.setModifier(true); + patient.addUndeclaredExtension(modExt); + + HumanNameDt name = patient.addName(); + name.addFamily("Blah"); + StringDt given = name.addGiven(); + given.setValue("Joe"); + ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given")); + given.addUndeclaredExtension(ext2); + + StringDt given2 = name.addGiven(); + given2.setValue("Shmoe"); + ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent"); + given2.addUndeclaredExtension(given2ext); + given2ext.addUndeclaredExtension(new ExtensionDt().setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD"))); + + String output = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient); + ourLog.info(output); + + String enc = ourCtx.newXmlParser().encodeResourceToString(patient); + assertThat(enc, containsString("")); + assertThat(enc, containsString("")); + assertThat( + enc, + containsString("")); + assertThat(enc, containsString("")); + assertThat(enc, containsString("")); + + /* + * Now parse this back + */ + + Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); + ext = parsed.getUndeclaredExtensions().get(0); + assertEquals("http://example.com/extensions#someext", ext.getUrl()); + assertEquals("2011-01-02T11:13:15", ((DateTimeDt) ext.getValue()).getValueAsString()); + + parent = patient.getUndeclaredExtensions().get(1); + assertEquals("http://example.com#parent", parent.getUrl()); + assertNull(parent.getValue()); + child1 = parent.getExtension().get(0); + assertEquals("http://example.com#child", child1.getUrl()); + assertEquals("value1", ((StringDt) child1.getValue()).getValueAsString()); + child2 = parent.getExtension().get(1); + assertEquals("http://example.com#child", child2.getUrl()); + assertEquals("value2", ((StringDt) child2.getValue()).getValueAsString()); + + modExt = parsed.getUndeclaredModifierExtensions().get(0); + assertEquals("http://example.com/extensions#modext", modExt.getUrl()); + assertEquals("1995-01-02", ((DateDt) modExt.getValue()).getValueAsString()); + + name = parsed.getName().get(0); + + ext2 = name.getGiven().get(0).getUndeclaredExtensions().get(0); + assertEquals("http://examples.com#givenext", ext2.getUrl()); + assertEquals("given", ((StringDt) ext2.getValue()).getValueAsString()); + + given2ext = name.getGiven().get(1).getUndeclaredExtensions().get(0); + assertEquals("http://examples.com#givenext_parent", given2ext.getUrl()); + assertNull(given2ext.getValue()); + ExtensionDt given2ext2 = given2ext.getExtension().get(0); + assertEquals("http://examples.com#givenext_child", given2ext2.getUrl()); + assertEquals("CHILD", ((StringDt) given2ext2.getValue()).getValue()); + + } + + @Test + public void testEncodeAndParseMetaProfileAndTags() { + Patient p = new Patient(); + p.addName().addFamily("FAMILY"); + + List profiles = new ArrayList(); + profiles.add(new IdDt("http://foo/Profile1")); + profiles.add(new IdDt("http://foo/Profile2")); + ResourceMetadataKeyEnum.PROFILES.put(p, profiles); + + TagList tagList = new TagList(); + tagList.addTag("scheme1", "term1", "label1"); + tagList.addTag("scheme2", "term2", "label2"); + ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList); + + String enc = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); + ourLog.info(enc); + + //@formatter:off + assertThat(enc, stringContainsInOrder("", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "")); + //@formatter:on + + Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); + List gotLabels = ResourceMetadataKeyEnum.PROFILES.get(parsed); + + assertEquals(2,gotLabels.size()); + + IdDt label = (IdDt) gotLabels.get(0); + assertEquals("http://foo/Profile1", label.getValue()); + label = (IdDt) gotLabels.get(1); + assertEquals("http://foo/Profile2", label.getValue()); + + tagList = ResourceMetadataKeyEnum.TAG_LIST.get(parsed); + assertEquals(2, tagList.size()); + + assertEquals(new Tag("scheme1", "term1", "label1"), tagList.get(0)); + assertEquals(new Tag("scheme2", "term2", "label2"), tagList.get(1)); + } + + @Test + public void testEncodeAndParseMetaProfiles() { + Patient p = new Patient(); + p.addName().addFamily("FAMILY"); + + TagList tagList = new TagList(); + tagList.addTag("scheme1", "term1", "label1"); + tagList.addTag("scheme2", "term2", "label2"); + ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList); + + String enc = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); + ourLog.info(enc); + + //@formatter:off + assertThat(enc, stringContainsInOrder("", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "")); + //@formatter:on + + Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); + List gotLabels = ResourceMetadataKeyEnum.PROFILES.get(parsed); + assertNull(gotLabels); + + tagList = ResourceMetadataKeyEnum.TAG_LIST.get(parsed); + assertEquals(2, tagList.size()); + + assertEquals(new Tag("scheme1", "term1", "label1"), tagList.get(0)); + assertEquals(new Tag("scheme2", "term2", "label2"), tagList.get(1)); + } + + @Test + public void testEncodeAndParseSecurityLabels() { + Patient p = new Patient(); + p.addName().addFamily("FAMILY"); + + List labels = new ArrayList(); + labels.add(new CodingDt().setSystem("SYSTEM1").setCode("CODE1").setDisplay("DISPLAY1").setPrimary(true).setVersion("VERSION1")); + labels.add(new CodingDt().setSystem("SYSTEM2").setCode("CODE2").setDisplay("DISPLAY2").setPrimary(false).setVersion("VERSION2")); + + ResourceMetadataKeyEnum.SECURITY_LABELS.put(p, labels); + + String enc = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); + ourLog.info(enc); + + //@formatter:off + assertThat(enc, stringContainsInOrder("", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "")); + //@formatter:on + + Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); + List gotLabels = ResourceMetadataKeyEnum.SECURITY_LABELS.get(parsed); + + assertEquals(2,gotLabels.size()); + + CodingDt label = (CodingDt) gotLabels.get(0); + assertEquals("SYSTEM1", label.getSystem()); + assertEquals("CODE1", label.getCode()); + assertEquals("DISPLAY1", label.getDisplay()); + assertEquals(true, label.getPrimary()); + assertEquals("VERSION1", label.getVersion()); + + label = (CodingDt) gotLabels.get(1); + assertEquals("SYSTEM2", label.getSystem()); + assertEquals("CODE2", label.getCode()); + assertEquals("DISPLAY2", label.getDisplay()); + assertEquals(false, label.getPrimary()); + assertEquals("VERSION2", label.getVersion()); + } + + /** + * See #103 + */ + @Test + public void testEncodeAndReEncodeContainedJson() { + Composition comp = new Composition(); + comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section0_Allergy0")); + comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section1_Allergy0")); + comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section2_Allergy0")); + + IParser parser = ourCtx.newJsonParser().setPrettyPrint(true); + + String string = parser.encodeResourceToString(comp); + ourLog.info(string); + + Composition parsed = parser.parseResource(Composition.class, string); + parsed.getSection().remove(0); + + string = parser.encodeResourceToString(parsed); + ourLog.info(string); + + parsed = parser.parseResource(Composition.class, string); + assertEquals(2, parsed.getContained().getContainedResources().size()); + } + + /** + * See #103 + */ + @Test + public void testEncodeAndReEncodeContainedXml() { + Composition comp = new Composition(); + comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section0_Allergy0")); + comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section1_Allergy0")); + comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section2_Allergy0")); + + IParser parser = ourCtx.newXmlParser().setPrettyPrint(true); + + String string = parser.encodeResourceToString(comp); + ourLog.info(string); + + Composition parsed = parser.parseResource(Composition.class, string); + parsed.getSection().remove(0); + + string = parser.encodeResourceToString(parsed); + ourLog.info(string); + + parsed = parser.parseResource(Composition.class, string); + assertEquals(2, parsed.getContained().getContainedResources().size()); + } + + + @Test + public void testEncodeBinaryWithNoContentType() { + Binary b = new Binary(); + b.setContent(new byte[] {1,2,3,4}); + + String output = ourCtx.newXmlParser().encodeResourceToString(b); + ourLog.info(output); + + assertEquals("", output); + } + + /** + * See #113 + */ + @Test + public void testEncodeContainedResources() { + + MedicationPrescription medicationPrescript = new MedicationPrescription(); + + String medId = "123"; + CodeableConceptDt codeDt = new CodeableConceptDt("urn:sys", "code1"); + + // Adding medication to Contained. + Medication medResource = new Medication(); + medResource.setCode(codeDt); + medResource.setId("#" + String.valueOf(medId)); + ArrayList medResList = new ArrayList(); + medResList.add(medResource); + ContainedDt medContainedDt = new ContainedDt(); + medContainedDt.setContainedResources(medResList); + medicationPrescript.setContained(medContainedDt); + + // Medication reference. This should point to the contained resource. + ResourceReferenceDt medRefDt = new ResourceReferenceDt("#" + medId); + medRefDt.setDisplay("MedRef"); + medicationPrescript.setMedication(medRefDt); + + IParser p = ourCtx.newXmlParser().setPrettyPrint(true); + String encoded = p.encodeResourceToString(medicationPrescript); + ourLog.info(encoded); + + //@formatter:on + assertThat(encoded, stringContainsInOrder( + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "")); + //@formatter:off + + } + + + + + + /** + * See #113 + */ + @Test + public void testEncodeContainedResourcesAutomatic() { + + MedicationPrescription medicationPrescript = new MedicationPrescription(); + String nameDisp = "MedRef"; + CodeableConceptDt codeDt = new CodeableConceptDt("urn:sys", "code1"); + + // Adding medication to Contained. + Medication medResource = new Medication(); + // No ID set + medResource.setCode(codeDt); + + // Medication reference. This should point to the contained resource. + ResourceReferenceDt medRefDt = new ResourceReferenceDt(); + medRefDt.setDisplay(nameDisp); + // Resource reference set, but no ID + medRefDt.setResource(medResource); + medicationPrescript.setMedication(medRefDt); + + IParser p = ourCtx.newXmlParser().setPrettyPrint(true); + String encoded = p.encodeResourceToString(medicationPrescript); + ourLog.info(encoded); + + //@formatter:on + assertThat(encoded, stringContainsInOrder( + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "")); + //@formatter:off + } + + /** + * See #113 + */ + @Test + public void testEncodeContainedResourcesManualContainUsingNonLocalId() { + + MedicationPrescription medicationPrescript = new MedicationPrescription(); + + String medId = "123"; + CodeableConceptDt codeDt = new CodeableConceptDt("urn:sys", "code1"); + + // Adding medication to Contained. + Medication medResource = new Medication(); + medResource.setCode(codeDt); + medResource.setId(String.valueOf(medId)); // ID does not start with '#' + ArrayList medResList = new ArrayList(); + medResList.add(medResource); + ContainedDt medContainedDt = new ContainedDt(); + medContainedDt.setContainedResources(medResList); + medicationPrescript.setContained(medContainedDt); + + // Medication reference. This should point to the contained resource. + ResourceReferenceDt medRefDt = new ResourceReferenceDt("#" + medId); + medRefDt.setDisplay("MedRef"); + medicationPrescript.setMedication(medRefDt); + + IParser p = ourCtx.newXmlParser().setPrettyPrint(true); + String encoded = p.encodeResourceToString(medicationPrescript); + ourLog.info(encoded); + + //@formatter:on + assertThat(encoded, stringContainsInOrder( + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "")); + //@formatter:off + + } + + + @Test + public void testEncodeContainedWithNarrativeIsSuppresed() throws Exception { + IParser parser = ourCtx.newXmlParser().setPrettyPrint(true); + + // Create an organization, note that the organization does not have an ID + Organization org = new Organization(); + org.getNameElement().setValue("Contained Test Organization"); + org.getText().setDiv("
FOOBAR
"); + + // Create a patient + Patient patient = new Patient(); + patient.setId("Patient/1333"); + patient.addIdentifier().setSystem("urn:mrns").setValue("253345"); + patient.getText().setDiv("
BARFOO
"); + patient.getManagingOrganization().setResource(org); + + String encoded = parser.encodeResourceToString(patient); + ourLog.info(encoded); + + assertThat(encoded, stringContainsInOrder("", "
BARFOO
", "", "", "", "")); + + Patient actual = parser.parseResource(Patient.class, val); + assertEquals(AddressUseEnum.HOME.getCode(), patient.getAddress().get(0).getUse()); + List ext = actual.getUndeclaredExtensions(); + assertEquals(1, ext.size()); + ResourceReferenceDt ref = (ResourceReferenceDt) ext.get(0).getValue(); + assertEquals("Organization/123", ref.getReference().getValue()); + + } + + @Test + public void testEncodeNonContained() { + // Create an organization + Organization org = new Organization(); + org.setId("Organization/65546"); + org.getNameElement().setValue("Contained Test Organization"); + + // Create a patient + Patient patient = new Patient(); + patient.setId("Patient/1333"); + patient.addIdentifier().setSystem("urn:mrns").setValue("253345"); + patient.getManagingOrganization().setResource(org); + + // Create a list containing both resources. In a server method, you might just + // return this list, but here we will create a bundle to encode. + List resources = new ArrayList(); + resources.add(org); + resources.add(patient); + + // Create a bundle with both + ca.uhn.fhir.model.dstu2.resource.Bundle b = new ca.uhn.fhir.model.dstu2.resource.Bundle(); + b.addEntry().setResource(org); + b.addEntry().setResource(patient); + + // Encode the buntdle + String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(b); + ourLog.info(encoded); + assertThat(encoded, not(containsString(""))); + assertThat(encoded, stringContainsInOrder("", "
")); + assertThat(encoded, containsString("")); + assertThat(encoded, stringContainsInOrder("", "
")); + + encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient); + ourLog.info(encoded); + assertThat(encoded, not(containsString(""))); + assertThat(encoded, containsString("")); + + + } + + @Test + public void testMoreExtensions() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135"); + + ExtensionDt ext = new ExtensionDt(); + ext.setUrl("http://example.com/extensions#someext"); + ext.setValue(new DateTimeDt("2011-01-02T11:13:15")); + + // Add the extension to the resource + patient.addUndeclaredExtension(ext); + // END SNIPPET: resourceExtension + + // START SNIPPET: resourceStringExtension + HumanNameDt name = patient.addName(); + name.addFamily("Shmoe"); + StringDt given = name.addGiven(); + given.setValue("Joe"); + ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given")); + given.addUndeclaredExtension(ext2); + + StringDt given2 = name.addGiven(); + given2.setValue("Shmoe"); + ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent"); + given2.addUndeclaredExtension(given2ext); + ExtensionDt givenExtChild = new ExtensionDt(); + givenExtChild.setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD")); + given2ext.addUndeclaredExtension(givenExtChild); + // END SNIPPET: resourceStringExtension + + // START SNIPPET: subExtension + ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent"); + patient.addUndeclaredExtension(parent); + + ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1")); + parent.addUndeclaredExtension(child1); + + ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1")); + parent.addUndeclaredExtension(child2); + // END SNIPPET: subExtension + + String output = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient); + ourLog.info(output); + + String enc = ourCtx.newXmlParser().encodeResourceToString(patient); + assertThat(enc, containsString("")); + assertThat( + enc, + containsString("")); + assertThat(enc, containsString("")); + assertThat(enc, containsString("")); + } + + @Test + public void testOmitResourceId() { + Patient p = new Patient(); + p.setId("123"); + p.addName().addFamily("ABC"); + + assertThat(ourCtx.newXmlParser().encodeResourceToString(p), stringContainsInOrder("123", "ABC")); + assertThat(ourCtx.newXmlParser().setOmitResourceId(true).encodeResourceToString(p), containsString("ABC")); + assertThat(ourCtx.newXmlParser().setOmitResourceId(true).encodeResourceToString(p), not(containsString("123"))); + } + + @Test + public void testParseAndEncodeBundle() throws Exception { + String content = IOUtils.toString(XmlParserDstu2Test.class.getResourceAsStream("/bundle-example.xml")); + + Bundle parsed = ourCtx.newXmlParser().parseBundle(content); + assertEquals("http://example.com/base/Bundle/example/_history/1", parsed.getId().getValue()); + assertEquals("1", parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION)); + assertEquals("1", parsed.getId().getVersionIdPart()); + assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED)); + assertEquals("searchset", parsed.getType().getValue()); + assertEquals(3, parsed.getTotalResults().getValue().intValue()); + assertEquals("http://example.com/base", parsed.getLinkBase().getValue()); + assertEquals("https://example.com/base/MedicationPrescription?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLinkNext().getValue()); + assertEquals("https://example.com/base/MedicationPrescription?patient=347&_include=MedicationPrescription.medication", parsed.getLinkSelf().getValue()); + + assertEquals(2, parsed.getEntries().size()); + assertEquals("http://foo?search", parsed.getEntries().get(0).getLinkSearch().getValue()); + + assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", parsed.getEntries().get(0).getLinkAlternate().getValue()); + MedicationPrescription p = (MedicationPrescription) parsed.getEntries().get(0).getResource(); + assertEquals("Patient/347", p.getPatient().getReference().getValue()); + assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString()); + assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue()); + + Medication m = (Medication) parsed.getEntries().get(1).getResource(); + assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); + assertSame(p.getMedication().getResource(), m); + + String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(parsed); + ourLog.info(reencoded); + + Diff d = new Diff(new StringReader(content), new StringReader(reencoded)); + assertTrue(d.toString(), d.identical()); + + } + + @Test + public void testParseAndEncodeBundleNewStyle() throws Exception { + String content = IOUtils.toString(XmlParserDstu2Test.class.getResourceAsStream("/bundle-example.xml")); + + IParser newXmlParser = ourCtx.newXmlParser(); + ca.uhn.fhir.model.dstu2.resource.Bundle parsed = newXmlParser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, content); + assertEquals("http://example.com/base/Bundle/example/_history/1", parsed.getId().getValue()); + assertEquals("1", parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION)); + assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED)); + assertEquals("searchset", parsed.getType()); + assertEquals(3, parsed.getTotal().intValue()); + assertEquals("http://example.com/base", parsed.getBaseElement().getValueAsString()); + assertEquals("https://example.com/base/MedicationPrescription?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink().get(0).getUrlElement().getValueAsString()); + assertEquals("https://example.com/base/MedicationPrescription?patient=347&_include=MedicationPrescription.medication", parsed.getLink().get(1).getUrlElement().getValueAsString()); + + assertEquals(2, parsed.getEntry().size()); + assertEquals("alternate", parsed.getEntry().get(0).getLink().get(0).getRelation()); + assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", parsed.getEntry().get(0).getLink().get(0).getUrl()); + assertEquals("http://foo?search", parsed.getEntry().get(0).getTransaction().getUrlElement().getValueAsString()); + + MedicationPrescription p = (MedicationPrescription) parsed.getEntry().get(0).getResource(); + assertEquals("Patient/347", p.getPatient().getReference().getValue()); + assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString()); + assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue()); +// assertEquals("3123", p.getId().getValue()); + + Medication m = (Medication) parsed.getEntry().get(1).getResource(); + assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); + assertSame(p.getMedication().getResource(), m); + + String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed); + ourLog.info(reencoded); + + Diff d = new Diff(new StringReader(content), new StringReader(reencoded)); + assertTrue(d.toString(), d.identical()); + + } + @Test public void testParseAndEncodeExtensionOnResourceReference() { //@formatter:off @@ -377,288 +1165,179 @@ public class XmlParserDstu2Test { } @Test - public void testEncodeBinaryWithNoContentType() { - Binary b = new Binary(); - b.setContent(new byte[] {1,2,3,4}); - - String output = ourCtx.newXmlParser().encodeResourceToString(b); - ourLog.info(output); - - assertEquals("", output); - } - - @Test - public void testMoreExtensions() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135"); - - ExtensionDt ext = new ExtensionDt(); - ext.setUrl("http://example.com/extensions#someext"); - ext.setValue(new DateTimeDt("2011-01-02T11:13:15")); - - // Add the extension to the resource - patient.addUndeclaredExtension(ext); - // END SNIPPET: resourceExtension - - // START SNIPPET: resourceStringExtension - HumanNameDt name = patient.addName(); - name.addFamily("Shmoe"); - StringDt given = name.addGiven(); - given.setValue("Joe"); - ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given")); - given.addUndeclaredExtension(ext2); - - StringDt given2 = name.addGiven(); - given2.setValue("Shmoe"); - ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent"); - given2.addUndeclaredExtension(given2ext); - ExtensionDt givenExtChild = new ExtensionDt(); - givenExtChild.setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD")); - given2ext.addUndeclaredExtension(givenExtChild); - // END SNIPPET: resourceStringExtension - - // START SNIPPET: subExtension - ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent"); - patient.addUndeclaredExtension(parent); - - ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1")); - parent.addUndeclaredExtension(child1); - - ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1")); - parent.addUndeclaredExtension(child2); - // END SNIPPET: subExtension - - String output = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient); - ourLog.info(output); - - String enc = ourCtx.newXmlParser().encodeResourceToString(patient); - assertThat(enc, containsString("")); - assertThat( - enc, - containsString("")); - assertThat(enc, containsString("")); - assertThat(enc, containsString("")); - } - - - @Test - public void testEncodeNonContained() { - // Create an organization - Organization org = new Organization(); - org.setId("Organization/65546"); - org.getNameElement().setValue("Contained Test Organization"); - - // Create a patient - Patient patient = new Patient(); - patient.setId("Patient/1333"); - patient.addIdentifier().setSystem("urn:mrns").setValue("253345"); - patient.getManagingOrganization().setResource(org); - - // Create a list containing both resources. In a server method, you might just - // return this list, but here we will create a bundle to encode. - List resources = new ArrayList(); - resources.add(org); - resources.add(patient); - - // Create a bundle with both - ca.uhn.fhir.model.dstu2.resource.Bundle b = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - b.addEntry().setResource(org); - b.addEntry().setResource(patient); - - // Encode the buntdle - String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(b); - ourLog.info(encoded); - assertThat(encoded, not(containsString(""))); - assertThat(encoded, stringContainsInOrder("", "")); - assertThat(encoded, containsString("")); - assertThat(encoded, stringContainsInOrder("", "")); - - encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient); - ourLog.info(encoded); - assertThat(encoded, not(containsString(""))); - assertThat(encoded, containsString("")); - - - } - - @Test - public void testParseNarrative() throws Exception { + public void testParseBundleNewWithPlaceholderIds() { //@formatter:off - String htmlNoNs = "
AAABBBCCC
"; - String htmlNs = htmlNoNs.replace("
", "
"); - String res= "\n" + - " \n" + - " \n" + - " " + htmlNs + "\n" + - " \n" + - ""; + String input = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, input); + assertEquals("urn:oid:0.1.2.3", parsed.getEntry().get(0).getResource().getId().getValue()); + + //@formatter:off + input = "\n" + + " \n" + + " \n" + + " \n" + // no trailing :, invalid but we'll be nice + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + parsed = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, input); + assertEquals("urn:oid:0.1.2.3", parsed.getEntry().get(0).getResource().getId().getValue()); + + } + + @Test + public void testParseBundleNewWithPlaceholderIdsInBase1() { + //@formatter:off + String input = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, input); + assertEquals("urn:oid:0.1.2.3", parsed.getEntry().get(0).getResource().getId().getValue()); + } + + @Test + public void testParseBundleNewWithPlaceholderIdsInBase2() { + //@formatter:off + String input = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, input); + assertEquals("urn:uuid:0.1.2.3", parsed.getEntry().get(0).getResource().getId().getValue()); + + //@formatter:off + input = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + parsed = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, input); + assertEquals("urn:uuid:0.1.2.3", parsed.getEntry().get(0).getResource().getId().getValue()); + + } + + @Test + public void testParseBundleOldStyleWithUnknownLinks() throws Exception { + //@formatter:off + String bundle = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; //@formatter:on - Patient p = ourCtx.newXmlParser().parseResource(Patient.class, res); - assertEquals(htmlNs, p.getText().getDiv().getValueAsString()); - } - - - - - - /** - * Thanks to Alexander Kley! - */ - @Test - public void testParseContainedBinaryResource() { - byte[] bin = new byte[] { 0, 1, 2, 3, 4 }; - final Binary binary = new Binary(); - binary.setContentType("PatientConsent").setContent(bin); - // binary.setId(UUID.randomUUID().toString()); - - ca.uhn.fhir.model.dstu2.resource.DocumentManifest manifest = new ca.uhn.fhir.model.dstu2.resource.DocumentManifest(); - // manifest.setId(UUID.randomUUID().toString()); - CodeableConceptDt cc = new CodeableConceptDt(); - cc.addCoding().setSystem("mySystem").setCode("PatientDocument"); - manifest.setType(cc); - manifest.setMasterIdentifier(new IdentifierDt().setSystem("mySystem").setValue(UUID.randomUUID().toString())); - manifest.addContent().setP(new ResourceReferenceDt(binary)); - manifest.setStatus(DocumentReferenceStatusEnum.CURRENT); - - String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(manifest); - ourLog.info(encoded); - assertThat(encoded, StringContainsInOrder.stringContainsInOrder(Arrays.asList("contained>", ""))); - - ca.uhn.fhir.model.dstu2.resource.DocumentManifest actual = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.DocumentManifest.class, encoded); - assertEquals(1, actual.getContained().getContainedResources().size()); - assertEquals(1, actual.getContent().size()); - assertNotNull(((ResourceReferenceDt)actual.getContent().get(0).getP()).getResource()); + Bundle b = ourCtx.newXmlParser().parseBundle(bundle); + assertEquals(1, b.getEntries().size()); + } @Test - public void testEncodeAndParseContained() { - IParser xmlParser = ourCtx.newXmlParser().setPrettyPrint(true); - - // Create an organization, note that the organization does not have an ID - Organization org = new Organization(); - org.getNameElement().setValue("Contained Test Organization"); - - // Create a patient - Patient patient = new Patient(); - patient.setId("Patient/1333"); - patient.addIdentifier().setSystem("urn:mrns").setValue("253345"); - - // Put the organization as a reference in the patient resource - patient.getManagingOrganization().setResource(org); - - String encoded = xmlParser.encodeResourceToString(patient); - ourLog.info(encoded); - assertThat(encoded, containsString("")); - assertThat(encoded, containsString("")); - - // Create a bundle with just the patient resource - ca.uhn.fhir.model.dstu2.resource.Bundle b = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - b.addEntry().setResource(patient); - - // Encode the bundle - encoded = xmlParser.encodeResourceToString(b); - ourLog.info(encoded); - assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", ""))); - assertThat(encoded, containsString("")); - assertThat(encoded, stringContainsInOrder(Arrays.asList("", ""))); - assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "", "")))); - - // Re-parse the bundle - patient = (Patient) xmlParser.parseResource(xmlParser.encodeResourceToString(patient)); - assertEquals("#1", patient.getManagingOrganization().getReference().getValue()); - - assertNotNull(patient.getManagingOrganization().getResource()); - org = (Organization) patient.getManagingOrganization().getResource(); - assertEquals("#1", org.getId().getValue()); - assertEquals("Contained Test Organization", org.getName()); - - // And re-encode a second time - encoded = xmlParser.encodeResourceToString(patient); - ourLog.info(encoded); - assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", "", ""))); - assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "")))); - assertThat(encoded, containsString("")); - - // And re-encode once more, with the references cleared - patient.getContained().getContainedResources().clear(); - patient.getManagingOrganization().setReference((String)null); - encoded = xmlParser.encodeResourceToString(patient); - ourLog.info(encoded); - assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", "", ""))); - assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "")))); - assertThat(encoded, containsString("")); - - // And re-encode once more, with the references cleared and a manually set local ID - patient.getContained().getContainedResources().clear(); - patient.getManagingOrganization().setReference((String)null); - patient.getManagingOrganization().getResource().setId(("#333")); - encoded = xmlParser.encodeResourceToString(patient); - ourLog.info(encoded); - assertThat(encoded, stringContainsInOrder(Arrays.asList("", "", "", ""))); - assertThat(encoded, not(stringContainsInOrder(Arrays.asList("", "")))); + public void testParseBundleOldWithPlaceholderIds() { + //@formatter:off + String input = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + Bundle parsed = ourCtx.newXmlParser().parseBundle(input); + assertEquals("urn:oid:0.1.2.3", parsed.getEntries().get(0).getResource().getId().getValue()); + + //@formatter:off + input = "\n" + + " \n" + + " \n" + + " \n" + // no trailing :, invalid but we'll be nice + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + //@formatter:on + + parsed = ourCtx.newXmlParser().parseBundle(input); + assertEquals("urn:oid:0.1.2.3", parsed.getEntries().get(0).getResource().getId().getValue()); } @Test - public void testEncodeContainedWithNarrativeIsSuppresed() throws Exception { - IParser parser = ourCtx.newXmlParser().setPrettyPrint(true); - - // Create an organization, note that the organization does not have an ID - Organization org = new Organization(); - org.getNameElement().setValue("Contained Test Organization"); - org.getText().setDiv("
FOOBAR
"); - - // Create a patient - Patient patient = new Patient(); - patient.setId("Patient/1333"); - patient.addIdentifier().setSystem("urn:mrns").setValue("253345"); - patient.getText().setDiv("
BARFOO
"); - patient.getManagingOrganization().setResource(org); - - String encoded = parser.encodeResourceToString(patient); - ourLog.info(encoded); - - assertThat(encoded, stringContainsInOrder("", "
BARFOO
", "", "", "", " medResList = new ArrayList(); - medResList.add(medResource); - ContainedDt medContainedDt = new ContainedDt(); - medContainedDt.setContainedResources(medResList); - medicationPrescript.setContained(medContainedDt); + ca.uhn.fhir.model.dstu2.resource.DocumentManifest manifest = new ca.uhn.fhir.model.dstu2.resource.DocumentManifest(); + // manifest.setId(UUID.randomUUID().toString()); + CodeableConceptDt cc = new CodeableConceptDt(); + cc.addCoding().setSystem("mySystem").setCode("PatientDocument"); + manifest.setType(cc); + manifest.setMasterIdentifier(new IdentifierDt().setSystem("mySystem").setValue(UUID.randomUUID().toString())); + manifest.addContent().setP(new ResourceReferenceDt(binary)); + manifest.setStatus(DocumentReferenceStatusEnum.CURRENT); - // Medication reference. This should point to the contained resource. - ResourceReferenceDt medRefDt = new ResourceReferenceDt("#" + medId); - medRefDt.setDisplay("MedRef"); - medicationPrescript.setMedication(medRefDt); - - IParser p = ourCtx.newXmlParser().setPrettyPrint(true); - String encoded = p.encodeResourceToString(medicationPrescript); + String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(manifest); ourLog.info(encoded); - - //@formatter:on - assertThat(encoded, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:off + assertThat(encoded, StringContainsInOrder.stringContainsInOrder(Arrays.asList("contained>", ""))); + + ca.uhn.fhir.model.dstu2.resource.DocumentManifest actual = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.DocumentManifest.class, encoded); + assertEquals(1, actual.getContained().getContainedResources().size()); + assertEquals(1, actual.getContent().size()); + assertNotNull(((ResourceReferenceDt)actual.getContent().get(0).getP()).getResource()); } - - /** - * See #113 - */ - @Test - public void testEncodeContainedResourcesManualContainUsingNonLocalId() { - - MedicationPrescription medicationPrescript = new MedicationPrescription(); - - String medId = "123"; - CodeableConceptDt codeDt = new CodeableConceptDt("urn:sys", "code1"); - - // Adding medication to Contained. - Medication medResource = new Medication(); - medResource.setCode(codeDt); - medResource.setId(String.valueOf(medId)); // ID does not start with '#' - ArrayList medResList = new ArrayList(); - medResList.add(medResource); - ContainedDt medContainedDt = new ContainedDt(); - medContainedDt.setContainedResources(medResList); - medicationPrescript.setContained(medContainedDt); - - // Medication reference. This should point to the contained resource. - ResourceReferenceDt medRefDt = new ResourceReferenceDt("#" + medId); - medRefDt.setDisplay("MedRef"); - medicationPrescript.setMedication(medRefDt); - - IParser p = ourCtx.newXmlParser().setPrettyPrint(true); - String encoded = p.encodeResourceToString(medicationPrescript); - ourLog.info(encoded); - - //@formatter:on - assertThat(encoded, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:off - - } - - /** - * See #113 - */ - @Test - public void testEncodeContainedResourcesAutomatic() { - - MedicationPrescription medicationPrescript = new MedicationPrescription(); - String nameDisp = "MedRef"; - CodeableConceptDt codeDt = new CodeableConceptDt("urn:sys", "code1"); - - // Adding medication to Contained. - Medication medResource = new Medication(); - // No ID set - medResource.setCode(codeDt); - - // Medication reference. This should point to the contained resource. - ResourceReferenceDt medRefDt = new ResourceReferenceDt(); - medRefDt.setDisplay(nameDisp); - // Resource reference set, but no ID - medRefDt.setResource(medResource); - medicationPrescript.setMedication(medRefDt); - - IParser p = ourCtx.newXmlParser().setPrettyPrint(true); - String encoded = p.encodeResourceToString(medicationPrescript); - ourLog.info(encoded); - - //@formatter:on - assertThat(encoded, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:off - } - - @Test - public void testEncodeAndParseSecurityLabels() { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - - List labels = new ArrayList(); - labels.add(new CodingDt().setSystem("SYSTEM1").setCode("CODE1").setDisplay("DISPLAY1").setPrimary(true).setVersion("VERSION1")); - labels.add(new CodingDt().setSystem("SYSTEM2").setCode("CODE2").setDisplay("DISPLAY2").setPrimary(false).setVersion("VERSION2")); - - ResourceMetadataKeyEnum.SECURITY_LABELS.put(p, labels); - - String enc = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); - ourLog.info(enc); - - //@formatter:off - assertThat(enc, stringContainsInOrder("", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - - Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); - List gotLabels = ResourceMetadataKeyEnum.SECURITY_LABELS.get(parsed); - - assertEquals(2,gotLabels.size()); - - CodingDt label = (CodingDt) gotLabels.get(0); - assertEquals("SYSTEM1", label.getSystem()); - assertEquals("CODE1", label.getCode()); - assertEquals("DISPLAY1", label.getDisplay()); - assertEquals(true, label.getPrimary()); - assertEquals("VERSION1", label.getVersion()); - - label = (CodingDt) gotLabels.get(1); - assertEquals("SYSTEM2", label.getSystem()); - assertEquals("CODE2", label.getCode()); - assertEquals("DISPLAY2", label.getDisplay()); - assertEquals(false, label.getPrimary()); - assertEquals("VERSION2", label.getVersion()); - } - - @Test - public void testEncodeAndParseMetaProfileAndTags() { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - - List profiles = new ArrayList(); - profiles.add(new IdDt("http://foo/Profile1")); - profiles.add(new IdDt("http://foo/Profile2")); - ResourceMetadataKeyEnum.PROFILES.put(p, profiles); - - TagList tagList = new TagList(); - tagList.addTag("scheme1", "term1", "label1"); - tagList.addTag("scheme2", "term2", "label2"); - ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList); - - String enc = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); - ourLog.info(enc); - - //@formatter:off - assertThat(enc, stringContainsInOrder("", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - - Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); - List gotLabels = ResourceMetadataKeyEnum.PROFILES.get(parsed); - - assertEquals(2,gotLabels.size()); - - IdDt label = (IdDt) gotLabels.get(0); - assertEquals("http://foo/Profile1", label.getValue()); - label = (IdDt) gotLabels.get(1); - assertEquals("http://foo/Profile2", label.getValue()); - - tagList = ResourceMetadataKeyEnum.TAG_LIST.get(parsed); - assertEquals(2, tagList.size()); - - assertEquals(new Tag("scheme1", "term1", "label1"), tagList.get(0)); - assertEquals(new Tag("scheme2", "term2", "label2"), tagList.get(1)); - } - - @Test - public void testEncodeAndParseMetaProfiles() { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - - TagList tagList = new TagList(); - tagList.addTag("scheme1", "term1", "label1"); - tagList.addTag("scheme2", "term2", "label2"); - ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList); - - String enc = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); - ourLog.info(enc); - - //@formatter:off - assertThat(enc, stringContainsInOrder("", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - - Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); - List gotLabels = ResourceMetadataKeyEnum.PROFILES.get(parsed); - assertNull(gotLabels); - - tagList = ResourceMetadataKeyEnum.TAG_LIST.get(parsed); - assertEquals(2, tagList.size()); - - assertEquals(new Tag("scheme1", "term1", "label1"), tagList.get(0)); - assertEquals(new Tag("scheme2", "term2", "label2"), tagList.get(1)); - } - - @Test - public void testDuration() { - Encounter enc = new Encounter(); - DurationDt duration = new DurationDt(); - duration.setUnits("day").setValue(123L); - enc.setLength(duration); - - String str = ourCtx.newXmlParser().encodeResourceToString(enc); - ourLog.info(str); - - assertThat(str, not(containsString("meta"))); - assertThat(str, containsString("")); - } - - @Test - public void testParseBundleWithBinary() { - // TODO: implement this test, make sure we handle ID and meta correctly in Binary - } - - @Test - public void testParseAndEncodeBundle() throws Exception { - String content = IOUtils.toString(XmlParserDstu2Test.class.getResourceAsStream("/bundle-example.xml")); - - Bundle parsed = ourCtx.newXmlParser().parseBundle(content); - assertEquals("http://example.com/base/Bundle/example/_history/1", parsed.getId().getValue()); - assertEquals("1", parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION)); - assertEquals("1", parsed.getId().getVersionIdPart()); - assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED)); - assertEquals("searchset", parsed.getType().getValue()); - assertEquals(3, parsed.getTotalResults().getValue().intValue()); - assertEquals("http://example.com/base", parsed.getLinkBase().getValue()); - assertEquals("https://example.com/base/MedicationPrescription?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLinkNext().getValue()); - assertEquals("https://example.com/base/MedicationPrescription?patient=347&_include=MedicationPrescription.medication", parsed.getLinkSelf().getValue()); - - assertEquals(2, parsed.getEntries().size()); - assertEquals("http://foo?search", parsed.getEntries().get(0).getLinkSearch().getValue()); - - assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", parsed.getEntries().get(0).getLinkAlternate().getValue()); - MedicationPrescription p = (MedicationPrescription) parsed.getEntries().get(0).getResource(); - assertEquals("Patient/347", p.getPatient().getReference().getValue()); - assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString()); - assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue()); - - Medication m = (Medication) parsed.getEntries().get(1).getResource(); - assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); - assertSame(p.getMedication().getResource(), m); - - String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(parsed); - ourLog.info(reencoded); - - Diff d = new Diff(new StringReader(content), new StringReader(reencoded)); - assertTrue(d.toString(), d.identical()); - - } - - @Test - public void testParseAndEncodeBundleNewStyle() throws Exception { - String content = IOUtils.toString(XmlParserDstu2Test.class.getResourceAsStream("/bundle-example.xml")); - - IParser newXmlParser = ourCtx.newXmlParser(); - ca.uhn.fhir.model.dstu2.resource.Bundle parsed = newXmlParser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, content); - assertEquals("http://example.com/base/Bundle/example/_history/1", parsed.getId().getValue()); - assertEquals("1", parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION)); - assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED)); - assertEquals("searchset", parsed.getType()); - assertEquals(3, parsed.getTotal().intValue()); - assertEquals("http://example.com/base", parsed.getBaseElement().getValueAsString()); - assertEquals("https://example.com/base/MedicationPrescription?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink().get(0).getUrlElement().getValueAsString()); - assertEquals("https://example.com/base/MedicationPrescription?patient=347&_include=MedicationPrescription.medication", parsed.getLink().get(1).getUrlElement().getValueAsString()); - - assertEquals(2, parsed.getEntry().size()); - assertEquals("alternate", parsed.getEntry().get(0).getLink().get(0).getRelation()); - assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", parsed.getEntry().get(0).getLink().get(0).getUrl()); - assertEquals("http://foo?search", parsed.getEntry().get(0).getTransaction().getUrlElement().getValueAsString()); - - MedicationPrescription p = (MedicationPrescription) parsed.getEntry().get(0).getResource(); - assertEquals("Patient/347", p.getPatient().getReference().getValue()); - assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString()); - assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue()); -// assertEquals("3123", p.getId().getValue()); - - Medication m = (Medication) parsed.getEntry().get(1).getResource(); - assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); - assertSame(p.getMedication().getResource(), m); - - String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed); - ourLog.info(reencoded); - - Diff d = new Diff(new StringReader(content), new StringReader(reencoded)); - assertTrue(d.toString(), d.identical()); - - } - - - @Test - public void testEncodeAndParseBundleWithoutResourceIds() { - Organization org = new Organization(); - org.addIdentifier().setSystem("urn:system").setValue("someval"); - - Bundle bundle = Bundle.withSingleResource(org); - String str = ourCtx.newXmlParser().encodeBundleToString(bundle); - ourLog.info(str); - - Bundle parsed = ourCtx.newXmlParser().parseBundle(str); - assertThat(parsed.getEntries().get(0).getResource().getId().getValue(), emptyOrNullString()); - assertTrue(parsed.getEntries().get(0).getResource().getId().isEmpty()); - } - - @Test - public void testBundleWithBinary() { - //@formatter:off - String bundle = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - //@formatter:on - - Bundle b = ourCtx.newXmlParser().parseBundle(bundle); - assertEquals(1, b.getEntries().size()); - - Binary bin = (Binary) b.getEntries().get(0).getResource(); - assertArrayEquals(new byte[] {1,2,3,4}, bin.getContent()); - - } - @Test public void testParseMetadata() throws Exception { @@ -1219,175 +1471,57 @@ public class XmlParserDstu2Test { } @Test - public void testParseBundleOldStyleWithUnknownLinks() throws Exception { + public void testParseNarrative() throws Exception { //@formatter:off - String bundle = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + String htmlNoNs = "
AAABBBCCC
"; + String htmlNs = htmlNoNs.replace("
", "
"); + String res= "\n" + + " \n" + + " \n" + + " " + htmlNs + "\n" + + " \n" + + ""; //@formatter:on - Bundle b = ourCtx.newXmlParser().parseBundle(bundle); - assertEquals(1, b.getEntries().size()); - - - } - - /** - * See #103 - */ - @Test - public void testEncodeAndReEncodeContainedXml() { - Composition comp = new Composition(); - comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section0_Allergy0")); - comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section1_Allergy0")); - comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section2_Allergy0")); - - IParser parser = ourCtx.newXmlParser().setPrettyPrint(true); - - String string = parser.encodeResourceToString(comp); - ourLog.info(string); - - Composition parsed = parser.parseResource(Composition.class, string); - parsed.getSection().remove(0); - - string = parser.encodeResourceToString(parsed); - ourLog.info(string); - - parsed = parser.parseResource(Composition.class, string); - assertEquals(2, parsed.getContained().getContainedResources().size()); + Patient p = ourCtx.newXmlParser().parseResource(Patient.class, res); + assertEquals(htmlNs, p.getText().getDiv().getValueAsString()); } /** - * See #103 + * See #163 */ @Test - public void testEncodeAndReEncodeContainedJson() { - Composition comp = new Composition(); - comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section0_Allergy0")); - comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section1_Allergy0")); - comp.addSection().getContent().setResource(new AllergyIntolerance().setComment("Section2_Allergy0")); + public void testParseResourceType() { + IParser xmlParser = ourCtx.newXmlParser().setPrettyPrint(true); + + // Patient + Patient patient = new Patient(); + String patientId = UUID.randomUUID().toString(); + patient.setId(new IdDt("Patient", patientId)); + patient.addName().addGiven("John").addFamily("Smith"); + patient.setGender(AdministrativeGenderEnum.MALE); + patient.setBirthDate(new DateDt("1987-04-16")); + + // Bundle + ca.uhn.fhir.model.dstu2.resource.Bundle bundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); + bundle.setType(BundleTypeEnum.COLLECTION); + bundle.addEntry().setResource(patient); + + String bundleText = xmlParser.encodeResourceToString(bundle); + ourLog.info(bundleText); - IParser parser = ourCtx.newJsonParser().setPrettyPrint(true); + ca.uhn.fhir.model.dstu2.resource.Bundle reincarnatedBundle = xmlParser.parseResource (ca.uhn.fhir.model.dstu2.resource.Bundle.class, bundleText); + Patient reincarnatedPatient = reincarnatedBundle.getAllPopulatedChildElementsOfType(Patient.class).get(0); - String string = parser.encodeResourceToString(comp); - ourLog.info(string); - - Composition parsed = parser.parseResource(Composition.class, string); - parsed.getSection().remove(0); - - string = parser.encodeResourceToString(parsed); - ourLog.info(string); - - parsed = parser.parseResource(Composition.class, string); - assertEquals(2, parsed.getContained().getContainedResources().size()); + assertEquals("Patient", patient.getId().getResourceType()); + assertEquals("Patient", reincarnatedPatient.getId().getResourceType()); } - @Test - public void testEncodeAndParseExtensions() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135"); - - ExtensionDt ext = new ExtensionDt(); - ext.setUrl("http://example.com/extensions#someext"); - ext.setValue(new DateTimeDt("2011-01-02T11:13:15")); - patient.addUndeclaredExtension(ext); - - ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent"); - patient.addUndeclaredExtension(parent); - ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1")); - parent.addUndeclaredExtension(child1); - ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value2")); - parent.addUndeclaredExtension(child2); - - ExtensionDt modExt = new ExtensionDt(); - modExt.setUrl("http://example.com/extensions#modext"); - modExt.setValue(new DateDt("1995-01-02")); - modExt.setModifier(true); - patient.addUndeclaredExtension(modExt); - - HumanNameDt name = patient.addName(); - name.addFamily("Blah"); - StringDt given = name.addGiven(); - given.setValue("Joe"); - ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given")); - given.addUndeclaredExtension(ext2); - - StringDt given2 = name.addGiven(); - given2.setValue("Shmoe"); - ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent"); - given2.addUndeclaredExtension(given2ext); - given2ext.addUndeclaredExtension(new ExtensionDt().setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD"))); - - String output = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient); - ourLog.info(output); - - String enc = ourCtx.newXmlParser().encodeResourceToString(patient); - assertThat(enc, containsString("")); - assertThat(enc, containsString("")); - assertThat( - enc, - containsString("")); - assertThat(enc, containsString("")); - assertThat(enc, containsString("")); - - /* - * Now parse this back - */ - - Patient parsed = ourCtx.newXmlParser().parseResource(Patient.class, enc); - ext = parsed.getUndeclaredExtensions().get(0); - assertEquals("http://example.com/extensions#someext", ext.getUrl()); - assertEquals("2011-01-02T11:13:15", ((DateTimeDt) ext.getValue()).getValueAsString()); - - parent = patient.getUndeclaredExtensions().get(1); - assertEquals("http://example.com#parent", parent.getUrl()); - assertNull(parent.getValue()); - child1 = parent.getExtension().get(0); - assertEquals("http://example.com#child", child1.getUrl()); - assertEquals("value1", ((StringDt) child1.getValue()).getValueAsString()); - child2 = parent.getExtension().get(1); - assertEquals("http://example.com#child", child2.getUrl()); - assertEquals("value2", ((StringDt) child2.getValue()).getValueAsString()); - - modExt = parsed.getUndeclaredModifierExtensions().get(0); - assertEquals("http://example.com/extensions#modext", modExt.getUrl()); - assertEquals("1995-01-02", ((DateDt) modExt.getValue()).getValueAsString()); - - name = parsed.getName().get(0); - - ext2 = name.getGiven().get(0).getUndeclaredExtensions().get(0); - assertEquals("http://examples.com#givenext", ext2.getUrl()); - assertEquals("given", ((StringDt) ext2.getValue()).getValueAsString()); - - given2ext = name.getGiven().get(1).getUndeclaredExtensions().get(0); - assertEquals("http://examples.com#givenext_parent", given2ext.getUrl()); - assertNull(given2ext.getValue()); - ExtensionDt given2ext2 = given2ext.getExtension().get(0); - assertEquals("http://examples.com#givenext_child", given2ext2.getUrl()); - assertEquals("CHILD", ((StringDt) given2ext2.getValue()).getValue()); - + @BeforeClass + public static void beforeClass() { + XMLUnit.setIgnoreAttributeOrder(true); + XMLUnit.setIgnoreComments(true); + XMLUnit.setIgnoreWhitespace(true); } diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 96c86d6811d..7c4655d5dde 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -84,6 +84,11 @@ now work, in order to be lenient. Thanks to Bill De Beaubien for reporting! + + When parsing Bundles, if Bundle.entry.base is set to "cid:" (for DSTU1) + or "urn:uuid:" / "urn:oid:" (for DSTU2) this is now correctly passed as + the base in resource.getId() +