HL7org unit tests all pass

This commit is contained in:
James Agnew 2015-05-01 11:09:29 -04:00
parent 9755ae8d35
commit 629bc5b7d3
16 changed files with 256 additions and 214 deletions

View File

@ -156,8 +156,11 @@ public class RuntimeChildUndeclaredExtensionDefinition extends BaseRuntimeChildD
RuntimeResourceReferenceDefinition def = new RuntimeResourceReferenceDefinition(value, types); RuntimeResourceReferenceDefinition def = new RuntimeResourceReferenceDefinition(value, types);
def.sealAndInitialize(theContext, theClassToElementDefinitions); def.sealAndInitialize(theContext, theClassToElementDefinitions);
myAttributeNameToDefinition.put(value, def); myAttributeNameToDefinition.put(value, def);
myDatatypeToDefinition.put(BaseResourceReferenceDt.class, def); myDatatypeToDefinition.put(BaseResourceReferenceDt.class, def);
myDatatypeToDefinition.put(theContext.getVersion().getResourceReferenceType(), def);
Class<? extends IBase> versionReferenceType = theContext.getVersion().getResourceReferenceType();
myDatatypeToDefinition.put(versionReferenceType, def);
} }
public static String createExtensionChildName(BaseRuntimeElementDefinition<?> next) { public static String createExtensionChildName(BaseRuntimeElementDefinition<?> next) {

View File

@ -678,7 +678,7 @@ public class JsonParser extends BaseParser implements IParser {
} }
} else if (theResource instanceof IAnyResource) { } else if (theResource instanceof IAnyResource) {
IAnyResource res = (IAnyResource) theResource; IAnyResource res = (IAnyResource) theResource;
if (theContainedResource && StringUtils.isNotBlank(res.getId().getIdPart())) { if (/*theContainedResource && */ StringUtils.isNotBlank(res.getId().getIdPart())) {
resourceId = res.getId().getIdPart(); resourceId = res.getId().getIdPart();
} }
} }

View File

