diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/api/IGenericClient.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/api/IGenericClient.java index ef4a0020163..522652eaee1 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/api/IGenericClient.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/api/IGenericClient.java @@ -1,5 +1,6 @@ package ca.uhn.fhir.rest.client.api; +import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseResource; import ca.uhn.fhir.model.primitive.IdDt; @@ -121,7 +122,7 @@ public interface IGenericClient extends IRestfulClient { * and how it should be returned. See the specification on search * for more information. */ - IUntypedQuery search(); + IUntypedQuery search(); /** * If set to true, the client will log all requests and all responses. This is probably not a good production setting since it will result in a lot of extra logging, but it can be diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IBaseQuery.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IBaseQuery.java index 11295fd737f..ae103cbb7ef 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IBaseQuery.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IBaseQuery.java @@ -1,5 +1,9 @@ package ca.uhn.fhir.rest.gclient; +import java.util.*; + +import ca.uhn.fhir.model.api.IQueryParameterType; + /* * #%L * HAPI FHIR - Core Library @@ -24,6 +28,8 @@ public interface IBaseQuery> { T where(ICriterion theCriterion); + T where(Map> theCriterion); + T and(ICriterion theCriterion); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IClientExecutable.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IClientExecutable.java index 85af5028207..93b9717ef89 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IClientExecutable.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IClientExecutable.java @@ -27,7 +27,7 @@ import ca.uhn.fhir.rest.api.SummaryEnum; */ -public interface IClientExecutable, Y> { +public interface IClientExecutable, Y> { /** * If set to true, the client will log the request and response to the SLF4J logger. This can be useful for diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaAddOrDeleteSourced.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaAddOrDeleteSourced.java index 4e161f98dd5..c92688a3a9f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaAddOrDeleteSourced.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaAddOrDeleteSourced.java @@ -24,5 +24,5 @@ import org.hl7.fhir.instance.model.api.IBaseMetaType; public interface IMetaAddOrDeleteSourced { - IClientExecutable, T> meta(T theMeta); + IClientExecutable, T> meta(T theMeta); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaGetUnsourced.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaGetUnsourced.java index b08c763a43b..9c0e6832ab1 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaGetUnsourced.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IMetaGetUnsourced.java @@ -10,7 +10,7 @@ package ca.uhn.fhir.rest.gclient; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,16 +25,16 @@ import org.hl7.fhir.instance.model.api.IIdType; public interface IMetaGetUnsourced { - IClientExecutable, T> fromServer(); - - IClientExecutable, T> fromType(String theResourceName); + IClientExecutable, T> fromServer(); + + IClientExecutable, T> fromType(String theResourceName); /** - * Get the meta from a resource instance by ID. + * Get the meta from a resource instance by ID. * - * @param theId The ID. Must contain both a resource type and an ID part + * @param theId + * The ID. Must contain both a resource type and an ID part */ - IClientExecutable, T> fromResource(IIdType theId); - + IClientExecutable, T> fromResource(IIdType theId); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQuery.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQuery.java index dc06356a822..9bc62219120 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQuery.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQuery.java @@ -28,7 +28,7 @@ import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.api.SearchStyleEnum; import ca.uhn.fhir.rest.param.DateRangeParam; -public interface IQuery extends IBaseQuery { +public interface IQuery extends IBaseQuery>, IClientExecutable, Y> { /** * Add an "_include" specification or an "_include:recurse" specification. If you are using @@ -39,9 +39,9 @@ public interface IQuery extends IBaseQuery { *
  • No Recurse: .include(Patient.INCLUDE_ORGANIZATION.asNonRecursive()) * */ - IQuery include(Include theInclude); + IQuery include(Include theInclude); - ISort sort(); + ISort sort(); /** * Specifies the _count parameter, which indicates to the server how many resources should be returned @@ -50,7 +50,7 @@ public interface IQuery extends IBaseQuery { * @deprecated This parameter is badly named, since FHIR calls this parameter "_count" and not "_limit". Use {@link #count(int)} instead (it also sets the _count parameter) */ @Deprecated - IQuery limitTo(int theLimitTo); + IQuery limitTo(int theLimitTo); /** * Specifies the _count parameter, which indicates to the server how many resources should be returned @@ -58,7 +58,7 @@ public interface IQuery extends IBaseQuery { * * @since 1.4 */ - IQuery count(int theCount); + IQuery count(int theCount); /** * Match only resources where the resource has the given tag. This parameter corresponds to @@ -66,7 +66,7 @@ public interface IQuery extends IBaseQuery { * @param theSystem The tag code system, or null to match any code system (this may not be supported on all servers) * @param theCode The tag code. Must not be null or empty. */ - IQuery withTag(String theSystem, String theCode); + IQuery withTag(String theSystem, String theCode); /** * Match only resources where the resource has the given security tag. This parameter corresponds to @@ -74,21 +74,21 @@ public interface IQuery extends IBaseQuery { * @param theSystem The tag code system, or null to match any code system (this may not be supported on all servers) * @param theCode The tag code. Must not be null or empty. */ - IQuery withSecurity(String theSystem, String theCode); + IQuery withSecurity(String theSystem, String theCode); /** * Match only resources where the resource has the given profile declaration. This parameter corresponds to * the _profile URL parameter. * @param theProfileUri The URI of a given profile to search for resources which match */ - IQuery withProfile(String theProfileUri); + IQuery withProfile(String theProfileUri); /** * Matches any of the profiles given as argument. This would result in an OR search for resources matching one or more profiles. * To do an AND search, make multiple calls to {@link #withProfile(String)}. * @param theProfileUris The URIs of a given profile to search for resources which match. */ - IQuery withAnyProfile(Collection theProfileUris); + IQuery withAnyProfile(Collection theProfileUris); /** * Forces the query to perform the search using the given method (allowable methods are described in the @@ -100,44 +100,44 @@ public interface IQuery extends IBaseQuery { * @see SearchStyleEnum * @since 0.6 */ - IQuery usingStyle(SearchStyleEnum theStyle); + IQuery usingStyle(SearchStyleEnum theStyle); - IQuery withIdAndCompartment(String theResourceId, String theCompartmentName); + IQuery withIdAndCompartment(String theResourceId, String theCompartmentName); /** * Add a "_revinclude" specification * * @since HAPI FHIR 1.0 - Note that option was added to FHIR itself in DSTU2 */ - IQuery revInclude(Include theIncludeTarget); + IQuery revInclude(Include theIncludeTarget); /** * Add a "_lastUpdated" specification * * @since HAPI FHIR 1.1 - Note that option was added to FHIR itself in DSTU2 */ - IQuery lastUpdated(DateRangeParam theLastUpdated); + IQuery lastUpdated(DateRangeParam theLastUpdated); /** * Request that the client return the specified bundle type, e.g. org.hl7.fhir.instance.model.Bundle.class * or ca.uhn.fhir.model.dstu2.resource.Bundle.class */ - IQueryTyped returnBundle(Class theClass); + IQuery returnBundle(Class theClass); /** * {@inheritDoc} */ // This is here as an overridden method to allow mocking clients with Mockito to work @Override - IQuery where(ICriterion theCriterion); + IQuery where(ICriterion theCriterion); /** * {@inheritDoc} */ // This is here as an overridden method to allow mocking clients with Mockito to work @Override - IQuery and(ICriterion theCriterion); + IQuery and(ICriterion theCriterion); -// T execute(); +// Y execute(); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQueryTyped.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQueryTyped.java deleted file mode 100644 index af8bb1877ce..00000000000 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IQueryTyped.java +++ /dev/null @@ -1,7 +0,0 @@ -package ca.uhn.fhir.rest.gclient; - -import org.hl7.fhir.instance.model.api.IBaseBundle; - -public interface IQueryTyped extends IQuery, IClientExecutable, T> { - -} diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/ISort.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/ISort.java index 72fdcaaaa5f..58807b32839 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/ISort.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/ISort.java @@ -20,19 +20,19 @@ package ca.uhn.fhir.rest.gclient; * #L% */ -public interface ISort { +public interface ISort { /** * Sort ascending */ - IQuery ascending(IParam theParam); + IQuery ascending(IParam theParam); /** * Sort ascending * * @param theParam The param name, e.g. "address" */ - IQuery ascending(String theParam); + IQuery ascending(String theParam); /** * Sort by the default order. Note that as of STU3, there is no longer @@ -40,7 +40,7 @@ public interface ISort { * technically implies "ascending" but it makes more sense to use * {@link #ascending(IParam)} */ - IQuery defaultOrder(IParam theParam); + IQuery defaultOrder(IParam theParam); /** * Sort descending @@ -48,13 +48,13 @@ public interface ISort { * @param theParam A query param - Could be a constant such as Patient.ADDRESS or a custom * param such as new StringClientParam("foo") */ - IQuery descending(IParam theParam); + IQuery descending(IParam theParam); /** * Sort ascending * * @param theParam The param name, e.g. "address" */ - IQuery descending(String theParam); + IQuery descending(String theParam); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IUntypedQuery.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IUntypedQuery.java index 822f7124763..082e7206e62 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IUntypedQuery.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IUntypedQuery.java @@ -22,13 +22,13 @@ package ca.uhn.fhir.rest.gclient; import org.hl7.fhir.instance.model.api.IBaseResource; -public interface IUntypedQuery { +public interface IUntypedQuery { - IQuery forAllResources(); + IQuery forAllResources(); - IQuery forResource(String theResourceName); + IQuery forResource(String theResourceName); - IQuery forResource(Class theClass); + IQuery forResource(Class theClass); /** * Perform a search directly by URL. It is usually better to construct the URL using the {@link #forAllResources()}, {@link #forResource(Class)} etc, but sometimes it is useful to simply search by @@ -38,6 +38,6 @@ public interface IUntypedQuery { * The URL to search for. Note that this URL may be complete (e.g. "http://example.com/base/Patient?name=foo") in which case the client's base URL will be ignored. Or it can be relative * (e.g. "Patient?name=foo") in which case the client's base URL will be used. */ - IQuery byUrl(String theSearchUrl); + IQuery byUrl(String theSearchUrl); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseParamWithPrefix.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseParamWithPrefix.java index 6d326ef520d..a1315267d3c 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseParamWithPrefix.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseParamWithPrefix.java @@ -1,8 +1,11 @@ package ca.uhn.fhir.rest.param; +import static org.apache.commons.lang3.StringUtils.isBlank; + public abstract class BaseParamWithPrefix extends BaseParam { private static final long serialVersionUID = 1L; + private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseParamWithPrefix.class); private ParamPrefixEnum myPrefix; @@ -32,8 +35,40 @@ public abstract class BaseParamWithPrefix extends BaseParam } String prefix = theString.substring(0, offset); - myPrefix = ParamPrefixEnum.forValue(prefix); - + if (!isBlank(prefix)) { + + myPrefix = ParamPrefixEnum.forValue(prefix); + + if (myPrefix == null) { + switch (prefix) { + case ">=": + myPrefix = ParamPrefixEnum.GREATERTHAN_OR_EQUALS; + break; + case ">": + myPrefix = ParamPrefixEnum.GREATERTHAN; + break; + case "<=": + myPrefix = ParamPrefixEnum.LESSTHAN_OR_EQUALS; + break; + case "<": + myPrefix = ParamPrefixEnum.LESSTHAN; + break; + case "~": + myPrefix = ParamPrefixEnum.APPROXIMATE; + break; + default : + ourLog.warn("Invalid prefix being ignored: {}", prefix); + break; + } + + if (myPrefix != null) { + ourLog.warn("Date parameter has legacy prefix '{}' which has been removed from FHIR. This should be replaced with '{}'", prefix, myPrefix); + } + + } + + } + return theString.substring(offset); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/BundleUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/BundleUtil.java index 476d2dfd8cb..c25c3aaf67f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/BundleUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/BundleUtil.java @@ -143,8 +143,9 @@ public class BundleUtil { /** * Extract all of the resources of a given type from a given bundle */ - public static List toListOfResourcesOfType(FhirContext theContext, IBaseBundle theBundle, Class theTypeToInclude) { - List retVal = new ArrayList(); + @SuppressWarnings("unchecked") + public static List toListOfResourcesOfType(FhirContext theContext, IBaseBundle theBundle, Class theTypeToInclude) { + List retVal = new ArrayList(); RuntimeResourceDefinition def = theContext.getResourceDefinition(theBundle); BaseRuntimeChildDefinition entryChild = def.getChildByName("entry"); @@ -157,7 +158,7 @@ public class BundleUtil { if (theTypeToInclude != null && !theTypeToInclude.isAssignableFrom(next.getClass())) { continue; } - retVal.add((IBaseResource) next); + retVal.add((T) next); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/BaseValidationContext.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/BaseValidationContext.java index 2d8fa7a9db4..9f7b7ff2360 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/BaseValidationContext.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/BaseValidationContext.java @@ -29,10 +29,15 @@ import ca.uhn.fhir.util.ObjectUtil; abstract class BaseValidationContext implements IValidationContext { protected final FhirContext myFhirContext; - private List myMessages = new ArrayList(); + private List myMessages; BaseValidationContext(FhirContext theFhirContext) { + this(theFhirContext, new ArrayList()); + } + + BaseValidationContext(FhirContext theFhirContext, List theMessages) { myFhirContext = theFhirContext; + myMessages = theMessages; } @Override @@ -46,6 +51,11 @@ abstract class BaseValidationContext implements IValidationContext { return myFhirContext; } + @Override + public List getMessages() { + return myMessages; + } + @Override public ValidationResult toResult() { return new ValidationResult(myFhirContext, myMessages); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/IValidationContext.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/IValidationContext.java index 7534ba4717a..cf05dc31ab1 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/IValidationContext.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/IValidationContext.java @@ -1,5 +1,7 @@ package ca.uhn.fhir.validation; +import java.util.List; + /* * #%L * HAPI FHIR - Core Library @@ -35,6 +37,8 @@ public interface IValidationContext { void addValidationMessage(SingleValidationMessage theMessage); + List getMessages(); + ValidationResult toResult(); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/ValidationContext.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/ValidationContext.java index 27e7c86f46a..9209bd088a7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/ValidationContext.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/ValidationContext.java @@ -1,5 +1,8 @@ package ca.uhn.fhir.validation; +import java.util.ArrayList; +import java.util.List; + /* * #%L * HAPI FHIR - Core Library @@ -37,7 +40,11 @@ public class ValidationContext extends BaseValidationContext implements IV private final EncodingEnum myResourceAsStringEncoding; private ValidationContext(FhirContext theContext, T theResource, IEncoder theEncoder) { - super(theContext); + this(theContext, theResource, theEncoder, new ArrayList()); + } + + private ValidationContext(FhirContext theContext, T theResource, IEncoder theEncoder, List theMessages) { + super(theContext, theMessages); myResource = theResource; myEncoder = theEncoder; if (theEncoder != null) { @@ -123,4 +130,18 @@ public class ValidationContext extends BaseValidationContext implements IV }; } + + public static IValidationContext subContext(final IValidationContext theCtx, final IBaseResource theResource) { + return new ValidationContext(theCtx.getFhirContext(), theResource, new IEncoder() { + @Override + public String encode() { + return theCtx.getFhirContext().newXmlParser().encodeResourceToString(theResource); + } + + @Override + public EncodingEnum getEncoding() { + return EncodingEnum.XML; + } + }, theCtx.getMessages()); + } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java index 17746893f8f..cc914f897a2 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java @@ -27,6 +27,7 @@ import java.util.*; import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.IOUtils; +import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseResource; import org.oclc.purl.dsdl.svrl.SchematronOutputType; @@ -39,6 +40,7 @@ import com.phloc.schematron.xslt.SchematronResourceSCH; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; +import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.validation.*; /** @@ -57,6 +59,14 @@ public class SchematronBaseValidator implements IValidatorModule { @Override public void validateResource(IValidationContext theCtx) { + if (theCtx.getResource() instanceof IBaseBundle) { + IBaseBundle bundle = (IBaseBundle) theCtx.getResource(); + List subResources = BundleUtil.toListOfResources(myCtx, bundle); + for (IBaseResource nextSubResource : subResources) { + validateResource(ValidationContext.subContext(theCtx, nextSubResource)); + } + } + ISchematronResource sch = getSchematron(theCtx); String resourceAsString; if (theCtx.getResourceAsStringEncoding() == EncodingEnum.XML) { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/impl/GenericClient.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/impl/GenericClient.java index 9d0cd2abb8e..4fe8224cba9 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/impl/GenericClient.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/impl/GenericClient.java @@ -25,6 +25,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.io.IOException; import java.io.Reader; import java.util.*; +import java.util.Map.Entry; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -75,13 +76,11 @@ public class GenericClient extends BaseClient implements IGenericClient { return new CreateInternal(); } - @Override public IDelete delete() { return new DeleteInternal(); } - private T doReadOrVRead(final Class theType, IIdType theId, boolean theVRead, ICallable theNotModifiedHandler, String theIfVersionMatches, Boolean thePrettyPrint, SummaryEnum theSummary, EncodingEnum theEncoding, Set theSubsetElements) { String resName = toResourceName(theType); @@ -165,15 +164,11 @@ public class GenericClient extends BaseClient implements IGenericClient { return theResource.getIdElement().getIdPart(); } - @Override public IHistory history() { return new HistoryInternal(); } - - - // @Override // public T read(final Class theType, IdDt theId) { // return doReadOrVRead(theType, theId, false, null, null); @@ -204,6 +199,11 @@ public class GenericClient extends BaseClient implements IGenericClient { return new OperationInternal(); } + @Override + public IPatch patch() { + return new PatchInternal(); + } + @Override public IRead read() { return new ReadInternal(); @@ -234,12 +234,12 @@ public class GenericClient extends BaseClient implements IGenericClient { return read(def.getImplementingClass(), id); } + @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public IUntypedQuery search() { return new SearchInternal(); } - /** * For now, this is a part of the internal API of HAPI - Use with caution as this method may change! */ @@ -262,12 +262,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return new TransactionInternal(); } - - @Override - public IPatch patch() { - return new PatchInternal(); - } - @Override public IUpdate update() { return new UpdateInternal(); @@ -366,18 +360,13 @@ public class GenericClient extends BaseClient implements IGenericClient { return b.toString(); } - private abstract class BaseClientExecutable, Y> implements IClientExecutable { + private abstract class BaseClientExecutable, Y> implements IClientExecutable { protected EncodingEnum myParamEncoding; - private List> myPreferResponseTypes; - protected Boolean myPrettyPrint; - private boolean myQueryLogRequestAndResponse; - private HashSet mySubsetElements; - protected SummaryEnum mySummaryMode; @Deprecated // override deprecated method @@ -491,25 +480,61 @@ public class GenericClient extends BaseClient implements IGenericClient { } + private abstract class BaseSearch, QUERY extends IBaseQuery, OUTPUT> extends BaseClientExecutable implements IBaseQuery { - private class CreateInternal extends BaseClientExecutable implements ICreate, ICreateTyped, ICreateWithQuery, ICreateWithQueryTyped { + private Map> myParams = new LinkedHashMap<>(); - private CriterionList myCriterionList; + @Override + public QUERY and(ICriterion theCriterion) { + return where(theCriterion); + } + + public Map> getParamMap() { + return myParams; + } + + @SuppressWarnings("unchecked") + @Override + public QUERY where(ICriterion theCriterion) { + ICriterionInternal criterion = (ICriterionInternal) theCriterion; + + String parameterName = criterion.getParameterName(); + String parameterValue = criterion.getParameterValue(myContext); + if (isNotBlank(parameterValue)) { + addParam(myParams, parameterName, parameterValue); + } + + return (QUERY) this; + } + + @SuppressWarnings("unchecked") + @Override + public QUERY where(Map> theCriterion) { + Validate.notNull(theCriterion, "theCriterion must not be null"); + for (Entry> nextEntry : theCriterion.entrySet()) { + String nextKey = nextEntry.getKey(); + List nextValues = nextEntry.getValue(); + for (IQueryParameterType nextValue : nextValues) { + addParam(myParams, nextKey, nextValue.getValueAsQueryToken(myContext)); + } + } + return (QUERY) this; + } + + } + + private class CreateInternal extends BaseSearch implements ICreate, ICreateTyped, ICreateWithQuery, ICreateWithQueryTyped { + + private boolean myConditional; private String myId; private PreferReturnEnum myPrefer; private IBaseResource myResource; private String myResourceBody; private String mySearchUrl; - @Override - public ICreateWithQueryTyped and(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - @Override public ICreateWithQuery conditional() { - myCriterionList = new CriterionList(); + myConditional = true; return this; } @@ -534,8 +559,8 @@ public class GenericClient extends BaseClient implements IGenericClient { BaseHttpClientInvocation invocation; if (mySearchUrl != null) { invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext, mySearchUrl); - } else if (myCriterionList != null) { - invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext, myCriterionList.toParamList()); + } else if (myConditional) { + invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext, getParamMap()); } else { invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext); } @@ -569,12 +594,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } - @Override - public ICreateWithQueryTyped where(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - @Override public CreateInternal withId(IdDt theId) { myId = theId.getIdPart(); @@ -589,49 +608,20 @@ public class GenericClient extends BaseClient implements IGenericClient { } - private class CriterionList extends ArrayList { + private class DeleteInternal extends BaseSearch implements IDelete, IDeleteTyped, IDeleteWithQuery, IDeleteWithQueryTyped { - private static final long serialVersionUID = 1L; - - public void populateParamList(Map> theParams) { - for (ICriterionInternal next : this) { - String parameterName = next.getParameterName(); - String parameterValue = next.getParameterValue(myContext); - if (isNotBlank(parameterValue)) { - addParam(theParams, parameterName, parameterValue); - } - } - } - - public Map> toParamList() { - LinkedHashMap> retVal = new LinkedHashMap>(); - populateParamList(retVal); - return retVal; - } - - } - - private class DeleteInternal extends BaseClientExecutable implements IDelete, IDeleteTyped, IDeleteWithQuery, IDeleteWithQueryTyped { - - private CriterionList myCriterionList; + private boolean myConditional; private IIdType myId; private String myResourceType; private String mySearchUrl; - @Override - public IDeleteWithQueryTyped and(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - @Override public IBaseOperationOutcome execute() { HttpDeleteClientInvocation invocation; if (myId != null) { invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), myId); - } else if (myCriterionList != null) { - Map> params = myCriterionList.toParamList(); - invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), myResourceType, params); + } else if (myConditional) { + invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), myResourceType, getParamMap()); } else { invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), mySearchUrl); } @@ -679,7 +669,7 @@ public class GenericClient extends BaseClient implements IGenericClient { @Override public IDeleteWithQuery resourceConditionalByType(Class theResourceType) { Validate.notNull(theResourceType, "theResourceType can not be null"); - myCriterionList = new CriterionList(); + myConditional = true; myResourceType = myContext.getResourceDefinition(theResourceType).getName(); return this; } @@ -691,7 +681,7 @@ public class GenericClient extends BaseClient implements IGenericClient { throw new IllegalArgumentException("Unknown resource type: " + theResourceType); } myResourceType = theResourceType; - myCriterionList = new CriterionList(); + myConditional = true; return this; } @@ -701,11 +691,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } - @Override - public IDeleteWithQueryTyped where(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -755,7 +740,6 @@ public class GenericClient extends BaseClient implements IGenericClient { } - @SuppressWarnings("rawtypes") private class HistoryInternal extends BaseClientExecutable implements IHistory, IHistoryUntyped, IHistoryTyped { @@ -854,7 +838,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return new GetPageInternal(myPageUrl, theBundleType); } - @Override public IGetPageUntyped byUrl(String thePageUrl) { if (isBlank(thePageUrl)) { @@ -864,7 +847,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } - @Override public IGetPageTyped next(T theBundle) { return nextOrPrevious("next", theBundle); @@ -898,13 +880,11 @@ public class GenericClient extends BaseClient implements IGenericClient { throw new IllegalArgumentException(myContext.getLocalizer().getMessage(GenericClient.class, "noPagingLinkFoundInBundle", theWantRel)); } - @Override public IGetPageTyped previous(T theBundle) { return nextOrPrevious(PREVIOUS, theBundle); } - } @SuppressWarnings("rawtypes") @@ -993,7 +973,7 @@ public class GenericClient extends BaseClient implements IGenericClient { @SuppressWarnings("unchecked") @Override - public IClientExecutable, T> meta(T theMeta) { + public IClientExecutable, T> meta(T theMeta) { Validate.notNull(theMeta, "theMeta must not be null"); myMeta = theMeta; myMetaType = myMeta.getClass(); @@ -1062,56 +1042,15 @@ public class GenericClient extends BaseClient implements IGenericClient { implements IOperation, IOperationUnnamed, IOperationUntyped, IOperationUntypedWithInput, IOperationUntypedWithInputAndPartialOutput, IOperationProcessMsg, IOperationProcessMsgMode { private IIdType myId; + private Boolean myIsAsync; + private IBaseBundle myMsgBundle; private String myOperationName; private IBaseParameters myParameters; private RuntimeResourceDefinition myParametersDef; + private String myResponseUrl; + private Class myReturnResourceType; private Class myType; private boolean myUseHttpGet; - private Class myReturnResourceType; - private IBaseBundle myMsgBundle; - private String myResponseUrl; - private Boolean myIsAsync; - - @SuppressWarnings("unchecked") - @Override - public IOperationProcessMsgMode setMessageBundle(IBaseBundle theMsgBundle) { - - Validate.notNull(theMsgBundle, "theMsgBundle must not be null"); - /* - * Validate.isTrue(theMsgBundle.getType().getValueAsEnum() == BundleTypeEnum.MESSAGE); - * Validate.isTrue(theMsgBundle.getEntries().size() > 0); - * Validate.notNull(theMsgBundle.getEntries().get(0).getResource(), "Message Bundle first entry must be a MessageHeader resource"); - * Validate.isTrue(theMsgBundle.getEntries().get(0).getResource().getResourceName().equals("MessageHeader"), "Message Bundle first entry must be a MessageHeader resource"); - */ - myMsgBundle = theMsgBundle; - return this; - } - - @Override - public IOperationProcessMsg setResponseUrlParam(String responseUrl) { - Validate.notEmpty(responseUrl, "responseUrl must not be null"); - Validate.matchesPattern(responseUrl, "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]", "responseUrl must be a valid URL"); - myResponseUrl = responseUrl; - return this; - } - - @Override - public IOperationProcessMsgMode asynchronous(Class theResponseClass) { - myIsAsync = true; - Validate.notNull(theResponseClass, "theReturnType must not be null"); - Validate.isTrue(IBaseResource.class.isAssignableFrom(theResponseClass), "theReturnType must be a class which extends from IBaseResource"); - myReturnResourceType = theResponseClass; - return this; - } - - @Override - public IOperationProcessMsgMode synchronous(Class theResponseClass) { - myIsAsync = false; - Validate.notNull(theResponseClass, "theReturnType must not be null"); - Validate.isTrue(IBaseResource.class.isAssignableFrom(theResponseClass), "theReturnType must be a class which extends from IBaseResource"); - myReturnResourceType = theResponseClass; - return this; - } @SuppressWarnings("unchecked") private void addParam(String theName, IBase theValue) { @@ -1143,12 +1082,6 @@ public class GenericClient extends BaseClient implements IGenericClient { } } - @Override - public IOperationProcessMsg processMessage() { - myOperationName = Constants.EXTOP_PROCESS_MESSAGE; - return this; - } - private void addParam(String theName, IQueryParameterType theValue) { IPrimitiveType stringType = ParametersUtil.createString(myContext, theValue.getValueAsQueryToken(myContext)); addParam(theName, stringType); @@ -1169,6 +1102,15 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } + @Override + public IOperationProcessMsgMode asynchronous(Class theResponseClass) { + myIsAsync = true; + Validate.notNull(theResponseClass, "theReturnType must not be null"); + Validate.isTrue(IBaseResource.class.isAssignableFrom(theResponseClass), "theReturnType must be a class which extends from IBaseResource"); + myReturnResourceType = theResponseClass; + return this; + } + @SuppressWarnings("unchecked") @Override public Object execute() { @@ -1259,6 +1201,52 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } + @Override + public IOperationProcessMsg processMessage() { + myOperationName = Constants.EXTOP_PROCESS_MESSAGE; + return this; + } + + @Override + public IOperationUntypedWithInput returnResourceType(Class theReturnType) { + Validate.notNull(theReturnType, "theReturnType must not be null"); + Validate.isTrue(IBaseResource.class.isAssignableFrom(theReturnType), "theReturnType must be a class which extends from IBaseResource"); + myReturnResourceType = theReturnType; + return this; + } + + @SuppressWarnings("unchecked") + @Override + public IOperationProcessMsgMode setMessageBundle(IBaseBundle theMsgBundle) { + + Validate.notNull(theMsgBundle, "theMsgBundle must not be null"); + /* + * Validate.isTrue(theMsgBundle.getType().getValueAsEnum() == BundleTypeEnum.MESSAGE); + * Validate.isTrue(theMsgBundle.getEntries().size() > 0); + * Validate.notNull(theMsgBundle.getEntries().get(0).getResource(), "Message Bundle first entry must be a MessageHeader resource"); + * Validate.isTrue(theMsgBundle.getEntries().get(0).getResource().getResourceName().equals("MessageHeader"), "Message Bundle first entry must be a MessageHeader resource"); + */ + myMsgBundle = theMsgBundle; + return this; + } + + @Override + public IOperationProcessMsg setResponseUrlParam(String responseUrl) { + Validate.notEmpty(responseUrl, "responseUrl must not be null"); + Validate.matchesPattern(responseUrl, "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]", "responseUrl must be a valid URL"); + myResponseUrl = responseUrl; + return this; + } + + @Override + public IOperationProcessMsgMode synchronous(Class theResponseClass) { + myIsAsync = false; + Validate.notNull(theResponseClass, "theReturnType must not be null"); + Validate.isTrue(IBaseResource.class.isAssignableFrom(theResponseClass), "theReturnType must be a class which extends from IBaseResource"); + myReturnResourceType = theResponseClass; + return this; + } + @Override public IOperationUntypedWithInput useHttpGet() { myUseHttpGet = true; @@ -1319,14 +1307,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } - @Override - public IOperationUntypedWithInput returnResourceType(Class theReturnType) { - Validate.notNull(theReturnType, "theReturnType must not be null"); - Validate.isTrue(IBaseResource.class.isAssignableFrom(theReturnType), "theReturnType must be a class which extends from IBaseResource"); - myReturnResourceType = theReturnType; - return this; - } - } private final class OperationOutcomeResponseHandler implements IClientResponseHandler { @@ -1386,6 +1366,119 @@ public class GenericClient extends BaseClient implements IGenericClient { } } + private class PatchInternal extends BaseSearch implements IPatch, IPatchWithBody, IPatchExecutable, IPatchWithQuery, IPatchWithQueryTyped { + + private boolean myConditional; + private IIdType myId; + private String myPatchBody; + private PatchTypeEnum myPatchType; + private PreferReturnEnum myPrefer; + private String myResourceType; + private String mySearchUrl; + + @Override + public IPatchWithQuery conditional(Class theClass) { + Validate.notNull(theClass, "theClass must not be null"); + String resourceType = myContext.getResourceDefinition(theClass).getName(); + return conditional(resourceType); + } + + @Override + public IPatchWithQuery conditional(String theResourceType) { + Validate.notBlank(theResourceType, "theResourceType must not be null"); + myResourceType = theResourceType; + myConditional = true; + return this; + } + + // TODO: This is not longer used.. Deprecate it or just remove it? + @Override + public IPatchWithBody conditionalByUrl(String theSearchUrl) { + mySearchUrl = validateAndEscapeConditionalUrl(theSearchUrl); + return this; + } + + @Override + public MethodOutcome execute() { + + if (myPatchType == null) { + throw new InvalidRequestException("No patch type supplied, cannot invoke server"); + } + if (myPatchBody == null) { + throw new InvalidRequestException("No patch body supplied, cannot invoke server"); + } + + BaseHttpClientInvocation invocation; + if (isNotBlank(mySearchUrl)) { + invocation = MethodUtil.createPatchInvocation(myContext, mySearchUrl, myPatchType, myPatchBody); + } else if (myConditional) { + invocation = MethodUtil.createPatchInvocation(myContext, myPatchType, myPatchBody, myResourceType, getParamMap()); + } else { + if (myId == null || myId.hasIdPart() == false) { + throw new InvalidRequestException("No ID supplied for resource to patch, can not invoke server"); + } + invocation = MethodUtil.createPatchInvocation(myContext, myId, myPatchType, myPatchBody); + } + + addPreferHeader(myPrefer, invocation); + + OutcomeResponseHandler binding = new OutcomeResponseHandler(myPrefer); + + Map> params = new HashMap>(); + return invoke(params, binding, invocation); + + } + + @Override + public IPatchExecutable prefer(PreferReturnEnum theReturn) { + myPrefer = theReturn; + return this; + } + + @Override + public IPatchWithBody withBody(String thePatchBody) { + Validate.notBlank(thePatchBody, "thePatchBody must not be blank"); + + myPatchBody = thePatchBody; + + EncodingEnum encoding = EncodingEnum.detectEncodingNoDefault(thePatchBody); + if (encoding == EncodingEnum.XML) { + myPatchType = PatchTypeEnum.XML_PATCH; + } else if (encoding == EncodingEnum.JSON) { + myPatchType = PatchTypeEnum.JSON_PATCH; + } else { + throw new IllegalArgumentException("Unable to determine encoding of patch"); + } + + return this; + } + + @Override + public IPatchExecutable withId(IIdType theId) { + if (theId == null) { + throw new NullPointerException("theId can not be null"); + } + if (theId.hasIdPart() == false) { + throw new NullPointerException("theId must not be blank and must contain an ID, found: " + theId.getValue()); + } + myId = theId; + return this; + } + + @Override + public IPatchExecutable withId(String theId) { + if (theId == null) { + throw new NullPointerException("theId can not be null"); + } + if (isBlank(theId)) { + throw new NullPointerException("theId must not be blank and must contain an ID, found: " + theId); + } + myId = new IdDt(theId); + return this; + } + + } + @SuppressWarnings({ "rawtypes", "unchecked" }) private class ReadInternal extends BaseClientExecutable implements IRead, IReadTyped, IReadExecutable { private IIdType myId; @@ -1533,10 +1626,9 @@ public class GenericClient extends BaseClient implements IGenericClient { } @SuppressWarnings({ "rawtypes", "unchecked" }) - private class SearchInternal extends BaseClientExecutable implements IQuery, IUntypedQuery, IQueryTyped { + private class SearchInternal extends BaseSearch, IQuery, OUTPUT> implements IQuery, IUntypedQuery> { private String myCompartmentName; - private CriterionList myCriterion = new CriterionList(); private List myInclude = new ArrayList(); private DateRangeParam myLastUpdated; private Integer myParamLimit; @@ -1558,12 +1650,6 @@ public class GenericClient extends BaseClient implements IGenericClient { mySearchUrl = null; } - @Override - public IQuery and(ICriterion theCriterion) { - myCriterion.add((ICriterionInternal) theCriterion); - return this; - } - @Override public IQuery byUrl(String theSearchUrl) { Validate.notBlank(theSearchUrl, "theSearchUrl must not be blank/null"); @@ -1603,15 +1689,9 @@ public class GenericClient extends BaseClient implements IGenericClient { } @Override - public Object execute() { + public OUTPUT execute() { - Map> params = new LinkedHashMap>(); - // Map> initial = createExtraParams(); - // if (initial != null) { - // params.putAll(initial); - // } - - myCriterion.populateParamList(params); + Map> params = getParamMap(); for (TokenParam next : myTags) { addParam(params, Constants.PARAM_TAG, next.getValueAsQueryToken(myContext)); @@ -1701,7 +1781,7 @@ public class GenericClient extends BaseClient implements IGenericClient { invocation = SearchMethodBinding.createSearchInvocation(myContext, myResourceName, params, resourceId, myCompartmentName, mySearchStyle); } - return invoke(params, binding, invocation); + return (OUTPUT) invoke(params, binding, invocation); } @@ -1711,7 +1791,7 @@ public class GenericClient extends BaseClient implements IGenericClient { } @Override - public IQuery forResource(Class theResourceType) { + public IQuery forResource(Class theResourceType) { setType(theResourceType); return this; } @@ -1741,7 +1821,7 @@ public class GenericClient extends BaseClient implements IGenericClient { } @Override - public IQueryTyped returnBundle(Class theClass) { + public IQuery returnBundle(Class theClass) { if (theClass == null) { throw new NullPointerException("theClass must not be null"); } @@ -1780,8 +1860,9 @@ public class GenericClient extends BaseClient implements IGenericClient { } @Override - public IQuery where(ICriterion theCriterion) { - myCriterion.add((ICriterionInternal) theCriterion); + public IQuery withAnyProfile(Collection theProfileUris) { + Validate.notEmpty(theProfileUris, "theProfileUris must not be null or empty"); + myProfiles.add(theProfileUris); return this; } @@ -1799,13 +1880,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } - @Override - public IQuery withAnyProfile(Collection theProfileUris) { - Validate.notEmpty(theProfileUris, "theProfileUris must not be null or empty"); - myProfiles.add(theProfileUris); - return this; - } - @Override public IQuery withSecurity(String theSystem, String theCode) { Validate.notBlank(theCode, "theCode must not be null or empty"); @@ -1822,12 +1896,13 @@ public class GenericClient extends BaseClient implements IGenericClient { } + @SuppressWarnings("rawtypes") private static class SortInternal implements ISort { + private SortOrderEnum myDirection; private SearchInternal myFor; private String myParamName; private String myParamValue; - private SortOrderEnum myDirection; public SortInternal(SearchInternal theFor) { myFor = theFor; @@ -1896,7 +1971,6 @@ public class GenericClient extends BaseClient implements IGenericClient { } } - private final class TransactionExecutable extends BaseClientExecutable, T> implements ITransactionTyped { private IBaseBundle myBaseBundle; @@ -1932,7 +2006,7 @@ public class GenericClient extends BaseClient implements IGenericClient { ResourceResponseHandler binding = new ResourceResponseHandler(myBaseBundle.getClass(), getPreferResponseTypes()); BaseHttpClientInvocation invocation = TransactionMethodBinding.createTransactionInvocation(myBaseBundle, myContext); return (T) invoke(params, binding, invocation); -// } else if (myRawBundle != null) { + // } else if (myRawBundle != null) { } else { StringResponseHandler binding = new StringResponseHandler(); /* @@ -1953,7 +2027,6 @@ public class GenericClient extends BaseClient implements IGenericClient { private final class TransactionInternal implements ITransaction { - @Override public ITransactionTyped withBundle(String theBundle) { Validate.notBlank(theBundle, "theBundle must not be null"); @@ -1974,149 +2047,19 @@ public class GenericClient extends BaseClient implements IGenericClient { } - private class PatchInternal extends BaseClientExecutable implements IPatch, IPatchWithBody, IPatchExecutable, IPatchWithQuery, IPatchWithQueryTyped { + private class UpdateInternal extends BaseSearch + implements IUpdate, IUpdateTyped, IUpdateExecutable, IUpdateWithQuery, IUpdateWithQueryTyped { - private CriterionList myCriterionList; - private IIdType myId; - private PreferReturnEnum myPrefer; - private PatchTypeEnum myPatchType; - private String myPatchBody; - private String mySearchUrl; - private String myResourceType; - - @Override - public IPatchWithQueryTyped and(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - - @Override - public IPatchWithQuery conditional(String theResourceType) { - Validate.notBlank(theResourceType, "theResourceType must not be null"); - myResourceType = theResourceType; - myCriterionList = new CriterionList(); - return this; - } - - // TODO: This is not longer used.. Deprecate it or just remove it? - @Override - public IPatchWithBody conditionalByUrl(String theSearchUrl) { - mySearchUrl = validateAndEscapeConditionalUrl(theSearchUrl); - return this; - } - - @Override - public MethodOutcome execute() { - - if (myPatchType == null) { - throw new InvalidRequestException("No patch type supplied, cannot invoke server"); - } - if (myPatchBody == null) { - throw new InvalidRequestException("No patch body supplied, cannot invoke server"); - } - - BaseHttpClientInvocation invocation; - if (isNotBlank(mySearchUrl)) { - invocation = MethodUtil.createPatchInvocation(myContext, mySearchUrl, myPatchType, myPatchBody); - } else if (myCriterionList != null) { - invocation = MethodUtil.createPatchInvocation(myContext, myPatchType, myPatchBody, myResourceType, myCriterionList.toParamList()); - } else { - if (myId == null || myId.hasIdPart() == false) { - throw new InvalidRequestException("No ID supplied for resource to patch, can not invoke server"); - } - invocation = MethodUtil.createPatchInvocation(myContext, myId, myPatchType, myPatchBody); - } - - addPreferHeader(myPrefer, invocation); - - OutcomeResponseHandler binding = new OutcomeResponseHandler(myPrefer); - - Map> params = new HashMap>(); - return invoke(params, binding, invocation); - - } - - @Override - public IPatchExecutable prefer(PreferReturnEnum theReturn) { - myPrefer = theReturn; - return this; - } - - @Override - public IPatchWithQueryTyped where(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - - @Override - public IPatchExecutable withId(IIdType theId) { - if (theId == null) { - throw new NullPointerException("theId can not be null"); - } - if (theId.hasIdPart() == false) { - throw new NullPointerException("theId must not be blank and must contain an ID, found: " + theId.getValue()); - } - myId = theId; - return this; - } - - @Override - public IPatchExecutable withId(String theId) { - if (theId == null) { - throw new NullPointerException("theId can not be null"); - } - if (isBlank(theId)) { - throw new NullPointerException("theId must not be blank and must contain an ID, found: " + theId); - } - myId = new IdDt(theId); - return this; - } - - @Override - public IPatchWithBody withBody(String thePatchBody) { - Validate.notBlank(thePatchBody, "thePatchBody must not be blank"); - - myPatchBody = thePatchBody; - - EncodingEnum encoding = EncodingEnum.detectEncodingNoDefault(thePatchBody); - if (encoding == EncodingEnum.XML) { - myPatchType = PatchTypeEnum.XML_PATCH; - } else if (encoding == EncodingEnum.JSON) { - myPatchType = PatchTypeEnum.JSON_PATCH; - } else { - throw new IllegalArgumentException("Unable to determine encoding of patch"); - } - - return this; - } - - @Override - public IPatchWithQuery conditional(Class theClass) { - Validate.notNull(theClass, "theClass must not be null"); - String resourceType = myContext.getResourceDefinition(theClass).getName(); - return conditional(resourceType); - } - - } - - private class UpdateInternal extends BaseClientExecutable implements IUpdate, IUpdateTyped, IUpdateExecutable, IUpdateWithQuery, IUpdateWithQueryTyped { - - private CriterionList myCriterionList; + private boolean myConditional; private IIdType myId; private PreferReturnEnum myPrefer; private IBaseResource myResource; private String myResourceBody; private String mySearchUrl; - @Override - public IUpdateWithQueryTyped and(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - @Override public IUpdateWithQuery conditional() { - myCriterionList = new CriterionList(); + myConditional = true; return this; } @@ -2140,8 +2083,8 @@ public class GenericClient extends BaseClient implements IGenericClient { BaseHttpClientInvocation invocation; if (mySearchUrl != null) { invocation = MethodUtil.createUpdateInvocation(myContext, myResource, myResourceBody, mySearchUrl); - } else if (myCriterionList != null) { - invocation = MethodUtil.createUpdateInvocation(myContext, myResource, myResourceBody, myCriterionList.toParamList()); + } else if (myConditional) { + invocation = MethodUtil.createUpdateInvocation(myContext, myResource, myResourceBody, getParamMap()); } else { if (myId == null) { myId = myResource.getIdElement(); @@ -2182,12 +2125,6 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } - @Override - public IUpdateWithQueryTyped where(ICriterion theCriterion) { - myCriterionList.add((ICriterionInternal) theCriterion); - return this; - } - @Override public IUpdateExecutable withId(IIdType theId) { if (theId == null) { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu2.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu2.java index 31b2c3a4245..e19cc9f2c81 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu2.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu2.java @@ -13,7 +13,8 @@ import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.context.RuntimeSearchParam; import ca.uhn.fhir.jpa.entity.ResourceTable; import ca.uhn.fhir.jpa.util.DeleteConflict; -import ca.uhn.fhir.model.api.*; +import ca.uhn.fhir.model.api.IResource; +import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; import ca.uhn.fhir.model.dstu2.resource.OperationOutcome; import ca.uhn.fhir.model.dstu2.valueset.IssueSeverityEnum; @@ -22,7 +23,6 @@ import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.*; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails; -import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.validation.*; @@ -36,7 +36,7 @@ import ca.uhn.fhir.validation.*; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -55,7 +55,7 @@ public class FhirResourceDaoDstu2 extends BaseHapiFhirResou @Autowired() @Qualifier("myInstanceValidatorDstu2") private IValidatorModule myInstanceValidator; - + @Override protected List getIncludeValues(FhirTerser theTerser, Include theInclude, IBaseResource theResource, RuntimeResourceDefinition theResourceDef) { List values; @@ -100,7 +100,7 @@ public class FhirResourceDaoDstu2 extends BaseHapiFhirResou List deleteConflicts = new ArrayList(); validateOkToDelete(deleteConflicts, entity); validateDeleteConflictsEmptyOrThrowException(deleteConflicts); - + OperationOutcome oo = new OperationOutcome(); oo.addIssue().setSeverity(IssueSeverityEnum.INFORMATION).setDiagnostics("Ok to delete"); return new MethodOutcome(new IdDt(theId.getValue()), oo); @@ -155,12 +155,6 @@ public class FhirResourceDaoDstu2 extends BaseHapiFhirResou } - @CoverageIgnore - @Override - public void validateBundle(IValidationContext theContext) { - throw new UnsupportedOperationException(); - } - } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3.java index cf17ae2d6f1..6e436d97b0a 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3.java @@ -10,7 +10,7 @@ package ca.uhn.fhir.jpa.dao.dstu3; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,19 +33,18 @@ import org.hl7.fhir.instance.model.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.RuntimeResourceDefinition; +import ca.uhn.fhir.context.RuntimeSearchParam; import ca.uhn.fhir.jpa.dao.BaseHapiFhirResourceDao; import ca.uhn.fhir.jpa.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.entity.ResourceTable; import ca.uhn.fhir.jpa.util.DeleteConflict; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.*; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails; -import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.validation.*; @@ -57,9 +56,6 @@ public class FhirResourceDaoDstu3 extends BaseHapiFhirRe @Qualifier("myInstanceValidatorDstu3") private IValidatorModule myInstanceValidator; - @Autowired - private FhirContext fhirContext; - @Override protected IBaseOperationOutcome createOperationOutcome(String theSeverity, String theMessage, String theCode) { OperationOutcome oo = new OperationOutcome(); @@ -127,7 +123,7 @@ public class FhirResourceDaoDstu3 extends BaseHapiFhirRe IFhirResourceDao dao = getDao(type); resourceToValidateById = dao.read(theId, theRequestDetails); } - + ValidationResult result; if (theResource == null) { if (resourceToValidateById != null) { @@ -160,12 +156,6 @@ public class FhirResourceDaoDstu3 extends BaseHapiFhirRe myMode = theMode; } - @CoverageIgnore - @Override - public void validateBundle(IValidationContext theContext) { - throw new UnsupportedOperationException(); - } - @Override public void validateResource(IValidationContext theCtx) { boolean hasId = theCtx.getResource().getIdElement().hasIdPart(); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4.java index d8e783c1499..b601a423e5d 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4.java @@ -24,28 +24,27 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.util.*; +import org.hl7.fhir.exceptions.FHIRException; +import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.OperationOutcome; import org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity; import org.hl7.fhir.r4.model.OperationOutcome.OperationOutcomeIssueComponent; -import org.hl7.fhir.exceptions.FHIRException; -import org.hl7.fhir.instance.model.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.RuntimeResourceDefinition; +import ca.uhn.fhir.context.RuntimeSearchParam; import ca.uhn.fhir.jpa.dao.BaseHapiFhirResourceDao; import ca.uhn.fhir.jpa.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.entity.ResourceTable; import ca.uhn.fhir.jpa.util.DeleteConflict; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.*; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails; -import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.validation.*; @@ -57,9 +56,6 @@ public class FhirResourceDaoR4 extends BaseHapiFhirResou @Qualifier("myInstanceValidatorDstu3") private IValidatorModule myInstanceValidator; - @Autowired - private FhirContext fhirContext; - @Override protected IBaseOperationOutcome createOperationOutcome(String theSeverity, String theMessage, String theCode) { OperationOutcome oo = new OperationOutcome(); @@ -160,12 +156,6 @@ public class FhirResourceDaoR4 extends BaseHapiFhirResou myMode = theMode; } - @CoverageIgnore - @Override - public void validateBundle(IValidationContext theContext) { - throw new UnsupportedOperationException(); - } - @Override public void validateResource(IValidationContext theCtx) { boolean hasId = theCtx.getResource().getIdElement().hasIdPart(); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java index 0d3c5039e92..746594b8969 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java @@ -10,7 +10,7 @@ package ca.uhn.fhir.jpa.provider; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,7 +30,6 @@ import org.springframework.beans.factory.annotation.Required; import ca.uhn.fhir.jpa.dao.DaoMethodOutcome; import ca.uhn.fhir.jpa.dao.IFhirResourceDao; -import ca.uhn.fhir.model.api.TagList; import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.PatchTypeEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; @@ -65,7 +64,7 @@ public abstract class BaseJpaResourceProvider extends B @At DateRangeParam theAt, RequestDetails theRequestDetails) { //@formatter:on - + startRequest(theRequest); try { DateRangeParam sinceOrAt = processSinceOrAt(theSince, theAt); @@ -77,9 +76,9 @@ public abstract class BaseJpaResourceProvider extends B @History public IBundleProvider getHistoryForResourceType( - HttpServletRequest theRequest, - @Since Date theSince, - @At DateRangeParam theAt, + HttpServletRequest theRequest, + @Since Date theSince, + @At DateRangeParam theAt, RequestDetails theRequestDetails) { startRequest(theRequest); try { @@ -95,26 +94,6 @@ public abstract class BaseJpaResourceProvider extends B return myDao.getResourceType(); } - @GetTags - public TagList getTagsForResourceInstance(HttpServletRequest theRequest, @IdParam IIdType theResourceId, RequestDetails theRequestDetails) { - startRequest(theRequest); - try { - return myDao.getTags(theResourceId, theRequestDetails); - } finally { - endRequest(theRequest); - } - } - - @GetTags - public TagList getTagsForResourceType(HttpServletRequest theRequest, RequestDetails theRequestDetails) { - startRequest(theRequest); - try { - return myDao.getAllResourceTags(theRequestDetails); - } finally { - endRequest(theRequest); - } - } - @Read(version = true) public T read(HttpServletRequest theRequest, @IdParam IIdType theId, RequestDetails theRequestDetails) { startRequest(theRequest); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java index 7451dcf461e..c3cb624b795 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java @@ -10,7 +10,7 @@ package ca.uhn.fhir.jpa.provider; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +27,6 @@ import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Required; import ca.uhn.fhir.jpa.dao.IFhirSystemDao; -import ca.uhn.fhir.model.api.TagList; import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; @@ -36,23 +35,13 @@ import ca.uhn.fhir.rest.param.DateRangeParam; public class BaseJpaSystemProvider extends BaseJpaProvider { public static final String MARK_ALL_RESOURCES_FOR_REINDEXING = "$mark-all-resources-for-reindexing"; - + private IFhirSystemDao myDao; public BaseJpaSystemProvider() { // nothing } - @GetTags - public TagList getAllTagsOnServer(HttpServletRequest theRequest, RequestDetails theRequestDetails) { - startRequest(theRequest); - try { - return myDao.getAllTags(theRequestDetails); - } finally { - endRequest(theRequest); - } - } - protected IFhirSystemDao getDao() { return myDao; } diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu2Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu2Test.java index 902b4f3ff78..0bd8df25f76 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu2Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu2Test.java @@ -1,7 +1,23 @@ package ca.uhn.fhir.jpa.provider; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsInRelativeOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.emptyString; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.*; import java.net.*; @@ -34,7 +50,6 @@ import ca.uhn.fhir.model.valueset.BundleTypeEnum; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.client.api.IGenericClient; -import ca.uhn.fhir.rest.gclient.*; import ca.uhn.fhir.rest.param.*; import ca.uhn.fhir.rest.server.exceptions.*; import ca.uhn.fhir.util.*; @@ -457,6 +472,7 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { .forResource(Organization.class) .where(Organization.NAME.matches().value("rpdstu2_testCountParam_01")) .count(10) + .returnBundle(Bundle.class) .execute(); assertEquals(100, found.getTotalElement().getValue().intValue()); assertEquals(10, found.getEntry().size()); @@ -466,6 +482,7 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { .forResource(Organization.class) .where(Organization.NAME.matches().value("rpdstu2_testCountParam_01")) .count(999) + .returnBundle(Bundle.class) .execute(); assertEquals(100, found.getTotalElement().getValue().intValue()); assertEquals(50, found.getEntry().size()); @@ -704,6 +721,7 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { .where(Encounter.IDENTIFIER.exactly().systemAndCode("urn:foo", "testDeepChainingE1")) .include(Encounter.INCLUDE_LOCATION.asRecursive()) .include(Location.INCLUDE_PARTOF.asRecursive()) + .returnBundle(Bundle.class) .execute(); assertEquals(3, res.getEntry().size()); @@ -1581,15 +1599,6 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { pat = new Patient(); pat.addIdentifier().setSystem("urn:system").setValue("testReadAllInstancesOfType_02"); ourClient.create().resource(pat).prettyPrint().encodedXml().execute().getId(); - { - IQuery a = ourClient - .search() - .forResource(Patient.class); - IQueryTyped b = a.returnBundle(Bundle.class); - IClientExecutable x = b.encodedXml(); - x.execute(); - - } { Bundle returned = ourClient .search() @@ -1598,10 +1607,15 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { .encodedXml() .execute(); assertThat(returned.getEntry().size(), greaterThan(1)); - assertEquals(BundleTypeEnum.SEARCHSET, returned.getType().getValueAsEnum()); + assertEquals(BundleTypeEnum.SEARCHSET, returned.getTypeElement().getValueAsEnum()); } { - Bundle returned = ourClient.search().forResource(Patient.class).encodedJson().execute(); + Bundle returned = ourClient + .search() + .forResource(Patient.class) + .encodedJson() + .returnBundle(Bundle.class) + .execute(); assertThat(returned.getEntry().size(), greaterThan(1)); } } @@ -1648,7 +1662,13 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { assertEquals(1, actual.getContained().getContainedResources().size()); assertThat(actual.getText().getDiv().getValueAsString(), containsString("IdentifiertestSaveAndRetrieveWithContained01")); - Bundle b = ourClient.search().forResource("Patient").where(Patient.IDENTIFIER.exactly().systemAndCode("urn:system:rpdstu2", "testSaveAndRetrieveWithContained01")).prettyPrint().execute(); + Bundle b = ourClient + .search() + .forResource("Patient") + .where(Patient.IDENTIFIER.exactly().systemAndCode("urn:system:rpdstu2", "testSaveAndRetrieveWithContained01")) + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); assertEquals(1, b.getEntry().size()); } @@ -1714,7 +1734,13 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { p1.addIdentifier().setValue("testSearchByIdentifierWithoutSystem01"); IdDt p1Id = (IdDt) ourClient.create().resource(p1).execute().getId(); - Bundle actual = ourClient.search().forResource(Patient.class).where(Patient.IDENTIFIER.exactly().systemAndCode(null, "testSearchByIdentifierWithoutSystem01")).encodedJson().prettyPrint() + Bundle actual = ourClient + .search() + .forResource(Patient.class) + .where(Patient.IDENTIFIER.exactly().systemAndCode(null, "testSearchByIdentifierWithoutSystem01")) + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) .execute(); assertEquals(1, actual.getEntry().size()); assertEquals(p1Id.getIdPart(), actual.getEntry().get(0).getResource().getId().getIdPart()); @@ -1736,14 +1762,13 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { id2 = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless(); } - //@formatter:off Bundle found = ourClient .search() .forResource(Patient.class) .where(BaseResource.RES_ID.matches().values(id1.getIdPart(), id2.getIdPart())) .and(BaseResource.RES_ID.matches().value(id1.getIdPart())) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertThat(toIdListUnqualifiedVersionless(found), containsInAnyOrder(id1)); } @@ -1761,21 +1786,24 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { p1.setManagingOrganization(new ResourceReferenceDt(o1id.toUnqualifiedVersionless())); IdDt p1Id = (IdDt) ourClient.create().resource(p1).execute().getId(); - //@formatter:off Bundle actual = ourClient.search() .forResource(Patient.class) .where(Patient.ORGANIZATION.hasId(o1id.getIdPart())) - .encodedJson().prettyPrint().execute(); - //@formatter:on + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); assertEquals(1, actual.getEntry().size()); assertEquals(p1Id.getIdPart(), actual.getEntry().get(0).getResource().getId().getIdPart()); - //@formatter:off - actual = ourClient.search() + actual = ourClient + .search() .forResource(Patient.class) .where(Patient.ORGANIZATION.hasId(o1id.getValue())) - .encodedJson().prettyPrint().execute(); - //@formatter:on + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); assertEquals(1, actual.getEntry().size()); assertEquals(p1Id.getIdPart(), actual.getEntry().get(0).getResource().getId().getIdPart()); @@ -1802,17 +1830,19 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { p2.setManagingOrganization(new ResourceReferenceDt(o2id.toUnqualifiedVersionless())); IdDt p2Id = (IdDt) ourClient.create().resource(p2).execute().getId(); - //@formatter:off Bundle actual = ourClient.search() .forResource(Patient.class) .where(Patient.ORGANIZATION.hasAnyOfIds(Arrays.asList(o1id.getIdPart(), o2id.getIdPart()))) - .encodedJson().prettyPrint().execute(); - //@formatter:on + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); + Set expectedIds = new HashSet(); expectedIds.add(p1Id.getIdPart()); expectedIds.add(p2Id.getIdPart()); Set actualIds = new HashSet(); - for (BundleEntry ele : actual.getEntry()) { + for (Entry ele : actual.getEntry()) { actualIds.add(ele.getResource().getId().getIdPart()); } assertEquals("Expects to retrieve the 2 patients which reference the two different organizations", expectedIds, actualIds); @@ -1828,40 +1858,49 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { o2.setName("testSearchByResourceChainName02"); o2.getMeta().addProfile("http://profile1").addProfile("http://profile3"); IdDt o2id = (IdDt) ourClient.create().resource(o2).execute().getId().toUnqualifiedVersionless(); - //@formatter:off + Bundle actual = ourClient.search() .forResource(Organization.class) .withProfile("http://profile1") .withProfile("http://profileX") - .encodedJson().prettyPrint().execute(); - //@formatter:on + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); + assertEquals("nothing matches profile x", Collections.emptyList(), actual.getEntry()); - //@formatter:off + actual = ourClient.search() .forResource(Organization.class) .withProfile("http://profile1") .withProfile("http://profile2") - .encodedJson().prettyPrint().execute(); - //@formatter:on + .returnBundle(Bundle.class) + .encodedJson() + .prettyPrint() + .execute(); + Set expectedIds = new HashSet(); expectedIds.add(o1id.getIdPart()); Set actualIds = new HashSet(); - for (BundleEntry ele : actual.getEntry()) { + for (Entry ele : actual.getEntry()) { actualIds.add(ele.getResource().getId().getIdPart()); } assertEquals("Expects to retrieve the 1 orgination matching on Org1's profiles", expectedIds, actualIds); - //@formatter:off + actual = ourClient.search() .forResource(Organization.class) .withProfile("http://profile1") .withAnyProfile(Arrays.asList("http://profile3", "http://profile2")) - .encodedJson().prettyPrint().execute(); - //@formatter:on + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); + expectedIds = new HashSet(); expectedIds.add(o1id.getIdPart()); expectedIds.add(o2id.getIdPart()); actualIds = new HashSet(); - for (BundleEntry ele : actual.getEntry()) { + for (Entry ele : actual.getEntry()) { actualIds.add(ele.getResource().getId().getIdPart()); } assertEquals("Expects to retrieve the 2 orginations, since we match on (the common profile AND (Org1's second profile OR org2's second profile))", expectedIds, actualIds); @@ -1905,60 +1944,58 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { ourLog.info("Before: {}", beforeAny.getValue()); { - //@formatter:off - Bundle found = ourClient.search() + Bundle found = ourClient + .search() .forResource(Patient.class) .where(Patient.NAME.matches().value("testSearchLastUpdatedParamRp")) .lastUpdated(new DateRangeParam(beforeAny, null)) + .returnBundle(Bundle.class) .execute(); - //@formatter:on List patients = toIdListUnqualifiedVersionless(found); assertThat(patients, hasItems(id1a, id1b, id2)); } { - //@formatter:off Bundle found = ourClient.search() .forResource(Patient.class) .where(Patient.NAME.matches().value("testSearchLastUpdatedParamRp")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on List patients = toIdListUnqualifiedVersionless(found); assertThat(patients, hasItems(id1a, id1b, id2)); } { - //@formatter:off Bundle found = ourClient.search() .forResource(Patient.class) .where(Patient.NAME.matches().value("testSearchLastUpdatedParamRp")) .lastUpdated(new DateRangeParam(beforeR2, null)) + .returnBundle(Bundle.class) .execute(); - //@formatter:on List patients = toIdListUnqualifiedVersionless(found); assertThat(patients, hasItems(id2)); assertThat(patients, not(hasItems(id1a, id1b))); } { - //@formatter:off Bundle found = ourClient.search() .forResource(Patient.class) .where(Patient.NAME.matches().value("testSearchLastUpdatedParamRp")) .lastUpdated(new DateRangeParam(beforeAny, beforeR2)) + .returnBundle(Bundle.class) .execute(); - //@formatter:on + List patients = toIdListUnqualifiedVersionless(found); assertThat(patients.toString(), patients, not(hasItems(id2))); assertThat(patients.toString(), patients, (hasItems(id1a, id1b))); } { - //@formatter:off Bundle found = ourClient.search() .forResource(Patient.class) .where(Patient.NAME.matches().value("testSearchLastUpdatedParamRp")) .lastUpdated(new DateRangeParam(null, beforeR2)) + .returnBundle(Bundle.class) .execute(); - //@formatter:on + List patients = toIdListUnqualifiedVersionless(found); assertThat(patients, (hasItems(id1a, id1b))); assertThat(patients, not(hasItems(id2))); @@ -1985,14 +2022,12 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { Date before = new Date(); Thread.sleep(100); - //@formatter:off ca.uhn.fhir.model.dstu2.resource.Bundle found = ourClient .search() .forResource(Patient.class) .prettyPrint() .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - //@formatter:on Thread.sleep(100); Date after = new Date(); @@ -2018,23 +2053,22 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { pat.getManagingOrganization().setReference(orgId.toUnqualifiedVersionless()); ourClient.create().resource(pat).prettyPrint().encodedXml().execute().getId(); - //@formatter:off Bundle found = ourClient .search() .forResource(Patient.class) .where(Patient.IDENTIFIER.exactly().systemAndIdentifier("urn:system:rpdstu2","testSearchWithInclude02")) .include(Patient.INCLUDE_ORGANIZATION) .prettyPrint() + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals(2, found.getEntry().size()); assertEquals(Patient.class, found.getEntry().get(0).getResource().getClass()); - assertEquals(BundleEntrySearchModeEnum.MATCH, found.getEntry().get(0).getSearchMode().getValueAsEnum()); + assertEquals(BundleEntrySearchModeEnum.MATCH, found.getEntry().get(0).getSearch().getModeElement().getValueAsEnum()); assertEquals(BundleEntrySearchModeEnum.MATCH, found.getEntry().get(0).getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE)); assertThat(found.getEntry().get(0).getResource().getText().getDiv().getValueAsString(), containsString(" list = toIdListUnqualifiedVersionless(found); ourLog.info(methodName + ": " + list.toString()); @@ -2104,15 +2135,14 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { assertThat(list, not(containsInRelativeOrder(orgMissing))); } - //@formatter:off - Bundle found = ourClient - .search() - .forResource(Organization.class) - .where(Organization.NAME.isMissing(true)) - .count(100) - .prettyPrint() - .execute(); - //@formatter:on + Bundle found = ourClient + .search() + .forResource(Organization.class) + .where(Organization.NAME.isMissing(true)) + .count(100) + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); List list = toIdListUnqualifiedVersionless(found); ourLog.info(methodName + " found: " + list.toString() + " - Wanted " + orgMissing + " but not " + orgNotMissing); @@ -2236,7 +2266,6 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { p.addName().addGiven("Sarah").addFamily("Graham"); ourClient.create().resource(p).execute(); - //@formatter:off Bundle resp = ourClient .search() .forResource(Patient.class) @@ -2244,14 +2273,13 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { .sort().ascending(Patient.FAMILY) .sort().ascending(Patient.GIVEN) .count(100) + .returnBundle(Bundle.class) .execute(); - //@formatter:on List names = toNameList(resp); ourLog.info(StringUtils.join(names, '\n')); - //@formatter:off assertThat(names, contains( // this matches in order only "Daniel Adams", "Aaron Alexis", @@ -2269,7 +2297,6 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { "Brian Gracia", "Sarah Graham", "Stephan Graham")); - //@formatter:om } @@ -2474,7 +2501,15 @@ public class ResourceProviderDstu2Test extends BaseResourceProviderDstu2Test { assertThat(p1Id.getValue(), containsString("Patient/testUpdateWithClientSuppliedIdWhichDoesntExistRpDstu2/_history")); - Bundle actual = ourClient.search().forResource(Patient.class).where(Patient.IDENTIFIER.exactly().systemAndCode("urn:system", "testUpdateWithClientSuppliedIdWhichDoesntExistRpDstu2")).encodedJson().prettyPrint().execute(); + Bundle actual = ourClient + .search() + .forResource(Patient.class) + .where(Patient.IDENTIFIER.exactly().systemAndCode("urn:system", "testUpdateWithClientSuppliedIdWhichDoesntExistRpDstu2")) + .encodedJson() + .prettyPrint() + .returnBundle(Bundle.class) + .execute(); + assertEquals(1, actual.getEntry().size()); assertEquals(p1Id.getIdPart(), actual.getEntry().get(0).getResource().getId().getIdPart()); diff --git a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/InterceptorTest.java b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/InterceptorTest.java index 7e7252b3e2c..dac4ec41112 100644 --- a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/InterceptorTest.java +++ b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/InterceptorTest.java @@ -1,12 +1,13 @@ package ca.uhn.fhir.rest.server; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; @@ -21,10 +22,7 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.mockito.InOrder; import ca.uhn.fhir.context.FhirContext; @@ -35,10 +33,7 @@ import ca.uhn.fhir.model.dstu.resource.Patient; import ca.uhn.fhir.model.dstu.valueset.IdentifierUseEnum; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.UriDt; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.annotation.RequiredParam; -import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.method.RequestDetails; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; diff --git a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerDstu1Test.java b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerDstu1Test.java deleted file mode 100644 index 566e6c97172..00000000000 --- a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerDstu1Test.java +++ /dev/null @@ -1,700 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import static ca.uhn.fhir.util.UrlUtil.escape; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicNameValuePair; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.google.common.net.UrlEscapers; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; -import ca.uhn.fhir.model.api.IResource; -import ca.uhn.fhir.model.api.Include; -import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; -import ca.uhn.fhir.model.base.composite.BaseCodingDt; -import ca.uhn.fhir.model.dstu.composite.CodingDt; -import ca.uhn.fhir.model.dstu.resource.BaseResource; -import ca.uhn.fhir.model.dstu.resource.Observation; -import ca.uhn.fhir.model.dstu.resource.Patient; -import ca.uhn.fhir.model.primitive.IdDt; -import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator; -import ca.uhn.fhir.rest.annotation.Create; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.IncludeParam; -import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.annotation.RequiredParam; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.client.IGenericClient; -import ca.uhn.fhir.rest.param.ReferenceParam; -import ca.uhn.fhir.rest.param.StringAndListParam; -import ca.uhn.fhir.rest.param.StringOrListParam; -import ca.uhn.fhir.rest.param.StringParam; -import ca.uhn.fhir.rest.param.TokenOrListParam; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.util.PortUtil; -import ca.uhn.fhir.util.TestUtil; - -public class SearchSearchServerDstu1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu1(); - private static IServerAddressStrategy ourDefaultAddressStrategy; - private static StringAndListParam ourLastAndList; - - private static Set ourLastIncludes; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchSearchServerDstu1Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; - - @Before - public void before() { - ourServlet.setServerAddressStrategy(ourDefaultAddressStrategy); - ourLastIncludes = null; - ourLastAndList = null; - } - - @Test - public void testEncodeConvertsReferencesToRelative() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - Patient patient = (Patient) ourCtx.newXmlParser().parseBundle(responseContent).getEntries().get(0).getResource(); - String ref = patient.getManagingOrganization().getReference().getValue(); - assertEquals("Organization/555", ref); - } - - /** - * Try loading the page as a POST just to make sure we get the right error - */ - @Test - public void testGetPagesWithPost() throws Exception { - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort); - List parameters = Collections.singletonList(new BasicNameValuePair("_getpages", "AAA")); - httpPost.setEntity(new UrlEncodedFormEntity(parameters)); - - CloseableHttpResponse status = ourClient.execute(httpPost); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(400, status.getStatusLine().getStatusCode()); -// assertThat(responseContent, containsString("Requests for _getpages must use HTTP GET")); - } - - @Test - public void testOmitEmptyOptionalParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id="); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals(null, p.getNameFirstRep().getFamilyFirstRep().getValue()); - } - - @Test - public void testParseEscapedValues() throws Exception { - - StringBuilder b = new StringBuilder(); - b.append("http://localhost:"); - b.append(ourPort); - b.append("/Patient?"); - b.append(escape("findPatientWithAndList")).append('=').append(escape("NE\\,NE,NE\\,NE")).append('&'); - b.append(escape("findPatientWithAndList")).append('=').append(escape("NE\\\\NE")).append('&'); - b.append(escape("findPatientWithAndList:exact")).append('=').append(escape("E\\$E")).append('&'); - b.append(escape("findPatientWithAndList:exact")).append('=').append(escape("E\\|E")).append('&'); - - HttpGet httpGet = new HttpGet(b.toString()); - - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals(4, ourLastAndList.getValuesAsQueryTokens().size()); - assertEquals(2, ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().size()); - assertFalse(ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).isExact()); - assertEquals("NE,NE", ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("NE,NE", ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(1).getValue()); - assertEquals("NE\\NE", ourLastAndList.getValuesAsQueryTokens().get(1).getValuesAsQueryTokens().get(0).getValue()); - assertTrue(ourLastAndList.getValuesAsQueryTokens().get(2).getValuesAsQueryTokens().get(0).isExact()); - assertEquals("E$E", ourLastAndList.getValuesAsQueryTokens().get(2).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("E|E", ourLastAndList.getValuesAsQueryTokens().get(3).getValuesAsQueryTokens().get(0).getValue()); - } - - @Test - public void testReturnLinks() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findWithLinks"); - - CloseableHttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(10, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("AAANamed", p.getIdentifierFirstRep().getValue().getValue()); - assertEquals("http://foo/Patient?_id=1", bundle.getEntries().get(0).getLinkSearch().getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/99881", bundle.getEntries().get(0).getLinkAlternate().getValue()); - - assertEquals("http://foo/Patient?_id=1", ResourceMetadataKeyEnum.LINK_SEARCH.get(p)); - assertEquals("http://localhost:" + ourPort + "/Patient/99881", ResourceMetadataKeyEnum.LINK_ALTERNATE.get(p)); - - } - - /** - * #149 - */ - @Test - public void testReturnLinksWithAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("https://blah.com/base")); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findWithLinks"); - - CloseableHttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - - ourLog.info(responseContent); - - assertEquals(10, bundle.getEntries().size()); - assertEquals("https://blah.com/base", bundle.getLinkBase().getValue()); - assertEquals("https://blah.com/base/Patient?_query=findWithLinks", bundle.getLinkSelf().getValue()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("AAANamed", p.getIdentifierFirstRep().getValue().getValue()); - assertEquals("http://foo/Patient?_id=1", bundle.getEntries().get(0).getLinkSearch().getValue()); - assertEquals("https://blah.com/base/Patient/99881", bundle.getEntries().get(0).getLinkAlternate().getValue()); - assertEquals("http://foo/Patient?_id=1", ResourceMetadataKeyEnum.LINK_SEARCH.get(p)); - assertEquals("https://blah.com/base/Patient/99881", ResourceMetadataKeyEnum.LINK_ALTERNATE.get(p)); - - String linkNext = bundle.getLinkNext().getValue(); - ourLog.info(linkNext); - assertThat(linkNext, startsWith("https://blah.com/base?_getpages=")); - - /* - * Load the second page - */ - String urlPart = linkNext.substring(linkNext.indexOf('?')); - String link = "http://localhost:" + ourPort + urlPart; - httpGet = new HttpGet(link); - - status = ourClient.execute(httpGet); - responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - bundle = ourCtx.newXmlParser().parseBundle(responseContent); - - ourLog.info(responseContent); - - assertEquals(10, bundle.getEntries().size()); - assertEquals("https://blah.com/base", bundle.getLinkBase().getValue()); - assertEquals(linkNext, bundle.getLinkSelf().getValue()); - - p = bundle.getResources(Patient.class).get(0); - assertEquals("AAANamed", p.getIdentifierFirstRep().getValue().getValue()); - assertEquals("http://foo/Patient?_id=11", bundle.getEntries().get(0).getLinkSearch().getValue()); - assertEquals("https://blah.com/base/Patient/998811", bundle.getEntries().get(0).getLinkAlternate().getValue()); - assertEquals("http://foo/Patient?_id=11", ResourceMetadataKeyEnum.LINK_SEARCH.get(p)); - assertEquals("https://blah.com/base/Patient/998811", ResourceMetadataKeyEnum.LINK_ALTERNATE.get(p)); - - } - - @Test - public void testSearchById() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("idaaa", p.getNameFirstRep().getFamilyAsSingleString()); - } - - @Test - public void testSearchByIdUsingClient() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); - - Bundle bundle = client.search().forResource("Patient").where(BaseResource.RES_ID.matches().value("aaa")).execute(); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("idaaa", p.getNameFirstRep().getFamilyAsSingleString()); - } - - @Test - public void testSearchByPost() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); - - // add parameters to the post method - List parameters = new ArrayList(); - parameters.add(new BasicNameValuePair("_id", "aaa")); - - UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8"); - filePost.setEntity(sendentity); - - HttpResponse status = ourClient.execute(filePost); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("idaaa", p.getNameFirstRep().getFamilyAsSingleString()); - } - - /** - * See #164 - */ - @Test - public void testSearchByPostWithInvalidPostUrl() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); // should end with - // _search - - // add parameters to the post method - List parameters = new ArrayList(); - parameters.add(new BasicNameValuePair("_id", "aaa")); - - UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8"); - filePost.setEntity(sendentity); - - HttpResponse status = ourClient.execute(filePost); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(400, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("
    ")); - } - - /** - * See #164 - */ - @Test - public void testSearchByPostWithMissingContentType() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); // should end with - // _search - - HttpEntity sendentity = new ByteArrayEntity(new byte[] { 1, 2, 3, 4 }); - filePost.setEntity(sendentity); - - HttpResponse status = ourClient.execute(filePost); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(400, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("
    ")); - } - - /** - * See #164 - */ - @Test - public void testSearchByPostWithParamsInBodyAndUrl() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?name=Central"); - - // add parameters to the post method - List parameters = new ArrayList(); - parameters.add(new BasicNameValuePair("_id", "aaa")); - - UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8"); - filePost.setEntity(sendentity); - - HttpResponse status = ourClient.execute(filePost); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("idaaa", p.getName().get(0).getFamilyAsSingleString()); - assertEquals("nameCentral", p.getName().get(1).getFamilyAsSingleString()); - - } - - @Test - public void testSearchCompartment() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/fooCompartment"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("fooCompartment", p.getIdentifierFirstRep().getValue().getValue()); - assertThat(bundle.getEntries().get(0).getResource().getId().getValue(), containsString("Patient/123")); - } - - @Test - public void testSearchGetWithUnderscoreSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/_search?subject%3APatient=100&name=3141-9%2C8302-2%2C8287-5%2C39156-5"); - - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Observation p = bundle.getResources(Observation.class).get(0); - assertEquals("Patient/100", p.getSubject().getReference().toString()); - assertEquals(4, p.getName().getCoding().size()); - assertEquals("3141-9", p.getName().getCoding().get(0).getCode().getValue()); - assertEquals("8302-2", p.getName().getCoding().get(1).getCode().getValue()); - - } - - @Test - public void testSearchIncludesParametersIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes&_include=foo&_include:recurse=bar"); - - CloseableHttpResponse status = ourClient.execute(httpGet); - IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals(2, ourLastIncludes.size()); - assertThat(ourLastIncludes, containsInAnyOrder(new Include("foo", false), new Include("bar", true))); - } - - @Test - public void testSearchIncludesParametersIncludesList() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludesList&_include=foo&_include:recurse=bar"); - - CloseableHttpResponse status = ourClient.execute(httpGet); - IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals(2, ourLastIncludes.size()); - assertThat(ourLastIncludes, containsInAnyOrder(new Include("foo", false), new Include("bar", true))); - } - - @Test - public void testSearchIncludesParametersNone() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes"); - - CloseableHttpResponse status = ourClient.execute(httpGet); - IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertThat(ourLastIncludes, empty()); - } - - @Test - public void testSearchWithOrList() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?findPatientWithOrList=aaa,bbb"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("aaa", p.getIdentifier().get(0).getValue().getValue()); - assertEquals("bbb", p.getIdentifier().get(1).getValue().getValue()); - } - - @Test - public void testSearchWithTokenParameter() throws Exception { - String token = UrlEscapers.urlFragmentEscaper().asFunction().apply("http://www.dmix.gov/vista/2957|301"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?tokenParam=" + token); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("http://www.dmix.gov/vista/2957", p.getNameFirstRep().getFamilyAsSingleString()); - assertEquals("301", p.getNameFirstRep().getGivenAsSingleString()); - } - - @Test - public void testSpecificallyNamedQueryGetsPrecedence() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?AAA=123"); - - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - Patient p = bundle.getResources(Patient.class).get(0); - assertEquals("AAA", p.getIdentifierFirstRep().getValue().getValue()); - - // Now the named query - - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findPatientByAAA&AAA=123"); - - status = ourClient.execute(httpGet); - responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - - p = bundle.getResources(Patient.class).get(0); - assertEquals("AAANamed", p.getIdentifierFirstRep().getValue().getValue()); - } - - - @AfterClass - public static void afterClassClearContext() throws Exception { - ourServer.stop(); - TestUtil.clearAllStaticFieldsForUnitTest(); - } - - @BeforeClass - public static void beforeClass() throws Exception { - ourPort = PortUtil.findFreePort(); - ourServer = new Server(ourPort); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(); - ourServlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(10)); - - ourServlet.setResourceProviders(patientProvider, new DummyObservationResourceProvider()); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - ourServer.start(); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourDefaultAddressStrategy = ourServlet.getServerAddressStrategy(); - } - - public static class DummyObservationResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Observation.class; - } - - @Search - public Observation search(@RequiredParam(name = "subject") ReferenceParam theSubject, @RequiredParam(name = "name") TokenOrListParam theName) { - Observation o = new Observation(); - o.setId("1"); - - o.getSubject().setReference(theSubject.getResourceType() + "/" + theSubject.getIdPart()); - for (BaseCodingDt next : theName.getListAsCodings()) { - o.getName().getCoding().add(new CodingDt(next)); - } - - return o; - } - - } - - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Search(compartmentName = "fooCompartment") - public List compartment(@IdParam IdDt theId) { - ArrayList retVal = new ArrayList(); - - Patient patient = new Patient(); - patient.setId(theId); - patient.addIdentifier("system", "fooCompartment"); - retVal.add(patient); - return retVal; - } - - /** - * Only needed for #164 - */ - @Create - public MethodOutcome create(@ResourceParam Patient thePatient) { - throw new IllegalArgumentException(); - } - - @Search - public List findPatient(@RequiredParam(name = "_id") StringParam theParam, @OptionalParam(name = "name") StringParam theName) { - ArrayList retVal = new ArrayList(); - - Patient patient = new Patient(); - patient.setId("1"); - patient.addIdentifier("system", "identifier123"); - if (theParam != null) { - patient.addName().addFamily("id" + theParam.getValue()); - if (theName != null) { - patient.addName().addFamily("name" + theName.getValue()); - } - } - retVal.add(patient); - return retVal; - } - - @Search - public List findPatientByAAA01(@RequiredParam(name = "AAA") StringParam theParam) { - ArrayList retVal = new ArrayList(); - - Patient patient = new Patient(); - patient.setId("1"); - patient.addIdentifier("system", "AAA"); - retVal.add(patient); - return retVal; - } - - @Search(queryName = "findPatientByAAA") - public List findPatientByAAA02Named(@OptionalParam(name = "AAA") StringParam theParam) { - ArrayList retVal = new ArrayList(); - - Patient patient = new Patient(); - patient.setId("1"); - patient.addIdentifier("system", "AAANamed"); - retVal.add(patient); - return retVal; - } - - @Search() - public List findPatientWithAndList(@RequiredParam(name = "findPatientWithAndList") StringAndListParam theParam) { - ourLastAndList = theParam; - ArrayList retVal = new ArrayList(); - return retVal; - } - - @Search() - public List findPatientWithOrList(@RequiredParam(name = "findPatientWithOrList") StringOrListParam theParam) { - ArrayList retVal = new ArrayList(); - - Patient patient = new Patient(); - patient.setId("1"); - for (StringParam next : theParam.getValuesAsQueryTokens()) { - patient.addIdentifier("system", next.getValue()); - } - retVal.add(patient); - return retVal; - } - - @Search() - public List findPatientWithToken(@RequiredParam(name = "tokenParam") TokenParam theParam) { - ArrayList retVal = new ArrayList(); - - Patient patient = new Patient(); - patient.setId("1"); - patient.addName().addFamily(theParam.getSystem()).addGiven(theParam.getValue()); - retVal.add(patient); - return retVal; - } - - @Search(queryName = "findWithLinks") - public List findWithLinks() { - ArrayList retVal = new ArrayList(); - - for (int i = 1; i <= 20; i++) { - Patient patient = new Patient(); - patient.setId("" + i); - patient.addIdentifier("system", "AAANamed"); - ResourceMetadataKeyEnum.LINK_SEARCH.put(patient, ("http://foo/Patient?_id=" + i)); - ResourceMetadataKeyEnum.LINK_ALTERNATE.put(patient, ("Patient/9988" + i)); - retVal.add(patient); - } - - return retVal; - } - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Search(queryName = "searchIncludes") - public List searchIncludes(@IncludeParam Set theIncludes) { - ourLastIncludes = theIncludes; - - ArrayList retVal = new ArrayList(); - return retVal; - } - - @Search(queryName = "searchIncludesList") - public List searchIncludesList(@IncludeParam List theIncludes) { - if (theIncludes != null) { - ourLastIncludes = new HashSet(theIncludes); - } - - ArrayList retVal = new ArrayList(); - return retVal; - } - - @Search(queryName = "searchWithRef") - public Patient searchWithRef() { - Patient patient = new Patient(); - patient.setId("Patient/1/_history/1"); - patient.getManagingOrganization().setReference("http://localhost:" + ourPort + "/Organization/555/_history/666"); - return patient; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/Dstu2_1BundleFactory.java b/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/Dstu2_1BundleFactory.java index 05812227f76..dfc86d1d2e4 100644 --- a/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/Dstu2_1BundleFactory.java +++ b/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/Dstu2_1BundleFactory.java @@ -265,11 +265,6 @@ public class Dstu2_1BundleFactory implements IVersionSpecificBundleFactory { } } - @Override - public ca.uhn.fhir.model.api.Bundle getDstu1Bundle() { - return null; - } - @Override public IBaseResource getResourceBundle() { return myBundle; diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2_1Test.java index ef1dd6d2433..7a7a7c81413 100644 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2_1Test.java +++ b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2_1Test.java @@ -122,10 +122,10 @@ public class GenericClientDstu2_1Test { String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; MethodOutcome outcome = client - .patch() - .withBody(patch) - .withId("Patient/123") - .execute(); + .patch() + .withBody(patch) + .withId("Patient/123") + .execute(); assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); @@ -136,6 +136,7 @@ public class GenericClientDstu2_1Test { OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); assertThat(oo.getText().getDivAsString(), containsString("OK!")); } + @Test public void testPatchJsonByIdType() throws Exception { OperationOutcome conf = new OperationOutcome(); @@ -159,10 +160,10 @@ public class GenericClientDstu2_1Test { String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; MethodOutcome outcome = client - .patch() - .withBody(patch) - .withId(new IdType("http://localhost/fhir/Patient/123/_history/234")) - .execute(); + .patch() + .withBody(patch) + .withId(new IdType("http://localhost/fhir/Patient/123/_history/234")) + .execute(); assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); @@ -173,6 +174,7 @@ public class GenericClientDstu2_1Test { OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); assertThat(oo.getText().getDivAsString(), containsString("OK!")); } + @Test public void testPatchJsonByConditionalString() throws Exception { OperationOutcome conf = new OperationOutcome(); @@ -196,10 +198,10 @@ public class GenericClientDstu2_1Test { String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; MethodOutcome outcome = client - .patch() - .withBody(patch) - .conditionalByUrl("Patient?foo=bar") - .execute(); + .patch() + .withBody(patch) + .conditionalByUrl("Patient?foo=bar") + .execute(); assertEquals("http://example.com/fhir/Patient?foo=bar", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); @@ -210,6 +212,7 @@ public class GenericClientDstu2_1Test { OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); assertThat(oo.getText().getDivAsString(), containsString("OK!")); } + @Test public void testPatchJsonByConditionalParam() throws Exception { OperationOutcome conf = new OperationOutcome(); @@ -233,11 +236,11 @@ public class GenericClientDstu2_1Test { String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; MethodOutcome outcome = client - .patch() - .withBody(patch) - .conditional("Patient").where(Patient.NAME.matches().value("TEST")) - .and(Patient.FAMILY.matches().value("TEST2")) - .execute(); + .patch() + .withBody(patch) + .conditional("Patient").where(Patient.NAME.matches().value("TEST")) + .and(Patient.FAMILY.matches().value("TEST2")) + .execute(); assertEquals("http://example.com/fhir/Patient?name=TEST&family=TEST2", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); @@ -248,6 +251,7 @@ public class GenericClientDstu2_1Test { OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); assertThat(oo.getText().getDivAsString(), containsString("OK!")); } + @Test public void testPatchJsonByConditionalParamResourceType() throws Exception { OperationOutcome conf = new OperationOutcome(); @@ -271,11 +275,11 @@ public class GenericClientDstu2_1Test { String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; MethodOutcome outcome = client - .patch() - .withBody(patch) - .conditional(Patient.class).where(Patient.NAME.matches().value("TEST")) - .and(Patient.FAMILY.matches().value("TEST2")) - .execute(); + .patch() + .withBody(patch) + .conditional(Patient.class).where(Patient.NAME.matches().value("TEST")) + .and(Patient.FAMILY.matches().value("TEST2")) + .execute(); assertEquals("http://example.com/fhir/Patient?name=TEST&family=TEST2", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); @@ -286,6 +290,7 @@ public class GenericClientDstu2_1Test { OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); assertThat(oo.getText().getDivAsString(), containsString("OK!")); } + @Test public void testPatchXmlByIdString() throws Exception { OperationOutcome conf = new OperationOutcome(); @@ -309,10 +314,10 @@ public class GenericClientDstu2_1Test { String patch = "false"; MethodOutcome outcome = client - .patch() - .withBody(patch) - .withId("Patient/123") - .execute(); + .patch() + .withBody(patch) + .withId("Patient/123") + .execute(); assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); @@ -330,10 +335,10 @@ public class GenericClientDstu2_1Test { try { client - .patch() - .withBody("AA") - .withId("Patient/123") - .execute(); + .patch() + .withBody("AA") + .withId("Patient/123") + .execute(); } catch (IllegalArgumentException e) { assertEquals("Unable to determine encoding of patch", e.getMessage()); } @@ -357,24 +362,22 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client.setEncoding(EncodingEnum.JSON); client.search() - .forResource("Device") - .returnBundle(Bundle.class) - .execute(); - + .forResource("Device") + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Device?_format=json", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals(Constants.CT_FHIR_JSON, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_ACCEPT).getValue()); idx++; - client.setEncoding(EncodingEnum.XML); client.search() - .forResource("Device") - .returnBundle(Bundle.class) - .execute(); - + .forResource("Device") + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Device?_format=xml", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals(Constants.CT_FHIR_XML, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_ACCEPT).getValue()); idx++; @@ -460,8 +463,6 @@ public class GenericClientDstu2_1Test { } - - @SuppressWarnings("unchecked") @Test public void testClientFailures() throws Exception { @@ -512,13 +513,11 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); client.registerInterceptor(new CookieInterceptor("foo=bar")); - Bundle resp = client - .history() - .onType(Patient.class) - .andReturnBundle(Bundle.class) - .execute(); - + .history() + .onType(Patient.class) + .andReturnBundle(Bundle.class) + .execute(); assertEquals("foo=bar", capt.getAllValues().get(0).getFirstHeader("Cookie").getValue()); } @@ -633,13 +632,11 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Bundle resp = client - .history() - .onType(CustomTypeDstu2_1Test.MyCustomPatient.class) - .andReturnBundle(Bundle.class) - .execute(); - + .history() + .onType(CustomTypeDstu2_1Test.MyCustomPatient.class) + .andReturnBundle(Bundle.class) + .execute(); assertEquals(1, resp.getEntry().size()); assertEquals(CustomTypeDstu2_1Test.MyCustomPatient.class, resp.getEntry().get(0).getResource().getClass()); @@ -664,25 +661,21 @@ public class GenericClientDstu2_1Test { Bundle bundle = new Bundle(); bundle.addLink().setRelation("next").setUrl("http://foo/next"); - Bundle resp = client - .loadPage() - .next(bundle) - .preferResponseType(MyCustomPatient.class) - .execute(); - + .loadPage() + .next(bundle) + .preferResponseType(MyCustomPatient.class) + .execute(); assertEquals(1, resp.getEntry().size()); assertEquals(CustomTypeDstu2_1Test.MyCustomPatient.class, resp.getEntry().get(0).getResource().getClass()); assertEquals("http://foo/next", capt.getAllValues().get(0).getURI().toASCIIString()); - resp = client - .loadPage() - .next(bundle) - .preferResponseTypes(toTypeList(MyCustomPatient.class)) - .execute(); - + .loadPage() + .next(bundle) + .preferResponseTypes(toTypeList(MyCustomPatient.class)) + .execute(); assertEquals(1, resp.getEntry().size()); assertEquals(CustomTypeDstu2_1Test.MyCustomPatient.class, resp.getEntry().get(0).getResource().getClass()); @@ -711,28 +704,24 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Parameters resp = client - .operation() - .onServer() - .named("foo") - .withNoParameters(Parameters.class) - .preferResponseType(MyCustomPatient.class) - .execute(); - + .operation() + .onServer() + .named("foo") + .withNoParameters(Parameters.class) + .preferResponseType(MyCustomPatient.class) + .execute(); assertEquals(1, resp.getParameter().size()); assertEquals(CustomTypeDstu2_1Test.MyCustomPatient.class, resp.getParameter().get(0).getResource().getClass()); assertEquals("http://example.com/fhir/$foo", capt.getAllValues().get(0).getURI().toASCIIString()); - resp = client - .operation() - .onType(MyCustomPatient.class) - .named("foo") - .withNoParameters(Parameters.class) - .execute(); - + .operation() + .onType(MyCustomPatient.class) + .named("foo") + .withNoParameters(Parameters.class) + .execute(); assertEquals(1, resp.getParameter().size()); assertEquals(CustomTypeDstu2_1Test.MyCustomPatient.class, resp.getParameter().get(0).getResource().getClass()); @@ -755,13 +744,11 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Bundle resp = client - .search() - .forResource(CustomTypeDstu2_1Test.MyCustomPatient.class) - .returnBundle(Bundle.class) - .execute(); - + .search() + .forResource(CustomTypeDstu2_1Test.MyCustomPatient.class) + .returnBundle(Bundle.class) + .execute(); assertEquals(1, resp.getEntry().size()); assertEquals(CustomTypeDstu2_1Test.MyCustomPatient.class, resp.getEntry().get(0).getResource().getClass()); @@ -966,18 +953,6 @@ public class GenericClientDstu2_1Test { } - @SuppressWarnings("deprecation") - @Test - public void testInvalidConformanceCall() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - try { - client.conformance(); - fail(); - } catch (IllegalArgumentException e) { - assertEquals("Must call fetchConformance() instead of conformance() for RI/STU3+ structures", e.getMessage()); - } - } - /** * See #150 */ @@ -988,41 +963,35 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - - client - .search() - .forResource(Patient.class) - .where(Patient.FAMILY.matches().value((String)null)) - .and(Patient.BIRTHDATE.exactly().day((Date)null)) - .and(Patient.GENDER.exactly().code((String)null)) - .and(Patient.ORGANIZATION.hasId((String)null)) - .returnBundle(Bundle.class) - .execute(); - + client + .search() + .forResource(Patient.class) + .where(Patient.FAMILY.matches().value((String) null)) + .and(Patient.BIRTHDATE.exactly().day((Date) null)) + .and(Patient.GENDER.exactly().code((String) null)) + .and(Patient.ORGANIZATION.hasId((String) null)) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); idx++; - - client - .search() - .forResource(Encounter.class) - .where(Encounter.LENGTH.exactly().number(null)) - .returnBundle(Bundle.class) - .execute(); - + client + .search() + .forResource(Encounter.class) + .where(Encounter.LENGTH.exactly().number(null)) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Encounter", capt.getAllValues().get(idx).getURI().toString()); idx++; - - client - .search() - .forResource(Observation.class) - .where(Observation.VALUE_QUANTITY.exactly().number(null).andUnits(null)) - .returnBundle(Bundle.class) - .execute(); - + client + .search() + .forResource(Observation.class) + .where(Observation.VALUE_QUANTITY.exactly().number(null).andUnits(null)) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Observation", capt.getAllValues().get(idx).getURI().toString()); idx++; @@ -1058,13 +1027,12 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client - .update() - .resource(bundle) - .prefer(PreferReturnEnum.REPRESENTATION) - .encodedJson() - .execute(); + .update() + .resource(bundle) + .prefer(PreferReturnEnum.REPRESENTATION) + .encodedJson() + .execute(); HttpPut httpRequest = (HttpPut) capt.getValue(); assertEquals("http://example.com/fhir/Bundle/BUNDLE1", httpRequest.getURI().toASCIIString()); @@ -1086,7 +1054,9 @@ public class GenericClientDstu2_1Test { bundle.addEntry().setResource(patient); final String encoded = p.encodeResourceToString(bundle); - assertEquals("", encoded); + assertEquals( + "", + encoded); ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -1102,12 +1072,11 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client - .update() - .resource(bundle) - .prefer(PreferReturnEnum.REPRESENTATION) - .execute(); + .update() + .resource(bundle) + .prefer(PreferReturnEnum.REPRESENTATION) + .execute(); HttpPut httpRequest = (HttpPut) capt.getValue(); assertEquals("http://example.com/fhir/Bundle/BUNDLE1", httpRequest.getURI().toASCIIString()); @@ -1132,7 +1101,9 @@ public class GenericClientDstu2_1Test { client.read().resource("Patient").withId("123").elementsSubset("name", "identifier").execute(); fail(); } catch (FhirClientConnectionException e) { - assertEquals("Failed to parse response from server when performing GET to URL http://example.com/fhir/Patient/123?_elements=identifier%2Cname - ca.uhn.fhir.parser.DataFormatException: Invalid JSON content detected, missing required element: 'resourceType'", e.getMessage()); + assertEquals( + "Failed to parse response from server when performing GET to URL http://example.com/fhir/Patient/123?_elements=identifier%2Cname - ca.uhn.fhir.parser.DataFormatException: Invalid JSON content detected, missing required element: 'resourceType'", + e.getMessage()); } } @@ -1146,7 +1117,7 @@ public class GenericClientDstu2_1Test { ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - // when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + // when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); when(myHttpResponse.getEntity().getContentType()).thenReturn(null); when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { @Override @@ -1163,8 +1134,8 @@ public class GenericClientDstu2_1Test { assertEquals("Response contains no Content-Type", e.getMessage()); } - // Patient resp = client.read().resource(Patient.class).withId("1").execute(); - // assertEquals("FAM", resp.getNameFirstRep().getFamilyAsSingleString()); + // Patient resp = client.read().resource(Patient.class).withId("1").execute(); + // assertEquals("FAM", resp.getNameFirstRep().getFamilyAsSingleString()); } @Test @@ -1178,7 +1149,7 @@ public class GenericClientDstu2_1Test { when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", "text/plain")); - // when(myHttpResponse.getEntity().getContentType()).thenReturn(null); + // when(myHttpResponse.getEntity().getContentType()).thenReturn(null); when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { @Override public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { @@ -1194,8 +1165,8 @@ public class GenericClientDstu2_1Test { assertEquals("Response contains non FHIR Content-Type 'text/plain' : ", e.getMessage()); } - // Patient resp = client.read().resource(Patient.class).withId("1").execute(); - // assertEquals("FAM", resp.getNameFirstRep().getFamilyAsSingleString()); + // Patient resp = client.read().resource(Patient.class).withId("1").execute(); + // assertEquals("FAM", resp.getNameFirstRep().getFamilyAsSingleString()); } @Test @@ -1219,93 +1190,84 @@ public class GenericClientDstu2_1Test { DateTimeDt now = DateTimeDt.withCurrentTime(); String dateString = now.getValueAsString().substring(0, 10); - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.after().day(dateString)) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/Patient?birthdate=gt"+dateString, capt.getAllValues().get(idx).getURI().toString()); + .forResource("Patient") + .where(Patient.BIRTHDATE.after().day(dateString)) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?birthdate=gt" + dateString, capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.after().day(now.getValue())) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/Patient?birthdate=gt"+dateString, capt.getAllValues().get(idx).getURI().toString()); + .forResource("Patient") + .where(Patient.BIRTHDATE.after().day(now.getValue())) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?birthdate=gt" + dateString, capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.afterOrEquals().day(dateString)) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/Patient?birthdate=ge"+dateString, capt.getAllValues().get(idx).getURI().toString()); + .forResource("Patient") + .where(Patient.BIRTHDATE.afterOrEquals().day(dateString)) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?birthdate=ge" + dateString, capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.before().day(dateString)) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/Patient?birthdate=lt"+dateString, capt.getAllValues().get(idx).getURI().toString()); + .forResource("Patient") + .where(Patient.BIRTHDATE.before().day(dateString)) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?birthdate=lt" + dateString, capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.beforeOrEquals().day(dateString)) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/Patient?birthdate=le"+dateString, capt.getAllValues().get(idx).getURI().toString()); + .forResource("Patient") + .where(Patient.BIRTHDATE.beforeOrEquals().day(dateString)) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?birthdate=le" + dateString, capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.exactly().day(dateString)) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/Patient?birthdate="+dateString, capt.getAllValues().get(idx).getURI().toString()); + .forResource("Patient") + .where(Patient.BIRTHDATE.exactly().day(dateString)) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?birthdate=" + dateString, capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.after().second("2011-01-02T22:33:01Z")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.BIRTHDATE.after().second("2011-01-02T22:33:01Z")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?birthdate=gt2011-01-02T22:33:01Z", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.after().second(now.getValueAsString())) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.BIRTHDATE.after().second(now.getValueAsString())) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?birthdate=gt" + now.getValueAsString(), UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Patient") - .where(Patient.BIRTHDATE.after().now()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.BIRTHDATE.after().now()) + .returnBundle(Bundle.class) + .execute(); + assertThat(capt.getAllValues().get(idx).getURI().toString(), startsWith("http://example.com/fhir/Patient?birthdate=gt2")); dateString = UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()).substring(44); ourLog.info(dateString); @@ -1332,113 +1294,102 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.approximately().number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.approximately().number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=ap123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.approximately().number("123").andUnits("CODE")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.approximately().number("123").andUnits("CODE")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=ap123||CODE", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.approximately().number("123").andUnits("SYSTEM", "CODE")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.approximately().number("123").andUnits("SYSTEM", "CODE")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=ap123|SYSTEM|CODE", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.exactly().number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.exactly().number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.exactly().number("123").andUnits("CODE")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.exactly().number("123").andUnits("CODE")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=123||CODE", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.exactly().number("123").andUnits("SYSTEM", "CODE")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.exactly().number("123").andUnits("SYSTEM", "CODE")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=123|SYSTEM|CODE", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.greaterThan().number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.greaterThan().number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=gt123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.lessThan().number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.lessThan().number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=lt123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.greaterThanOrEquals().number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.greaterThanOrEquals().number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=ge123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.lessThanOrEquals().number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.lessThanOrEquals().number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=le123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Observation") - .where(Observation.VALUE_QUANTITY.withPrefix(ParamPrefixEnum.GREATERTHAN).number(123).andNoUnits()) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Observation") + .where(Observation.VALUE_QUANTITY.withPrefix(ParamPrefixEnum.GREATERTHAN).number(123).andNoUnits()) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Observation?value-quantity=gt123||", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; @@ -1462,83 +1413,75 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("AAA")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matches().value("AAA")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name=AAA", capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value(new StringDt("AAA"))) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matches().value(new StringDt("AAA"))) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name=AAA", capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matches().values("AAA", "BBB")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matches().values("AAA", "BBB")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name=AAA,BBB", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matches().values(Arrays.asList("AAA", "BBB"))) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matches().values(Arrays.asList("AAA", "BBB"))) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name=AAA,BBB", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matchesExactly().value("AAA")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matchesExactly().value("AAA")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name%3Aexact=AAA", capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matchesExactly().value(new StringDt("AAA"))) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matchesExactly().value(new StringDt("AAA"))) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name%3Aexact=AAA", capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matchesExactly().values("AAA", "BBB")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matchesExactly().values("AAA", "BBB")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name:exact=AAA,BBB", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; - client.search() - .forResource("Patient") - .where(Patient.NAME.matchesExactly().values(Arrays.asList("AAA", "BBB"))) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.NAME.matchesExactly().values(Arrays.asList("AAA", "BBB"))) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?name:exact=AAA,BBB", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; @@ -1562,40 +1505,27 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client.search() - .forResource("Device") - .where(Device.URL.matches().value("http://foo.com")) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Device") + .where(Device.URL.matches().value("http://foo.com")) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Device?url=http://foo.com", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("http://example.com/fhir/Device?url=http%3A%2F%2Ffoo.com", capt.getAllValues().get(idx).getURI().toString()); idx++; - client.search() - .forResource("Device") - .where(Device.URL.matches().value(new StringDt("http://foo.com"))) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Device") + .where(Device.URL.matches().value(new StringDt("http://foo.com"))) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Device?url=http://foo.com", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; } - @Test - public void testSearchForUnknownType() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - try { - client.search(new UriDt("?aaaa")); - fail(); - } catch (IllegalArgumentException e) { - assertEquals("Unable to determine the resource type from the given URI: ?aaaa", e.getMessage()); - } - } - @Test public void testSearchWithMultipleTokens() throws Exception { ArgumentCaptor capt = prepareClientForSearchResponse(); @@ -1605,13 +1535,12 @@ public class GenericClientDstu2_1Test { Collection values = Arrays.asList("VAL1", "VAL2", "VAL3A,B"); - client.search() - .forResource("Patient") - .where(Patient.IDENTIFIER.exactly().systemAndValues("SYS", values)) - .returnBundle(Bundle.class) - .execute(); - + .forResource("Patient") + .where(Patient.IDENTIFIER.exactly().systemAndValues("SYS", values)) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient?identifier=SYS%7CVAL1%2CSYS%7CVAL2%2CSYS%7CVAL3A%5C%2CB", capt.getAllValues().get(idx).getURI().toString()); assertEquals("http://example.com/fhir/Patient?identifier=SYS|VAL1,SYS|VAL2,SYS|VAL3A\\,B", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); idx++; @@ -1643,33 +1572,32 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - client - .search() - .forResource(Patient.class) - .sort().ascending("address") - .returnBundle(Bundle.class) - .execute(); + .search() + .forResource(Patient.class) + .sort().ascending("address") + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?_sort=address", capt.getAllValues().get(idx++).getURI().toASCIIString()); - client - .search() - .forResource(Patient.class) - .sort().descending("address") - .returnBundle(Bundle.class) - .execute(); + client + .search() + .forResource(Patient.class) + .sort().descending("address") + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?_sort=-address", capt.getAllValues().get(idx++).getURI().toASCIIString()); - client - .search() - .forResource(Patient.class) - .sort().descending("address") - .sort().ascending("name") - .sort().descending(Patient.BIRTHDATE) - .returnBundle(Bundle.class) - .execute(); + client + .search() + .forResource(Patient.class) + .sort().descending("address") + .sort().ascending("name") + .sort().descending(Patient.BIRTHDATE) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?_sort=-address%2Cname%2C-birthdate", capt.getAllValues().get(idx++).getURI().toASCIIString()); - + } @Test @@ -1708,7 +1636,6 @@ public class GenericClientDstu2_1Test { assertEquals("Unable to determing encoding of request (body does not appear to be valid XML or JSON)", e.getMessage()); } - } @Test @@ -1923,13 +1850,11 @@ public class GenericClientDstu2_1Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); client.registerInterceptor(new UserInfoInterceptor("user_id", "user_name", "app-name")); - Bundle resp = client - .history() - .onType(Patient.class) - .andReturnBundle(Bundle.class) - .execute(); - + .history() + .onType(Patient.class) + .andReturnBundle(Bundle.class) + .execute(); } @@ -2016,7 +1941,6 @@ public class GenericClientDstu2_1Test { patient.getText().setDivAsString("OK!"); b.addEntry().setResource(patient); - final String respString = p.encodeResourceToString(b); ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -2047,8 +1971,6 @@ public class GenericClientDstu2_1Test { assertEquals(expectedUserAgent(), capt.getAllValues().get(0).getHeaders("User-Agent")[0].getValue()); } - - @AfterClass public static void afterClassClearContext() { TestUtil.clearAllStaticFieldsForUnitTest(); diff --git a/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java b/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java index 4bb344d978d..676a1184782 100644 --- a/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java +++ b/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java @@ -258,11 +258,6 @@ public class Dstu2BundleFactory implements IVersionSpecificBundleFactory { } } - @Override - public ca.uhn.fhir.model.api.Bundle getDstu1Bundle() { - return null; - } - @Override public IResource getResourceBundle() { return myBundle; diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserDstu2Test.java index bc7e82845a7..938263abb2f 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserDstu2Test.java @@ -36,7 +36,6 @@ import com.google.common.collect.Sets; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.*; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.base.composite.BaseCodingDt; import ca.uhn.fhir.model.dstu2.composite.*; import ca.uhn.fhir.model.dstu2.resource.*; @@ -74,7 +73,7 @@ public class JsonParserDstu2Test { ourCtx = FhirContext.forDstu2(); } } - + @Test public void testOverrideResourceIdWithBundleEntryFullUrlDisabled_ConfiguredOnParser() { try { @@ -94,30 +93,30 @@ public class JsonParserDstu2Test { ourCtx = FhirContext.forDstu2(); } } - + /** * See #544 */ @Test public void testBundleStitchReferencesByUuid() throws Exception { ca.uhn.fhir.model.dstu2.resource.Bundle bundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - + DocumentManifest dm = new DocumentManifest(); dm.getSubject().setReference("urn:uuid:96e85cca-9797-45d6-834a-c4eb27f331d3"); bundle.addEntry().setResource(dm); - + Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); bundle.addEntry().setResource(patient).setFullUrl("urn:uuid:96e85cca-9797-45d6-834a-c4eb27f331d3"); - + String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle); ourLog.info(encoded); - + bundle = ourCtx.newJsonParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, encoded); dm = (DocumentManifest) bundle.getEntry().get(0).getResource(); - + assertEquals("urn:uuid:96e85cca-9797-45d6-834a-c4eb27f331d3", dm.getSubject().getReference().getValue()); - + Patient subject = (Patient) dm.getSubject().getResource(); assertNotNull(subject); assertEquals("FAMILY", subject.getNameFirstRep().getFamilyAsSingleString()); @@ -145,21 +144,6 @@ public class JsonParserDstu2Test { assertEquals("ORG", o.getName()); } - @Test - public void testEncodeBundleOldStyleContainingResourceWithUuidBase() { - Patient p = new Patient(); - p.setId(IdDt.newRandomUuid()); - p.addName().addFamily("PATIENT"); - - Bundle b = new Bundle(); - b.addEntry().setResource(p); - - String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b); - ourLog.info(encoded); - assertThat(encoded, stringContainsInOrder("fullUrl", p.getId().getValue(), "Patient")); - } - - /** * See #308 */ @@ -536,43 +520,6 @@ public class JsonParserDstu2Test { } - @Test - public void testEncodeBundleOldBundleNoText() { - - Bundle b = new Bundle(); - - BundleEntry e = b.addEntry(); - e.setResource(new Patient()); - b.addCategory("scheme", "term", "label"); - - String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeBundleToString(b); - ourLog.info(val); - - assertThat(val, not(containsString("text"))); - - b = ourCtx.newJsonParser().parseBundle(val); - assertEquals(1, b.getEntries().size()); - - } - - /** - * Fixing #89 - */ - @Test - public void testEncodeBundleWithDeletedEntry() throws ConfigurationException, DataFormatException, IOException { - Bundle b = ourCtx.newXmlParser().parseBundle(IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/xml-bundle.xml"))); - String val = ourCtx.newJsonParser().encodeBundleToString(b); - - ourLog.info(val); - - //@formatter:off - assertThat(val, containsString("\"deleted\":{" + - "\"type\":\"Patient\"," + - "\"resourceId\":\"4384\"," + - "\"instant\":\"2015-01-15T11:04:43.054-05:00\"" + - "}")); - //@formatter:on - } @Test public void testEncodeDoesntIncludeUuidId() { @@ -1055,28 +1002,28 @@ public class JsonParserDstu2Test { public void testParseAndEncodeBundle() throws Exception { String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-example.json")); - Bundle parsed = ourCtx.newJsonParser().parseBundle(content); + Bundle parsed = ourCtx.newJsonParser().parseResource(Bundle.class, content); assertEquals("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("https://example.com/base/MedicationOrder?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLinkNext().getValue()); - assertEquals("https://example.com/base/MedicationOrder?patient=347&_include=MedicationOrder.medication", parsed.getLinkSelf().getValue()); + assertEquals("searchset", parsed.getTypeElement().getValueAsString()); + assertEquals(3, parsed.getTotalElement().getValue().intValue()); + assertEquals("https://example.com/base/MedicationOrder?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink("next").getUrl()); + assertEquals("https://example.com/base/MedicationOrder?patient=347&_include=MedicationOrder.medication", parsed.getLink("self").getUrl()); - assertEquals(2, parsed.getEntries().size()); + assertEquals(2, parsed.getEntry().size()); - MedicationOrder p = (MedicationOrder) parsed.getEntries().get(0).getResource(); + MedicationOrder p = (MedicationOrder) 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/MedicationOrder/3123/_history/1", p.getId().getValue()); - Medication m = (Medication) parsed.getEntries().get(1).getResource(); + Medication m = (Medication) parsed.getEntry().get(1).getResource(); assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); assertSame(((ResourceReferenceDt) p.getMedication()).getResource(), m); - String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(parsed); + String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed); ourLog.info(reencoded); JsonConfig cfg = new JsonConfig(); @@ -1130,7 +1077,7 @@ public class JsonParserDstu2Test { 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()); + assertEquals("searchset", parsed.getTypeElement().getValue()); assertEquals(3, parsed.getTotal().intValue()); assertEquals("https://example.com/base/MedicationOrder?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink().get(0).getUrlElement().getValueAsString()); assertEquals("https://example.com/base/MedicationOrder?patient=347&_include=MedicationOrder.medication", parsed.getLink().get(1).getUrlElement().getValueAsString()); @@ -1169,25 +1116,25 @@ public class JsonParserDstu2Test { public void testParseAndEncodeBundleOldStyle() throws Exception { String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-example.json")); - Bundle parsed = ourCtx.newJsonParser().parseBundle(content); + Bundle parsed = ourCtx.newJsonParser().parseResource(Bundle.class, content); 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("searchset", parsed.getTypeElement().getValue()); + assertEquals(3, parsed.getTotalElement().getValue().intValue()); - assertEquals(2, parsed.getEntries().size()); + assertEquals(2, parsed.getEntry().size()); - MedicationOrder p = (MedicationOrder) parsed.getEntries().get(0).getResource(); + MedicationOrder p = (MedicationOrder) 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/MedicationOrder/3123/_history/1", p.getId().getValue()); - Medication m = (Medication) parsed.getEntries().get(1).getResource(); + Medication m = (Medication) parsed.getEntry().get(1).getResource(); assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); assertEquals("Medication/example", ((ResourceReferenceDt) p.getMedication()).getReference().getValue()); assertSame(((ResourceReferenceDt) p.getMedication()).getResource(), m); - String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(parsed); + String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed); ourLog.info(reencoded); JsonConfig cfg = new JsonConfig(); @@ -1211,31 +1158,13 @@ public class JsonParserDstu2Test { public void testParseAndEncodeBundleResourceWithComments() throws Exception { String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-transaction2.json")); - ourCtx.newJsonParser().parseBundle(content); + ourCtx.newJsonParser().parseResource(Bundle.class, content); ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newJsonParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, content); // TODO: preserve comments } - @Test - public void testParseAndEncodeBundleWithDeletedEntry() { - - Patient res = new Patient(); - res.setId(new IdDt("Patient", "111", "222")); - ResourceMetadataKeyEnum.DELETED_AT.put(res, new InstantDt("2011-01-01T12:12:22Z")); - - Bundle bundle = new Bundle(); - bundle.addResource(res, ourCtx, "http://foo/base"); - - String actual = ourCtx.newJsonParser().encodeBundleToString(bundle); - ourLog.info(actual); - - String expected = "{\"resourceType\":\"Bundle\",\"entry\":[{\"deleted\":{\"type\":\"Patient\",\"resourceId\":\"111\",\"versionId\":\"222\",\"instant\":\"2011-01-01T12:12:22Z\"}}]}"; - assertEquals(expected, actual); - - } - @Test public void testParseAndEncodeBundleWithUuidBase() { //@formatter:off @@ -1531,38 +1460,32 @@ public class JsonParserDstu2Test { " \"lastUpdated\" : \"2001-02-22T11:22:33-05:00\"\n" + " },\n" + " \"birthDate\" : \"2012-01-02\"\n" + - " },\n" + - " \"search\" : {\n" + - " \"mode\" : \"match\",\n" + - " \"score\" : 0.123\n" + - " },\n" + - " \"request\" : {\n" + - " \"method\" : \"POST\",\n" + - " \"url\" : \"http://foo/Patient?identifier=value\"\n" + - " }\n" + + " }\n" + " }]\n" + "}"; //@formatter:on - Bundle b = ourCtx.newJsonParser().parseBundle(bundle); - assertEquals(1, b.getEntries().size()); + Bundle b = ourCtx.newJsonParser().parseResource(Bundle.class, bundle); + assertEquals(1, b.getEntry().size()); - Patient pt = (Patient) b.getEntries().get(0).getResource(); + Patient pt = (Patient) b.getEntry().get(0).getResource(); assertEquals("http://foo/fhirBase2/Patient/1/_history/2", pt.getId().getValue()); assertEquals("2012-01-02", pt.getBirthDateElement().getValueAsString()); - assertEquals("0.123", ResourceMetadataKeyEnum.ENTRY_SCORE.get(pt).getValueAsString()); - assertEquals("match", ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(pt).getCode()); - assertEquals("POST", ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(pt).getCode()); - assertEquals("http://foo/Patient?identifier=value", ResourceMetadataKeyEnum.LINK_SEARCH.get(pt)); - assertEquals("2001-02-22T11:22:33-05:00", ResourceMetadataKeyEnum.UPDATED.get(pt).getValueAsString()); +// assertEquals("match", ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(pt).getCode()); +// assertEquals("POST", ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(pt).getCode()); +// assertEquals("http://foo/Patient?identifier=value", ResourceMetadataKeyEnum.LINK_SEARCH.get(pt)); +// assertEquals("2001-02-22T11:22:33-05:00", ResourceMetadataKeyEnum.UPDATED.get(pt).getValueAsString()); Bundle toBundle = new Bundle(); - toBundle.getLinkBase().setValue("http://foo/fhirBase1"); - toBundle.getTotalResults().setValue(1); - toBundle.getLinkSelf().setValue("http://localhost:52788/Binary?_pretty=true"); + toBundle.getTotalElement().setValue(1); +// toBundle.getLinkOrCreate("base").setUrl("http://foo/fhirBase1"); + toBundle.getLinkOrCreate("self").setUrl("http://localhost:52788/Binary?_pretty=true"); - toBundle.addResource(pt, ourCtx, "http://foo/fhirBase1"); - String reEncoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(toBundle); + toBundle + .addEntry() + .setFullUrl("http://foo/fhirBase2/Patient/1/_history/2") + .setResource(pt); + String reEncoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(toBundle); JsonConfig cfg = new JsonConfig(); @@ -1692,9 +1615,9 @@ public class JsonParserDstu2Test { String text = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; FhirContext ctx = FhirContext.forDstu2(); - Bundle b = ctx.newJsonParser().parseBundle(text); + Bundle b = ctx.newJsonParser().parseResource(Bundle.class, text); - IResource patient = b.getEntries().get(0).getResource(); + IResource patient = b.getEntry().get(0).getResource(); assertEquals(Patient.class, patient.getClass()); assertNull(ResourceMetadataKeyEnum.TAG_LIST.get(patient)); @@ -1999,29 +1922,29 @@ public class JsonParserDstu2Test { patient.setPetName(new StringDt("myName")); final Bundle bundle = new Bundle(); - final BundleEntry entry = new BundleEntry(); + final Entry entry = new Entry(); entry.setResource(patient); bundle.addEntry(entry); final IParser jsonParser = ourCtx.newJsonParser(); jsonParser.setServerBaseUrl("http://www.example.com"); - final String parsedBundle = jsonParser.encodeBundleToString(bundle); + final String parsedBundle = jsonParser.encodeResourceToString(bundle); System.out.println(parsedBundle); assertEquals(expected, parsedBundle); // Parse with string - Bundle newBundle = jsonParser.parseBundle(parsedBundle); + Bundle newBundle = jsonParser.parseResource(Bundle.class, parsedBundle); assertNotNull(newBundle); - assertEquals(1, newBundle.getEntries().size()); - Patient newPatient = (Patient) newBundle.getEntries().get(0).getResource(); + assertEquals(1, newBundle.getEntry().size()); + Patient newPatient = (Patient) newBundle.getEntry().get(0).getResource(); assertEquals("myName", ((StringDt) newPatient.getUndeclaredExtensionsByUrl("http://www.example.com/petname").get(0).getValue()).getValue()); // Parse with stream - newBundle = jsonParser.parseBundle(new StringReader(parsedBundle)); + newBundle = jsonParser.parseResource(Bundle.class, new StringReader(parsedBundle)); assertNotNull(newBundle); - assertEquals(1, newBundle.getEntries().size()); - newPatient = (Patient) newBundle.getEntries().get(0).getResource(); + assertEquals(1, newBundle.getEntry().size()); + newPatient = (Patient) newBundle.getEntry().get(0).getResource(); assertEquals("myName", ((StringDt) newPatient.getUndeclaredExtensionsByUrl("http://www.example.com/petname").get(0).getValue()).getValue()); } 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 b5fac94dbab..7cf1a816eea 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 @@ -41,7 +41,6 @@ import com.google.common.collect.Sets; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.*; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.base.composite.BaseCodingDt; @@ -67,7 +66,7 @@ public class XmlParserDstu2Test { ourCtx = FhirContext.forDstu2(); } } - + @Test public void testOverrideResourceIdWithBundleEntryFullUrlDisabled_ConfiguredOnFhirContext() { try { @@ -88,7 +87,7 @@ public class XmlParserDstu2Test { ourCtx = null; } } - + @Test public void testOverrideResourceIdWithBundleEntryFullUrlDisabled_ConfiguredOnParser() { try { @@ -108,7 +107,7 @@ public class XmlParserDstu2Test { ourCtx = null; } } - + /** * See #414 */ @@ -137,10 +136,9 @@ public class XmlParserDstu2Test { } catch (DataFormatException e) { assertEquals("Resource is missing required element 'url' in parent element 'extension'", e.getCause().getMessage()); } - + } - /** * See #414 */ @@ -169,9 +167,9 @@ public class XmlParserDstu2Test { } catch (DataFormatException e) { assertEquals("Resource is missing required element 'url' in parent element 'modifierExtension'", e.getCause().getMessage()); } - + } - + /** * If a contained resource refers to a contained resource that comes after it, it should still be successfully * woven together. @@ -179,11 +177,11 @@ public class XmlParserDstu2Test { @Test public void testParseWovenContainedResources() throws IOException { String string = IOUtils.toString(getClass().getResourceAsStream("/bundle_with_woven_obs.xml"), StandardCharsets.UTF_8); - + IParser parser = ourCtx.newXmlParser(); parser.setParserErrorHandler(new StrictErrorHandler()); ca.uhn.fhir.model.dstu2.resource.Bundle bundle = parser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, string); - + DiagnosticReport resource = (DiagnosticReport) bundle.getEntry().get(0).getResource(); Observation obs = (Observation) resource.getResult().get(1).getResource(); assertEquals("#2", obs.getId().getValue()); @@ -191,30 +189,29 @@ public class XmlParserDstu2Test { Practitioner performer = (Practitioner) performerFirstRep.getResource(); assertEquals("#3", performer.getId().getValue()); } - - @Test(expected=DataFormatException.class) + + @Test(expected = DataFormatException.class) public void testContainedResourceWithNoId() throws IOException { String string = IOUtils.toString(getClass().getResourceAsStream("/bundle_with_contained_with_no_id.xml"), StandardCharsets.UTF_8); - + IParser parser = ourCtx.newXmlParser(); parser.setParserErrorHandler(new StrictErrorHandler()); parser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, string); } - @Test() public void testContainedResourceWithNoIdLenient() throws IOException { String string = IOUtils.toString(getClass().getResourceAsStream("/bundle_with_contained_with_no_id.xml"), StandardCharsets.UTF_8); - + IParser parser = ourCtx.newXmlParser(); parser.setParserErrorHandler(new LenientErrorHandler()); parser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, string); } - @Test(expected=DataFormatException.class) + @Test(expected = DataFormatException.class) public void testParseWithInvalidLocalRef() throws IOException { String string = IOUtils.toString(getClass().getResourceAsStream("/bundle_with_invalid_contained_ref.xml"), StandardCharsets.UTF_8); - + IParser parser = ourCtx.newXmlParser(); parser.setParserErrorHandler(new StrictErrorHandler()); parser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, string); @@ -223,13 +220,12 @@ public class XmlParserDstu2Test { @Test() public void testParseWithInvalidLocalRefLenient() throws IOException { String string = IOUtils.toString(getClass().getResourceAsStream("/bundle_with_invalid_contained_ref.xml"), StandardCharsets.UTF_8); - + IParser parser = ourCtx.newXmlParser(); parser.setParserErrorHandler(new LenientErrorHandler()); parser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, string); } - @Test public void testBundleWithBinary() { //@formatter:off @@ -254,14 +250,14 @@ public class XmlParserDstu2Test { ""; //@formatter:on - Bundle b = ourCtx.newXmlParser().parseBundle(bundle); - assertEquals(1, b.getEntries().size()); + Bundle b = ourCtx.newXmlParser().parseResource(Bundle.class, bundle); + assertEquals(1, b.getEntry().size()); - Binary bin = (Binary) b.getEntries().get(0).getResource(); + Binary bin = (Binary) b.getEntry().get(0).getResource(); assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bin.getContent()); } - + @Test public void testChoiceTypeWithProfiledType() { //@formatter:off @@ -281,7 +277,7 @@ public class XmlParserDstu2Test { String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed); assertThat(encoded, containsString("")); } - + @Test public void testChoiceTypeWithProfiledType2() { Parameters par = new Parameters(); @@ -299,7 +295,6 @@ public class XmlParserDstu2Test { assertEquals(MarkdownDt.class, par.getParameter().get(1).getValue().getClass()); } - @Test public void testContainedResourceInExtensionUndeclared() { Patient p = new Patient(); @@ -359,13 +354,14 @@ public class XmlParserDstu2Test { Organization org = new Organization(); org.addIdentifier().setSystem("urn:system").setValue("someval"); - Bundle bundle = Bundle.withSingleResource(org); - String str = ourCtx.newXmlParser().encodeBundleToString(bundle); + Bundle bundle = new Bundle(); + bundle.addEntry().setResource(org); + String str = ourCtx.newXmlParser().encodeResourceToString(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()); + Bundle parsed = ourCtx.newXmlParser().parseResource(Bundle.class, str); + assertThat(parsed.getEntry().get(0).getResource().getId().getValue(), emptyOrNullString()); + assertTrue(parsed.getEntry().get(0).getResource().getId().isEmpty()); } @Test @@ -479,20 +475,20 @@ public class XmlParserDstu2Test { ourCtx = FhirContext.forDstu2(); ourCtx.setDefaultTypeForProfile(CustomObservationDstu2.PROFILE, CustomObservationDstu2.class); ourCtx.setDefaultTypeForProfile(CustomDiagnosticReportDstu2.PROFILE, CustomDiagnosticReportDstu2.class); - + CustomObservationDstu2 obs = new CustomObservationDstu2(); obs.setStatus(ObservationStatusEnum.FINAL); - + CustomDiagnosticReportDstu2 dr = new CustomDiagnosticReportDstu2(); dr.setStatus(DiagnosticReportStatusEnum.FINAL); dr.addResult().setResource(obs); - + IParser parser = ourCtx.newXmlParser(); parser.setPrettyPrint(true); - + String output = parser.encodeResourceToString(dr); ourLog.info(output); - + //@formatter:off assertThat(output,stringContainsInOrder( "", @@ -514,11 +510,11 @@ public class XmlParserDstu2Test { "", "")); //@formatter:on - + /* * Now PARSE! */ - + dr = (CustomDiagnosticReportDstu2) parser.parseResource(output); assertEquals(DiagnosticReportStatusEnum.FINAL, dr.getStatusElement().getValueAsEnum()); @@ -549,35 +545,34 @@ public class XmlParserDstu2Test { "" + ""; //@formatter:on - + IParser parser = ourCtx.newXmlParser(); CustomDiagnosticReportDstu2 dr = (CustomDiagnosticReportDstu2) parser.parseResource(input); assertEquals(DiagnosticReportStatusEnum.FINAL, dr.getStatusElement().getValueAsEnum()); List profiles = ResourceMetadataKeyEnum.PROFILES.get(dr); assertEquals(3, profiles.size()); - + ourCtx = null; } - @Test public void testEncodeAndParseContainedNonCustomTypes() { ourCtx = FhirContext.forDstu2(); - + Observation obs = new Observation(); obs.setStatus(ObservationStatusEnum.FINAL); - + DiagnosticReport dr = new DiagnosticReport(); dr.setStatus(DiagnosticReportStatusEnum.FINAL); dr.addResult().setResource(obs); - + IParser parser = ourCtx.newXmlParser(); parser.setPrettyPrint(true); - + String output = parser.encodeResourceToString(dr); ourLog.info(output); - + //@formatter:off assertThat(output,stringContainsInOrder( "", @@ -593,11 +588,11 @@ public class XmlParserDstu2Test { "", "")); //@formatter:on - + /* * Now PARSE! */ - + dr = (DiagnosticReport) parser.parseResource(output); assertEquals(DiagnosticReportStatusEnum.FINAL, dr.getStatusElement().getValueAsEnum()); @@ -621,10 +616,10 @@ public class XmlParserDstu2Test { condition.setOurAbatement(new DateTimeDt(new Date())); String conditionXml = parser.encodeResourceToString(condition); - + ourLog.info(conditionXml); assertThat(conditionXml, containsString("abatementDateTime")); - + CustomCondition parsedCondition = (CustomCondition) parser.parseResource(conditionXml); assertNotNull(parsedCondition.getOurAbatement()); } @@ -1120,9 +1115,9 @@ public class XmlParserDstu2Test { p.addName().addFamily("PATIENT"); Bundle b = new Bundle(); - b.addEntry().setResource(p); + b.addEntry().setFullUrl(p.getId().getValue()).setResource(p); - String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(b); + String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(b); ourLog.info(encoded); assertThat(encoded, stringContainsInOrder("", "", ""))); @@ -1135,10 +1130,10 @@ public class XmlParserDstu2Test { p.addName().addFamily("PATIENT"); Bundle b = new Bundle(); - b.getLinkBase().setValue("urn:uuid:"); + b.getLinkOrCreate("base").setUrl("urn:uuid:"); b.addEntry().setResource(p); - String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(b); + String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(b); ourLog.info(encoded); // Base element has been removed! assertThat(encoded, not(stringContainsInOrder("", "line1\nline2\nline3 BOLD" )); //@formatter:on - + } /** @@ -1326,13 +1321,13 @@ public class XmlParserDstu2Test { */ @Test public void testEncodeDivWithPrePrettyPrint() { - + Patient p = new Patient(); p.getText().setDiv("
    \n\n

    A P TAG

    line1\nline2\nline3  BOLD

    "); - + String output = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); ourLog.info(output); - + //@formatter:off assertThat(output, stringContainsInOrder( " ", @@ -1340,7 +1335,7 @@ public class XmlParserDstu2Test { "
    line1\nline2\nline3  BOLD
    " )); //@formatter:on - + } @Test @@ -1352,7 +1347,7 @@ public class XmlParserDstu2Test { String actual = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p); assertThat(actual, not(containsString("78ef6f64c2f2"))); } - + @Test public void testEncodeEmptyBinary() { String output = ourCtx.newXmlParser().encodeResourceToString(new Binary()); @@ -1367,10 +1362,10 @@ public class XmlParserDstu2Test { TagList tagList = new TagList(); tagList.addTag(null, null, null); tagList.addTag(null, null, "Label"); - + Patient p = new Patient(); ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList); - + String encoded = ourCtx.newXmlParser().encodeResourceToString(p); assertThat(encoded, not(containsString("tag"))); } @@ -1383,10 +1378,10 @@ public class XmlParserDstu2Test { TagList tagList = new TagList(); tagList.addTag("scheme", "code", null); tagList.addTag(null, null, "Label"); - + Patient p = new Patient(); ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList); - + String encoded = ourCtx.newXmlParser().encodeResourceToString(p); assertThat(encoded, containsString("tag")); assertThat(encoded, containsString("scheme")); @@ -1400,11 +1395,11 @@ public class XmlParserDstu2Test { obs.getMeta().addProfile("http://profile"); ExtensionDt ext = obs.addUndeclaredExtension(false, "http://exturl"); ext.setUrl("http://exturl").setValue(new StringDt("ext_url_value")); - + obs.getCode().setText("CODE"); - + IParser parser = ourCtx.newXmlParser(); - + String output = parser.setPrettyPrint(true).encodeResourceToString(obs); ourLog.info(output); @@ -1912,30 +1907,30 @@ public class XmlParserDstu2Test { public void testParseAndEncodeBundle() throws Exception { String content = IOUtils.toString(XmlParserDstu2Test.class.getResourceAsStream("/bundle-example.xml"), StandardCharsets.UTF_8); - Bundle parsed = ourCtx.newXmlParser().parseBundle(content); + Bundle parsed = ourCtx.newXmlParser().parseResource(Bundle.class, content); assertEquals("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("https://example.com/base/MedicationOrder?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLinkNext().getValue()); - assertEquals("https://example.com/base/MedicationOrder?patient=347&_include=MedicationOrder.medication", parsed.getLinkSelf().getValue()); + assertEquals("searchset", parsed.getTypeElement().getValue()); + assertEquals(3, parsed.getTotalElement().getValue().intValue()); + assertEquals("https://example.com/base/MedicationOrder?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink("next").getUrl()); + assertEquals("https://example.com/base/MedicationOrder?patient=347&_include=MedicationOrder.medication", parsed.getLink("self").getUrl()); - assertEquals(2, parsed.getEntries().size()); - assertEquals("http://foo?search", parsed.getEntries().get(0).getLinkSearch().getValue()); + assertEquals(2, parsed.getEntry().size()); + // assertEquals("http://foo?search", parsed.getEntry().get(0).getLink("search").getUrl()); + // assertEquals("http://example.com/base/MedicationOrder/3123/_history/1", parsed.getEntry().get(0).getLink("alternate").getUrl()); - assertEquals("http://example.com/base/MedicationOrder/3123/_history/1", parsed.getEntries().get(0).getLinkAlternate().getValue()); - MedicationOrder p = (MedicationOrder) parsed.getEntries().get(0).getResource(); + MedicationOrder p = (MedicationOrder) 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/MedicationOrder/3123/_history/1", p.getId().getValue()); - Medication m = (Medication) parsed.getEntries().get(1).getResource(); + Medication m = (Medication) parsed.getEntry().get(1).getResource(); assertEquals("http://example.com/base/Medication/example", m.getId().getValue()); assertSame(((ResourceReferenceDt) p.getMedication()).getResource(), m); - String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(parsed); + String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed); ourLog.info(reencoded); Diff d = new Diff(new StringReader(content), new StringReader(reencoded)); @@ -1952,7 +1947,7 @@ public class XmlParserDstu2Test { assertEquals("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("searchset", parsed.getTypeElement().getValueAsString()); assertEquals(3, parsed.getTotal().intValue()); assertEquals("https://example.com/base/MedicationOrder?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink().get(0).getUrlElement().getValueAsString()); assertEquals("https://example.com/base/MedicationOrder?patient=347&_include=MedicationOrder.medication", parsed.getLink().get(1).getUrlElement().getValueAsString()); @@ -2404,46 +2399,8 @@ public class XmlParserDstu2Test { ""; //@formatter:on - Bundle b = ourCtx.newXmlParser().parseBundle(bundle); - assertEquals(1, b.getEntries().size()); - - } - - @Test - 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()); + Bundle b = ourCtx.newXmlParser().parseResource(Bundle.class, bundle); + assertEquals(1, b.getEntry().size()); } @@ -2452,8 +2409,6 @@ public class XmlParserDstu2Test { // TODO: implement this test, make sure we handle ID and meta correctly in Binary } - - /** * See #191 */ @@ -2559,15 +2514,14 @@ public class XmlParserDstu2Test { /** * See #366 */ - @Test(expected=DataFormatException.class) + @Test(expected = DataFormatException.class) public void testParseInvalidBoolean() { //@formatter:off String resource = "\n" + " \n" + ""; //@formatter:on - - + IParser parser = ourCtx.newXmlParser(); parser.setParserErrorHandler(new StrictErrorHandler()); parser.parseResource(resource); @@ -2621,6 +2575,10 @@ public class XmlParserDstu2Test { String bundle = "\n" + " \n" + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + " \n" + " \n" + " \n" + @@ -2636,37 +2594,33 @@ public class XmlParserDstu2Test { " \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()); + Bundle b = ourCtx.newXmlParser().parseResource(Bundle.class, bundle); + assertEquals(1, b.getEntry().size()); - Patient pt = (Patient) b.getEntries().get(0).getResource(); + Patient pt = (Patient) b.getEntry().get(0).getResource(); assertEquals("http://foo/fhirBase2/Patient/1/_history/2", pt.getId().getValue()); assertEquals("2012-01-02", pt.getBirthDateElement().getValueAsString()); - assertEquals("0.123", ResourceMetadataKeyEnum.ENTRY_SCORE.get(pt).getValueAsString()); - assertEquals("match", ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(pt).getCode()); - assertEquals("POST", ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(pt).getCode()); - assertEquals("http://foo/Patient?identifier=value", ResourceMetadataKeyEnum.LINK_SEARCH.get(pt)); - assertEquals("2001-02-22T11:22:33-05:00", ResourceMetadataKeyEnum.UPDATED.get(pt).getValueAsString()); + // assertEquals("0.123", ResourceMetadataKeyEnum.ENTRY_SCORE.get(pt).getValueAsString()); + // assertEquals("match", ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(pt).getCode()); + // assertEquals("POST", ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(pt).getCode()); + // assertEquals("http://foo/Patient?identifier=value", ResourceMetadataKeyEnum.LINK_SEARCH.get(pt)); + // assertEquals("2001-02-22T11:22:33-05:00", ResourceMetadataKeyEnum.UPDATED.get(pt).getValueAsString()); Bundle toBundle = new Bundle(); - toBundle.getLinkBase().setValue("http://foo/fhirBase1"); - toBundle.getTotalResults().setValue(1); - toBundle.getLinkSelf().setValue("http://localhost:52788/Binary?_pretty=true"); + toBundle.getLinkOrCreate("base").setUrl("http://foo/fhirBase1"); + toBundle.getTotalElement().setValue(1); + toBundle.getLinkOrCreate("self").setUrl("http://localhost:52788/Binary?_pretty=true"); - toBundle.addResource(pt, ourCtx, "http://foo/fhirBase1"); - String reEncoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(toBundle); + toBundle + .addEntry() + .setResource(pt) + .setFullUrl("http://foo/fhirBase2/Patient/1/_history/2"); + + String reEncoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(toBundle); ourLog.info(reEncoded); @@ -2769,7 +2723,7 @@ public class XmlParserDstu2Test { assertEquals("Patient", reincarnatedPatient.getId().getResourceType()); } - /** + /** * Test for the url generated based on the server config */ @Test @@ -2811,7 +2765,7 @@ public class XmlParserDstu2Test { newPatient = xmlParser.parseResource(MyPatientWithCustomUrlExtension.class, new StringReader(parsedPatient)); assertEquals("myName", newPatient.getPetName().getValue()); - //Check no NPE if base server not configure + // Check no NPE if base server not configure newPatient = ourCtx.newXmlParser().parseResource(MyPatientWithCustomUrlExtension.class, new StringReader(parsedPatient)); assertNull("myName", newPatient.getPetName().getValue()); assertEquals("myName", ((StringDt) newPatient.getUndeclaredExtensionsByUrl("http://www.example.com/petname").get(0).getValue()).getValue()); @@ -2825,33 +2779,33 @@ public class XmlParserDstu2Test { patient.setPetName(new StringDt("myName")); final Bundle bundle = new Bundle(); - final BundleEntry entry = new BundleEntry(); + final Entry entry = new Entry(); entry.setResource(patient); bundle.addEntry(entry); final IParser xmlParser = ourCtx.newXmlParser(); xmlParser.setServerBaseUrl("http://www.example.com"); - final String parsedBundle = xmlParser.encodeBundleToString(bundle); + final String parsedBundle = xmlParser.encodeResourceToString(bundle); System.out.println(parsedBundle); assertEquals(expected, parsedBundle); // Parse with string - Bundle newBundle = xmlParser.parseBundle(parsedBundle); + Bundle newBundle = xmlParser.parseResource(Bundle.class, parsedBundle); assertNotNull(newBundle); - assertEquals(1, newBundle.getEntries().size()); - Patient newPatient = (Patient) newBundle.getEntries().get(0).getResource(); + assertEquals(1, newBundle.getEntry().size()); + Patient newPatient = (Patient) newBundle.getEntry().get(0).getResource(); assertEquals("myName", ((StringDt) newPatient.getUndeclaredExtensionsByUrl("http://www.example.com/petname").get(0).getValue()).getValue()); // Parse with stream - newBundle = xmlParser.parseBundle(new StringReader(parsedBundle)); + newBundle = xmlParser.parseResource(Bundle.class, new StringReader(parsedBundle)); assertNotNull(newBundle); - assertEquals(1, newBundle.getEntries().size()); - newPatient = (Patient) newBundle.getEntries().get(0).getResource(); + assertEquals(1, newBundle.getEntry().size()); + newPatient = (Patient) newBundle.getEntry().get(0).getResource(); assertEquals("myName", ((StringDt) newPatient.getUndeclaredExtensionsByUrl("http://www.example.com/petname").get(0).getValue()).getValue()); } - + @AfterClass public static void afterClassClearContext() { TestUtil.clearAllStaticFieldsForUnitTest(); @@ -2885,7 +2839,7 @@ public class XmlParserDstu2Test { this.myAbatement = theAbatement; } } - + @ResourceDef(name = "Patient") public static class TestPatientFor327 extends Patient { diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/BundleTypeDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/BundleTypeDstu2Test.java index e838bc0ea6c..78bdd49cb53 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/BundleTypeDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/BundleTypeDstu2Test.java @@ -25,7 +25,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; +import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.model.valueset.BundleTypeEnum; import ca.uhn.fhir.rest.api.Constants; @@ -62,7 +62,7 @@ public class BundleTypeDstu2Test { @Test public void testTransaction() throws Exception { - String retVal = ourCtx.newXmlParser().encodeBundleToString(new Bundle()); + String retVal = ourCtx.newXmlParser().encodeResourceToString(new Bundle()); ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(ourHttpClient.execute(capt.capture())).thenReturn(ourHttpResponse); @@ -94,9 +94,9 @@ public class BundleTypeDstu2Test { IGenericClient client = ctx.newRestfulGenericClient("http://54.165.58.158:8081/FHIRServer/fhir"); client.registerInterceptor(new BearerTokenAuthInterceptor("AN3uCTC5B")); client.registerInterceptor(new LoggingInterceptor(true)); - Bundle result = client.search().forResource(Patient.class).where(Patient.NAME.matches().value("Alice")).execute(); + Bundle result = client.search().forResource(Patient.class).where(Patient.NAME.matches().value("Alice")).returnBundle(Bundle.class).execute(); - System.out.println(result.getEntries().size()); + System.out.println(result.getEntry().size()); } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Test.java index 862f537280a..2c618758489 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Test.java @@ -36,7 +36,6 @@ import org.mockito.stubbing.Answer; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.*; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.dstu2.composite.IdentifierDt; import ca.uhn.fhir.model.dstu2.composite.MetaDt; import ca.uhn.fhir.model.dstu2.resource.*; @@ -74,12 +73,12 @@ public class GenericClientDstu2Test { ourCtx.getRestfulClientFactory().setConnectTimeout(10000); ourCtx.getRestfulClientFactory().setPoolMaxPerRoute(100); ourCtx.getRestfulClientFactory().setPoolMaxTotal(100); - + ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient); ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); myResponseCount = 0; - + System.setProperty(BaseClient.HAPI_CLIENT_KEEPRESPONSES, "true"); } @@ -108,7 +107,7 @@ public class GenericClientDstu2Test { //@formatter:on return msg; } - + @Test public void testAcceptHeaderFetchConformance() throws Exception { IParser p = ourCtx.newXmlParser(); @@ -261,7 +260,7 @@ public class GenericClientDstu2Test { int idx = 0; //@formatter:off - Conformance resp = (Conformance)client.conformance(); + Conformance resp = (Conformance)client.fetchConformance().ofType(Conformance.class).execute(); //@formatter:on assertEquals("http://example.com/fhir/metadata", capt.getAllValues().get(idx).getURI().toASCIIString()); @@ -381,7 +380,7 @@ public class GenericClientDstu2Test { Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); - client.create(p); + client.create().resource(p).execute(); assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); @@ -468,7 +467,7 @@ public class GenericClientDstu2Test { Patient pat = new Patient(); pat.setId("Patient/123"); - + client.delete().resource(pat).execute(); assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString()); @@ -513,74 +512,45 @@ public class GenericClientDstu2Test { public void testDeleteInvalidRequest() throws Exception { Patient pat = new Patient(); pat.setId("123"); - + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); try { client.delete().resource(pat).execute(); fail(); - } catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("theResource.getId() must contain a resource type and logical ID at a minimum (e.g. Patient/1234), found: 123", e.getMessage()); } - + try { client.delete().resourceById(new IdDt("123")).execute(); fail(); - } catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("theId must contain a resource type and logical ID at a minimum (e.g. Patient/1234)found: 123", e.getMessage()); } try { client.delete().resourceById("", "123").execute(); fail(); - } catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("theResourceType can not be blank/null", e.getMessage()); } try { client.delete().resourceById("Patient", "").execute(); fail(); - } catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("theLogicalId can not be blank/null", e.getMessage()); } try { client.delete().resourceConditionalByType("InvalidType"); fail(); - } catch (DataFormatException e){ + } catch (DataFormatException e) { assertEquals("Unknown resource name \"InvalidType\" (this name is not known in FHIR version \"DSTU2\")", e.getMessage()); } } - @SuppressWarnings("deprecation") - @Test - public void testDeleteNonFluent() throws Exception { - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - - int idx = 0; - - client.delete(Patient.class, new IdDt("Patient/123")); - assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); - assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.delete(Patient.class, "123"); - assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); - assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - } - /** * See #322 */ @@ -731,7 +701,8 @@ public class GenericClientDstu2Test { .since(new InstantDt("2001-01-02T11:22:33Z")) .execute(); //@formatter:on - assertThat(capt.getAllValues().get(idx).getURI().toString(), either(equalTo("http://example.com/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")).or(equalTo("http://example.com/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); + assertThat(capt.getAllValues().get(idx).getURI().toString(), either(equalTo("http://example.com/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")) + .or(equalTo("http://example.com/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); assertEquals(1, response.getEntry().size()); idx++; @@ -794,7 +765,8 @@ public class GenericClientDstu2Test { assertEquals("http://example.com/fhir/Patient/123/$meta-add", capt.getAllValues().get(idx).getURI().toASCIIString()); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("", extractBody(capt, idx)); + assertEquals("", + extractBody(capt, idx)); idx++; } @@ -1148,7 +1120,9 @@ public class GenericClientDstu2Test { assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("", (extractBody(capt, idx))); + assertEquals( + "", + (extractBody(capt, idx))); idx++; /* @@ -1169,7 +1143,8 @@ public class GenericClientDstu2Test { assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("", + assertEquals( + "", (extractBody(capt, idx))); idx++; @@ -1709,7 +1684,8 @@ public class GenericClientDstu2Test { .execute(); //@formatter:on - assertThat(capt.getValue().getURI().toString(), either(equalTo("http://example.com/fhir/Patient/123?_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient/123?_elements=identifier%2Cname"))); + assertThat(capt.getValue().getURI().toString(), + either(equalTo("http://example.com/fhir/Patient/123?_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient/123?_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getClass()); } @@ -1848,21 +1824,20 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("james")) - .elementsSubset("name", "identifier") - .usingStyle(SearchStyleEnum.POST) - .execute(); - //@formatter:on + .forResource("Patient") + .where(Patient.NAME.matches().value("james")) + .elementsSubset("name", "identifier") + .usingStyle(SearchStyleEnum.POST) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient/_search?_elements=identifier%2Cname", capt.getValue().getURI().toString()); - // assertThat(capt.getValue().getURI().toString(), - // either(equalTo("http://example.com/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient?name=james&_elements=identifier%2Cname"))); + // assertThat(capt.getValue().getURI().toString(), + // either(equalTo("http://example.com/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient?name=james&_elements=identifier%2Cname"))); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); ourLog.info(Arrays.asList(capt.getValue().getAllHeaders()).toString()); ourLog.info(capt.getValue().toString()); @@ -1888,24 +1863,23 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("james")) - .elementsSubset("name", "identifier") - .usingStyle(SearchStyleEnum.POST) - .encodedJson() - .execute(); - //@formatter:on + .forResource("Patient") + .where(Patient.NAME.matches().value("james")) + .elementsSubset("name", "identifier") + .usingStyle(SearchStyleEnum.POST) + .encodedJson() + .returnBundle(Bundle.class) + .execute(); assertThat(capt.getValue().getURI().toString(), containsString("http://example.com/fhir/Patient/_search?")); assertThat(capt.getValue().getURI().toString(), containsString("_elements=identifier%2Cname")); assertThat(capt.getValue().getURI().toString(), not(containsString("_format=json"))); - // assertThat(capt.getValue().getURI().toString(), - // either(equalTo("http://example.com/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient?name=james&_elements=identifier%2Cname"))); + // assertThat(capt.getValue().getURI().toString(), + // either(equalTo("http://example.com/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient?name=james&_elements=identifier%2Cname"))); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); ourLog.info(Arrays.asList(capt.getValue().getAllHeaders()).toString()); ourLog.info(capt.getValue().toString()); @@ -1930,15 +1904,14 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off - Bundle response = client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("james")) - .execute(); - //@formatter:on + Bundle response = client.search() + .forResource("Patient") + .where(Patient.NAME.matches().value("james")) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?name=james", capt.getValue().getURI().toString()); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -2065,16 +2038,16 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off - Bundle response = client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("james")) - .elementsSubset("name", "identifier") - .execute(); - //@formatter:on + Bundle response = client.search() + .forResource("Patient") + .where(Patient.NAME.matches().value("james")) + .elementsSubset("name", "identifier") + .returnBundle(Bundle.class) + .execute(); - assertThat(capt.getValue().getURI().toString(), either(equalTo("http://example.com/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient?name=james&_elements=identifier%2Cname"))); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertThat(capt.getValue().getURI().toString(), + either(equalTo("http://example.com/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://example.com/fhir/Patient?name=james&_elements=identifier%2Cname"))); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -2090,16 +2063,15 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off - Bundle response = client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("james")) - .lastUpdated(new DateRangeParam("2011-01-01", "2012-01-01")) - .execute(); - //@formatter:on + Bundle response = client.search() + .forResource("Patient") + .where(Patient.NAME.matches().value("james")) + .lastUpdated(new DateRangeParam("2011-01-01", "2012-01-01")) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", capt.getValue().getURI().toString()); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -2116,11 +2088,16 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); HashMap> params = new HashMap>(); - params.put("foo", Arrays.asList((IQueryParameterType)new DateParam("2001"))); - Bundle response = client.search(Patient.class, params); + params.put("foo", Arrays.asList((IQueryParameterType) new DateParam("2001"))); + Bundle response = client + .search() + .forResource(Patient.class) + .where(params) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?foo=2001", capt.getValue().getURI().toString()); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -2136,18 +2113,17 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off - Bundle response = client.search() - .forResource("Patient") - .withProfile("http://foo1") - .withProfile("http://foo2") - .withSecurity("system1", "code1") - .withSecurity("system2", "code2") - .execute(); - //@formatter:on + Bundle response = client.search() + .forResource("Patient") + .withProfile("http://foo1") + .withProfile("http://foo2") + .withSecurity("system1", "code1") + .withSecurity("system2", "code2") + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", capt.getValue().getURI().toString()); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -2165,13 +2141,12 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) .encodedJson() .revInclude(new Include("Provenance:target")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", capt.getValue().getURI().toString()); @@ -2189,16 +2164,15 @@ public class GenericClientDstu2Test { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off - Bundle response = client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value("james")) - .summaryMode(SummaryEnum.FALSE) - .execute(); - //@formatter:on + Bundle response = client.search() + .forResource("Patient") + .where(Patient.NAME.matches().value("james")) + .summaryMode(SummaryEnum.FALSE) + .returnBundle(Bundle.class) + .execute(); assertEquals("http://example.com/fhir/Patient?name=james&_summary=false", capt.getValue().getURI().toString()); - assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -2540,7 +2514,9 @@ public class GenericClientDstu2Test { assertEquals("http://example.com/fhir/Patient/$validate", capt.getAllValues().get(idx).getURI().toASCIIString()); assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); assertEquals("application/xml+fhir", capt.getAllValues().get(idx).getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals("", extractBody(capt, idx)); + assertEquals( + "", + extractBody(capt, idx)); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); idx++; @@ -2549,7 +2525,9 @@ public class GenericClientDstu2Test { assertEquals("http://example.com/fhir/Patient/$validate", capt.getAllValues().get(idx).getURI().toASCIIString()); assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); assertEquals("application/xml+fhir", capt.getAllValues().get(idx).getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals("", extractBody(capt, idx)); + assertEquals( + "", + extractBody(capt, idx)); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); idx++; @@ -2605,7 +2583,9 @@ public class GenericClientDstu2Test { assertEquals("http://example.com/fhir/Patient/$validate", capt.getAllValues().get(idx).getURI().toASCIIString()); assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("", extractBody(capt, idx)); + assertEquals( + "", + extractBody(capt, idx)); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); idx++; @@ -2648,27 +2628,27 @@ public class GenericClientDstu2Test { @Override public void registerInterceptor(IClientInterceptor theInterceptor) { - //nothing + // nothing } @Override public void setEncoding(EncodingEnum theEncoding) { - //nothing + // nothing } @Override public void setPrettyPrint(Boolean thePrettyPrint) { - //nothing + // nothing } @Override public void setSummary(SummaryEnum theSummary) { - //nothing + // nothing } @Override public void unregisterInterceptor(IClientInterceptor theInterceptor) { - //nothing + // nothing } @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java index af1e4605ffe..2c9b88bc86a 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java @@ -16,7 +16,6 @@ import ca.uhn.fhir.model.primitive.InstantDt; public class DateParamTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DateParamTest.class); - @SuppressWarnings("deprecation") @Test public void testConstructors() { new DateParam(); @@ -97,5 +96,15 @@ public class DateParamTest { ourLog.info("POST: " + dt.getValue()); assertEquals("2016-06-09T16:38:00.000-04:00", dt.getValueAsString()); } + + @Test + public void testParseLegacyPrefixes() { + assertEquals(ParamPrefixEnum.APPROXIMATE, new DateParam("ap2012").getPrefix()); + assertEquals(ParamPrefixEnum.GREATERTHAN, new DateParam("gt2012").getPrefix()); + assertEquals(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, new DateParam("ge2012").getPrefix()); + assertEquals(ParamPrefixEnum.LESSTHAN, new DateParam("lt2012").getPrefix()); + assertEquals(ParamPrefixEnum.LESSTHAN_OR_EQUALS, new DateParam("le2012").getPrefix()); + } + } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java index cdd79f514cd..9d11a807696 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java @@ -25,9 +25,9 @@ import org.eclipse.jetty.servlet.ServletHolder; import org.junit.*; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.dstu2.resource.Binary; +import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.Constants; @@ -183,8 +183,8 @@ public class BinaryDstu2Test { ourLog.info(responseContent); - Bundle bundle = ourCtx.newJsonParser().parseBundle(responseContent); - Binary bin = (Binary) bundle.getEntries().get(0).getResource(); + Bundle bundle = ourCtx.newJsonParser().parseResource(Bundle.class, responseContent); + Binary bin = (Binary) bundle.getEntry().get(0).getResource(); assertEquals("text/plain", bin.getContentType()); assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bin.getContent()); @@ -201,8 +201,8 @@ public class BinaryDstu2Test { ourLog.info(responseContent); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - Binary bin = (Binary) bundle.getEntries().get(0).getResource(); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + Binary bin = (Binary) bundle.getEntry().get(0).getResource(); assertEquals("text/plain", bin.getContentType()); assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bin.getContent()); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java index 62554ceac57..7fae0aac1cb 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java @@ -15,13 +15,11 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.IResource; +import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.model.valueset.BundleTypeEnum; import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator; @@ -51,9 +49,9 @@ public class BundleTypeInResponseTest { ourLog.info(responseContent); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.getEntries().size()); - assertEquals(BundleTypeEnum.SEARCHSET, bundle.getType().getValueAsEnum()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + assertEquals(BundleTypeEnum.SEARCHSET, bundle.getTypeElement().getValueAsEnum()); } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java index e2f8a8c5a69..49da3572315 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java @@ -22,7 +22,6 @@ import org.junit.Test; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.api.BundleInclusionRule; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.model.api.annotation.*; @@ -61,20 +60,21 @@ public class IncludeDstu2Test { IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); ourLog.info(responseContent); - assertEquals(3, bundle.size()); - assertEquals(new IdDt("Patient/p1"), bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Patient/p2"), bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Organization/o1"), bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless()); - assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntries().get(2).getSearchMode().getValueAsEnum()); + assertEquals(3, bundle.getEntry().size()); + + assertEquals(new IdDt("Patient/p1"), BundleUtil.toListOfResources(ourCtx, bundle).get(0).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Patient/p2"), BundleUtil.toListOfResources(ourCtx, bundle).get(1).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Organization/o1"), BundleUtil.toListOfResources(ourCtx, bundle).get(2).getIdElement().toUnqualifiedVersionless()); + assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntry().get(2).getSearch().getModeElement().getValueAsEnum()); - Patient p1 = (Patient) bundle.toListOfResources().get(0); + Patient p1 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(0); assertEquals(0, p1.getContained().getContainedResources().size()); - Patient p2 = (Patient) bundle.toListOfResources().get(1); + Patient p2 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(1); assertEquals(0, p2.getContained().getContainedResources().size()); } @@ -87,22 +87,22 @@ public class IncludeDstu2Test { IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); ourLog.info(responseContent); - assertEquals(4, bundle.size()); - assertEquals(new IdDt("Patient/p1"), bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Patient/p2"), bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Organization/o1"), bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Organization/o2"), bundle.toListOfResources().get(3).getId().toUnqualifiedVersionless()); - assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntries().get(2).getSearchMode().getValueAsEnum()); - assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntries().get(3).getSearchMode().getValueAsEnum()); + assertEquals(4, bundle.getEntry().size()); + assertEquals(new IdDt("Patient/p1"), BundleUtil.toListOfResources(ourCtx, bundle).get(0).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Patient/p2"), BundleUtil.toListOfResources(ourCtx, bundle).get(1).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Organization/o1"), BundleUtil.toListOfResources(ourCtx, bundle).get(2).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Organization/o2"), BundleUtil.toListOfResources(ourCtx, bundle).get(3).getIdElement().toUnqualifiedVersionless()); + assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntry().get(2).getSearch().getModeElement().getValueAsEnum()); + assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntry().get(3).getSearch().getModeElement().getValueAsEnum()); - Patient p1 = (Patient) bundle.toListOfResources().get(0); + Patient p1 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(0); assertEquals(0, p1.getContained().getContainedResources().size()); - Patient p2 = (Patient) bundle.toListOfResources().get(1); + Patient p2 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(1); assertEquals(0, p2.getContained().getContainedResources().size()); } @@ -115,20 +115,20 @@ public class IncludeDstu2Test { IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); ourLog.info(responseContent); - assertEquals(3, bundle.size()); - assertEquals(new IdDt("Patient/p1"), bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Patient/p2"), bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Organization/o1"), bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless()); - assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntries().get(2).getSearchMode().getValueAsEnum()); + assertEquals(3, bundle.getEntry().size()); + assertEquals(new IdDt("Patient/p1"), BundleUtil.toListOfResources(ourCtx, bundle).get(0).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Patient/p2"), BundleUtil.toListOfResources(ourCtx, bundle).get(1).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Organization/o1"), BundleUtil.toListOfResources(ourCtx, bundle).get(2).getIdElement().toUnqualifiedVersionless()); + assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntry().get(2).getSearch().getModeElement().getValueAsEnum()); - Patient p1 = (Patient) bundle.toListOfResources().get(0); + Patient p1 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(0); assertEquals(0, p1.getContained().getContainedResources().size()); - Patient p2 = (Patient) bundle.toListOfResources().get(1); + Patient p2 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(1); assertEquals(0, p2.getContained().getContainedResources().size()); } @@ -141,20 +141,20 @@ public class IncludeDstu2Test { IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newJsonParser().parseBundle(responseContent); + Bundle bundle = ourCtx.newJsonParser().parseResource(Bundle.class, responseContent); ourLog.info(responseContent); - assertEquals(3, bundle.size()); - assertEquals(new IdDt("Patient/p1"), bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Patient/p2"), bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless()); - assertEquals(new IdDt("Organization/o1"), bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless()); - assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntries().get(2).getSearchMode().getValueAsEnum()); + assertEquals(3, bundle.getEntry().size()); + assertEquals(new IdDt("Patient/p1"), BundleUtil.toListOfResources(ourCtx, bundle).get(0).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Patient/p2"), BundleUtil.toListOfResources(ourCtx, bundle).get(1).getIdElement().toUnqualifiedVersionless()); + assertEquals(new IdDt("Organization/o1"), BundleUtil.toListOfResources(ourCtx, bundle).get(2).getIdElement().toUnqualifiedVersionless()); + assertEquals(BundleEntrySearchModeEnum.INCLUDE, bundle.getEntry().get(2).getSearch().getModeElement().getValueAsEnum()); - Patient p1 = (Patient) bundle.toListOfResources().get(0); + Patient p1 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(0); assertEquals(0, p1.getContained().getContainedResources().size()); - Patient p2 = (Patient) bundle.toListOfResources().get(1); + Patient p2 = (Patient) BundleUtil.toListOfResources(ourCtx, bundle).get(1); assertEquals(0, p2.getContained().getContainedResources().size()); } @@ -169,8 +169,8 @@ public class IncludeDstu2Test { ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(4, bundle.size()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(4, bundle.getEntry().size()); } @Test @@ -181,10 +181,10 @@ public class IncludeDstu2Test { IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.size()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); - Patient p = bundle.getResources(Patient.class).get(0); + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); assertEquals(0, p.getName().size()); assertEquals("Hello", p.getId().getIdPart()); } @@ -200,10 +200,10 @@ public class IncludeDstu2Test { ourLog.info(responseContent); - Bundle bundle = ourCtx.newJsonParser().parseBundle(responseContent); - assertEquals(1, bundle.size()); + Bundle bundle = ourCtx.newJsonParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); - Patient p = bundle.getResources(Patient.class).get(0); + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); assertEquals(1, p.getName().size()); assertEquals("Hello", p.getId().getIdPart()); assertEquals("foo", p.getName().get(0).getFamilyFirstRep().getValue()); @@ -220,10 +220,10 @@ public class IncludeDstu2Test { ourLog.info(responseContent); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.size()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); - Patient p = bundle.getResources(Patient.class).get(0); + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); assertEquals(1, p.getName().size()); assertEquals("Hello", p.getId().getIdPart()); assertEquals("foo", p.getName().get(0).getFamilyFirstRep().getValue()); @@ -239,10 +239,10 @@ public class IncludeDstu2Test { ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); - Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); - assertEquals(1, bundle.size()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); - Patient p = bundle.getResources(Patient.class).get(0); + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); assertEquals(2, p.getName().size()); assertEquals("Hello", p.getId().getIdPart()); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionDstu2Test.java index d62a583bce3..5ccf6ddadb2 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionDstu2Test.java @@ -12,13 +12,7 @@ import org.junit.Test; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.dstu2.resource.Patient; -import ca.uhn.fhir.model.primitive.StringDt; -import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; -import ca.uhn.fhir.rest.annotation.Operation; -import ca.uhn.fhir.rest.annotation.OperationParam; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Update; -import ca.uhn.fhir.rest.annotation.Validate; +import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.util.TestUtil; @@ -32,22 +26,6 @@ public class ServerInvalidDefinitionDstu2Test { TestUtil.clearAllStaticFieldsForUnitTest(); } - - @Test - public void testOperationReturningOldBundleProvider() { - RestfulServer srv = new RestfulServer(ourCtx); - srv.setFhirContext(ourCtx); - srv.setResourceProviders(new OperationReturningOldBundleProvider()); - - try { - srv.init(); - fail(); - } catch (ServletException e) { - assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); - assertThat(e.getCause().toString(), StringContains.containsString("Can not return a DSTU1 bundle")); - } - } - @Test public void testWrongConditionalUrlType() { RestfulServer srv = new RestfulServer(ourCtx); @@ -59,7 +37,8 @@ public class ServerInvalidDefinitionDstu2Test { fail(); } catch (ServletException e) { assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); - assertThat(e.getCause().toString(), StringContains.containsString("Parameters annotated with @ConditionalUrlParam must be of type String, found incorrect parameteter in method \"public ca.uhn.fhir.rest.api.MethodOutcome ca.uhn.fhir.rest.server.ServerInvalidDefinitionDstu2Test$UpdateWithWrongConditionalUrlType.update(ca.uhn.fhir.rest.param.TokenParam,ca.uhn.fhir.model.dstu2.resource.Patient)")); + assertThat(e.getCause().toString(), StringContains.containsString( + "Parameters annotated with @ConditionalUrlParam must be of type String, found incorrect parameteter in method \"public ca.uhn.fhir.rest.api.MethodOutcome ca.uhn.fhir.rest.server.ServerInvalidDefinitionDstu2Test$UpdateWithWrongConditionalUrlType.update(ca.uhn.fhir.rest.param.TokenParam,ca.uhn.fhir.model.dstu2.resource.Patient)")); } } @@ -74,7 +53,8 @@ public class ServerInvalidDefinitionDstu2Test { fail(); } catch (ServletException e) { assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); - assertThat(e.getCause().toString(), StringContains.containsString("Method 'update' is annotated with @ResourceParam but has a type that is not an implemtation of org.hl7.fhir.instance.model.api.IBaseResource or String or byte[]")); + assertThat(e.getCause().toString(), StringContains + .containsString("Method 'update' is annotated with @ResourceParam but has a type that is not an implemtation of org.hl7.fhir.instance.model.api.IBaseResource or String or byte[]")); } } @@ -108,20 +88,6 @@ public class ServerInvalidDefinitionDstu2Test { } } - public static class OperationReturningOldBundleProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Operation(name = "$OP_TYPE_RET_OLD_BUNDLE") - public ca.uhn.fhir.model.api.Bundle opTypeRetOldBundle(@OperationParam(name = "PARAM1") StringDt theParam1, @OperationParam(name = "PARAM2") Patient theParam2) { - return null; - } - - } - public static class UpdateWithWrongConditionalUrlType implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/validation/ResourceValidatorDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/validation/ResourceValidatorDstu2Test.java index 25489b13322..e7af28a7e87 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/validation/ResourceValidatorDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/validation/ResourceValidatorDstu2Test.java @@ -12,9 +12,7 @@ import static org.junit.Assert.fail; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; +import java.util.*; import org.apache.commons.io.IOUtils; import org.hamcrest.core.StringContains; @@ -22,27 +20,12 @@ import org.junit.AfterClass; import org.junit.Test; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; -import ca.uhn.fhir.model.api.ExtensionDt; -import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; -import ca.uhn.fhir.model.api.TemporalPrecisionEnum; -import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt; -import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt; -import ca.uhn.fhir.model.dstu2.composite.TimingDt; -import ca.uhn.fhir.model.dstu2.resource.Condition; -import ca.uhn.fhir.model.dstu2.resource.MedicationOrder; -import ca.uhn.fhir.model.dstu2.resource.OperationOutcome; -import ca.uhn.fhir.model.dstu2.resource.Patient; -import ca.uhn.fhir.model.dstu2.valueset.ConditionVerificationStatusEnum; -import ca.uhn.fhir.model.dstu2.valueset.ContactPointSystemEnum; -import ca.uhn.fhir.model.dstu2.valueset.NarrativeStatusEnum; -import ca.uhn.fhir.model.dstu2.valueset.UnitsOfTimeEnum; -import ca.uhn.fhir.model.primitive.DateDt; -import ca.uhn.fhir.model.primitive.InstantDt; -import ca.uhn.fhir.model.primitive.StringDt; -import ca.uhn.fhir.parser.DataFormatException; -import ca.uhn.fhir.parser.IParser; -import ca.uhn.fhir.parser.StrictErrorHandler; +import ca.uhn.fhir.model.api.*; +import ca.uhn.fhir.model.dstu2.composite.*; +import ca.uhn.fhir.model.dstu2.resource.*; +import ca.uhn.fhir.model.dstu2.valueset.*; +import ca.uhn.fhir.model.primitive.*; +import ca.uhn.fhir.parser.*; import ca.uhn.fhir.parser.XmlParserDstu2Test.TestPatientFor327; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.validation.schematron.SchematronBaseValidator; @@ -102,13 +85,13 @@ public class ResourceValidatorDstu2Test { @Test public void testSchemaBundleValidator() throws IOException { String res = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("bundle-example.json")); - Bundle b = ourCtx.newJsonParser().parseBundle(res); + Bundle b = ourCtx.newJsonParser().parseResource(Bundle.class, res); FhirValidator val = createFhirValidator(); val.validate(b); - MedicationOrder p = (MedicationOrder) b.getEntries().get(0).getResource(); + MedicationOrder p = (MedicationOrder) b.getEntry().get(0).getResource(); TimingDt timing = new TimingDt(); timing.getRepeat().setDuration(123); timing.getRepeat().setDurationUnits((UnitsOfTimeEnum) null); @@ -127,20 +110,26 @@ public class ResourceValidatorDstu2Test { @Test public void testSchemaBundleValidatorFails() throws IOException { String res = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("bundle-example.json"), StandardCharsets.UTF_8); - Bundle b = ourCtx.newJsonParser().parseBundle(res); + Bundle b = ourCtx.newJsonParser().parseResource(Bundle.class, res); + FhirValidator val = createFhirValidator(); ValidationResult validationResult = val.validateWithResult(b); assertTrue(validationResult.isSuccessful()); - MedicationOrder p = (MedicationOrder) b.getEntries().get(0).getResource(); + MedicationOrder p = (MedicationOrder) b.getEntry().get(0).getResource(); TimingDt timing = new TimingDt(); timing.getRepeat().setDuration(123); timing.getRepeat().setDurationUnits((UnitsOfTimeEnum) null); p.getDosageInstructionFirstRep().setTiming(timing); + ourLog.info(ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(b)); + validationResult = val.validateWithResult(b); + + ourLog.info(ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(validationResult.toOperationOutcome())); + assertFalse(validationResult.isSuccessful()); String encoded = logOperationOutcome(validationResult); @@ -150,9 +139,9 @@ public class ResourceValidatorDstu2Test { @Test public void testSchemaBundleValidatorIsSuccessful() throws IOException { String res = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("bundle-example.json"), StandardCharsets.UTF_8); - Bundle b = ourCtx.newJsonParser().parseBundle(res); + Bundle b = ourCtx.newJsonParser().parseResource(Bundle.class, res); - ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(b)); + ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(b)); FhirValidator val = createFhirValidator(); diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu3Test.java index 0cb499db02d..8fd30f66f53 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu3Test.java @@ -114,8 +114,13 @@ public class GenericClientDstu3Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://example.com/fhir/EpisodeOfCare?patient=123&_revinclude=Encounter%3Aepisodeofcare&_revinclude%3Arecurse=Observation%3Aencounter", - capt.getAllValues().get(idx).getURI().toString()); + String expected = "http://example.com/fhir/EpisodeOfCare?patient=123&_revinclude=Encounter%3Aepisodeofcare&_revinclude%3Arecurse=Observation%3Aencounter"; + String actual = capt.getAllValues().get(idx).getURI().toString(); + + ourLog.info("EXP: {}", expected); + ourLog.info("ACT: {}", actual); + + assertEquals(expected, actual); idx++; } @@ -1526,17 +1531,6 @@ public class GenericClientDstu3Test { } - @Test - public void testSearchForUnknownType() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - try { - client.search(new UriDt("?aaaa")); - fail(); - } catch (IllegalArgumentException e) { - assertEquals("Unable to determine the resource type from the given URI: ?aaaa", e.getMessage()); - } - } - @Test public void testSearchWithMultipleTokens() throws Exception { ArgumentCaptor capt = prepareClientForSearchResponse(); diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java index d0dcb7309be..205f528cd99 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java @@ -67,9 +67,13 @@ public class DateRangeParamTest { public void testDay() throws Exception { assertEquals(parse("2011-01-01 00:00:00.0000"), create(">=2011-01-01", "<2011-01-02").getLowerBoundAsInstant()); assertEquals(parseM1("2011-01-02 00:00:00.0000"), create(">=2011-01-01", "<2011-01-02").getUpperBoundAsInstant()); - assertEquals(parse("2011-01-02 00:00:00.0000"), create(">2011-01-01", "<=2011-01-02").getLowerBoundAsInstant()); assertEquals(parseM1("2011-01-03 00:00:00.0000"), create(">2011-01-01", "<=2011-01-02").getUpperBoundAsInstant()); + + assertEquals(parse("2011-01-01 00:00:00.0000"), create("ge2011-01-01", "lt2011-01-02").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-01-02 00:00:00.0000"), create("ge2011-01-01", "lt2011-01-02").getUpperBoundAsInstant()); + assertEquals(parse("2011-01-02 00:00:00.0000"), create("gt2011-01-01", "le2011-01-02").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-01-03 00:00:00.0000"), create("gt2011-01-01", "le2011-01-02").getUpperBoundAsInstant()); } @Test @@ -77,20 +81,20 @@ public class DateRangeParamTest { assertEquals(parse("2011-01-01 00:00:00.0000"), create("2011-01-01").getLowerBoundAsInstant()); assertEquals(parseM1("2011-01-02 00:00:00.0000"), create("2011-01-01").getUpperBoundAsInstant()); - assertEquals(parse("2011-01-01 00:00:00.0000"), create(">=2011-01-01").getLowerBoundAsInstant()); - assertEquals(null, create(">=2011-01-01").getUpperBoundAsInstant()); + assertEquals(parse("2011-01-01 00:00:00.0000"), create("ge2011-01-01").getLowerBoundAsInstant()); + assertEquals(null, create("ge2011-01-01").getUpperBoundAsInstant()); - assertEquals(null, create("<=2011-01-01").getLowerBoundAsInstant()); - assertEquals(parseM1("2011-01-02 00:00:00.0000"), create("<=2011-01-01").getUpperBoundAsInstant()); + assertEquals(null, create("le2011-01-01").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-01-02 00:00:00.0000"), create("le2011-01-01").getUpperBoundAsInstant()); } @Test public void testMonth() throws Exception { - assertEquals(parse("2011-01-01 00:00:00.0000"), create(">=2011-01", "<2011-02").getLowerBoundAsInstant()); - assertEquals(parseM1("2011-02-01 00:00:00.0000"), create(">=2011-01", "<2011-02").getUpperBoundAsInstant()); + assertEquals(parse("2011-01-01 00:00:00.0000"), create("ge2011-01", "lt2011-02").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-02-01 00:00:00.0000"), create("ge2011-01", "lt2011-02").getUpperBoundAsInstant()); - assertEquals(parse("2011-02-01 00:00:00.0000"), create(">2011-01", "<=2011-02").getLowerBoundAsInstant()); - assertEquals(parseM1("2011-03-01 00:00:00.0000"), create(">2011-01", "<=2011-02").getUpperBoundAsInstant()); + assertEquals(parse("2011-02-01 00:00:00.0000"), create("gt2011-01", "le2011-02").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-03-01 00:00:00.0000"), create("gt2011-01", "le2011-02").getUpperBoundAsInstant()); } @Test @@ -159,20 +163,20 @@ public class DateRangeParamTest { @Test public void testSecond() throws Exception { - assertEquals(parse("2011-01-01 00:00:00.0000"), create(">=2011-01-01T00:00:00", "<2011-01-01T01:00:00").getLowerBoundAsInstant()); - assertEquals(parseM1("2011-01-01 02:00:00.0000"), create(">=2011-01-01T00:00:00", "<2011-01-01T02:00:00").getUpperBoundAsInstant()); + assertEquals(parse("2011-01-01 00:00:00.0000"), create("ge2011-01-01T00:00:00", "lt2011-01-01T01:00:00").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-01-01 02:00:00.0000"), create("ge2011-01-01T00:00:00", "lt2011-01-01T02:00:00").getUpperBoundAsInstant()); - assertEquals(parse("2011-01-01 00:00:01.0000"), create(">2011-01-01T00:00:00", "<=2011-01-01T02:00:00").getLowerBoundAsInstant()); - assertEquals(parseM1("2011-01-01 02:00:01.0000"), create(">2011-01-01T00:00:00", "<=2011-01-01T02:00:00").getUpperBoundAsInstant()); + assertEquals(parse("2011-01-01 00:00:01.0000"), create("gt2011-01-01T00:00:00", "le2011-01-01T02:00:00").getLowerBoundAsInstant()); + assertEquals(parseM1("2011-01-01 02:00:01.0000"), create("gt2011-01-01T00:00:00", "le2011-01-01T02:00:00").getUpperBoundAsInstant()); } @Test public void testYear() throws Exception { - assertEquals(parse("2011-01-01 00:00:00.0000"), create(">=2011", "<2012").getLowerBoundAsInstant()); - assertEquals(parseM1("2012-01-01 00:00:00.0000"), create(">=2011", "<2012").getUpperBoundAsInstant()); + assertEquals(parse("2011-01-01 00:00:00.0000"), create("ge2011", "lt2012").getLowerBoundAsInstant()); + assertEquals(parseM1("2012-01-01 00:00:00.0000"), create("ge2011", "lt2012").getUpperBoundAsInstant()); - assertEquals(parse("2012-01-01 00:00:00.0000"), create(">2011", "<=2012").getLowerBoundAsInstant()); - assertEquals(parseM1("2014-01-01 00:00:00.0000"), create(">2011", "<=2013").getUpperBoundAsInstant()); + assertEquals(parse("2012-01-01 00:00:00.0000"), create("gt2011", "le2012").getLowerBoundAsInstant()); + assertEquals(parseM1("2014-01-01 00:00:00.0000"), create("gt2011", "le2013").getUpperBoundAsInstant()); } @AfterClass diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserHl7OrgDstu2Test.java index 9d1a341bfb4..c3b02b7433c 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/parser/JsonParserHl7OrgDstu2Test.java @@ -1286,72 +1286,6 @@ public class JsonParserHl7OrgDstu2Test { } - @Test - public void testTagList() { - - //@formatter:off - String tagListStr = "{\n" + - " \"resourceType\" : \"TagList\", " + - " \"category\" : [" + - " { " + - " \"term\" : \"term0\", " + - " \"label\" : \"label0\", " + - " \"scheme\" : \"scheme0\" " + - " }," + - " { " + - " \"term\" : \"term1\", " + - " \"label\" : \"label1\", " + - " \"scheme\" : null " + - " }," + - " { " + - " \"term\" : \"term2\", " + - " \"label\" : \"label2\" " + - " }" + - " ] " + - "}"; - //@formatter:on - - TagList tagList = ourCtx.newJsonParser().parseTagList(tagListStr); - assertEquals(3, tagList.size()); - assertEquals("term0", tagList.get(0).getTerm()); - assertEquals("label0", tagList.get(0).getLabel()); - assertEquals("scheme0", tagList.get(0).getScheme()); - assertEquals("term1", tagList.get(1).getTerm()); - assertEquals("label1", tagList.get(1).getLabel()); - assertEquals(null, tagList.get(1).getScheme()); - assertEquals("term2", tagList.get(2).getTerm()); - assertEquals("label2", tagList.get(2).getLabel()); - assertEquals(null, tagList.get(2).getScheme()); - - /* - * Encode - */ - - //@formatter:off - String expected = "{" + - "\"resourceType\":\"TagList\"," + - "\"category\":[" + - "{" + - "\"term\":\"term0\"," + - "\"label\":\"label0\"," + - "\"scheme\":\"scheme0\"" + - "}," + - "{" + - "\"term\":\"term1\"," + - "\"label\":\"label1\"" + - "}," + - "{" + - "\"term\":\"term2\"," + - "\"label\":\"label2\"" + - "}" + - "]" + - "}"; - //@formatter:on - - String encoded = ourCtx.newJsonParser().encodeTagListToString(tagList); - assertEquals(expected, encoded); - - } @ResourceDef(name = "Patient") public static class MyPatientWithOneDeclaredAddressExtension extends Patient { diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Hl7OrgTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Hl7OrgTest.java index 4f38244a00c..3514d795398 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Hl7OrgTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/client/GenericClientDstu2Hl7OrgTest.java @@ -29,7 +29,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.rest.api.Constants; @@ -39,29 +38,27 @@ import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.rest.gclient.StringClientParam; public class GenericClientDstu2Hl7OrgTest { - private static FhirContext ourCtx; - private HttpClient myHttpClient; - private HttpResponse myHttpResponse; + private static FhirContext ourCtx; + private HttpClient myHttpClient; + private HttpResponse myHttpResponse; - @BeforeClass - public static void beforeClass() { - ourCtx = FhirContext.forDstu2Hl7Org(); - } + @BeforeClass + public static void beforeClass() { + ourCtx = FhirContext.forDstu2Hl7Org(); + } - @Before - public void before() { - myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs()); - ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient); - ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); - myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); - } + @Before + public void before() { + myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs()); + ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient); + ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); + myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); + } - - - @Test - public void testReadUpdatedHeaderDoesntOverwriteResourceValue() throws Exception { + @Test + public void testReadUpdatedHeaderDoesntOverwriteResourceValue() throws Exception { - //@formatter:off + //@formatter:off final String input = "\n" + " \n" + " \n" + @@ -77,51 +74,50 @@ public class GenericClientDstu2Hl7OrgTest { ""; //@formatter:on - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getAllHeaders()).thenReturn(new Header[] { - new BasicHeader(Constants.HEADER_LAST_MODIFIED, "Sat, 20 Jun 2015 19:32:17 GMT") - }); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(input), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getAllHeaders()).thenReturn(new Header[] { + new BasicHeader(Constants.HEADER_LAST_MODIFIED, "Sat, 20 Jun 2015 19:32:17 GMT") + }); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(input), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - org.hl7.fhir.instance.model.Bundle response; + org.hl7.fhir.instance.model.Bundle response; - //@formatter:off + //@formatter:off response = client .search() .forResource(Patient.class) .returnBundle(org.hl7.fhir.instance.model.Bundle.class) .execute(); //@formatter:on - - assertEquals("2015-06-22T15:48:57.554-04:00", response.getMeta().getLastUpdatedElement().getValueAsString()); - } - - @SuppressWarnings("unused") - @Test - public void testSearchWithReverseInclude() throws Exception { + assertEquals("2015-06-22T15:48:57.554-04:00", response.getMeta().getLastUpdatedElement().getValueAsString()); + } - String msg = getPatientFeedWithOneResult(); + @SuppressWarnings("unused") + @Test + public void testSearchWithReverseInclude() throws Exception { - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + String msg = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - //@formatter:off + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + + //@formatter:off org.hl7.fhir.instance.model.Bundle response = client.search() .forResource(Patient.class) .encodedJson() @@ -130,15 +126,14 @@ public class GenericClientDstu2Hl7OrgTest { .execute(); //@formatter:on - assertEquals( - "http://example.com/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", - capt.getValue().getURI().toString()); + assertEquals( + "http://example.com/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", + capt.getValue().getURI().toString()); - } + } - - private String getPatientFeedWithOneResult() { - //@formatter:off + private String getPatientFeedWithOneResult() { + //@formatter:off String msg = "\n" + "d039f91a-cc3c-4013-988e-af4d8d0614bd\n" + "\n" + @@ -155,77 +150,77 @@ public class GenericClientDstu2Hl7OrgTest { + " \n" + ""; //@formatter:on - return msg; - } + return msg; + } - @Test - public void testHistory() throws Exception { + @Test + public void testHistory() throws Exception { - final String msg = getPatientFeedWithOneResult(); + final String msg = getPatientFeedWithOneResult(); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - org.hl7.fhir.instance.model.Bundle response; + int idx = 0; + org.hl7.fhir.instance.model.Bundle response; - //@formatter:off + //@formatter:off response = client .history() .onServer() .andReturnBundle(org.hl7.fhir.instance.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://example.com/fhir/_history", capt.getAllValues().get(idx).getURI().toString()); - assertEquals(1, response.getEntry().size()); - idx++; + assertEquals("http://example.com/fhir/_history", capt.getAllValues().get(idx).getURI().toString()); + assertEquals(1, response.getEntry().size()); + idx++; - //@formatter:off + //@formatter:off response = client .history() .onType(Patient.class) .andReturnBundle(org.hl7.fhir.instance.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/_history", capt.getAllValues().get(idx).getURI().toString()); - assertEquals(1, response.getEntry().size()); - idx++; + assertEquals("http://example.com/fhir/Patient/_history", capt.getAllValues().get(idx).getURI().toString()); + assertEquals(1, response.getEntry().size()); + idx++; - //@formatter:off + //@formatter:off response = client .history() .onInstance(new IdType("Patient", "123")) .andReturnBundle(org.hl7.fhir.instance.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/123/_history", capt.getAllValues().get(idx).getURI().toString()); - assertEquals(1, response.getEntry().size()); - idx++; - } + assertEquals("http://example.com/fhir/Patient/123/_history", capt.getAllValues().get(idx).getURI().toString()); + assertEquals(1, response.getEntry().size()); + idx++; + } - @Test - public void testSearchByString() throws Exception { - String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; + @Test + public void testSearchByString() throws Exception { + String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off + //@formatter:off org.hl7.fhir.instance.model.Bundle response = client.search() .forResource("Patient") .where(new StringClientParam("name").matches().value("james")) @@ -233,182 +228,165 @@ public class GenericClientDstu2Hl7OrgTest { .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient?name=james", capt.getValue().getURI().toString()); - assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); + assertEquals("http://example.com/fhir/Patient?name=james", capt.getValue().getURI().toString()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - } + } - @SuppressWarnings("unused") - @Test - public void testSearchRequiresBundleType() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - try { - //@formatter:off - Bundle response = client.search() - .forResource("Patient") - .where(new StringClientParam("name").matches().value("james")) - .execute(); - //@formatter:on - fail(); - } catch (IllegalArgumentException e) { - // good - } - } - - @Test - public void testOperationWithListOfParameterResponse() throws Exception { - IParser p = ourCtx.newXmlParser(); + @Test + public void testOperationWithListOfParameterResponse() throws Exception { + IParser p = ourCtx.newXmlParser(); - Parameters inParams = new Parameters(); - inParams.addParameter().setValue(new StringType("STRINGVALIN1")); - inParams.addParameter().setValue(new StringType("STRINGVALIN2")); - String reqString = p.encodeResourceToString(inParams); + Parameters inParams = new Parameters(); + inParams.addParameter().setValue(new StringType("STRINGVALIN1")); + inParams.addParameter().setValue(new StringType("STRINGVALIN2")); + String reqString = p.encodeResourceToString(inParams); - Parameters outParams = new Parameters(); - outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); - outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); - final String respString = p.encodeResourceToString(outParams); + Parameters outParams = new Parameters(); + outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); + outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); + final String respString = p.encodeResourceToString(outParams); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - //@formatter:off + //@formatter:off Parameters resp = client .operation() .onServer() .named("$SOMEOPERATION") .withParameters(inParams).execute(); //@formatter:on - assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onType(Patient.class) .named("$SOMEOPERATION") .withParameters(inParams).execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onInstance(new IdType("Patient", "123")) .named("$SOMEOPERATION") .withParameters(inParams).execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - resp = client.operation().onInstance(new IdType("http://foo.com/bar/baz/Patient/123/_history/22")).named("$SOMEOPERATION").withParameters(inParams).execute(); - // @formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - idx++; - } + resp = client.operation().onInstance(new IdType("http://foo.com/bar/baz/Patient/123/_history/22")).named("$SOMEOPERATION").withParameters(inParams).execute(); + // @formatter:on + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + idx++; + } - @Test - public void testOperationWithNoInParameters() throws Exception { - IParser p = ourCtx.newXmlParser(); + @Test + public void testOperationWithNoInParameters() throws Exception { + IParser p = ourCtx.newXmlParser(); - Parameters inParams = new Parameters(); - final String reqString = p.encodeResourceToString(inParams); + Parameters inParams = new Parameters(); + final String reqString = p.encodeResourceToString(inParams); - Parameters outParams = new Parameters(); - outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); - outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); - final String respString = p.encodeResourceToString(outParams); + Parameters outParams = new Parameters(); + outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); + outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); + final String respString = p.encodeResourceToString(outParams); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - //@formatter:off + //@formatter:off Parameters resp = client .operation() .onServer() .named("$SOMEOPERATION") .withNoParameters(Parameters.class).execute(); //@formatter:on - assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onType(Patient.class) .named("$SOMEOPERATION") .withNoParameters(Parameters.class).execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onInstance(new IdType("Patient", "123")) .named("$SOMEOPERATION") .withNoParameters(Parameters.class).execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - // @formatter:off + // @formatter:off resp = client .operation() .onInstance(new IdType("http://foo.com/bar/baz/Patient/123/_history/22")) @@ -416,35 +394,35 @@ public class GenericClientDstu2Hl7OrgTest { .withNoParameters(Parameters.class) .execute(); // @formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - idx++; - } + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + idx++; + } - @Test - public void testOperationAsGetWithNoInParameters() throws Exception { - IParser p = ourCtx.newXmlParser(); + @Test + public void testOperationAsGetWithNoInParameters() throws Exception { + IParser p = ourCtx.newXmlParser(); - Parameters outParams = new Parameters(); - outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); - outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); - final String respString = p.encodeResourceToString(outParams); + Parameters outParams = new Parameters(); + outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); + outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); + final String respString = p.encodeResourceToString(outParams); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - //@formatter:off + //@formatter:off Parameters resp = client .operation() .onServer() @@ -453,12 +431,12 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onType(Patient.class) @@ -467,12 +445,12 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onInstance(new IdType("Patient", "123")) @@ -481,12 +459,12 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - // @formatter:off + // @formatter:off resp = client .operation() .onInstance(new IdType("http://foo.com/bar/baz/Patient/123/_history/22")) @@ -495,40 +473,40 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); // @formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - idx++; - } + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + idx++; + } - @Test - public void testOperationAsGetWithInParameters() throws Exception { - IParser p = ourCtx.newXmlParser(); + @Test + public void testOperationAsGetWithInParameters() throws Exception { + IParser p = ourCtx.newXmlParser(); - Parameters inParams = new Parameters(); - inParams.addParameter().setName("param1").setValue(new StringType("STRINGVALIN1")); - inParams.addParameter().setName("param1").setValue(new StringType("STRINGVALIN1b")); - inParams.addParameter().setName("param2").setValue(new StringType("STRINGVALIN2")); + Parameters inParams = new Parameters(); + inParams.addParameter().setName("param1").setValue(new StringType("STRINGVALIN1")); + inParams.addParameter().setName("param1").setValue(new StringType("STRINGVALIN1b")); + inParams.addParameter().setName("param2").setValue(new StringType("STRINGVALIN2")); - Parameters outParams = new Parameters(); - outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); - outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); - final String respString = p.encodeResourceToString(outParams); + Parameters outParams = new Parameters(); + outParams.addParameter().setValue(new StringType("STRINGVALOUT1")); + outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); + final String respString = p.encodeResourceToString(outParams); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - //@formatter:off + //@formatter:off Parameters resp = client .operation() .onServer() @@ -537,12 +515,12 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://example.com/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onType(Patient.class) @@ -551,12 +529,12 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - //@formatter:off + //@formatter:off resp = client .operation() .onInstance(new IdType("Patient", "123")) @@ -565,12 +543,12 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(respString, p.encodeResourceToString(resp)); + assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - // @formatter:off + // @formatter:off resp = client .operation() .onInstance(new IdType("http://foo.com/bar/baz/Patient/123/_history/22")) @@ -579,279 +557,280 @@ public class GenericClientDstu2Hl7OrgTest { .useHttpGet() .execute(); // @formatter:on - assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); - idx++; - } + assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString()); + idx++; + } - @Test - public void testOperationWithBundleResponse() throws Exception { - IParser p = ourCtx.newXmlParser(); + @Test + public void testOperationWithBundleResponse() throws Exception { + IParser p = ourCtx.newXmlParser(); - Parameters inParams = new Parameters(); - inParams.addParameter().setValue(new StringType("STRINGVALIN1")); - inParams.addParameter().setValue(new StringType("STRINGVALIN2")); - String reqString = p.encodeResourceToString(inParams); + Parameters inParams = new Parameters(); + inParams.addParameter().setValue(new StringType("STRINGVALIN1")); + inParams.addParameter().setValue(new StringType("STRINGVALIN2")); + String reqString = p.encodeResourceToString(inParams); - org.hl7.fhir.instance.model.Bundle outParams = new org.hl7.fhir.instance.model.Bundle(); - outParams.setTotal(123); - final String respString = p.encodeResourceToString(outParams); + org.hl7.fhir.instance.model.Bundle outParams = new org.hl7.fhir.instance.model.Bundle(); + outParams.setTotal(123); + final String respString = p.encodeResourceToString(outParams); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - //@formatter:off + //@formatter:off Parameters resp = client .operation() .onServer() .named("$SOMEOPERATION") .withParameters(inParams).execute(); //@formatter:on - assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals(extractBody(capt, idx), reqString); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals(1, resp.getParameter().size()); - assertEquals(org.hl7.fhir.instance.model.Bundle.class, resp.getParameter().get(0).getResource().getClass()); - idx++; - } + assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString()); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals(extractBody(capt, idx), reqString); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + assertEquals(1, resp.getParameter().size()); + assertEquals(org.hl7.fhir.instance.model.Bundle.class, resp.getParameter().get(0).getResource().getClass()); + idx++; + } - @Test - public void testTransactionWithListOfResources() throws Exception { + @Test + public void testTransactionWithListOfResources() throws Exception { - org.hl7.fhir.instance.model.Bundle resp = new org.hl7.fhir.instance.model.Bundle(); - resp.addEntry().getResponse().setLocation("Patient/1/_history/1"); - resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); - String respString = ourCtx.newJsonParser().encodeResourceToString(resp); + org.hl7.fhir.instance.model.Bundle resp = new org.hl7.fhir.instance.model.Bundle(); + resp.addEntry().getResponse().setLocation("Patient/1/_history/1"); + resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); + String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"))); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"))); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - List input = new ArrayList(); + List input = new ArrayList(); - Patient p1 = new Patient(); // No ID - p1.addName().addFamily("PATIENT1"); - input.add(p1); + Patient p1 = new Patient(); // No ID + p1.addName().addFamily("PATIENT1"); + input.add(p1); - Patient p2 = new Patient(); // Yes ID - p2.addName().addFamily("PATIENT2"); - p2.setId("Patient/2"); - input.add(p2); + Patient p2 = new Patient(); // Yes ID + p2.addName().addFamily("PATIENT2"); + p2.setId("Patient/2"); + input.add(p2); - //@formatter:off + //@formatter:off List response = client.transaction() .withResources(input) .encodedJson() .execute(); //@formatter:on - assertEquals("http://example.com/fhir", capt.getValue().getURI().toString()); - assertEquals(2, response.size()); + assertEquals("http://example.com/fhir", capt.getValue().getURI().toString()); + assertEquals(2, response.size()); - String requestString = IOUtils.toString(((HttpEntityEnclosingRequest) capt.getValue()).getEntity().getContent()); - org.hl7.fhir.instance.model.Bundle requestBundle = ourCtx.newJsonParser().parseResource(org.hl7.fhir.instance.model.Bundle.class, requestString); - assertEquals(2, requestBundle.getEntry().size()); - assertEquals("POST", requestBundle.getEntry().get(0).getRequest().getMethod().name()); - assertEquals("PUT", requestBundle.getEntry().get(1).getRequest().getMethod().name()); - assertEquals("Patient/2", requestBundle.getEntry().get(1).getRequest().getUrl()); + String requestString = IOUtils.toString(((HttpEntityEnclosingRequest) capt.getValue()).getEntity().getContent()); + org.hl7.fhir.instance.model.Bundle requestBundle = ourCtx.newJsonParser().parseResource(org.hl7.fhir.instance.model.Bundle.class, requestString); + assertEquals(2, requestBundle.getEntry().size()); + assertEquals("POST", requestBundle.getEntry().get(0).getRequest().getMethod().name()); + assertEquals("PUT", requestBundle.getEntry().get(1).getRequest().getMethod().name()); + assertEquals("Patient/2", requestBundle.getEntry().get(1).getRequest().getUrl()); - p1 = (Patient) response.get(0); - assertEquals(new IdType("Patient/1/_history/1"), p1.getIdElement().toUnqualified()); - // assertEquals("PATIENT1", p1.getName().get(0).getFamily().get(0).getValue()); + p1 = (Patient) response.get(0); + assertEquals(new IdType("Patient/1/_history/1"), p1.getIdElement().toUnqualified()); + // assertEquals("PATIENT1", p1.getName().get(0).getFamily().get(0).getValue()); - p2 = (Patient) response.get(1); - assertEquals(new IdType("Patient/2/_history/2"), p2.getIdElement().toUnqualified()); - // assertEquals("PATIENT2", p2.getName().get(0).getFamily().get(0).getValue()); - } + p2 = (Patient) response.get(1); + assertEquals(new IdType("Patient/2/_history/2"), p2.getIdElement().toUnqualified()); + // assertEquals("PATIENT2", p2.getName().get(0).getFamily().get(0).getValue()); + } - @Test - public void testTransactionWithTransactionResource() throws Exception { + @Test + public void testTransactionWithTransactionResource() throws Exception { - org.hl7.fhir.instance.model.Bundle resp = new org.hl7.fhir.instance.model.Bundle(); - resp.addEntry().getResponse().setLocation("Patient/1/_history/1"); - resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); - String respString = ourCtx.newJsonParser().encodeResourceToString(resp); + org.hl7.fhir.instance.model.Bundle resp = new org.hl7.fhir.instance.model.Bundle(); + resp.addEntry().getResponse().setLocation("Patient/1/_history/1"); + resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); + String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"))); + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"))); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - org.hl7.fhir.instance.model.Bundle input = new org.hl7.fhir.instance.model.Bundle(); + org.hl7.fhir.instance.model.Bundle input = new org.hl7.fhir.instance.model.Bundle(); - Patient p1 = new Patient(); // No ID - p1.addName().addFamily("PATIENT1"); - input.addEntry().setResource(p1); + Patient p1 = new Patient(); // No ID + p1.addName().addFamily("PATIENT1"); + input.addEntry().setResource(p1); - Patient p2 = new Patient(); // Yes ID - p2.addName().addFamily("PATIENT2"); - p2.setId("Patient/2"); - input.addEntry().setResource(p2); + Patient p2 = new Patient(); // Yes ID + p2.addName().addFamily("PATIENT2"); + p2.setId("Patient/2"); + input.addEntry().setResource(p2); - //@formatter:off + //@formatter:off org.hl7.fhir.instance.model.Bundle response = client.transaction() .withBundle(input) .encodedJson() .execute(); //@formatter:on - assertEquals("http://example.com/fhir", capt.getValue().getURI().toString()); - assertEquals(2, response.getEntry().size()); + assertEquals("http://example.com/fhir", capt.getValue().getURI().toString()); + assertEquals(2, response.getEntry().size()); - assertEquals("Patient/1/_history/1", response.getEntry().get(0).getResponse().getLocation()); - assertEquals("Patient/2/_history/2", response.getEntry().get(1).getResponse().getLocation()); - } + assertEquals("Patient/1/_history/1", response.getEntry().get(0).getResponse().getLocation()); + assertEquals("Patient/2/_history/2", response.getEntry().get(1).getResponse().getLocation()); + } - @Test - public void testDeleteConditional() throws Exception { - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); - // when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", - // Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); - } - }); + @Test + public void testDeleteConditional() throws Exception { + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); + // when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", + // Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - client.delete().resourceById(new IdType("Patient/123")).execute(); - assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); - assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.delete().resourceById(new IdType("Patient/123")).execute(); + assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); + assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString()); + idx++; - client.delete().resourceConditionalByUrl("Patient?name=foo").execute(); - assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); - assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.delete().resourceConditionalByUrl("Patient?name=foo").execute(); + assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); + assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); + idx++; - client.delete().resourceConditionalByType("Patient").where(new StringClientParam("name").matches().value("foo")).execute(); - assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); - assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.delete().resourceConditionalByType("Patient").where(new StringClientParam("name").matches().value("foo")).execute(); + assertEquals("DELETE", capt.getAllValues().get(idx).getMethod()); + assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); + idx++; - } + } - @Test - public void testCreateConditional() throws Exception { - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); - } - }); + @Test + public void testCreateConditional() throws Exception { + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - Patient p = new Patient(); - p.addName().addFamily("FOOFAMILY"); + Patient p = new Patient(); + p.addName().addFamily("FOOFAMILY"); - client.create().resource(p).conditionalByUrl("Patient?name=foo").execute(); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertThat(extractBody(capt, idx), containsString("")); - assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); - assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + client.create().resource(p).conditionalByUrl("Patient?name=foo").execute(); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertThat(extractBody(capt, idx), containsString("")); + assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); + assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - client.create().resource(p).conditional().where(new StringClientParam("name").matches().value("foo")).execute(); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertThat(extractBody(capt, idx), containsString("")); - assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); - assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); - idx++; + client.create().resource(p).conditional().where(new StringClientParam("name").matches().value("foo")).execute(); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertThat(extractBody(capt, idx), containsString("")); + assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); + assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod()); + idx++; - } + } - @Test - public void testUpdateConditional() throws Exception { - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); - } - }); + @Test + public void testUpdateConditional() throws Exception { + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, "")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8")); + } + }); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; + int idx = 0; - Patient p = new Patient(); - p.addName().addFamily("FOOFAMILY"); + Patient p = new Patient(); + p.addName().addFamily("FOOFAMILY"); - client.update().resource(p).conditionalByUrl("Patient?name=foo").execute(); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertThat(extractBody(capt, idx), containsString("")); - assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.update().resource(p).conditionalByUrl("Patient?name=foo").execute(); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertThat(extractBody(capt, idx), containsString("")); + assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); + assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); + idx++; - client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditionalByUrl("Patient?name=foo").execute(); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertThat(extractBody(capt, idx), containsString("")); - assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditionalByUrl("Patient?name=foo").execute(); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertThat(extractBody(capt, idx), containsString("")); + assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); + assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString()); + idx++; - client.update().resource(p).conditional().where(new StringClientParam("name").matches().value("foo")).and(new StringClientParam("address").matches().value("AAA|BBB")).execute(); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertThat(extractBody(capt, idx), containsString("")); - assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("http://example.com/fhir/Patient?name=foo&address=AAA%5C%7CBBB", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.update().resource(p).conditional().where(new StringClientParam("name").matches().value("foo")).and(new StringClientParam("address").matches().value("AAA|BBB")).execute(); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertThat(extractBody(capt, idx), containsString("")); + assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); + assertEquals("http://example.com/fhir/Patient?name=foo&address=AAA%5C%7CBBB", capt.getAllValues().get(idx).getURI().toString()); + idx++; - client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditional().where(new StringClientParam("name").matches().value("foo")).and(new StringClientParam("address").matches().value("AAA|BBB")).execute(); - assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertThat(extractBody(capt, idx), containsString("")); - assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); - assertEquals("http://example.com/fhir/Patient?name=foo&address=AAA%5C%7CBBB", capt.getAllValues().get(idx).getURI().toString()); - idx++; + client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditional().where(new StringClientParam("name").matches().value("foo")) + .and(new StringClientParam("address").matches().value("AAA|BBB")).execute(); + assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertThat(extractBody(capt, idx), containsString("")); + assertEquals("PUT", capt.getAllValues().get(idx).getRequestLine().getMethod()); + assertEquals("http://example.com/fhir/Patient?name=foo&address=AAA%5C%7CBBB", capt.getAllValues().get(idx).getURI().toString()); + idx++; - } + } - private String extractBody(ArgumentCaptor capt, int count) throws IOException { - String body = IOUtils.toString(((HttpEntityEnclosingRequestBase) capt.getAllValues().get(count)).getEntity().getContent(), "UTF-8"); - return body; - } + private String extractBody(ArgumentCaptor capt, int count) throws IOException { + String body = IOUtils.toString(((HttpEntityEnclosingRequestBase) capt.getAllValues().get(count)).getEntity().getContent(), "UTF-8"); + return body; + } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionHl7OrgDstu2Test.java deleted file mode 100644 index e80e9e9b9ec..00000000000 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionHl7OrgDstu2Test.java +++ /dev/null @@ -1,56 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import javax.servlet.ServletException; - -import org.hamcrest.core.StringContains; -import org.hl7.fhir.instance.model.Patient; -import org.hl7.fhir.instance.model.StringType; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.Test; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Operation; -import ca.uhn.fhir.rest.annotation.OperationParam; - -public class ServerInvalidDefinitionHl7OrgDstu2Test { - - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory - .getLogger(ServerInvalidDefinitionHl7OrgDstu2Test.class); - - @Test - public void testOperationReturningOldBundleProvider() { - RestfulServer srv = new RestfulServer(ourCtx); - srv.setFhirContext(ourCtx); - srv.setResourceProviders(new OperationReturningOldBundleProvider()); - - try { - srv.init(); - fail(); - } catch (ServletException e) { - ourLog.info(e.getCause().toString()); - assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); - assertThat(e.getCause().toString(), StringContains.containsString("Can not return a DSTU1 bundle")); - } - } - - public static class OperationReturningOldBundleProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Operation(name = "$OP_TYPE_RET_OLD_BUNDLE") - public ca.uhn.fhir.model.api.Bundle opTypeRetOldBundle(@OperationParam(name = "PARAM1") StringType theParam1, - @OperationParam(name = "PARAM2") Patient theParam2) { - return null; - } - - } - -} diff --git a/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/hapi/rest/server/R4BundleFactory.java b/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/hapi/rest/server/R4BundleFactory.java index a4e555be609..538dc47dc7c 100644 --- a/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/hapi/rest/server/R4BundleFactory.java +++ b/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/hapi/rest/server/R4BundleFactory.java @@ -264,11 +264,6 @@ public class R4BundleFactory implements IVersionSpecificBundleFactory { } } - @Override - public ca.uhn.fhir.model.api.Bundle getDstu1Bundle() { - return null; - } - @Override public IBaseResource getResourceBundle() { return myBundle; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientR4Test.java index d25eda09dfa..3402fff3d54 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientR4Test.java @@ -2,7 +2,13 @@ package ca.uhn.fhir.rest.client; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -33,8 +39,10 @@ import com.phloc.commons.io.streams.StringInputStream; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirVersionEnum; +import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.model.api.TemporalPrecisionEnum; -import ca.uhn.fhir.model.primitive.*; +import ca.uhn.fhir.model.primitive.DateTimeDt; +import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.parser.CustomTypeR4Test; import ca.uhn.fhir.parser.CustomTypeR4Test.MyCustomPatient; import ca.uhn.fhir.parser.IParser; @@ -47,6 +55,7 @@ import ca.uhn.fhir.rest.client.exceptions.NonFhirResponseException; import ca.uhn.fhir.rest.client.impl.BaseClient; import ca.uhn.fhir.rest.client.interceptor.CookieInterceptor; import ca.uhn.fhir.rest.client.interceptor.UserInfoInterceptor; +import ca.uhn.fhir.rest.param.DateParam; import ca.uhn.fhir.rest.param.ParamPrefixEnum; import ca.uhn.fhir.rest.server.exceptions.NotImplementedOperationException; import ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException; @@ -99,272 +108,6 @@ public class GenericClientR4Test { return capt; } - @Test - public void testRevIncludeRecursive() throws ClientProtocolException, IOException { - ArgumentCaptor capt = prepareClientForSearchResponse(); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - client.search() - .forResource(EpisodeOfCare.class) - .where(EpisodeOfCare.PATIENT.hasId("123")) - .revInclude(Encounter.INCLUDE_EPISODEOFCARE) - .revInclude(Observation.INCLUDE_ENCOUNTER.asRecursive()) - .returnBundle(Bundle.class) - .execute(); - - assertEquals("http://example.com/fhir/EpisodeOfCare?patient=123&_revinclude=Encounter%3Aepisodeofcare&_revinclude%3Arecurse=Observation%3Aencounter", - capt.getAllValues().get(idx).getURI().toString()); - idx++; - - } - - @Test - public void testPatchJsonByIdString() throws Exception { - OperationOutcome conf = new OperationOutcome(); - conf.getText().setDivAsString("OK!"); - final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; - - MethodOutcome outcome = client - .patch() - .withBody(patch) - .withId("Patient/123") - .execute(); - - assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); - assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); - assertEquals(patch, extractBodyAsString(capt)); - assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); - idx++; - - OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); - assertThat(oo.getText().getDivAsString(), containsString("OK!")); - } - - @Test - public void testPatchJsonByIdType() throws Exception { - OperationOutcome conf = new OperationOutcome(); - conf.getText().setDivAsString("OK!"); - final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; - - MethodOutcome outcome = client - .patch() - .withBody(patch) - .withId(new IdType("http://localhost/fhir/Patient/123/_history/234")) - .execute(); - - assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); - assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); - assertEquals(patch, extractBodyAsString(capt)); - assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); - idx++; - - OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); - assertThat(oo.getText().getDivAsString(), containsString("OK!")); - } - - @Test - public void testPatchJsonByConditionalString() throws Exception { - OperationOutcome conf = new OperationOutcome(); - conf.getText().setDivAsString("OK!"); - final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; - - MethodOutcome outcome = client - .patch() - .withBody(patch) - .conditionalByUrl("Patient?foo=bar") - .execute(); - - assertEquals("http://example.com/fhir/Patient?foo=bar", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); - assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); - assertEquals(patch, extractBodyAsString(capt)); - assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); - idx++; - - OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); - assertThat(oo.getText().getDivAsString(), containsString("OK!")); - } - - @Test - public void testPatchJsonByConditionalParam() throws Exception { - OperationOutcome conf = new OperationOutcome(); - conf.getText().setDivAsString("OK!"); - final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; - - MethodOutcome outcome = client - .patch() - .withBody(patch) - .conditional("Patient").where(Patient.NAME.matches().value("TEST")) - .and(Patient.FAMILY.matches().value("TEST2")) - .execute(); - - assertEquals("http://example.com/fhir/Patient?name=TEST&family=TEST2", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); - assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); - assertEquals(patch, extractBodyAsString(capt)); - assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); - idx++; - - OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); - assertThat(oo.getText().getDivAsString(), containsString("OK!")); - } - - @Test - public void testPatchJsonByConditionalParamResourceType() throws Exception { - OperationOutcome conf = new OperationOutcome(); - conf.getText().setDivAsString("OK!"); - final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; - - MethodOutcome outcome = client - .patch() - .withBody(patch) - .conditional(Patient.class).where(Patient.NAME.matches().value("TEST")) - .and(Patient.FAMILY.matches().value("TEST2")) - .execute(); - - assertEquals("http://example.com/fhir/Patient?name=TEST&family=TEST2", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); - assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); - assertEquals(patch, extractBodyAsString(capt)); - assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); - idx++; - - OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); - assertThat(oo.getText().getDivAsString(), containsString("OK!")); - } - - @Test - public void testPatchXmlByIdString() throws Exception { - OperationOutcome conf = new OperationOutcome(); - conf.getText().setDivAsString("OK!"); - final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); - } - }); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - int idx = 0; - - String patch = "false"; - - MethodOutcome outcome = client - .patch() - .withBody(patch) - .withId("Patient/123") - .execute(); - - assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); - assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); - assertEquals(patch, extractBodyAsString(capt)); - assertEquals(Constants.CT_XML_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); - idx++; - - OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); - assertThat(oo.getText().getDivAsString(), containsString("OK!")); - } - - @Test - public void testPatchInvalid() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - - try { - client - .patch() - .withBody("AA") - .withId("Patient/123") - .execute(); - } catch (IllegalArgumentException e) { - assertEquals("Unable to determine encoding of patch", e.getMessage()); - } - } - @Test public void testAcceptHeaderWithEncodingSpecified() throws Exception { final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; @@ -923,18 +666,6 @@ public class GenericClientR4Test { } - @SuppressWarnings("deprecation") - @Test - public void testInvalidConformanceCall() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - try { - client.conformance(); - fail(); - } catch (IllegalArgumentException e) { - assertEquals("Must call fetchConformance() instead of conformance() for RI/STU3+ structures", e.getMessage()); - } - } - /** * See #150 */ @@ -980,6 +711,251 @@ public class GenericClientR4Test { } + @Test + public void testPatchInvalid() throws Exception { + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + + try { + client + .patch() + .withBody("AA") + .withId("Patient/123") + .execute(); + } catch (IllegalArgumentException e) { + assertEquals("Unable to determine encoding of patch", e.getMessage()); + } + } + + @Test + public void testPatchJsonByConditionalParam() throws Exception { + OperationOutcome conf = new OperationOutcome(); + conf.getText().setDivAsString("OK!"); + final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; + + MethodOutcome outcome = client + .patch() + .withBody(patch) + .conditional("Patient").where(Patient.NAME.matches().value("TEST")) + .and(Patient.FAMILY.matches().value("TEST2")) + .execute(); + + assertEquals("http://example.com/fhir/Patient?name=TEST&family=TEST2", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); + assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); + assertEquals(patch, extractBodyAsString(capt)); + assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); + idx++; + + OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); + assertThat(oo.getText().getDivAsString(), containsString("OK!")); + } + + @Test + public void testPatchJsonByConditionalParamResourceType() throws Exception { + OperationOutcome conf = new OperationOutcome(); + conf.getText().setDivAsString("OK!"); + final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; + + MethodOutcome outcome = client + .patch() + .withBody(patch) + .conditional(Patient.class).where(Patient.NAME.matches().value("TEST")) + .and(Patient.FAMILY.matches().value("TEST2")) + .execute(); + + assertEquals("http://example.com/fhir/Patient?name=TEST&family=TEST2", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); + assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); + assertEquals(patch, extractBodyAsString(capt)); + assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); + idx++; + + OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); + assertThat(oo.getText().getDivAsString(), containsString("OK!")); + } + + @Test + public void testPatchJsonByConditionalString() throws Exception { + OperationOutcome conf = new OperationOutcome(); + conf.getText().setDivAsString("OK!"); + final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; + + MethodOutcome outcome = client + .patch() + .withBody(patch) + .conditionalByUrl("Patient?foo=bar") + .execute(); + + assertEquals("http://example.com/fhir/Patient?foo=bar", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); + assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); + assertEquals(patch, extractBodyAsString(capt)); + assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); + idx++; + + OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); + assertThat(oo.getText().getDivAsString(), containsString("OK!")); + } + + @Test + public void testPatchJsonByIdString() throws Exception { + OperationOutcome conf = new OperationOutcome(); + conf.getText().setDivAsString("OK!"); + final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; + + MethodOutcome outcome = client + .patch() + .withBody(patch) + .withId("Patient/123") + .execute(); + + assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); + assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); + assertEquals(patch, extractBodyAsString(capt)); + assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); + idx++; + + OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); + assertThat(oo.getText().getDivAsString(), containsString("OK!")); + } + + @Test + public void testPatchJsonByIdType() throws Exception { + OperationOutcome conf = new OperationOutcome(); + conf.getText().setDivAsString("OK!"); + final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + String patch = "[ { \"op\":\"replace\", \"path\":\"/active\", \"value\":false } ]"; + + MethodOutcome outcome = client + .patch() + .withBody(patch) + .withId(new IdType("http://localhost/fhir/Patient/123/_history/234")) + .execute(); + + assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); + assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); + assertEquals(patch, extractBodyAsString(capt)); + assertEquals(Constants.CT_JSON_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); + idx++; + + OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); + assertThat(oo.getText().getDivAsString(), containsString("OK!")); + } + + @Test + public void testPatchXmlByIdString() throws Exception { + OperationOutcome conf = new OperationOutcome(); + conf.getText().setDivAsString("OK!"); + final String respString = ourCtx.newJsonParser().encodeResourceToString(conf); + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + String patch = "false"; + + MethodOutcome outcome = client + .patch() + .withBody(patch) + .withId("Patient/123") + .execute(); + + assertEquals("http://example.com/fhir/Patient/123", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); + assertEquals("PATCH", capt.getAllValues().get(0).getRequestLine().getMethod()); + assertEquals(patch, extractBodyAsString(capt)); + assertEquals(Constants.CT_XML_PATCH, capt.getAllValues().get(idx).getFirstHeader("Content-Type").getValue().replaceAll(";.*", "")); + idx++; + + OperationOutcome oo = (OperationOutcome) outcome.getOperationOutcome(); + assertThat(oo.getText().getDivAsString(), containsString("OK!")); + } + @Test public void testPutDoesntForceAllIdsJson() throws Exception { IParser p = ourCtx.newJsonParser(); @@ -1152,33 +1128,24 @@ public class GenericClientR4Test { } @Test - public void testSearchWithNullParameters() throws Exception { - final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).then(new Answer() { - @Override - public InputStream answer(InvocationOnMock theInvocation) throws Throwable { - return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); - } - }); + public void testRevIncludeRecursive() throws ClientProtocolException, IOException { + ArgumentCaptor capt = prepareClientForSearchResponse(); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - DateTimeDt now = DateTimeDt.withCurrentTime(); - String dateString = now.getValueAsString().substring(0, 10); - client.search() - .forResource("Patient") - .where(Patient.NAME.matches().value((String) null)) + .forResource(EpisodeOfCare.class) + .where(EpisodeOfCare.PATIENT.hasId("123")) + .revInclude(Encounter.INCLUDE_EPISODEOFCARE) + .revInclude(Observation.INCLUDE_ENCOUNTER.asRecursive()) .returnBundle(Bundle.class) .execute(); - assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); + + assertEquals("http://example.com/fhir/EpisodeOfCare?patient=123&_revinclude=Encounter%3Aepisodeofcare&_revinclude%3Arecurse=Observation%3Aencounter", + capt.getAllValues().get(idx).getURI().toString()); idx++; + } @Test @@ -1530,14 +1497,29 @@ public class GenericClientR4Test { } @Test - public void testSearchForUnknownType() throws Exception { + public void testSearchWithMap() throws Exception { + String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - try { - client.search(new UriDt("?aaaa")); - fail(); - } catch (IllegalArgumentException e) { - assertEquals("Unable to determine the resource type from the given URI: ?aaaa", e.getMessage()); - } + + HashMap> params = new HashMap>(); + params.put("foo", Arrays.asList((IQueryParameterType) new DateParam("2001"))); + Bundle response = client + .search() + .forResource(Patient.class) + .where(params) + .returnBundle(Bundle.class) + .execute(); + + assertEquals("http://example.com/fhir/Patient?foo=2001", capt.getValue().getURI().toString()); + assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); + } @Test @@ -1561,6 +1543,36 @@ public class GenericClientR4Test { } + @Test + public void testSearchWithNullParameters() throws Exception { + final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; + + ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).then(new Answer() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); + } + }); + + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + int idx = 0; + + DateTimeDt now = DateTimeDt.withCurrentTime(); + String dateString = now.getValueAsString().substring(0, 10); + + client.search() + .forResource("Patient") + .where(Patient.NAME.matches().value((String) null)) + .returnBundle(Bundle.class) + .execute(); + assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString()); + idx++; + } + /** * See #371 */ diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerDstu1Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerDstu1Test.java new file mode 100644 index 00000000000..7ac6de97773 --- /dev/null +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerDstu1Test.java @@ -0,0 +1,654 @@ +package ca.uhn.fhir.rest.server; + +import static ca.uhn.fhir.util.UrlUtil.escape; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.io.IOUtils; +import org.apache.http.*; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.hl7.fhir.r4.model.*; +import org.junit.*; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.model.api.Include; +import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator; +import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.client.api.IGenericClient; +import ca.uhn.fhir.rest.param.*; +import ca.uhn.fhir.util.*; + +public class SearchSearchServerDstu1Test { + + private static CloseableHttpClient ourClient; + private static FhirContext ourCtx = FhirContext.forR4(); + private static IServerAddressStrategy ourDefaultAddressStrategy; + private static StringAndListParam ourLastAndList; + + private static Set ourLastIncludes; + private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchSearchServerDstu1Test.class); + private static int ourPort; + private static Server ourServer; + private static RestfulServer ourServlet; + + @Before + public void before() { + ourServlet.setServerAddressStrategy(ourDefaultAddressStrategy); + ourLastIncludes = null; + ourLastAndList = null; + } + + @Test + public void testEncodeConvertsReferencesToRelative() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + ourLog.info(responseContent); + + assertEquals(200, status.getStatusLine().getStatusCode()); + Patient patient = (Patient) ourCtx.newXmlParser().parseResource(Bundle.class, responseContent).getEntry().get(0).getResource(); + String ref = patient.getManagingOrganization().getReference(); + assertEquals("Organization/555", ref); + } + + /** + * Try loading the page as a POST just to make sure we get the right error + */ + @Test + public void testGetPagesWithPost() throws Exception { + + HttpPost httpPost = new HttpPost("http://localhost:" + ourPort); + List parameters = Collections.singletonList(new BasicNameValuePair("_getpages", "AAA")); + httpPost.setEntity(new UrlEncodedFormEntity(parameters)); + + CloseableHttpResponse status = ourClient.execute(httpPost); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + ourLog.info(responseContent); + assertEquals(400, status.getStatusLine().getStatusCode()); + // assertThat(responseContent, containsString("Requests for _getpages must use HTTP GET")); + } + + @Test + public void testOmitEmptyOptionalParam() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id="); + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals(null, p.getNameFirstRep().getFamily()); + } + + @Test + public void testParseEscapedValues() throws Exception { + + StringBuilder b = new StringBuilder(); + b.append("http://localhost:"); + b.append(ourPort); + b.append("/Patient?"); + b.append(escape("findPatientWithAndList")).append('=').append(escape("NE\\,NE,NE\\,NE")).append('&'); + b.append(escape("findPatientWithAndList")).append('=').append(escape("NE\\\\NE")).append('&'); + b.append(escape("findPatientWithAndList:exact")).append('=').append(escape("E\\$E")).append('&'); + b.append(escape("findPatientWithAndList:exact")).append('=').append(escape("E\\|E")).append('&'); + + HttpGet httpGet = new HttpGet(b.toString()); + + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + ourLog.info(responseContent); + + assertEquals(200, status.getStatusLine().getStatusCode()); + + assertEquals(4, ourLastAndList.getValuesAsQueryTokens().size()); + assertEquals(2, ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().size()); + assertFalse(ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).isExact()); + assertEquals("NE,NE", ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); + assertEquals("NE,NE", ourLastAndList.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(1).getValue()); + assertEquals("NE\\NE", ourLastAndList.getValuesAsQueryTokens().get(1).getValuesAsQueryTokens().get(0).getValue()); + assertTrue(ourLastAndList.getValuesAsQueryTokens().get(2).getValuesAsQueryTokens().get(0).isExact()); + assertEquals("E$E", ourLastAndList.getValuesAsQueryTokens().get(2).getValuesAsQueryTokens().get(0).getValue()); + assertEquals("E|E", ourLastAndList.getValuesAsQueryTokens().get(3).getValuesAsQueryTokens().get(0).getValue()); + } + + @Test + public void testReturnLinks() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findWithLinks"); + + CloseableHttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(10, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("AAANamed", p.getIdentifierFirstRep().getValue()); + + } + + /** + * #149 + */ + @Test + public void testReturnLinksWithAddressStrategy() throws Exception { + ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("https://blah.com/base")); + + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findWithLinks"); + + CloseableHttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + + ourLog.info(responseContent); + + assertEquals(10, bundle.getEntry().size()); + assertEquals("https://blah.com/base/Patient?_query=findWithLinks", bundle.getLink("self").getUrl()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("AAANamed", p.getIdentifierFirstRep().getValue()); + + String linkNext = bundle.getLink("next").getUrl(); + ourLog.info(linkNext); + assertThat(linkNext, startsWith("https://blah.com/base?_getpages=")); + + /* + * Load the second page + */ + String urlPart = linkNext.substring(linkNext.indexOf('?')); + String link = "http://localhost:" + ourPort + urlPart; + httpGet = new HttpGet(link); + + status = ourClient.execute(httpGet); + responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + + ourLog.info(responseContent); + + assertEquals(10, bundle.getEntry().size()); + assertEquals(linkNext, bundle.getLink("self").getUrl()); + + p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("AAANamed", p.getIdentifierFirstRep().getValue()); + + } + + @Test + public void testSearchById() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa"); + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("idaaa", p.getNameFirstRep().getFamily()); + } + + @Test + public void testSearchByIdUsingClient() throws Exception { + IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); + + Bundle bundle = client + .search() + .forResource("Patient") + .where(BaseResource.RES_ID.exactly().code("aaa")) + .returnBundle(Bundle.class) + .execute(); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("idaaa", p.getNameFirstRep().getFamily()); + } + + @Test + public void testSearchByPost() throws Exception { + HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); + + // add parameters to the post method + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair("_id", "aaa")); + + UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8"); + filePost.setEntity(sendentity); + + HttpResponse status = ourClient.execute(filePost); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("idaaa", p.getNameFirstRep().getFamily()); + } + + /** + * See #164 + */ + @Test + public void testSearchByPostWithInvalidPostUrl() throws Exception { + HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); // should end with + // _search + + // add parameters to the post method + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair("_id", "aaa")); + + UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8"); + filePost.setEntity(sendentity); + + HttpResponse status = ourClient.execute(filePost); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + ourLog.info(responseContent); + assertEquals(400, status.getStatusLine().getStatusCode()); + assertThat(responseContent, containsString( + "")); + } + + /** + * See #164 + */ + @Test + public void testSearchByPostWithMissingContentType() throws Exception { + HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); // should end with + // _search + + HttpEntity sendentity = new ByteArrayEntity(new byte[] { 1, 2, 3, 4 }); + filePost.setEntity(sendentity); + + HttpResponse status = ourClient.execute(filePost); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + ourLog.info(responseContent); + assertEquals(400, status.getStatusLine().getStatusCode()); + assertThat(responseContent, containsString("")); + } + + /** + * See #164 + */ + @Test + public void testSearchByPostWithParamsInBodyAndUrl() throws Exception { + HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?name=Central"); + + // add parameters to the post method + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair("_id", "aaa")); + + UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8"); + filePost.setEntity(sendentity); + + HttpResponse status = ourClient.execute(filePost); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + ourLog.info(responseContent); + assertEquals(200, status.getStatusLine().getStatusCode()); + + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("idaaa", p.getName().get(0).getFamily()); + assertEquals("nameCentral", p.getName().get(1).getGiven().get(0).getValue()); + + } + + @Test + public void testSearchCompartment() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/fooCompartment"); + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + ourLog.info(responseContent); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("fooCompartment", p.getIdentifierFirstRep().getValue()); + assertThat(bundle.getEntry().get(0).getResource().getIdElement().getValue(), containsString("Patient/123")); + } + + @Test + public void testSearchGetWithUnderscoreSearch() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/_search?subject%3APatient=100&name=3141-9%2C8302-2%2C8287-5%2C39156-5"); + + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Observation p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Observation.class).get(0); + assertEquals("Patient/100", p.getSubject().getReference().toString()); + assertEquals(4, p.getCode().getCoding().size()); + assertEquals("3141-9", p.getCode().getCoding().get(0).getCode()); + assertEquals("8302-2", p.getCode().getCoding().get(1).getCode()); + + } + + @Test + public void testSearchIncludesParametersIncludes() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes&_include=foo&_include:recurse=bar"); + + CloseableHttpResponse status = ourClient.execute(httpGet); + IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + + assertEquals(2, ourLastIncludes.size()); + assertThat(ourLastIncludes, containsInAnyOrder(new Include("foo", false), new Include("bar", true))); + } + + @Test + public void testSearchIncludesParametersIncludesList() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludesList&_include=foo&_include:recurse=bar"); + + CloseableHttpResponse status = ourClient.execute(httpGet); + IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + + assertEquals(2, ourLastIncludes.size()); + assertThat(ourLastIncludes, containsInAnyOrder(new Include("foo", false), new Include("bar", true))); + } + + @Test + public void testSearchIncludesParametersNone() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes"); + + CloseableHttpResponse status = ourClient.execute(httpGet); + IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + + assertThat(ourLastIncludes, empty()); + } + + @Test + public void testSearchWithOrList() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?findPatientWithOrList=aaa,bbb"); + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("aaa", p.getIdentifier().get(0).getValue()); + assertEquals("bbb", p.getIdentifier().get(1).getValue()); + } + + @Test + public void testSearchWithTokenParameter() throws Exception { + String token = UrlUtil.escape("http://www.dmix.gov/vista/2957|301"); + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?tokenParam=" + token); + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("http://www.dmix.gov/vista/2957", p.getNameFirstRep().getFamily()); + assertEquals("301", p.getNameFirstRep().getGivenAsSingleString()); + } + + @Test + public void testSpecificallyNamedQueryGetsPrecedence() throws Exception { + HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?AAA=123"); + + HttpResponse status = ourClient.execute(httpGet); + String responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + Patient p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("AAA", p.getIdentifierFirstRep().getValue()); + + // Now the named query + + httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findPatientByAAA&AAA=123"); + + status = ourClient.execute(httpGet); + responseContent = IOUtils.toString(status.getEntity().getContent()); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); + assertEquals(1, bundle.getEntry().size()); + + p = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class).get(0); + assertEquals("AAANamed", p.getIdentifierFirstRep().getValue()); + } + + @AfterClass + public static void afterClassClearContext() throws Exception { + ourServer.stop(); + TestUtil.clearAllStaticFieldsForUnitTest(); + } + + @BeforeClass + public static void beforeClass() throws Exception { + ourPort = PortUtil.findFreePort(); + ourServer = new Server(ourPort); + + DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); + + ServletHandler proxyHandler = new ServletHandler(); + ourServlet = new RestfulServer(ourCtx); + ourServlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); + ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(10)); + + ourServlet.setResourceProviders(patientProvider, new DummyObservationResourceProvider()); + ServletHolder servletHolder = new ServletHolder(ourServlet); + proxyHandler.addServletWithMapping(servletHolder, "/*"); + ourServer.setHandler(proxyHandler); + ourServer.start(); + + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); + HttpClientBuilder builder = HttpClientBuilder.create(); + builder.setConnectionManager(connectionManager); + ourClient = builder.build(); + + ourDefaultAddressStrategy = ourServlet.getServerAddressStrategy(); + } + + public static class DummyObservationResourceProvider implements IResourceProvider { + + @Override + public Class getResourceType() { + return Observation.class; + } + + @Search + public Observation search(@RequiredParam(name = "subject") ReferenceParam theSubject, @RequiredParam(name = "name") TokenOrListParam theName) { + Observation o = new Observation(); + o.setId("1"); + + o.getSubject().setReference(theSubject.getResourceType() + "/" + theSubject.getIdPart()); + for (TokenParam next : theName.getValuesAsQueryTokens()) { + o.getCode().addCoding().setSystem(next.getSystem()).setCode(next.getValue()); + } + + return o; + } + + } + + public static class DummyPatientResourceProvider implements IResourceProvider { + + @Search(compartmentName = "fooCompartment") + public List compartment(@IdParam IdType theId) { + ArrayList retVal = new ArrayList(); + + Patient patient = new Patient(); + patient.setId(theId); + patient.addIdentifier().setSystem("system").setValue("fooCompartment"); + retVal.add(patient); + return retVal; + } + + /** + * Only needed for #164 + */ + @Create + public MethodOutcome create(@ResourceParam Patient thePatient) { + throw new IllegalArgumentException(); + } + + @Search + public List findPatient(@RequiredParam(name = "_id") StringParam theParam, @OptionalParam(name = "name") StringParam theName) { + ArrayList retVal = new ArrayList(); + + Patient patient = new Patient(); + patient.setId("1"); + patient.addIdentifier().setSystem("system").setValue("identifier123"); + if (theParam != null) { + patient.addName().setFamily("id" + theParam.getValue()); + if (theName != null) { + patient.addName().addGiven("name" + theName.getValue()); + } + } + retVal.add(patient); + return retVal; + } + + @Search + public List findPatientByAAA01(@RequiredParam(name = "AAA") StringParam theParam) { + ArrayList retVal = new ArrayList(); + + Patient patient = new Patient(); + patient.setId("1"); + patient.addIdentifier().setSystem("system").setValue("AAA"); + retVal.add(patient); + return retVal; + } + + @Search(queryName = "findPatientByAAA") + public List findPatientByAAA02Named(@OptionalParam(name = "AAA") StringParam theParam) { + ArrayList retVal = new ArrayList(); + + Patient patient = new Patient(); + patient.setId("1"); + patient.addIdentifier().setSystem("system").setValue( "AAANamed"); + retVal.add(patient); + return retVal; + } + + @Search() + public List findPatientWithAndList(@RequiredParam(name = "findPatientWithAndList") StringAndListParam theParam) { + ourLastAndList = theParam; + ArrayList retVal = new ArrayList(); + return retVal; + } + + @Search() + public List findPatientWithOrList(@RequiredParam(name = "findPatientWithOrList") StringOrListParam theParam) { + ArrayList retVal = new ArrayList(); + + Patient patient = new Patient(); + patient.setId("1"); + for (StringParam next : theParam.getValuesAsQueryTokens()) { + patient.addIdentifier().setSystem("system").setValue( next.getValue()); + } + retVal.add(patient); + return retVal; + } + + @Search() + public List findPatientWithToken(@RequiredParam(name = "tokenParam") TokenParam theParam) { + ArrayList retVal = new ArrayList(); + + Patient patient = new Patient(); + patient.setId("1"); + patient.addName().setFamily(theParam.getSystem()).addGiven(theParam.getValue()); + retVal.add(patient); + return retVal; + } + + @Search(queryName = "findWithLinks") + public List findWithLinks() { + ArrayList retVal = new ArrayList(); + + for (int i = 1; i <= 20; i++) { + Patient patient = new Patient(); + patient.setId("" + i); + patient.addIdentifier().setSystem("system").setValue( "AAANamed"); + retVal.add(patient); + } + + return retVal; + } + + @Override + public Class getResourceType() { + return Patient.class; + } + + @Search(queryName = "searchIncludes") + public List searchIncludes(@IncludeParam Set theIncludes) { + ourLastIncludes = theIncludes; + + ArrayList retVal = new ArrayList(); + return retVal; + } + + @Search(queryName = "searchIncludesList") + public List searchIncludesList(@IncludeParam List theIncludes) { + if (theIncludes != null) { + ourLastIncludes = new HashSet(theIncludes); + } + + ArrayList retVal = new ArrayList(); + return retVal; + } + + @Search(queryName = "searchWithRef") + public Patient searchWithRef() { + Patient patient = new Patient(); + patient.setId("Patient/1/_history/1"); + patient.getManagingOrganization().setReference("http://localhost:" + ourPort + "/Organization/555/_history/666"); + return patient; + } + + } + +} diff --git a/hapi-fhir-structures-r4/src/test/resource/logback-test.xml b/hapi-fhir-structures-r4/src/test/resource/logback-test.xml new file mode 100644 index 00000000000..e5cbbb9c22e --- /dev/null +++ b/hapi-fhir-structures-r4/src/test/resource/logback-test.xml @@ -0,0 +1,30 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} [%file:%line] - %msg%n + + + + + + + + + + + + + + + + + + + + + diff --git a/hapi-fhir-validation/src/main/java/org/hl7/fhir/instance/hapi/validation/BaseValidatorBridge.java b/hapi-fhir-validation/src/main/java/org/hl7/fhir/instance/hapi/validation/BaseValidatorBridge.java index 4ce3520973e..502102f37f7 100644 --- a/hapi-fhir-validation/src/main/java/org/hl7/fhir/instance/hapi/validation/BaseValidatorBridge.java +++ b/hapi-fhir-validation/src/main/java/org/hl7/fhir/instance/hapi/validation/BaseValidatorBridge.java @@ -5,7 +5,6 @@ import java.util.List; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.utilities.validation.ValidationMessage; -import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.validation.*; /** @@ -39,11 +38,6 @@ abstract class BaseValidatorBridge implements IValidatorModule { protected abstract List validate(IValidationContext theCtx); - @Override - public void validateBundle(IValidationContext theCtx) { - doValidate(theCtx); - } - @Override public void validateResource(IValidationContext theCtx) { doValidate(theCtx); diff --git a/hapi-fhir-validation/src/main/java/org/hl7/fhir/r4/hapi/validation/BaseValidatorBridge.java b/hapi-fhir-validation/src/main/java/org/hl7/fhir/r4/hapi/validation/BaseValidatorBridge.java index 4fe6da19b8d..4a86411c66f 100644 --- a/hapi-fhir-validation/src/main/java/org/hl7/fhir/r4/hapi/validation/BaseValidatorBridge.java +++ b/hapi-fhir-validation/src/main/java/org/hl7/fhir/r4/hapi/validation/BaseValidatorBridge.java @@ -5,11 +5,7 @@ import java.util.List; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.utilities.validation.ValidationMessage; -import ca.uhn.fhir.model.api.Bundle; -import ca.uhn.fhir.validation.IValidationContext; -import ca.uhn.fhir.validation.IValidatorModule; -import ca.uhn.fhir.validation.ResultSeverityEnum; -import ca.uhn.fhir.validation.SingleValidationMessage; +import ca.uhn.fhir.validation.*; /** * Base class for a bridge between the RI validation tools and HAPI @@ -42,11 +38,6 @@ abstract class BaseValidatorBridge implements IValidatorModule { protected abstract List validate(IValidationContext theCtx); - @Override - public void validateBundle(IValidationContext theCtx) { - doValidate(theCtx); - } - @Override public void validateResource(IValidationContext theCtx) { doValidate(theCtx); diff --git a/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java b/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java index fb62905c86e..40ee89dc323 100644 --- a/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java +++ b/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/Dstu2BundleFactory.java @@ -265,11 +265,6 @@ public class Dstu2BundleFactory implements IVersionSpecificBundleFactory { } } - @Override - public ca.uhn.fhir.model.api.Bundle getDstu1Bundle() { - return null; - } - @Override public IResource getResourceBundle() { return myBundle; diff --git a/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/ValueSetGenerator.java b/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/ValueSetGenerator.java index a994b8874ad..f7fc6f83b1b 100644 --- a/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/ValueSetGenerator.java +++ b/hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/ValueSetGenerator.java @@ -1,23 +1,8 @@ package ca.uhn.fhir.tinder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; +import java.io.*; import java.nio.charset.Charset; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; +import java.util.*; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -28,23 +13,17 @@ import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.tools.generic.EscapeTool; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Bundle; -import ca.uhn.fhir.model.api.BundleEntry; import ca.uhn.fhir.model.dstu.resource.ValueSet; import ca.uhn.fhir.model.dstu.resource.ValueSet.ComposeInclude; import ca.uhn.fhir.model.dstu.resource.ValueSet.Define; import ca.uhn.fhir.model.dstu.resource.ValueSet.DefineConcept; import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry; -import ca.uhn.fhir.model.dstu2.resource.ValueSet.CodeSystem; -import ca.uhn.fhir.model.dstu2.resource.ValueSet.CodeSystemConcept; -import ca.uhn.fhir.model.dstu2.resource.ValueSet.ComposeIncludeConcept; +import ca.uhn.fhir.model.dstu2.resource.ValueSet.*; import ca.uhn.fhir.model.primitive.CodeDt; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.parser.LenientErrorHandler; import ca.uhn.fhir.tinder.TinderStructuresMojo.ValueSetFileDefinition; -import ca.uhn.fhir.tinder.model.BaseRootType; import ca.uhn.fhir.tinder.model.ValueSetTm; -import ca.uhn.fhir.tinder.parser.ResourceGeneratorUsingSpreadsheet; import ca.uhn.fhir.tinder.parser.TargetType; public class ValueSetGenerator { @@ -126,18 +105,14 @@ public class ValueSetGenerator { throw new FileNotFoundException(name); } String vs = IOUtils.toString(is, Charset.defaultCharset()); - if ("dstu".equals(myVersion)) { - Bundle bundle = newXmlParser.parseBundle(vs); - for (BundleEntry next : bundle.getEntries()) { - ValueSet nextVs = (ValueSet) next.getResource(); - parseValueSet(nextVs); - } - } else { + if ("dstu2".equals(myVersion)) { ca.uhn.fhir.model.dstu2.resource.Bundle bundle = newXmlParser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, vs); for (Entry nextEntry : bundle.getEntry()) { ca.uhn.fhir.model.dstu2.resource.ValueSet nextVs = (ca.uhn.fhir.model.dstu2.resource.ValueSet) nextEntry.getResource(); parseValueSet(nextVs); } + } else { + throw new IllegalStateException("Fhir version not supported"); } if (myResourceValueSetFiles != null) { diff --git a/src/changes/changes.xml b/src/changes/changes.xml index ff774d3a3bf..8aea0798ab0 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -18,6 +18,10 @@ being used in Bundle.entry.request.url as a part of the conditional URL within transactions. + + Schematron validator now applies invariants to resources within a Bundle, not + just to the outer Bundle resource itself +