@ -1959,8 +1959,10 @@ class ParserState<T> {
IDomainResource elem = (IDomainResource) getCurrentElement(); IDomainResource elem = (IDomainResource) getCurrentElement();
String resourceName = myContext.getResourceDefinition(elem).getName(); String resourceName = myContext.getResourceDefinition(elem).getName();
String versionId = elem.getMeta().getVersionId(); String versionId = elem.getMeta().getVersionId();
if (StringUtils.isNotBlank(versionId)) { if (StringUtils.isBlank(elem.getId().getIdPart())) {
elem.getIdElement().setValue(resourceName + "/" + elem.getId().getIdPart() + "/_history/" + versionId); // nothing
} else if (StringUtils.isNotBlank(versionId)) {
elem.getIdElement().setValue(resourceName + "/" + elem.getId().getIdPart() + "/_history/" + versionId);
} else { } else {
elem.getIdElement().setValue(resourceName + "/" + elem.getId().getIdPart()); elem.getIdElement().setValue(resourceName + "/" + elem.getId().getIdPart());
} }

View File

@ -35,7 +35,7 @@ import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.client.api.IRestfulClient; import ca.uhn.fhir.rest.client.api.IRestfulClient;
import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException; import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
import ca.uhn.fhir.rest.client.exceptions.FhirClientInnapropriateForServerException; import ca.uhn.fhir.rest.client.exceptions.FhirClientInappropriateForServerException;
import ca.uhn.fhir.rest.gclient.ICreate; import ca.uhn.fhir.rest.gclient.ICreate;
import ca.uhn.fhir.rest.gclient.IDelete; import ca.uhn.fhir.rest.gclient.IDelete;
import ca.uhn.fhir.rest.gclient.IFetchConformanceUntyped; import ca.uhn.fhir.rest.gclient.IFetchConformanceUntyped;
@ -116,7 +116,7 @@ public interface IGenericClient extends IRestfulClient {
* *
* @throws FhirClientConnectionException * @throws FhirClientConnectionException
* if the conformance statement cannot be read, or if the client * if the conformance statement cannot be read, or if the client
* @throws FhirClientInnapropriateForServerException * @throws FhirClientInappropriateForServerException
* If the conformance statement indicates that the server is inappropriate for this client (e.g. it implements the wrong version of FHIR) * If the conformance statement indicates that the server is inappropriate for this client (e.g. it implements the wrong version of FHIR)
*/ */
void forceConformanceCheck() throws FhirClientConnectionException; void forceConformanceCheck() throws FhirClientConnectionException;

View File

@ -51,7 +51,7 @@ import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.rest.client.api.IRestfulClient; import ca.uhn.fhir.rest.client.api.IRestfulClient;
import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException; import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
import ca.uhn.fhir.rest.client.exceptions.FhirClientInnapropriateForServerException; import ca.uhn.fhir.rest.client.exceptions.FhirClientInappropriateForServerException;
import ca.uhn.fhir.rest.method.BaseMethodBinding; import ca.uhn.fhir.rest.method.BaseMethodBinding;
import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.util.FhirTerser;
@ -316,7 +316,7 @@ public class RestfulClientFactory implements IRestfulClientFactory {
if (serverFhirVersionEnum != null) { if (serverFhirVersionEnum != null) {
FhirVersionEnum contextFhirVersion = myContext.getVersion().getVersion(); FhirVersionEnum contextFhirVersion = myContext.getVersion().getVersion();
if (!contextFhirVersion.isEquivalentTo(serverFhirVersionEnum)) { if (!contextFhirVersion.isEquivalentTo(serverFhirVersionEnum)) {
throw new FhirClientInnapropriateForServerException(myContext.getLocalizer().getMessage(RestfulClientFactory.class, "wrongVersionInConformance", theServerBase + Constants.URL_TOKEN_METADATA, serverFhirVersionString, serverFhirVersionEnum, contextFhirVersion)); throw new FhirClientInappropriateForServerException(myContext.getLocalizer().getMessage(RestfulClientFactory.class, "wrongVersionInConformance", theServerBase + Constants.URL_TOKEN_METADATA, serverFhirVersionString, serverFhirVersionEnum, contextFhirVersion));
} }
} }

View File

@ -27,19 +27,19 @@ import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
* communicate with a server which is a valid FHIR server but is incompatible * communicate with a server which is a valid FHIR server but is incompatible
* with this client for some reason. * with this client for some reason.
*/ */
public class FhirClientInnapropriateForServerException extends BaseServerResponseException { public class FhirClientInappropriateForServerException extends BaseServerResponseException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FhirClientInnapropriateForServerException(Throwable theCause) { public FhirClientInappropriateForServerException(Throwable theCause) {
super(0, theCause); super(0, theCause);
} }
public FhirClientInnapropriateForServerException(String theMessage, Throwable theCause) { public FhirClientInappropriateForServerException(String theMessage, Throwable theCause) {
super(0, theMessage, theCause); super(0, theMessage, theCause);
} }
public FhirClientInnapropriateForServerException(String theMessage) { public FhirClientInappropriateForServerException(String theMessage) {
super(0, theMessage); super(0, theMessage);
} }

View File

@ -127,8 +127,8 @@ public class FhirTerser {
if (theElement == null || theElement.isEmpty()) { if (theElement == null || theElement.isEmpty()) {
return; return;
} }
if (BaseResourceReferenceDt.class.isAssignableFrom(theElement.getClass())) { if (IReference.class.isAssignableFrom(theElement.getClass())) {
retVal.add(new ResourceReferenceInfo(theResource, thePathToElement, (BaseResourceReferenceDt)theElement)); retVal.add(new ResourceReferenceInfo(myContext, theResource, thePathToElement, (IReference)theElement));
} }
} }
@ -136,7 +136,7 @@ public class FhirTerser {
public void acceptUndeclaredExtension(ISupportsUndeclaredExtensions theContainingElement, List<String> thePathToElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition, public void acceptUndeclaredExtension(ISupportsUndeclaredExtensions theContainingElement, List<String> thePathToElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition,
ExtensionDt theNextExt) { ExtensionDt theNextExt) {
if (theNextExt.getValue() != null && BaseResourceReferenceDt.class.isAssignableFrom(theNextExt.getValue().getClass())) { if (theNextExt.getValue() != null && BaseResourceReferenceDt.class.isAssignableFrom(theNextExt.getValue().getClass())) {
retVal.add(new ResourceReferenceInfo(theResource, thePathToElement, (BaseResourceReferenceDt)theNextExt.getValue())); retVal.add(new ResourceReferenceInfo(myContext, theResource, thePathToElement, (BaseResourceReferenceDt)theNextExt.getValue()));
} }
} }
}); });

View File

@ -20,79 +20,82 @@ package ca.uhn.fhir.util;
* #L% * #L%
*/ */
import ca.uhn.fhir.model.api.Include; import java.util.Iterator;
import ca.uhn.fhir.model.api.annotation.ResourceDef; import java.util.List;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; import java.util.Set;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
import org.hl7.fhir.instance.model.IBaseResource; import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.api.IReference;
import java.util.Iterator; import ca.uhn.fhir.context.FhirContext;
import java.util.List; import ca.uhn.fhir.model.api.Include;
import java.util.Set; import ca.uhn.fhir.model.api.annotation.ResourceDef;
/** /**
* Created by Bill de Beaubien on 2/26/2015. * Created by Bill de Beaubien on 2/26/2015.
*/ */
public class ResourceReferenceInfo { public class ResourceReferenceInfo {
private String myOwningResource; private String myOwningResource;
private String myName; private String myName;
private BaseResourceReferenceDt myResource; private IReference myResource;
public ResourceReferenceInfo(IBaseResource theOwningResource, List<String> thePathToElement, BaseResourceReferenceDt theResource) { public ResourceReferenceInfo(FhirContext theContext, IBaseResource theOwningResource, List<String> thePathToElement, IReference theElement) {
myOwningResource = theOwningResource.getClass().getAnnotation(ResourceDef.class).name();
myResource = theResource;
if (thePathToElement != null && !thePathToElement.isEmpty()) {
StringBuilder sb = new StringBuilder();
thePathToElement.iterator();
for (Iterator<String> iterator = thePathToElement.iterator(); iterator.hasNext(); ) {
sb.append(iterator.next());
if (iterator.hasNext())
sb.append(".");
}
myName = sb.toString();
} else {
myName = null;
}
}
@Override myOwningResource = theContext.getResourceDefinition(theOwningResource).getName();
public String toString() {
ToStringBuilder b = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
b.append("name", myName);
b.append("resource", myResource.getReference());
return b.build();
}
public String getName() { myResource = theElement;
return myName; if (thePathToElement != null && !thePathToElement.isEmpty()) {
} StringBuilder sb = new StringBuilder();
thePathToElement.iterator();
for (Iterator<String> iterator = thePathToElement.iterator(); iterator.hasNext();) {
sb.append(iterator.next());
if (iterator.hasNext())
sb.append(".");
}
myName = sb.toString();
} else {
myName = null;
}
}
public BaseResourceReferenceDt getResourceReference() { @Override
return myResource; public String toString() {
} ToStringBuilder b = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
b.append("name", myName);
b.append("resource", myResource.getReference());
return b.build();
}
public boolean matchesIncludeSet(Set<Include> theIncludes) { public String getName() {
if (theIncludes == null) return myName;
return false; }
for (Include include : theIncludes) {
if (matchesInclude(include))
return true;
}
return false;
}
public boolean matchesInclude(Include theInclude) { public IReference getResourceReference() {
if (theInclude.getValue().equals("*")) { return myResource;
return true; }
}
if (theInclude.getValue().indexOf(':') != -1) { public boolean matchesIncludeSet(Set<Include> theIncludes) {
// DSTU2 style if (theIncludes == null)
return (theInclude.getValue().equals(myOwningResource + ':' + myName)); return false;
} else { for (Include include : theIncludes) {
// DSTU1 style if (matchesInclude(include))
return (theInclude.getValue().equals(myOwningResource + '.' + myName)); return true;
} }
} return false;
}
public boolean matchesInclude(Include theInclude) {
if (theInclude.getValue().equals("*")) {
return true;
}
if (theInclude.getValue().indexOf(':') != -1) {
// DSTU2 style
return (theInclude.getValue().equals(myOwningResource + ':' + myName));
} else {
// DSTU1 style
return (theInclude.getValue().equals(myOwningResource + '.' + myName));
}
}
} }

View File

@ -22,9 +22,10 @@ package org.hl7.fhir.instance.model.api;
import org.hl7.fhir.instance.model.IBase; import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource; import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.ICompositeType;
import org.hl7.fhir.instance.model.IPrimitiveType; import org.hl7.fhir.instance.model.IPrimitiveType;
public interface IReference extends IBase { public interface IReference extends ICompositeType {
IBaseResource getResource(); IBaseResource getResource();

View File

@ -99,15 +99,15 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
} }
} }
List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next); List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
do { do {
List<IBaseResource> addedResourcesThisPass = new ArrayList<IBaseResource>(); List<IBaseResource> addedResourcesThisPass = new ArrayList<IBaseResource>();
for (ResourceReferenceInfo nextRefInfo : references) { for (ResourceReferenceInfo nextRefInfo : references) {
if (!theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) if (!theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes))
continue; continue;
IBaseResource nextRes = (IBaseResource) nextRefInfo.getResourceReference().getResource(); IBaseResource nextRes = (IBaseResource) nextRefInfo.getResourceReference().getResource();
if (nextRes != null) { if (nextRes != null) {
if (nextRes.getId().hasIdPart()) { if (nextRes.getId().hasIdPart()) {
if (containedIds.contains(nextRes.getId().getValue())) { if (containedIds.contains(nextRes.getId().getValue())) {
@ -130,22 +130,22 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
} }
} }
includedResources.addAll(addedResourcesThisPass); includedResources.addAll(addedResourcesThisPass);
// Linked resources may themselves have linked resources // Linked resources may themselves have linked resources
references = new ArrayList<ResourceReferenceInfo>(); references = new ArrayList<ResourceReferenceInfo>();
for (IBaseResource iResource : addedResourcesThisPass) { for (IBaseResource iResource : addedResourcesThisPass) {
List<ResourceReferenceInfo> newReferences = myContext.newTerser().getAllResourceReferences(iResource); List<ResourceReferenceInfo> newReferences = myContext.newTerser().getAllResourceReferences(iResource);
references.addAll(newReferences); references.addAll(newReferences);
} }
} while (references.isEmpty() == false); } while (references.isEmpty() == false);
BundleEntryComponent entry = myBundle.addEntry().setResource((Resource) next); BundleEntryComponent entry = myBundle.addEntry().setResource((Resource) next);
// BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(next); // BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(next);
// if (searchMode != null) { // if (searchMode != null) {
// entry.getSearch().getModeElement().setValue(searchMode.getCode()); // entry.getSearch().getModeElement().setValue(searchMode.getCode());
// } // }
} }
/* /*
@ -157,7 +157,7 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
} }
@Override @Override
public void addRootPropertiesToBundle(String theAuthor, String theServerBase, String theCompleteUrl, Integer theTotalResults, BundleTypeEnum theBundleType) { public void addRootPropertiesToBundle(String theAuthor, String theServerBase, String theCompleteUrl, Integer theTotalResults, BundleTypeEnum theBundleType) {
if (myBundle.getId().isEmpty()) { if (myBundle.getId().isEmpty()) {
@ -194,7 +194,8 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
} }
@Override @Override
public void initializeBundleFromBundleProvider(RestfulServer theServer, IBundleProvider theResult, EncodingEnum theResponseEncoding, String theServerBase, String theCompleteUrl, boolean thePrettyPrint, int theOffset, Integer theLimit, String theSearchId, BundleTypeEnum theBundleType, Set<Include> theIncludes) { public void initializeBundleFromBundleProvider(RestfulServer theServer, IBundleProvider theResult, EncodingEnum theResponseEncoding, String theServerBase, String theCompleteUrl,
boolean thePrettyPrint, int theOffset, Integer theLimit, String theSearchId, BundleTypeEnum theBundleType, Set<Include> theIncludes) {
int numToReturn; int numToReturn;
String searchId = null; String searchId = null;
List<IBaseResource> resourceList; List<IBaseResource> resourceList;
@ -252,11 +253,13 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
if (searchId != null) { if (searchId != null) {
if (theOffset + numToReturn < theResult.size()) { if (theOffset + numToReturn < theResult.size()) {
myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(RestfulServerUtils.createPagingLink(theIncludes, theServerBase, searchId, theOffset + numToReturn, numToReturn, theResponseEncoding, thePrettyPrint)); myBundle.addLink().setRelation(Constants.LINK_NEXT)
.setUrl(RestfulServerUtils.createPagingLink(theIncludes, theServerBase, searchId, theOffset + numToReturn, numToReturn, theResponseEncoding, thePrettyPrint));
} }
if (theOffset > 0) { if (theOffset > 0) {
int start = Math.max(0, theOffset - limit); int start = Math.max(0, theOffset - limit);
myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(RestfulServerUtils.createPagingLink(theIncludes, theServerBase, searchId, start, limit, theResponseEncoding, thePrettyPrint)); myBundle.addLink().setRelation(Constants.LINK_PREVIOUS)
.setUrl(RestfulServerUtils.createPagingLink(theIncludes, theServerBase, searchId, start, limit, theResponseEncoding, thePrettyPrint));
} }
} }
} }
@ -273,7 +276,8 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
} }
@Override @Override
public void initializeBundleFromResourceList(String theAuthor, List<IBaseResource> theResources, String theServerBase, String theCompleteUrl, int theTotalResults, BundleTypeEnum theBundleType) { public void initializeBundleFromResourceList(String theAuthor, List<? extends IBaseResource> theResources, String theServerBase, String theCompleteUrl, int theTotalResults,
BundleTypeEnum theBundleType) {
myBundle = new Bundle(); myBundle = new Bundle();
myBundle.setId(UUID.randomUUID().toString()); myBundle.setId(UUID.randomUUID().toString());
@ -286,7 +290,7 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
if (theBundleType.equals(BundleTypeEnum.TRANSACTION)) { if (theBundleType.equals(BundleTypeEnum.TRANSACTION)) {
for (IBaseResource nextBaseRes : theResources) { for (IBaseResource nextBaseRes : theResources) {
IBaseResource next = (IBaseResource)nextBaseRes; IBaseResource next = (IBaseResource) nextBaseRes;
BundleEntryComponent nextEntry = myBundle.addEntry(); BundleEntryComponent nextEntry = myBundle.addEntry();
nextEntry.setResource((Resource) next); nextEntry.setResource((Resource) next);
@ -309,7 +313,7 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
myBundle.getTotalElement().setValue(theTotalResults); myBundle.getTotalElement().setValue(theTotalResults);
} }
private void addResourcesForSearch(List<IBaseResource> theResult) { private void addResourcesForSearch(List<? extends IBaseResource> theResult) {
List<IBaseResource> includedResources = new ArrayList<IBaseResource>(); List<IBaseResource> includedResources = new ArrayList<IBaseResource>();
Set<IIdType> addedResourceIds = new HashSet<IIdType>(); Set<IIdType> addedResourceIds = new HashSet<IIdType>();
@ -320,7 +324,7 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
} }
for (IBaseResource nextBaseRes : theResult) { for (IBaseResource nextBaseRes : theResult) {
IDomainResource next = (IDomainResource)nextBaseRes; IDomainResource next = (IDomainResource) nextBaseRes;
Set<String> containedIds = new HashSet<String>(); Set<String> containedIds = new HashSet<String>();
for (IBaseResource nextContained : next.getContained()) { for (IBaseResource nextContained : next.getContained()) {
if (nextContained.getId().isEmpty() == false) { if (nextContained.getId().isEmpty() == false) {
@ -388,7 +392,7 @@ public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
public List<IBaseResource> toListOfResources() { public List<IBaseResource> toListOfResources() {
ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>(); ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
for (BundleEntryComponent next : myBundle.getEntry()) { for (BundleEntryComponent next : myBundle.getEntry()) {
if (next.getResource()!=null) { if (next.getResource() != null) {
retVal.add(next.getResource()); retVal.add(next.getResource());
} else if (next.getTransactionResponse().getLocationElement().isEmpty() == false) { } else if (next.getTransactionResponse().getLocationElement().isEmpty() == false) {
IdType id = new IdType(next.getTransactionResponse().getLocation()); IdType id = new IdType(next.getTransactionResponse().getLocation());

View File

@ -85,6 +85,9 @@ public class XhtmlNode implements IBaseXhtml {
} }
public List<XhtmlNode> getChildNodes() { public List<XhtmlNode> getChildNodes() {
if (childNodes == null) {
childNodes = new ArrayList<XhtmlNode>();
}
return childNodes; return childNodes;
} }

View File

@ -92,8 +92,8 @@ resource.Supply=org.hl7.fhir.instance.model.Supply
resource.ValueSet=org.hl7.fhir.instance.model.ValueSet resource.ValueSet=org.hl7.fhir.instance.model.ValueSet
resource.VisionPrescription=org.hl7.fhir.instance.model.VisionPrescription resource.VisionPrescription=org.hl7.fhir.instance.model.VisionPrescription
datatype.Address=org.hl7.fhir.instance.model.AddressType datatype.Address=org.hl7.fhir.instance.model.Address
datatype.Attachment=org.hl7.fhir.instance.model.AttachmentType datatype.Attachment=org.hl7.fhir.instance.model.Attachment
datatype.CodeableConcept=org.hl7.fhir.instance.model.CodeableConceptType datatype.CodeableConcept=org.hl7.fhir.instance.model.CodeableConceptType
datatype.Coding=org.hl7.fhir.instance.model.CodingType datatype.Coding=org.hl7.fhir.instance.model.CodingType
datatype.ContactPoint=org.hl7.fhir.instance.model.ContactPointType datatype.ContactPoint=org.hl7.fhir.instance.model.ContactPointType
@ -125,3 +125,4 @@ datatype.time=org.hl7.fhir.instance.model.TimeType
datatype.unsignedInt=org.hl7.fhir.instance.model.UnsignedIntType datatype.unsignedInt=org.hl7.fhir.instance.model.UnsignedIntType
datatype.uri=org.hl7.fhir.instance.model.UriType datatype.uri=org.hl7.fhir.instance.model.UriType
datatype.xhtml=org.hl7.fhir.instance.model.XhtmlType datatype.xhtml=org.hl7.fhir.instance.model.XhtmlType
datatype.reference=org.hl7.fhir.instance.model.Reference

View File

@ -3,7 +3,9 @@ package ca.uhn.fhir.parser;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
import org.hl7.fhir.instance.model.CodeableConcept; import org.hl7.fhir.instance.model.CodeableConcept;
@ -29,7 +31,11 @@ import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.rest.server.BundleInclusionRule;
import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.provider.dstu2hl7org.Dstu2Hl7OrgBundleFactory;
/** /**
* Initially contributed by Alexander Kley for bug #29 * Initially contributed by Alexander Kley for bug #29
@ -38,26 +44,26 @@ public class ContainedResourceEncodingTest {
private static Logger logger = LoggerFactory.getLogger(ContainedResourceEncodingTest.class); private static Logger logger = LoggerFactory.getLogger(ContainedResourceEncodingTest.class);
private FhirContext ctx; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ContainedResourceEncodingTest.class);
private Composition comp;
private Practitioner author; private Practitioner author;
private Patient patient; private Composition comp;
private FhirContext ctx;
private final String patFamName1 = "FirstFamilyName"; private final String patFamName1 = "FirstFamilyName";
private final String patGivName1 = "FirstGivenName"; private final String patGivName1 = "FirstGivenName";
@Before private Patient patient;
public void initTest() {
logger.info("[initTest]");
initPatient(); private void initAuthor() {
initAuthor(); this.author = new Practitioner();
initComposition(); this.author.setId((UUID.randomUUID().toString()));
this.ctx = new FhirContext(); this.author.addIdentifier().setSystem("DoctorID").setValue("4711");
this.author.addPractitionerRole().getRole().addCoding().setCode("doctor");
this.author.setName(new HumanName().addFamily("Mueller").addGiven("Klaus").addPrefix("Prof. Dr."));
} }
@ -99,40 +105,109 @@ public class ContainedResourceEncodingTest {
} }
private void initAuthor() { @Before
this.author = new Practitioner(); public void initTest() {
this.author.setId((UUID.randomUUID().toString())); logger.info("[initTest]");
this.author.addIdentifier().setSystem("DoctorID").setValue("4711");
this.author.addPractitionerRole().getRole().addCoding().setCode("doctor"); initPatient();
this.author.setName(new HumanName().addFamily("Mueller").addGiven("Klaus").addPrefix("Prof. Dr.")); initAuthor();
initComposition();
this.ctx = new FhirContext();
} }
@Test @Test
public void testPatient() { public void testBundleWithContained() {
logger.debug("[xmlEncoding] encode resource to xml.");
/** DiagnosticReport dr = new DiagnosticReport();
* This works fine, although patient instance is modifing from encoder dr.setId(("123"));
*/
final String expectedPatientXml = this.ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(this.patient);
logger.debug("[xmlEncoding] first encoding: {}", expectedPatientXml);
final String actualPatientXml = this.ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(this.patient);
// second encoding - xml is corrupt - i.e.: patient content 4 times! should be the same as after first encoding!
logger.debug("[xmlEncoding] second encoding: {}", actualPatientXml);
Assert.assertEquals(expectedPatientXml.length(), actualPatientXml.length()); Observation observation = new Observation();
Assert.assertArrayEquals(expectedPatientXml.getBytes(), actualPatientXml.getBytes());
CodeableConcept obsName = new CodeableConcept();
obsName.setText("name");
observation.setCode(obsName);
Reference result = dr.addResult();
result.setResource(observation);
ArrayList<Reference> performers = new ArrayList<Reference>();
Reference performer = new Reference();
Practitioner p = new Practitioner();
p.setId((UUID.randomUUID().toString()));
p.addIdentifier().setSystem("DoctorID").setValue("4711");
p.addPractitionerRole().getRole().setText("Doctor");
p.setName(new HumanName().addFamily("Mueller").addGiven("Klaus").addPrefix("Prof. Dr."));
performer.setResource(p);
performers.add(performer);
observation.getPerformer().addAll(performers);
List<IBaseResource> list = new ArrayList<IBaseResource>();
list.add(dr);
Dstu2Hl7OrgBundleFactory builder = new Dstu2Hl7OrgBundleFactory(ctx);
Set<Include> inc2 = Collections.emptySet();
builder.addResourcesToBundle(list, BundleTypeEnum.TRANSACTION, "http://foo", BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE, inc2);
IBaseResource bundle = builder.getResourceBundle();
IParser parser = this.ctx.newXmlParser().setPrettyPrint(true);
String xml = parser.encodeResourceToString(bundle);
ourLog.info(xml);
Assert.assertTrue(xml.contains("Mueller"));
} }
@Test
public void testBundleWithContainedWithNoIdDt() {
DiagnosticReport dr = new DiagnosticReport();
dr.setId("123");
Observation observation = new Observation();
CodeableConcept obsName = new CodeableConcept();
obsName.setText("name");
observation.setCode(obsName);
Reference result = dr.addResult();
result.setResource(observation);
ArrayList<Reference> performers = new ArrayList<Reference>();
Reference performer = new Reference();
Practitioner p = new Practitioner();
// no idDt on practitioner p
p.addIdentifier().setSystem("DoctorID").setValue("4711");
p.addPractitionerRole().getRole().setText("Doctor");
p.setName(new HumanName().addFamily("Mueller").addGiven("Klaus").addPrefix("Prof. Dr."));
performer.setResource(p);
performers.add(performer);
observation.getPerformer().addAll(performers);
List<IBaseResource> list = new ArrayList<IBaseResource>();
list.add(dr);
Dstu2Hl7OrgBundleFactory builder = new Dstu2Hl7OrgBundleFactory(ctx);
Set<Include> inc2 = Collections.emptySet();
builder.addResourcesToBundle(list, BundleTypeEnum.TRANSACTION, "http://foo", BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE, inc2);
IBaseResource bundle = builder.getResourceBundle();
IParser parser = this.ctx.newXmlParser().setPrettyPrint(true);
String xml = parser.encodeResourceToString(bundle);
Assert.assertTrue(xml.contains("Mueller"));
}
@Test @Test
public void testComposition() { public void testComposition() {
IParser parser = this.ctx.newXmlParser().setPrettyPrint(true); IParser parser = this.ctx.newXmlParser().setPrettyPrint(true);
assertEquals(0, this.comp.getContained().size()); assertEquals(0, this.comp.getContained().size());
/** /**
* This doesn't works, secund encoding creates corrupt xml * This doesn't works, secund encoding creates corrupt xml
*/ */
@ -161,84 +236,23 @@ public class ContainedResourceEncodingTest {
Assert.assertArrayEquals(expectedCompXml.getBytes(), actualCompXml.getBytes()); Assert.assertArrayEquals(expectedCompXml.getBytes(), actualCompXml.getBytes());
} }
@Test @Test
public void testBundleWithContained() { public void testPatient() {
logger.debug("[xmlEncoding] encode resource to xml.");
DiagnosticReport dr = new DiagnosticReport();
dr.setId(("123"));
Observation observation = new Observation();
CodeableConcept obsName = new CodeableConcept();
obsName.setText("name");
observation.setCode(obsName);
Reference result = dr.addResult(); /**
result.setResource(observation); * This works fine, although patient instance is modifing from encoder
*/
final String expectedPatientXml = this.ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(this.patient);
logger.debug("[xmlEncoding] first encoding: {}", expectedPatientXml);
final String actualPatientXml = this.ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(this.patient);
// second encoding - xml is corrupt - i.e.: patient content 4 times! should be the same as after first encoding!
logger.debug("[xmlEncoding] second encoding: {}", actualPatientXml);
ArrayList<Reference> performers = new ArrayList<Reference>(); Assert.assertEquals(expectedPatientXml.length(), actualPatientXml.length());
Reference performer = new Reference(); Assert.assertArrayEquals(expectedPatientXml.getBytes(), actualPatientXml.getBytes());
Practitioner p = new Practitioner();
p.setId((UUID.randomUUID().toString()));
p.addIdentifier().setSystem("DoctorID").setValue("4711");
p.addPractitionerRole().getRole().setText("Doctor");
p.setName(new HumanName().addFamily("Mueller").addGiven("Klaus").addPrefix("Prof. Dr."));
performer.setResource(p);
performers.add(performer);
observation.getPerformer().addAll(performers);
List<IBaseResource> list = new ArrayList<IBaseResource>();
list.add(dr);
Bundle bundle = null; // RestfulServer.createBundleFromResourceList(new FhirContext(), null, list, null, null, 0);
IParser parser = this.ctx.newXmlParser().setPrettyPrint(true);
String xml = parser.encodeBundleToString(bundle);
Assert.assertTrue(xml.contains("Mueller"));
}
@Test
public void testBundleWithContainedWithNoIdDt() {
DiagnosticReport dr = new DiagnosticReport();
dr.setId("123");
Observation observation = new Observation();
CodeableConcept obsName = new CodeableConcept();
obsName.setText("name");
observation.setCode(obsName);
Reference result = dr.addResult();
result.setResource(observation);
ArrayList<Reference> performers = new ArrayList<Reference>();
Reference performer = new Reference();
Practitioner p = new Practitioner();
// no idDt on practitioner p
p.addIdentifier().setSystem("DoctorID").setValue("4711");
p.addPractitionerRole().getRole().setText("Doctor");
p.setName(new HumanName().addFamily("Mueller").addGiven("Klaus").addPrefix("Prof. Dr."));
performer.setResource(p);
performers.add(performer);
observation.getPerformer().addAll(performers);
List<IAnyResource> list = new ArrayList<IAnyResource>();
list.add(dr);
Bundle bundle = null; // RestfulServer.createBundleFromResourceList(new FhirContext(), null, list, null, null, 0);
IParser parser = this.ctx.newXmlParser().setPrettyPrint(true);
String xml = parser.encodeBundleToString(bundle);
Assert.assertTrue(xml.contains("Mueller"));
} }
} }

View File

@ -595,7 +595,7 @@ public class JsonParserHl7OrgTest {
String val = parser.encodeResourceToString(patient); String val = parser.encodeResourceToString(patient);
ourLog.info(val); ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueResource\":{\"reference\":\"Organization/123\"}}]")); assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueReference\":{\"reference\":\"Organization/123\"}}]"));
Patient actual = parser.parseResource(Patient.class, val); Patient actual = parser.parseResource(Patient.class, val);
assertEquals(AddressUse.HOME, patient.getAddress().get(0).getUse()); assertEquals(AddressUse.HOME, patient.getAddress().get(0).getUse());
@ -664,7 +664,7 @@ public class JsonParserHl7OrgTest {
out = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(b); out = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(b);
ourLog.info(out); ourLog.info(out);
// Backslashes need to be escaped because they are in a JSON value // Backslashes need to be escaped because they are in a JSON value
assertThat(out, containsString("<div>hello</div>")); assertThat(out, containsString("<xhtml:div xmlns:xhtml=\\\"http://www.w3.org/1999/xhtml\\\">hello</xhtml:div>"));
} }

View File

@ -484,7 +484,7 @@ public class XmlParserHl7OrgDstu2Test {
public void testParseNarrative() throws Exception { public void testParseNarrative() throws Exception {
//@formatter:off //@formatter:off
String htmlNoNs = "<div>AAA<b>BBB</b>CCC</div>"; String htmlNoNs = "<div>AAA<b>BBB</b>CCC</div>";
String htmlNs = htmlNoNs.replace("<div>", "<div xmlns=\"http://www.w3.org/1999/xhtml\">"); String htmlNs = fixDivNodeText(htmlNoNs);
String res= "<Patient xmlns=\"http://hl7.org/fhir\">\n" + String res= "<Patient xmlns=\"http://hl7.org/fhir\">\n" +
" <id value=\"1333\"/>\n" + " <id value=\"1333\"/>\n" +
" <text>\n" + " <text>\n" +
@ -494,7 +494,14 @@ public class XmlParserHl7OrgDstu2Test {
//@formatter:on //@formatter:on
Patient p = ourCtx.newXmlParser().parseResource(Patient.class, res); Patient p = ourCtx.newXmlParser().parseResource(Patient.class, res);
assertEquals(htmlNoNs, p.getText().getDivAsString()); assertEquals(htmlNs, p.getText().getDivAsString());
}
private String fixDivNodeText(String htmlNoNs) {
return htmlNoNs.replace("<div>", "<div xmlns=\"http://www.w3.org/1999/xhtml\">");
}
private String fixDivNodeTextJson(String htmlNoNs) {
return htmlNoNs.replace("<div>", "<div xmlns=\\\"http://www.w3.org/1999/xhtml\\\">");
} }
@Test @Test
@ -841,7 +848,7 @@ public class XmlParserHl7OrgDstu2Test {
String val = parser.encodeResourceToString(patient); String val = parser.encodeResourceToString(patient);
ourLog.info(val); ourLog.info(val);
assertThat(val, StringContains.containsString("<extension url=\"urn:foo\"><valueResource><reference value=\"Organization/123\"/></valueResource></extension>")); assertThat(val, StringContains.containsString("<extension url=\"urn:foo\"><valueReference><reference value=\"Organization/123\"/></valueReference></extension>"));
Patient actual = parser.parseResource(Patient.class, val); Patient actual = parser.parseResource(Patient.class, val);
assertEquals(AddressUse.HOME, patient.getAddress().get(0).getUse()); assertEquals(AddressUse.HOME, patient.getAddress().get(0).getUse());
@ -1062,7 +1069,7 @@ public class XmlParserHl7OrgDstu2Test {
Patient patient = ourCtx.newXmlParser().parseResource(Patient.class, msg); Patient patient = ourCtx.newXmlParser().parseResource(Patient.class, msg);
assertEquals(NarrativeStatus.GENERATED, patient.getText().getStatus()); assertEquals(NarrativeStatus.GENERATED, patient.getText().getStatus());
assertEquals("<div>John Cardinal: 444333333 </div>", patient.getText().getDiv().getValueAsString()); assertEquals("<div xmlns=\"http://www.w3.org/1999/xhtml\">John Cardinal: 444333333 </div>", patient.getText().getDiv().getValueAsString());
assertEquals("PRP1660", patient.getIdentifier().get(0).getValue()); assertEquals("PRP1660", patient.getIdentifier().get(0).getValue());
String encoded = ourCtx.newXmlParser().encodeResourceToString(patient); String encoded = ourCtx.newXmlParser().encodeResourceToString(patient);
@ -1197,6 +1204,9 @@ public class XmlParserHl7OrgDstu2Test {
Patient patient1 = ourCtx.newXmlParser().parseResource(Patient.class, msg); Patient patient1 = ourCtx.newXmlParser().parseResource(Patient.class, msg);
String encoded1 = ourCtx.newXmlParser().encodeResourceToString(patient1); String encoded1 = ourCtx.newXmlParser().encodeResourceToString(patient1);
ourLog.info("Expected: {}", msg);
ourLog.info("Actual: {}", encoded1);
Diff d = new Diff(new StringReader(msg), new StringReader(encoded1)); Diff d = new Diff(new StringReader(msg), new StringReader(encoded1));
assertTrue(d.toString(), d.identical()); assertTrue(d.toString(), d.identical());
@ -1492,8 +1502,8 @@ public class XmlParserHl7OrgDstu2Test {
JSON actual = JSONSerializer.toJSON(encoded.trim()); JSON actual = JSONSerializer.toJSON(encoded.trim());
// The encoded escapes quote marks using XML escaping instead of JSON escaping, which is probably nicer anyhow... // The encoded escapes quote marks using XML escaping instead of JSON escaping, which is probably nicer anyhow...
String exp = expected.toString().replace("\\\"Jim\\\"", "&quot;Jim&quot;"); String exp = fixDivNodeTextJson(expected.toString().replace("\\\"Jim\\\"", "&quot;Jim&quot;"));
String act = actual.toString(); String act = fixDivNodeTextJson(actual.toString());
ourLog.info("Expected: {}", exp); ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act); ourLog.info("Actual : {}", act);

View File

@ -34,6 +34,7 @@ import org.mockito.stubbing.Answer;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.primitive.UriDt; import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException; import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
import ca.uhn.fhir.rest.client.exceptions.FhirClientInappropriateForServerException;
import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.rest.server.Constants;
public class ClientServerValidationTestDstu2 { public class ClientServerValidationTestDstu2 {
@ -146,7 +147,7 @@ public class ClientServerValidationTestDstu2 {
try { try {
myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123")); myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123"));
fail(); fail();
} catch (FhirClientConnectionException e) { } catch (FhirClientInappropriateForServerException e) {
String out = e.toString(); String out = e.toString();
String want = "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2_HL7ORG (via the FhirContext)"; String want = "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2_HL7ORG (via the FhirContext)";
ourLog.info(out); ourLog.info(out);