From 3fb75aa61ad29d9f3876a1c30c912627486147af Mon Sep 17 00:00:00 2001 From: James Date: Mon, 31 Jul 2017 15:21:30 -0400 Subject: [PATCH] More work on cleanup --- .../ca/uhn/fhir/rest/annotation/Create.java | 4 +- .../fhir/rest/gclient/TokenClientParam.java | 140 +- .../uhn/fhir/rest/gclient/TokenCriterion.java | 19 + .../ca/uhn/fhir/rest/param/ParameterUtil.java | 29 +- .../rest/client/method/CountParameter.java | 9 +- .../method/TransactionMethodBinding.java | 8 +- hapi-fhir-jacoco/pom.xml | 18 +- .../rest/server/method/CountParameter.java | 7 +- .../uhn/fhir/rest/server/CustomTypeTest.java | 13 +- .../fhir/rest/client/BinaryClientTest.java | 2 +- .../uhn/fhir/rest/client/ClientDstu1Test.java | 1440 ----------------- .../rest/client/ClientIntegrationTest.java | 21 +- .../ca/uhn/fhir/rest/client/ClientR4Test.java | 1262 +++++++++++++++ .../ClientServerValidationDstu1Test.java | 22 +- .../rest/client/ExceptionHandlingTest.java | 34 +- .../fhir/rest/client/GenericClientTest.java | 468 +++--- .../uhn/fhir/rest/client/HttpProxyTest.java | 26 +- .../ca/uhn/fhir/rest/client/ITestClient.java | 15 +- .../IncludedResourceStitchingClientTest.java | 171 +- .../ca/uhn/fhir/rest/server/IncludeTest.java | 10 +- 20 files changed, 1740 insertions(+), 1978 deletions(-) delete mode 100644 hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientDstu1Test.java create mode 100644 hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientR4Test.java diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Create.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Create.java index 1cbe41ef8a2..605e6350feb 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Create.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Create.java @@ -23,7 +23,7 @@ package ca.uhn.fhir.rest.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import ca.uhn.fhir.model.api.IResource; +import org.hl7.fhir.instance.model.api.IBaseResource; @Retention(RetentionPolicy.RUNTIME) @@ -44,7 +44,7 @@ public @interface Create { * for client implementations. */ // NB: Read, Search (maybe others) share this annotation, so update the javadocs everywhere - Class type() default IResource.class; + Class type() default IBaseResource.class; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java index 91d7cc84b1f..b05467a2d6d 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java @@ -2,11 +2,10 @@ package ca.uhn.fhir.rest.gclient; import static org.apache.commons.lang3.StringUtils.defaultString; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import java.util.*; import org.apache.commons.lang3.ObjectUtils; +import org.hl7.fhir.instance.model.api.IBaseCoding; import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; @@ -20,7 +19,7 @@ import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; * 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,14 +29,13 @@ import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; * #L% */ - /** * Token parameter type for use in fluent client interfaces */ -public class TokenClientParam extends BaseClientParam implements IParam { +public class TokenClientParam extends BaseClientParam implements IParam { private static final String[] EMPTY_STRING_LIST = new String[0]; - + private String myParamName; public TokenClientParam(String theParamName) { @@ -51,6 +49,21 @@ public class TokenClientParam extends BaseClientParam implements IParam { return new TokenCriterion(getParamName(), null, theCode); } + @Override + public ICriterion codes(Collection theCodes) { + return new TokenCriterion(getParamName(), theCodes); + } + + @Override + public ICriterion codes(String... theCodes) { + return new TokenCriterion(getParamName(), convertToList(theCodes)); + } + + private List convertToList(String[] theValues) { + String[] values = ObjectUtils.defaultIfNull(theValues, EMPTY_STRING_LIST); + return Arrays.asList(values); + } + @Override public ICriterion identifier(BaseIdentifierDt theIdentifier) { return new TokenCriterion(getParamName(), theIdentifier.getSystemElement().getValueAsString(), theIdentifier.getValueElement().getValue()); @@ -81,33 +94,21 @@ public class TokenClientParam extends BaseClientParam implements IParam { return new TokenCriterion(getParamName(), defaultString(theSystem), theCode); } + @Override + public ICriterion systemAndValues(String theSystem, Collection theValues) { + return new TokenCriterion(getParamName(), defaultString(theSystem), theValues); + } + @Override public ICriterion systemAndValues(String theSystem, String... theValues) { return new TokenCriterion(getParamName(), defaultString(theSystem), convertToList(theValues)); } @Override - public ICriterion codes(String... theCodes) { - return new TokenCriterion(getParamName(), convertToList(theCodes)); + public ICriterion codings(IBaseCoding... theCodings) { + return new TokenCriterion(getParamName(), theCodings); } - - @Override - public ICriterion codes(Collection theCodes) { - return new TokenCriterion(getParamName(), theCodes); - } - - - - private List convertToList(String[] theValues) { - String[] values = ObjectUtils.defaultIfNull(theValues, EMPTY_STRING_LIST); - return Arrays.asList(values); - } - - @Override - public ICriterion systemAndValues(String theSystem, Collection theValues) { - return new TokenCriterion(getParamName(), defaultString(theSystem), theValues); - } -}; + }; } @Override @@ -124,7 +125,7 @@ public class TokenClientParam extends BaseClientParam implements IParam { *

*/ public ICriterion hasSystemWithAnyCode(String theSystem) { - return new TokenCriterion(getParamName(), theSystem, (String)null); + return new TokenCriterion(getParamName(), theSystem, (String) null); } public interface IMatches { @@ -132,28 +133,52 @@ public class TokenClientParam extends BaseClientParam implements IParam { * Creates a search criterion that matches against the given code, with no code system specified * * @param theIdentifier - * The identifier + * The identifier * @return A criterion */ ICriterion code(String theIdentifier); - /** - * Creates a search criterion that matches a given system with a collection of possible + * Creates a search criterion that matches a given system with a collection of possible * codes (this will be used to form a comma-separated OR query) with any system value. - * The URL form of this method will create a parameter like + * The URL form of this method will create a parameter like * parameter=code1,code2 * - * @param theCodes The codes + * @param theCodes + * The codes */ ICriterion codes(Collection theCodes); + /** + * Creates a search criterion that matches a given system with a collection of possible + * codes (this will be used to form a comma-separated OR query) with any system value. + * The URL form of this method will create a parameter like + * parameter=code1,code2 + * + * @param theCodes + * The codes + */ + ICriterion codes(String... theCodes); + + /** + * Creates a search criterion that matches a given system with a collection of possible + * codes (this will be used to form a comma-separated OR query) with the given + * Coding.system and Coding.value values. + *

+ * The URL form of this method will create a parameter like + * parameter=system1|code1,system2|code2 + *

+ * + * @param theCodings + * The codings + */ + ICriterion codings(IBaseCoding... theCodings); /** * Creates a search criterion that matches against the given identifier (system and code if both are present, or whatever is present) * * @param theIdentifier - * The identifier + * The identifier * @return A criterion */ ICriterion identifier(BaseIdentifierDt theIdentifier); @@ -162,7 +187,7 @@ public class TokenClientParam extends BaseClientParam implements IParam { * Creates a search criterion that matches against the given identifier, with no system specified * * @param theIdentifier - * The identifier + * The identifier * @return A criterion */ ICriterion identifier(String theIdentifier); @@ -172,7 +197,7 @@ public class TokenClientParam extends BaseClientParam implements IParam { * In the query URL that is generated, identifiers will be joined with a ',' to create an OR query. * * @param theIdentifiers - * The identifier + * The identifier * @return A criterion */ ICriterion identifiers(BaseIdentifierDt... theIdentifiers); @@ -182,18 +207,18 @@ public class TokenClientParam extends BaseClientParam implements IParam { * In the query URL that is generated, identifiers will be joined with a ',' to create an OR query. * * @param theIdentifiers - * The identifier + * The identifier * @return A criterion */ ICriterion identifiers(List theIdentifiers); - + /** * Creates a search criterion that matches against the given code system and code * * @param theSystem - * The code system (should be a URI) + * The code system (should be a URI) * @param theCode - * The code + * The code * @return A criterion */ ICriterion systemAndCode(String theSystem, String theCode); @@ -202,41 +227,34 @@ public class TokenClientParam extends BaseClientParam implements IParam { * Creates a search criterion that matches against the given system and identifier * * @param theSystem - * The code system (should be a URI) + * The code system (should be a URI) * @param theIdentifier - * The identifier + * The identifier * @return A criterion */ ICriterion systemAndIdentifier(String theSystem, String theIdentifier); /** - * Creates a search criterion that matches a given system with a collection of possible + * Creates a search criterion that matches a given system with a collection of possible * values (this will be used to form a comma-separated OR query) * - * @param theSystem The system, which will be used with each value - * @param theValues The values - */ - ICriterion systemAndValues(String theSystem, String... theValues); - - /** - * Creates a search criterion that matches a given system with a collection of possible - * values (this will be used to form a comma-separated OR query) - * - * @param theSystem The system, which will be used with each value - * @param theValues The values + * @param theSystem + * The system, which will be used with each value + * @param theValues + * The values */ public ICriterion systemAndValues(String theSystem, Collection theValues); - /** - * Creates a search criterion that matches a given system with a collection of possible - * codes (this will be used to form a comma-separated OR query) with any system value. - * The URL form of this method will create a parameter like - * parameter=code1,code2 + * Creates a search criterion that matches a given system with a collection of possible + * values (this will be used to form a comma-separated OR query) * - * @param theCodes The codes + * @param theSystem + * The system, which will be used with each value + * @param theValues + * The values */ - ICriterion codes(String...theCodes); + ICriterion systemAndValues(String theSystem, String... theValues); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenCriterion.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenCriterion.java index 66ff0668534..e7b7f308d52 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenCriterion.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenCriterion.java @@ -1,5 +1,6 @@ package ca.uhn.fhir.rest.gclient; +import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.util.Collection; @@ -27,6 +28,7 @@ import java.util.Collection; import java.util.List; import org.apache.commons.lang3.StringUtils; +import org.hl7.fhir.instance.model.api.IBaseCoding; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; @@ -89,6 +91,23 @@ class TokenCriterion implements ICriterion, ICriterionInternal this(theParamName, null, theCodes); } + public TokenCriterion(String theParamName, IBaseCoding... theCodings) { + myName=theParamName; + StringBuilder b = new StringBuilder(); + if (theCodings != null) { + for (IBaseCoding next : theCodings) { + if (isBlank(next.getSystem()) && isBlank(next.getCode())) { + continue; + } + if (b.length() > 0) { + b.append(','); + } + b.append(toValue(next.getSystem(), next.getCode())); + } + } + myValue = b.toString(); + } + @Override public String getParameterValue(FhirContext theContext) { return myValue; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java index 36083c33872..4573967ec51 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java @@ -26,6 +26,7 @@ import java.lang.reflect.Method; import java.util.*; import org.hl7.fhir.instance.model.api.IIdType; +import org.hl7.fhir.instance.model.api.IPrimitiveType; import ca.uhn.fhir.context.*; import ca.uhn.fhir.model.api.*; @@ -39,19 +40,10 @@ import ca.uhn.fhir.util.UrlUtil; public class ParameterUtil { - private static final Set> BINDABLE_INTEGER_TYPES; private static final String LABEL = "label=\""; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ParameterUtil.class); - private static final String SCHEME = "scheme=\""; - static { - HashSet> intTypes = new HashSet>(); - intTypes.add(IntegerDt.class); - intTypes.add(Integer.class); - BINDABLE_INTEGER_TYPES = Collections.unmodifiableSet(intTypes); - - } @SuppressWarnings("unchecked") public static T convertIdToType(IIdType value, Class theIdParamType) { @@ -213,23 +205,20 @@ public class ParameterUtil { } public static Object fromInteger(Class theType, IntegerDt theArgument) { - if (theType.equals(IntegerDt.class)) { - if (theArgument == null) { - return null; - } - return theArgument; - } if (theType.equals(Integer.class)) { if (theArgument == null) { return null; } return theArgument.getValue(); } - throw new IllegalArgumentException("Invalid Integer type:" + theType); + IPrimitiveType retVal = (IPrimitiveType) ReflectionUtil.newInstance(theType); + retVal.setValueAsString(theArgument.getValueAsString()); + return retVal; } - public static Set> getBindableIntegerTypes() { - return BINDABLE_INTEGER_TYPES; + public static boolean isBindableIntegerType(Class theClass) { + return Integer.class.isAssignableFrom(theClass) + || IPrimitiveType.class.isAssignableFrom(theClass); } public static int nonEscapedIndexOf(String theString, char theCharacter) { @@ -422,6 +411,10 @@ public class ParameterUtil { if (theArgument instanceof Integer) { return new IntegerDt((Integer) theArgument); } + if (theArgument instanceof IPrimitiveType) { + IPrimitiveType pt = (IPrimitiveType)theArgument; + return new IntegerDt(pt.getValueAsString()); + } return null; } diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/CountParameter.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/CountParameter.java index c26ae20a62d..4f2aab2bdb1 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/CountParameter.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/CountParameter.java @@ -31,6 +31,7 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.primitive.IntegerDt; +import ca.uhn.fhir.rest.annotation.Count; import ca.uhn.fhir.rest.annotation.Since; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.param.ParameterUtil; @@ -52,12 +53,12 @@ public class CountParameter implements IParameter { @Override public void initializeTypes(Method theMethod, Class> theOuterCollectionType, Class> theInnerCollectionType, Class theParameterType) { if (theOuterCollectionType != null) { - throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @" + Since.class.getName() + throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @" + Count.class.getName() + " but can not be of collection type"); } - if (!ParameterUtil.getBindableIntegerTypes().contains(theParameterType)) { - throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @" + Since.class.getName() - + " but type '" + theParameterType + "' is an invalid type, must be one of: " + ParameterUtil.getBindableIntegerTypes()); + if (!ParameterUtil.isBindableIntegerType(theParameterType)) { + throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @" + Count.class.getName() + + " but type '" + theParameterType + "' is an invalid type, must be Integer or IntegerType"); } } diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionMethodBinding.java index 890f11f9f8c..ba4476096a9 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionMethodBinding.java @@ -59,8 +59,14 @@ public class TransactionMethodBinding extends BaseResourceReturningMethodBinding @Override public BaseHttpClientInvocation invokeClient(Object[] theArgs) throws InternalErrorException { FhirContext context = getContext(); + Object arg = theArgs[myTransactionParamIndex]; + + if (arg instanceof IBaseBundle) { + return createTransactionInvocation((IBaseBundle) arg, context); + } + @SuppressWarnings("unchecked") - List resources = (List) theArgs[myTransactionParamIndex]; + List resources = (List) arg; return createTransactionInvocation(resources, context); } diff --git a/hapi-fhir-jacoco/pom.xml b/hapi-fhir-jacoco/pom.xml index 6597a529425..a6754817541 100644 --- a/hapi-fhir-jacoco/pom.xml +++ b/hapi-fhir-jacoco/pom.xml @@ -139,11 +139,6 @@ jetty-util test - - xmlunit - xmlunit - test - net.sf.json-lib @@ -290,6 +285,19 @@ + + post-integration-test + install + + report + + + ${project.build.directory}/jacoco.exec + ${project.reporting.outputDirectory}/jacoco-report + + + + diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/CountParameter.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/CountParameter.java index d7bb4e5f644..4cf24ed1095 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/CountParameter.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/CountParameter.java @@ -28,6 +28,7 @@ import org.apache.commons.lang3.StringUtils; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.model.primitive.IntegerDt; import ca.uhn.fhir.parser.DataFormatException; +import ca.uhn.fhir.rest.annotation.Count; import ca.uhn.fhir.rest.annotation.Since; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.server.RequestDetails; @@ -60,10 +61,10 @@ public class CountParameter implements IParameter { @Override public void initializeTypes(Method theMethod, Class> theOuterCollectionType, Class> theInnerCollectionType, Class theParameterType) { if (theOuterCollectionType != null) { - throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" +theMethod.getDeclaringClass().getCanonicalName()+ "' is annotated with @" + Since.class.getName() + " but can not be of collection type"); + throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" +theMethod.getDeclaringClass().getCanonicalName()+ "' is annotated with @" + Count.class.getName() + " but can not be of collection type"); } - if (!ParameterUtil.getBindableIntegerTypes().contains(theParameterType)) { - throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" +theMethod.getDeclaringClass().getCanonicalName()+ "' is annotated with @" + Since.class.getName() + " but type '" + theParameterType + "' is an invalid type, must be one of: " + ParameterUtil.getBindableIntegerTypes()); + if (!ParameterUtil.isBindableIntegerType(theParameterType)) { + throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" +theMethod.getDeclaringClass().getCanonicalName()+ "' is annotated with @" + Count.class.getName() + " but type '" + theParameterType + "' is an invalid type, must be one of Integer or IntegerType"); } myType = theParameterType; } diff --git a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/CustomTypeTest.java b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/CustomTypeTest.java index 68857c65f36..517d8d4959c 100644 --- a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/CustomTypeTest.java +++ b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/CustomTypeTest.java @@ -15,19 +15,15 @@ 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.context.api.AddProfileTagEnum; import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.BundleEntry; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.Tag; -import ca.uhn.fhir.model.api.annotation.Child; -import ca.uhn.fhir.model.api.annotation.Description; -import ca.uhn.fhir.model.api.annotation.Extension; -import ca.uhn.fhir.model.api.annotation.ResourceDef; +import ca.uhn.fhir.model.api.annotation.*; import ca.uhn.fhir.model.dstu.resource.Patient; import ca.uhn.fhir.model.dstu.resource.Profile; import ca.uhn.fhir.model.primitive.StringDt; @@ -38,9 +34,6 @@ import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.util.PortUtil; import ca.uhn.fhir.util.TestUtil; -/** - * Created by dsotnikov on 2/25/2014. - */ public class CustomTypeTest { private static CloseableHttpClient ourClient; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/BinaryClientTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/BinaryClientTest.java index fe118aed630..2df30ecdfbf 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/BinaryClientTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/BinaryClientTest.java @@ -15,12 +15,12 @@ import org.apache.http.client.methods.*; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicStatusLine; import org.hl7.fhir.r4.model.Binary; +import org.hl7.fhir.r4.model.IdType; import org.junit.*; import org.mockito.ArgumentCaptor; import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.primitive.IdType; import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.MethodOutcome; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientDstu1Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientDstu1Test.java deleted file mode 100644 index 3af5ada826e..00000000000 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientDstu1Test.java +++ /dev/null @@ -1,1440 +0,0 @@ -package ca.uhn.fhir.rest.client; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.either; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.InputStream; -import java.io.StringReader; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.input.ReaderInputStream; -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicStatusLine; -import org.hamcrest.core.StringContains; -import org.hamcrest.core.StringEndsWith; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.*; -import ca.uhn.fhir.model.api.annotation.ResourceDef; -import ca.uhn.fhir.model.base.resource.BaseConformance; -import ca.uhn.fhir.model.dstu.composite.CodingDt; -import ca.uhn.fhir.model.dstu.resource.Observation; -import ca.uhn.fhir.model.dstu.resource.OperationOutcome; -import ca.uhn.fhir.model.dstu.resource.Organization; -import ca.uhn.fhir.model.dstu.resource.Patient; -import ca.uhn.fhir.model.dstu.valueset.QuantityCompararatorEnum; -import ca.uhn.fhir.model.primitive.IdType; -import ca.uhn.fhir.model.primitive.InstantDt; -import ca.uhn.fhir.model.primitive.IntegerDt; -import ca.uhn.fhir.rest.annotation.Elements; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.IncludeParam; -import ca.uhn.fhir.rest.annotation.RequiredParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.api.SummaryEnum; -import ca.uhn.fhir.rest.client.apache.ApacheHttpRequest; -import ca.uhn.fhir.rest.client.api.IBasicClient; -import ca.uhn.fhir.rest.client.interceptor.CapturingInterceptor; -import ca.uhn.fhir.rest.param.*; -import ca.uhn.fhir.rest.server.Constants; -import ca.uhn.fhir.rest.server.EncodingEnum; -import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; -import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; -import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; -import ca.uhn.fhir.util.TestUtil; -import ca.uhn.fhir.util.UrlUtil; - -public class ClientDstu1Test { - - private FhirContext ourCtx; - private HttpClient myHttpClient; - private HttpResponse myHttpResponse; - - @Before - public void before() { - ourCtx = FhirContext.forDstu1(); - - myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs()); - ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient); - ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); - - myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); - } - - // atom-document-large.xml - - private String getPatientFeedWithOneResult() { - String msg = "\n" + - "\n" + - "<id>d039f91a-cc3c-4013-988e-af4d8d0614bd</id>\n" + - "<os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">1</os:totalResults>\n" + - "<author>\n" + - "<name>ca.uhn.fhir.rest.server.DummyRestfulServer</name>\n" + - "</author>\n" + - "<entry>\n" + - "<content type=\"text/xml\">" - + "<Patient xmlns=\"http://hl7.org/fhir\">" - + "<text><status value=\"generated\" /><div xmlns=\"http://www.w3.org/1999/xhtml\">John Cardinal: 444333333 </div></text>" - + "<identifier><label value=\"SSN\" /><system value=\"http://orionhealth.com/mrn\" /><value value=\"PRP1660\" /></identifier>" - + "<name><use value=\"official\" /><family value=\"Cardinal\" /><given value=\"John\" /></name>" - + "<name><family value=\"Kramer\" /><given value=\"Doe\" /></name>" - + "<telecom><system value=\"phone\" /><value value=\"555-555-2004\" /><use value=\"work\" /></telecom>" - + "<gender><coding><system value=\"http://hl7.org/fhir/v3/AdministrativeGender\" /><code value=\"M\" /></coding></gender>" - + "<address><use value=\"home\" /><line value=\"2222 Home Street\" /></address><active value=\"true\" />" - + "</Patient>" - + "</content>\n" - + " </entry>\n" - + "</feed>"; - return msg; - } - - @Test - public void testCreate() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - CapturingInterceptor interceptor = new CapturingInterceptor(); - client.registerInterceptor(interceptor); - - MethodOutcome response = client.createPatient(patient); - - assertEquals(((ApacheHttpRequest) interceptor.getLastRequest()).getApacheRequest().getURI().toASCIIString(), "http://foo/Patient"); - - assertEquals(HttpPost.class, capt.getValue().getClass()); - HttpPost post = (HttpPost) capt.getValue(); - assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); - assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(0).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - assertEquals("200", response.getId().getVersionIdPart()); - } - - @Test - public void testCreateBad() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 400, "foobar")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader("foobar"), Charset.forName("UTF-8"))); - - try { - ourCtx.newRestfulClient(ITestClient.class, "http://foo").createPatient(patient); - fail(); - } catch (InvalidRequestException e) { - assertThat(e.getMessage(), StringContains.containsString("foobar")); - } - } - - /** - * Some servers (older ones?) return the resourcde you created instead of an OperationOutcome. We just need to ignore - * it. - */ - @Test - public void testCreateWithResourceResponse() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "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(ourCtx.newXmlParser().encodeResourceToString(patient)), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - MethodOutcome response = client.createPatient(patient); - - assertEquals(HttpPost.class, capt.getValue().getClass()); - HttpPost post = (HttpPost) capt.getValue(); - assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); - assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); - assertEquals("200", response.getId().getVersionIdPart()); - } - - @Test - public void testCreateWithTagList() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - TagList tagList = new TagList(); - tagList.add(new Tag((String) null, "Dog", "DogLabel")); - tagList.add(new Tag("http://cats", "Cat", "CatLabel")); - patient.getResourceMetadata().put(ResourceMetadataKeyEnum.TAG_LIST, tagList); - - MethodOutcome response = client.createPatient(patient); - - assertEquals(HttpPost.class, capt.getValue().getClass()); - HttpPost post = (HttpPost) capt.getValue(); - assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); - assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); - assertEquals("200", response.getId().getVersionIdPart()); - - Header[] headers = post.getHeaders("Category"); - assertEquals(2, headers.length); - assertEquals("Dog; label=\"DogLabel\"", headers[0].getValue()); - assertEquals("Cat; label=\"CatLabel\"; scheme=\"http://cats\"", headers[1].getValue()); - - } - - @Test - public void testDelete() throws Exception { - - OperationOutcome oo = new OperationOutcome(); - oo.addIssue().setDetails("Hello"); - String resp = ourCtx.newXmlParser().encodeResourceToString(oo); - - ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "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(resp), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - MethodOutcome response = client.deletePatient(new IdType("1234")); - - assertEquals(HttpDelete.class, capt.getValue().getClass()); - assertEquals("http://foo/Patient/1234", capt.getValue().getURI().toString()); - assertEquals("Hello", ((OperationOutcome) response.getOperationOutcome()).getIssueFirstRep().getDetailsElement().getValue()); - } - - @Test - public void testDeleteNoResponse() throws Exception { - - ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 204, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.deleteDiagnosticReport(new IdType("1234")); - - assertEquals(HttpDelete.class, capt.getValue().getClass()); - assertEquals("http://foo/DiagnosticReport/1234", capt.getValue().getURI().toString()); - } - - @Test - public void testGetConformance() throws Exception { - - String msg = IOUtils.toString(ClientDstu1Test.class.getResourceAsStream("/example-metadata.xml")); - - ArgumentCaptor<HttpUriRequest> 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"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - BaseConformance response = client.getServerConformanceStatement(); - - assertEquals("http://foo/metadata", capt.getValue().getURI().toString()); - assertEquals("Health Intersections", response.getPublisherElement().getValue()); - - } - - @SuppressWarnings("deprecation") - @Test - public void testHistoryResourceInstance() throws Exception { - - InstantDt date1 = new InstantDt(new Date(20000L)); - InstantDt date2 = new InstantDt(new Date(10000L)); - InstantDt date3 = new InstantDt(new Date(30000L)); - InstantDt date4 = new InstantDt(new Date(10000L)); - - //@formatter:off - String msg = "<feed xmlns=\"http://www.w3.org/2005/Atom\"><title/><id>6c1d93be-027f-468d-9d47-f826cd15cf42</id>" - + "<link rel=\"self\" href=\"http://localhost:51698/Patient/222/_history\"/>" - + "<link rel=\"fhir-base\" href=\"http://localhost:51698\"/><os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults>" - + "<author><name>ca.uhn.fhir.rest.method.HistoryMethodBinding</name></author>" - + "<entry><title>Patient 222222" - + ""+date1.getValueAsString()+"" - + ""+date2.getValueAsString()+"" - + "" - + "" - + "" - + "Patient 222222" - + ""+date3.getValueAsString()+"" - + ""+date4.getValueAsString()+"" - + ""; - //@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_ATOM_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - Bundle response = client.getHistoryPatientInstance(new IdType("111")); - - assertEquals("http://foo/Patient/111/_history", capt.getValue().getURI().toString()); - - assertEquals(2, response.getEntries().size()); - - // Older resource - { - BundleEntry olderEntry = response.getEntries().get(0); - assertEquals("222", olderEntry.getId().getValue()); - assertThat(olderEntry.getLinkSelf().getValue(), StringEndsWith.endsWith("/Patient/222/_history/1")); - InstantDt pubExpected = new InstantDt(new Date(10000L)); - InstantDt pubActualRes = (InstantDt) olderEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.PUBLISHED); - InstantDt pubActualBundle = olderEntry.getPublished(); - assertEquals(pubExpected.getValueAsString(), pubActualRes.getValueAsString()); - assertEquals(pubExpected.getValueAsString(), pubActualBundle.getValueAsString()); - InstantDt updExpected = new InstantDt(new Date(20000L)); - InstantDt updActualRes = (InstantDt) olderEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - InstantDt updActualBundle = olderEntry.getUpdated(); - assertEquals(updExpected.getValueAsString(), updActualRes.getValueAsString()); - assertEquals(updExpected.getValueAsString(), updActualBundle.getValueAsString()); - } - // Newer resource - { - BundleEntry newerEntry = response.getEntries().get(1); - assertEquals("222", newerEntry.getId().getValue()); - assertThat(newerEntry.getLinkSelf().getValue(), StringEndsWith.endsWith("/Patient/222/_history/2")); - InstantDt pubExpected = new InstantDt(new Date(10000L)); - InstantDt pubActualRes = (InstantDt) newerEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.PUBLISHED); - InstantDt pubActualBundle = newerEntry.getPublished(); - assertEquals(pubExpected.getValueAsString(), pubActualRes.getValueAsString()); - assertEquals(pubExpected.getValueAsString(), pubActualBundle.getValueAsString()); - InstantDt updExpected = new InstantDt(new Date(30000L)); - InstantDt updActualRes = (InstantDt) newerEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - InstantDt updActualBundle = newerEntry.getUpdated(); - assertEquals(updExpected.getValueAsString(), updActualRes.getValueAsString()); - assertEquals(updExpected.getValueAsString(), updActualBundle.getValueAsString()); - } - } - - @SuppressWarnings("deprecation") - @Test - public void testHistoryResourceType() throws Exception { - - InstantDt date1 = new InstantDt(new Date(20000L)); - InstantDt date2 = new InstantDt(new Date(10000L)); - InstantDt date3 = new InstantDt(new Date(30000L)); - InstantDt date4 = new InstantDt(new Date(10000L)); - - //@formatter:off - String msg = "<id>6c1d93be-027f-468d-9d47-f826cd15cf42</id>" - + "<link rel=\"self\" href=\"http://localhost:51698/Patient/222/_history\"/>" - + "<link rel=\"fhir-base\" href=\"http://localhost:51698\"/><os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults>" - + "<author><name>ca.uhn.fhir.rest.method.HistoryMethodBinding</name></author>" - + "<entry><title>Patient 222222" - + ""+date1.getValueAsString()+"" - + ""+date2.getValueAsString()+"" - + "" - + "" - + "" - + "Patient 222222" - + ""+date3.getValueAsString()+"" - + ""+date4.getValueAsString()+"" - + ""; - //@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_ATOM_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - Bundle response = client.getHistoryPatientType(); - - assertEquals("http://foo/Patient/_history", capt.getValue().getURI().toString()); - - assertEquals(2, response.getEntries().size()); - - // Older resource - { - BundleEntry olderEntry = response.getEntries().get(0); - assertEquals("222", olderEntry.getId().getValue()); - assertThat(olderEntry.getLinkSelf().getValue(), StringEndsWith.endsWith("/Patient/222/_history/1")); - InstantDt pubExpected = new InstantDt(new Date(10000L)); - InstantDt pubActualRes = (InstantDt) olderEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.PUBLISHED); - InstantDt pubActualBundle = olderEntry.getPublished(); - assertEquals(pubExpected.getValueAsString(), pubActualRes.getValueAsString()); - assertEquals(pubExpected.getValueAsString(), pubActualBundle.getValueAsString()); - InstantDt updExpected = new InstantDt(new Date(20000L)); - InstantDt updActualRes = (InstantDt) olderEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - InstantDt updActualBundle = olderEntry.getUpdated(); - assertEquals(updExpected.getValueAsString(), updActualRes.getValueAsString()); - assertEquals(updExpected.getValueAsString(), updActualBundle.getValueAsString()); - } - // Newer resource - { - BundleEntry newerEntry = response.getEntries().get(1); - assertEquals("222", newerEntry.getId().getValue()); - assertThat(newerEntry.getLinkSelf().getValue(), StringEndsWith.endsWith("/Patient/222/_history/2")); - InstantDt pubExpected = new InstantDt(new Date(10000L)); - InstantDt pubActualRes = (InstantDt) newerEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.PUBLISHED); - InstantDt pubActualBundle = newerEntry.getPublished(); - assertEquals(pubExpected.getValueAsString(), pubActualRes.getValueAsString()); - assertEquals(pubExpected.getValueAsString(), pubActualBundle.getValueAsString()); - InstantDt updExpected = new InstantDt(new Date(30000L)); - InstantDt updActualRes = (InstantDt) newerEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - InstantDt updActualBundle = newerEntry.getUpdated(); - assertEquals(updExpected.getValueAsString(), updActualRes.getValueAsString()); - assertEquals(updExpected.getValueAsString(), updActualBundle.getValueAsString()); - } - } - - @SuppressWarnings("deprecation") - @Test - public void testHistoryServer() throws Exception { - InstantDt date1 = new InstantDt(new Date(20000L)); - InstantDt date2 = new InstantDt(new Date(10000L)); - InstantDt date3 = new InstantDt(new Date(30000L)); - InstantDt date4 = new InstantDt(new Date(10000L)); - - //@formatter:off - String msg = "<id>6c1d93be-027f-468d-9d47-f826cd15cf42</id>" - + "<link rel=\"self\" href=\"http://localhost:51698/Patient/222/_history\"/>" - + "<link rel=\"fhir-base\" href=\"http://localhost:51698\"/><os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults>" - + "<author><name>ca.uhn.fhir.rest.method.HistoryMethodBinding</name></author>" - + "<entry><title>Patient 222222" - + ""+date1.getValueAsString()+"" - + ""+date2.getValueAsString()+"" - + "" - + "" - + "" - + "Patient 222222" - + ""+date3.getValueAsString()+"" - + ""+date4.getValueAsString()+"" - + ""; - //@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_ATOM_XML + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - Bundle response = client.getHistoryServer(); - - assertEquals("http://foo/_history", capt.getValue().getURI().toString()); - - assertEquals(2, response.getEntries().size()); - - // Older resource - { - BundleEntry olderEntry = response.getEntries().get(0); - assertEquals("222", olderEntry.getId().getValue()); - assertThat(olderEntry.getLinkSelf().getValue(), StringEndsWith.endsWith("/Patient/222/_history/1")); - InstantDt pubExpected = new InstantDt(new Date(10000L)); - InstantDt pubActualRes = (InstantDt) olderEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.PUBLISHED); - InstantDt pubActualBundle = olderEntry.getPublished(); - assertEquals(pubExpected.getValueAsString(), pubActualRes.getValueAsString()); - assertEquals(pubExpected.getValueAsString(), pubActualBundle.getValueAsString()); - InstantDt updExpected = new InstantDt(new Date(20000L)); - InstantDt updActualRes = (InstantDt) olderEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - InstantDt updActualBundle = olderEntry.getUpdated(); - assertEquals(updExpected.getValueAsString(), updActualRes.getValueAsString()); - assertEquals(updExpected.getValueAsString(), updActualBundle.getValueAsString()); - } - // Newer resource - { - BundleEntry newerEntry = response.getEntries().get(1); - assertEquals("222", newerEntry.getId().getValue()); - assertThat(newerEntry.getLinkSelf().getValue(), StringEndsWith.endsWith("/Patient/222/_history/2")); - InstantDt pubExpected = new InstantDt(new Date(10000L)); - InstantDt pubActualRes = (InstantDt) newerEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.PUBLISHED); - InstantDt pubActualBundle = newerEntry.getPublished(); - assertEquals(pubExpected.getValueAsString(), pubActualRes.getValueAsString()); - assertEquals(pubExpected.getValueAsString(), pubActualBundle.getValueAsString()); - InstantDt updExpected = new InstantDt(new Date(30000L)); - InstantDt updActualRes = (InstantDt) newerEntry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - InstantDt updActualBundle = newerEntry.getUpdated(); - assertEquals(updExpected.getValueAsString(), updActualRes.getValueAsString()); - assertEquals(updExpected.getValueAsString(), updActualBundle.getValueAsString()); - } - } - - @Test - public void testHistoryWithParams() throws Exception { - - //@formatter:off - final String msg = "<id>6c1d93be-027f-468d-9d47-f826cd15cf42</id><link rel=\"self\" href=\"http://localhost:51698/Patient/222/_history\"/><link rel=\"fhir-base\" href=\"http://localhost:51698\"/><os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults><author><name>ca.uhn.fhir.rest.method.HistoryMethodBinding</name></author><entry><title>Patient 2222221969-12-31T19:00:20.000-05:001969-12-31T19:00:10.000-05:00Patient 2222221969-12-31T19:00:30.000-05:001969-12-31T19:00:10.000-05:00"; - //@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_ATOM_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")); - } - }); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - - // ensures the local timezone - String expectedDateString = new InstantDt(new InstantDt("2012-01-02T12:01:02").getValue()).getValueAsString(); - expectedDateString = expectedDateString.replace(":", "%3A").replace("+", "%2B"); - - client.getHistoryPatientInstance(new IdType("111"), new InstantDt("2012-01-02T12:01:02"), new IntegerDt(12)); - assertThat(capt.getAllValues().get(0).getURI().toString(), containsString("http://foo/Patient/111/_history?")); - assertThat(capt.getAllValues().get(0).getURI().toString(), containsString("_since=" + expectedDateString.replaceAll("\\..*", ""))); - assertThat(capt.getAllValues().get(0).getURI().toString(), containsString("_count=12")); - - client.getHistoryPatientInstance(new IdType("111"), new InstantDt("2012-01-02T12:01:02").getValue(), new IntegerDt(12).getValue()); - assertThat(capt.getAllValues().get(1).getURI().toString(), containsString("http://foo/Patient/111/_history?")); - assertThat(capt.getAllValues().get(1).getURI().toString(), containsString("_since=" + expectedDateString)); - assertThat(capt.getAllValues().get(1).getURI().toString(), containsString("_count=12")); - - client.getHistoryPatientInstance(new IdType("111"), null, new IntegerDt(12)); - assertEquals("http://foo/Patient/111/_history?_count=12", capt.getAllValues().get(2).getURI().toString()); - - client.getHistoryPatientInstance(new IdType("111"), new InstantDt("2012-01-02T00:01:02"), null); - assertEquals("http://foo/Patient/111/_history?_since=2012-01-02T00%3A01%3A02", capt.getAllValues().get(3).getURI().toString()); - - client.getHistoryPatientInstance(new IdType("111"), new InstantDt(), new IntegerDt(12)); - assertEquals("http://foo/Patient/111/_history?_count=12", capt.getAllValues().get(4).getURI().toString()); - - client.getHistoryPatientInstance(new IdType("111"), new InstantDt("2012-01-02T00:01:02"), new IntegerDt()); - assertEquals("http://foo/Patient/111/_history?_since=2012-01-02T00%3A01%3A02", capt.getAllValues().get(5).getURI().toString()); - - } - - @Test - public void testNonAnnotatedMethodFailsGracefully() { - - // TODO: remove the read annotation and make sure we get a sensible - // error message to tell the user why the method isn't working - FhirContext ctx = ourCtx; - ctx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); - - ClientWithoutAnnotation client = ctx.newRestfulClient(ClientWithoutAnnotation.class, "http://wildfhir.aegis.net/fhir"); - - try { - client.read(new IdType("8")); - fail(); - } catch (UnsupportedOperationException e) { - assertThat(e.getMessage(), containsString("annotation")); - } - - } - - @Test - public void testRead() throws Exception { - - //@formatter:off - String msg = "" - + "
John Cardinal: 444333333
" - + "" - + "" - + "" - + "" - + "" - + "
" - + "
"; - //@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")); - Header[] headers = new Header[] { new BasicHeader(Constants.HEADER_LAST_MODIFIED, "Wed, 15 Nov 1995 04:58:08 GMT"), new BasicHeader(Constants.HEADER_CONTENT_LOCATION, "http://foo.com/Patient/123/_history/2333"), - new BasicHeader(Constants.HEADER_CATEGORY, "http://foo/tagdefinition.html; scheme=\"http://hl7.org/fhir/tag\"; label=\"Some tag\"") }; - - when(myHttpResponse.getAllHeaders()).thenReturn(headers); - 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"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - // Patient response = client.findPatientByMrn(new - // IdentifierDt("urn:foo", "123")); - Patient response = client.getPatientById(new IdType("111")); - - assertEquals("http://foo/Patient/111", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - assertEquals("http://foo.com/Patient/123/_history/2333", response.getId().getValue()); - - InstantDt lm = (InstantDt) response.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - lm.setTimeZoneZulu(true); - assertEquals("1995-11-15T04:58:08.000Z", lm.getValueAsString()); - - TagList tags = ResourceMetadataKeyEnum.TAG_LIST.get(response); - assertNotNull(tags); - assertEquals(1, tags.size()); - assertEquals("http://foo/tagdefinition.html", tags.get(0).getTerm()); - assertEquals("http://hl7.org/fhir/tag", tags.get(0).getScheme()); - assertEquals("Some tag", tags.get(0).getLabel()); - - } - - @Test - public void testResponseContainingOldStyleXmlContentType() throws Exception { - - //@formatter:off - String msg = "" - + "
John Cardinal: 444333333
" - + "" - + "" - + "" - + "" - + "" - + "
" - + "
"; - //@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", "application/fhir+xml; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - // Patient response = client.findPatientByMrn(new - // IdentifierDt("urn:foo", "123")); - Patient response = client.getPatientById(new IdType("111")); - - assertEquals("http://foo/Patient/111", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testReadFailureInternalError() 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), 500, "INTERNAL")); - Header[] headers = new Header[1]; - headers[0] = new BasicHeader(Constants.HEADER_LAST_MODIFIED, "2011-01-02T22:01:02"); - when(myHttpResponse.getAllHeaders()).thenReturn(headers); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT)); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader("Internal Failure"), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - try { - client.getPatientById(new IdType("111")); - fail(); - } catch (InternalErrorException e) { - assertThat(e.getMessage(), containsString("INTERNAL")); - assertThat(e.getResponseBody(), containsString("Internal Failure")); - } - - } - - @Test - public void testReadFailureNoCharset() throws Exception { - - //@formatter:off - String msg = ""; - //@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), 404, "NOT FOUND")); - Header[] headers = new Header[1]; - headers[0] = new BasicHeader(Constants.HEADER_LAST_MODIFIED, "2011-01-02T22:01:02"); - when(myHttpResponse.getAllHeaders()).thenReturn(headers); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML)); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - try { - client.getPatientById(new IdType("111")); - fail(); - } catch (ResourceNotFoundException e) { - // good - } - - } - - @Test - public void testReadNoCharset() throws Exception { - - //@formatter:off - String msg = "" - + "
John Cardinal: 444333333
" - + "" - + "" - + "" - + "" - + "" - + "
" - + "
"; - //@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")); - Header[] headers = new Header[1]; - headers[0] = new BasicHeader(Constants.HEADER_LAST_MODIFIED, "Wed, 15 Nov 1995 04:58:08 GMT"); - when(myHttpResponse.getAllHeaders()).thenReturn(headers); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML)); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - // Patient response = client.findPatientByMrn(new - // IdentifierDt("urn:foo", "123")); - Patient response = client.getPatientById(new IdType("111")); - - assertEquals("http://foo/Patient/111", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - InstantDt lm = (InstantDt) response.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); - lm.setTimeZoneZulu(true); - assertEquals("1995-11-15T04:58:08.000Z", lm.getValueAsString()); - - } - - @Test - public void testSearchByDateRange() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - DateRangeParam param = new DateRangeParam(); - param.setLowerBound(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-01")); - param.setUpperBound(new DateParam(QuantityCompararatorEnum.LESSTHAN_OR_EQUALS, "2021-01-01")); - client.getPatientByDateRange(param); - - assertEquals("http://foo/Patient?dateRange=%3E%3D2011-01-01&dateRange=%3C%3D2021-01-01", capt.getValue().getURI().toString()); - - } - - @Test - public void testSearchByDob() throws Exception { - - String msg = getPatientFeedWithOneResult(); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - - 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"))); - - // httpResponse = new BasicHttpResponse(statusline, catalog, locale) - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - List response = client.getPatientByDob(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.get(0).getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchWithGenericReturnType() throws Exception { - - Bundle bundle = new Bundle(); - - Patient patient = new Patient(); - patient.addIdentifier().setValue("PRP1660"); - bundle.addEntry().setResource(patient); - - Organization org = new Organization(); - org.setName("FOO"); - patient.getManagingOrganization().setResource(org); - - String msg = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(bundle); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - - 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"))); - - // httpResponse = new BasicHttpResponse(statusline, catalog, locale) - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - List response = client.getPatientByDobWithGenericResourceReturnType(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02", capt.getValue().getURI().toString()); - ExtendedPatient patientResp = (ExtendedPatient) response.get(0); - assertEquals("PRP1660", patientResp.getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchWithSummary() throws Exception { - - final String msg = getPatientFeedWithOneResult(); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - - 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")); - } - }); - - // httpResponse = new BasicHttpResponse(statusline, catalog, locale) - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - - ITestClientWithSummary client = ourCtx.newRestfulClient(ITestClientWithSummary.class, "http://foo"); - - int idx = 0; - - client.getPatientWithIncludes((SummaryEnum) null); - assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes(SummaryEnum.COUNT); - assertEquals("http://foo/Patient?_summary=count", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes(SummaryEnum.DATA); - assertEquals("http://foo/Patient?_summary=data", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes(Arrays.asList(SummaryEnum.DATA)); - assertEquals("http://foo/Patient?_summary=data", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes(Arrays.asList(SummaryEnum.COUNT, SummaryEnum.DATA)); - assertThat(capt.getAllValues().get(idx).getURI().toString(), either(equalTo("http://foo/Patient?_summary=data&_summary=count")).or(equalTo("http://foo/Patient?_summary=count&_summary=data"))); - idx++; - - client.getPatientWithIncludes(new ArrayList()); - assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); - idx++; - } - - @Test - public void testSearchWithElements() throws Exception { - - final String msg = getPatientFeedWithOneResult(); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - - 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")); - } - }); - - // httpResponse = new BasicHttpResponse(statusline, catalog, locale) - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - - ITestClientWithElements client = ourCtx.newRestfulClient(ITestClientWithElements.class, "http://foo"); - - int idx = 0; - - client.getPatientWithIncludes((String) null); - assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes((Set) null); - assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes("test"); - assertEquals("http://foo/Patient?_elements=test", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes("test,foo"); - assertEquals("http://foo/Patient?_elements=test%2Cfoo", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - client.getPatientWithIncludes(new HashSet(Arrays.asList("test","foo", ""))); - assertEquals("http://foo/Patient?_elements=test%2Cfoo", capt.getAllValues().get(idx).getURI().toString()); - idx++; - - } - - @Test - public void testSearchByCompartment() throws Exception { - - String msg = getPatientFeedWithOneResult(); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - - 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"))); - - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - List response = client.getPatientByCompartmentAndDob(new IdType("123"), new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - - assertEquals("http://foo/Patient/123/compartmentName?birthdate=%3E%3D2011-01-02", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.get(0).getIdentifier().get(0).getValue().getValue()); - - try { - client.getPatientByCompartmentAndDob(new IdType(""), new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - fail(); - } catch (InvalidRequestException e) { - assertThat(e.toString(), containsString("null or empty for compartment")); - } - - } - - @Test - public void testSearchByQuantity() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - Patient response = client.findPatientQuantity(new QuantityParam(QuantityCompararatorEnum.GREATERTHAN, 123L, "foo", "bar")); - - assertEquals("http://foo/Patient?quantityParam=%3E123%7Cfoo%7Cbar", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchByToken() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - Patient response = client.findPatientByMrn(new TokenParam("urn:foo", "123")); - - assertEquals("http://foo/Patient?identifier=urn%3Afoo%7C123", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchOrList() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - TokenOrListParam identifiers = new TokenOrListParam(); - identifiers.add(new CodingDt("foo", "bar")); - identifiers.add(new CodingDt("baz", "boz")); - client.getPatientMultipleIdentifiers(identifiers); - - assertEquals("http://foo/Patient?ids=foo%7Cbar%2Cbaz%7Cboz", capt.getValue().getURI().toString()); - - } - - @Test - public void testSearchNamedQueryNoParams() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.getPatientNoParams(); - - assertEquals("http://foo/Patient?_query=someQueryNoParams", capt.getValue().getURI().toString()); - - } - - @Test - public void testSearchNamedQueryOneParam() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.getPatientOneParam(new StringParam("BB")); - - assertEquals("http://foo/Patient?_query=someQueryOneParam¶m1=BB", capt.getValue().getURI().toString()); - - } - - @Test - public void testSearchWithCustomType() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClientWithCustomType client = ourCtx.newRestfulClient(ITestClientWithCustomType.class, "http://foo"); - CustomPatient response = client.getPatientByDob(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchWithCustomTypeList() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClientWithCustomTypeList client = ourCtx.newRestfulClient(ITestClientWithCustomTypeList.class, "http://foo"); - List response = client.getPatientByDob(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.get(0).getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchWithFormatAndPrettyPrint() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - // TODO: document this - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.getPatientByDob(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02", capt.getAllValues().get(0).getURI().toString()); - - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - client.setEncoding(EncodingEnum.JSON); // this needs to be actually - // implemented - client.getPatientByDob(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02&_format=json", capt.getAllValues().get(1).getURI().toString()); - - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - client.setPrettyPrint(true); - client.getPatientByDob(new DateParam(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); - assertEquals("http://foo/Patient?birthdate=%3E%3D2011-01-02&_format=json&_pretty=true", capt.getAllValues().get(2).getURI().toString()); - - } - - @Test - public void testSearchWithIncludes() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.getPatientWithIncludes(new StringParam("aaa"), Arrays.asList(new Include[] { new Include("inc1"), new Include("inc2", true), new Include("inc3", true) })); - - assertEquals("http://foo/Patient?withIncludes=aaa&_include=inc1&_include%3Arecurse=inc2&_include%3Arecurse=inc3", capt.getValue().getURI().toString()); - - } - - @Test - public void testSearchWithGlobalSummary() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.setSummary(SummaryEnum.DATA); - client.findPatientByMrn(new TokenParam("sysm", "val")); - - assertEquals("http://foo/Patient?identifier=sysm%7Cval&_summary=data", capt.getValue().getURI().toString()); - - } - - - @Test - public void testSearchWithOptionalParam() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - Bundle response = client.findPatientByName(new StringParam("AAA"), null); - - assertEquals("http://foo/Patient?family=AAA", capt.getValue().getURI().toString()); - Patient resource = (Patient) response.getEntries().get(0).getResource(); - assertEquals("PRP1660", resource.getIdentifier().get(0).getValue().getValue()); - - /* - * Now with a first name - */ - - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - response = client.findPatientByName(new StringParam("AAA"), new StringParam("BBB")); - - assertEquals("http://foo/Patient?family=AAA&given=BBB", capt.getValue().getURI().toString()); - resource = (Patient) response.getEntries().get(0).getResource(); - assertEquals("PRP1660", resource.getIdentifier().get(0).getValue().getValue()); - - } - - @Test - public void testSearchWithEscapedValues() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - StringAndListParam andListParam = new StringAndListParam(); - StringOrListParam orListParam1 = new StringOrListParam().addOr(new StringParam("NE,NE", false)).addOr(new StringParam("NE,NE", false)); - StringOrListParam orListParam2 = new StringOrListParam().addOr(new StringParam("E$E", true)); - StringOrListParam orListParam3 = new StringOrListParam().addOr(new StringParam("NE\\NE", false)); - StringOrListParam orListParam4 = new StringOrListParam().addOr(new StringParam("E|E", true)); - client.findPatient(andListParam.addAnd(orListParam1).addAnd(orListParam2).addAnd(orListParam3).addAnd(orListParam4)); - - assertThat(capt.getValue().getURI().toString(), containsString("%3A")); - assertEquals("http://foo/Patient?param=NE\\,NE,NE\\,NE¶m=NE\\\\NE¶m:exact=E\\$E¶m:exact=E\\|E", UrlUtil.unescape(capt.getValue().getURI().toString())); - - } - - - @Test - public void testSearchByCompositeParam() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - StringParam str = new StringParam("FOO$BAR"); - DateParam date = new DateParam("2001-01-01"); - client.getObservationByNameValueDate(new CompositeParam(str, date)); - - assertEquals("http://foo/Observation?" + Observation.SP_NAME_VALUE_DATE + "=" + URLEncoder.encode("FOO\\$BAR$2001-01-01", "UTF-8"), capt.getValue().getURI().toString()); - - } - - @Test - public void testSearchWithStringIncludes() throws Exception { - - 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()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClientWithStringIncludes client = ourCtx.newRestfulClient(ITestClientWithStringIncludes.class, "http://foo"); - client.getPatientWithIncludes(new StringParam("aaa"), "inc1"); - - assertEquals("http://foo/Patient?withIncludes=aaa&_include=inc1", capt.getValue().getURI().toString()); - - } - - @Test - public void testUpdate() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - MethodOutcome response = client.updatePatient(new IdType("100"), patient); - - assertEquals(HttpPut.class, capt.getValue().getClass()); - HttpPut post = (HttpPut) capt.getValue(); - assertThat(post.getURI().toASCIIString(), StringEndsWith.endsWith("/Patient/100")); - assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString(" capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "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(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Content-Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.updatePatient(new IdType("Patient/100/_history/200"), patient); - - assertEquals(HttpPut.class, capt.getValue().getClass()); - HttpPut post = (HttpPut) capt.getValue(); - assertEquals("http://foo/Patient/100", post.getURI().toASCIIString()); - - Header h = post.getFirstHeader("content-location"); - assertEquals("Patient/100/_history/200", h.getValue()); - - } - - @Test(expected = ResourceVersionConflictException.class) - public void testUpdateWithResourceConflict() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - 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(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_409_CONFLICT, "Conflict")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - client.updatePatient(new IdType("Patient/100/_history/200"), patient); - } - - @Test - public void testUpdateWithVersion() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier("urn:foo", "123"); - - ArgumentCaptor capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - MethodOutcome response = client.updatePatient(new IdType("Patient/100/_history/200"), patient); - - assertEquals(HttpPut.class, capt.getValue().getClass()); - HttpPut post = (HttpPut) capt.getValue(); - assertThat(post.getURI().toASCIIString(), StringEndsWith.endsWith("/Patient/100")); - assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString(" capt = ArgumentCaptor.forClass(HttpUriRequest.class); - when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); - when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); - when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); - when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - MethodOutcome response = client.validatePatient(patient); - - assertEquals(HttpPost.class, capt.getValue().getClass()); - HttpPost post = (HttpPost) capt.getValue(); - assertThat(post.getURI().toASCIIString(), StringEndsWith.endsWith("/Patient/_validate")); - assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("" - + "
John Cardinal: 444333333
" - + "" - + "" - + "" - + "" - + "" - + "
" - + "
"; - //@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.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - - ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); - // Patient response = client.findPatientByMrn(new - // IdentifierDt("urn:foo", "123")); - Patient response = client.getPatientById(new IdType("Patient/111/_history/999")); - - assertEquals("http://foo/Patient/111/_history/999", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getIdentifier().get(0).getValue().getValue()); - - } - - private Header[] toHeaderArray(String theName, String theValue) { - return new Header[] { new BasicHeader(theName, theValue) }; - } - - private interface ClientWithoutAnnotation extends IBasicClient { - Patient read(@IdParam IdType theId); - } - - @ResourceDef(name = "Patient") - public static class CustomPatient extends Patient { - - private static final long serialVersionUID = 1L; - - // nothing - } - - public interface ITestClientWithCustomType extends IBasicClient { - @Search() - public CustomPatient getPatientByDob(@RequiredParam(name = Patient.SP_BIRTHDATE) DateParam theBirthDate); - } - - public interface ITestClientWithCustomTypeList extends IBasicClient { - @Search() - public List getPatientByDob(@RequiredParam(name = Patient.SP_BIRTHDATE) DateParam theBirthDate); - } - - public interface ITestClientWithStringIncludes extends IBasicClient { - @Search() - public Patient getPatientWithIncludes(@RequiredParam(name = "withIncludes") StringParam theString, @IncludeParam String theInclude); - } - - public interface ITestClientWithSummary extends IBasicClient { - @Search() - public List getPatientWithIncludes(SummaryEnum theSummary); - - @Search() - public List getPatientWithIncludes(List theSummary); - - } - - public interface ITestClientWithElements extends IBasicClient { - @Search() - public List getPatientWithIncludes(@Elements String theElements); - - @Search() - public List getPatientWithIncludes(@Elements Set theElements); - - } - - - @AfterClass - public static void afterClassClearContext() { - TestUtil.clearAllStaticFieldsForUnitTest(); - } - -} diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java index 70d82658df3..f4d523c47bb 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java @@ -1,6 +1,6 @@ package ca.uhn.fhir.rest.client; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.List; @@ -14,18 +14,15 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.hl7.fhir.r4.model.Patient; +import org.junit.*; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.IResource; -import ca.uhn.fhir.model.dstu.resource.Patient; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.client.api.IBasicClient; +import ca.uhn.fhir.rest.client.impl.HttpBasicAuthInterceptor; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.util.PortUtil; @@ -36,7 +33,7 @@ public class ClientIntegrationTest { private int myPort; private Server myServer; private MyPatientResourceProvider myPatientProvider; - private static FhirContext ourCtx = FhirContext.forDstu1(); + private static FhirContext ourCtx = FhirContext.forR4(); @Before public void before() { @@ -60,7 +57,7 @@ public class ClientIntegrationTest { myServer.start(); - FhirContext ctx = FhirContext.forDstu1(); + FhirContext ctx = FhirContext.forR4(); HttpClientBuilder builder = HttpClientBuilder.create(); // PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); @@ -74,7 +71,7 @@ public class ClientIntegrationTest { List actualPatients = client.searchForPatients(new StringDt("AAAABBBB")); assertEquals(1, actualPatients.size()); - assertEquals("AAAABBBB", actualPatients.get(0).getNameFirstRep().getFamilyAsSingleString()); + assertEquals("AAAABBBB", actualPatients.get(0).getNameFirstRep().getFamily()); assertEquals("Basic Zm9vYmFyOmJvb2JlYXI=", myPatientProvider.getAuthorizationHeader()); } @@ -92,7 +89,7 @@ public class ClientIntegrationTest { } @Override - public Class getResourceType() { + public Class getResourceType() { return Patient.class; } @@ -105,7 +102,7 @@ public class ClientIntegrationTest { Patient retVal = new Patient(); retVal.setId("1"); - retVal.addName().addFamily(theFooParam.getValue()); + retVal.addName().setFamily(theFooParam.getValue()); return Collections.singletonList(retVal); } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientR4Test.java new file mode 100644 index 00000000000..958b1fa56b1 --- /dev/null +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientR4Test.java @@ -0,0 +1,1262 @@ +package ca.uhn.fhir.rest.client; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.io.StringReader; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.*; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.input.ReaderInputStream; +import org.apache.http.*; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.*; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicStatusLine; +import org.hamcrest.core.StringContains; +import org.hamcrest.core.StringEndsWith; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.junit.*; +import org.mockito.ArgumentCaptor; +import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.model.api.Include; +import ca.uhn.fhir.model.api.annotation.ResourceDef; +import ca.uhn.fhir.model.base.resource.BaseConformance; +import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.client.apache.ApacheHttpRequest; +import ca.uhn.fhir.rest.client.api.IBasicClient; +import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; +import ca.uhn.fhir.rest.client.interceptor.CapturingInterceptor; +import ca.uhn.fhir.rest.param.*; +import ca.uhn.fhir.rest.server.exceptions.*; +import ca.uhn.fhir.util.TestUtil; +import ca.uhn.fhir.util.UrlUtil; + +public class ClientR4Test { + + private HttpClient myHttpClient; + private HttpResponse myHttpResponse; + private FhirContext ourCtx; + + @Before + public void before() { + ourCtx = FhirContext.forR4(); + + myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs()); + ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient); + ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); + + myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); + } + + // atom-document-large.xml + + public String getHistoryBundleWithTwoResults() { + /* + * //@formatter:off + String msg = "<id>6c1d93be-027f-468d-9d47-f826cd15cf42</id>" + + "<link rel=\"self\" href=\"http://localhost:51698/Patient/222/_history\"/>" + + "<link rel=\"fhir-base\" href=\"http://localhost:51698\"/><os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults>" + + "<author><name>ca.uhn.fhir.rest.method.HistoryMethodBinding</name></author>" + + "<entry><title>Patient 222222" + + ""+date1.getValueAsString()+"" + + ""+date2.getValueAsString()+"" + + "" + + "" + + "" + + "Patient 222222" + + ""+date3.getValueAsString()+"" + + ""+date4.getValueAsString()+"" + + ""; + //@formatter:on + */ + + Bundle retVal = new Bundle(); + + Patient p1 = new Patient(); + p1.addName().setFamily("OldeerFamily").addGiven("PatientOne"); + retVal + .addEntry() + .setFullUrl("http://acme.com/Patient/111") + .setResource(p1); + + Patient p2 = new Patient(); + p2.addName().setFamily("NewerFamily").addGiven("PatientOne"); + retVal + .addEntry() + .setFullUrl("http://acme.com/Patient/222") + .setResource(p2); + + return ourCtx.newXmlParser().encodeResourceToString(retVal); + + } + + private String getPatient() { + Patient p = new Patient(); + p.getMeta().getLastUpdatedElement().setValueAsString("1995-11-15T03:58:08.000-01:00"); + p + .getMeta() + .addTag() + .setSystem("http://hl7.org/fhir/tag") + .setCode("http://foo/tagdefinition.html") + .setDisplay("Some tag"); + + p.setId("http://foo.com/Patient/123/_history/2333"); + p.addName().setFamily("Kramer").addGiven("Doe"); + String msg = EncodingEnum.XML.newParser(ourCtx).setPrettyPrint(true).encodeResourceToString(p); + return msg; + } + + private String getPatientFeedWithOneResult() { + + Bundle retVal = new Bundle(); + + Patient p = new Patient(); + p.addName().setFamily("Cardinal").addGiven("John"); + retVal.addEntry().setResource(p); + + return ourCtx.newXmlParser().encodeResourceToString(retVal); + + // String msg = "\n" + + // "\n" + + // "<id>d039f91a-cc3c-4013-988e-af4d8d0614bd</id>\n" + + // "<os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">1</os:totalResults>\n" + + // "<author>\n" + + // "<name>ca.uhn.fhir.rest.server.DummyRestfulServer</name>\n" + + // "</author>\n" + + // "<entry>\n" + + // "<content type=\"text/xml\">" + // + "<Patient xmlns=\"http://hl7.org/fhir\">" + // + "<text><status value=\"generated\" /><div xmlns=\"http://www.w3.org/1999/xhtml\">John Cardinal: 444333333 </div></text>" + // + "<identifier><label value=\"SSN\" /><system value=\"http://orionhealth.com/mrn\" /><value value=\"PRP1660\" /></identifier>" + // + "<name><use value=\"official\" /><family value=\"Cardinal\" /><given value=\"John\" /></name>" + // + "<name><family value=\"Kramer\" /><given value=\"Doe\" /></name>" + // + "<telecom><system value=\"phone\" /><value value=\"555-555-2004\" /><use value=\"work\" /></telecom>" + // + "<gender><coding><system value=\"http://hl7.org/fhir/v3/AdministrativeGender\" /><code value=\"M\" /></coding></gender>" + // + "<address><use value=\"home\" /><line value=\"2222 Home Street\" /></address><active value=\"true\" />" + // + "</Patient>" + // + "</content>\n" + // + " </entry>\n" + // + "</feed>"; + // return msg; + } + + @Test + public void testCreate() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); + when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + CapturingInterceptor interceptor = new CapturingInterceptor(); + client.registerInterceptor(interceptor); + + MethodOutcome response = client.createPatient(patient); + + assertEquals(((ApacheHttpRequest) interceptor.getLastRequest()).getApacheRequest().getURI().toASCIIString(), "http://foo/Patient"); + + assertEquals(HttpPost.class, capt.getValue().getClass()); + HttpPost post = (HttpPost) capt.getValue(); + assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); + assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(0).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + assertEquals("200", response.getId().getVersionIdPart()); + } + + @Test + public void testCreateBad() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 400, "foobar")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader("foobar"), Charset.forName("UTF-8"))); + + try { + ourCtx.newRestfulClient(ITestClient.class, "http://foo").createPatient(patient); + fail(); + } catch (InvalidRequestException e) { + assertThat(e.getMessage(), StringContains.containsString("foobar")); + } + } + + /** + * Some servers (older ones?) return the resourcde you created instead of an OperationOutcome. We just need to ignore + * it. + */ + @Test + public void testCreateWithResourceResponse() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "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(ourCtx.newXmlParser().encodeResourceToString(patient)), Charset.forName("UTF-8"))); + when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + MethodOutcome response = client.createPatient(patient); + + assertEquals(HttpPost.class, capt.getValue().getClass()); + HttpPost post = (HttpPost) capt.getValue(); + assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); + assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); + assertEquals("200", response.getId().getVersionIdPart()); + } + + @Test + public void testDelete() throws Exception { + + OperationOutcome oo = new OperationOutcome(); + oo.addIssue().setDiagnostics("Hello"); + String resp = ourCtx.newXmlParser().encodeResourceToString(oo); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "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(resp), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + MethodOutcome response = client.deletePatient(new IdType("1234")); + + assertEquals(HttpDelete.class, capt.getValue().getClass()); + assertEquals("http://foo/Patient/1234", capt.getValue().getURI().toString()); + assertEquals("Hello", ((OperationOutcome) response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); + } + + @Test + public void testDeleteNoResponse() throws Exception { + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 204, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.deleteDiagnosticReport(new IdType("1234")); + + assertEquals(HttpDelete.class, capt.getValue().getClass()); + assertEquals("http://foo/DiagnosticReport/1234", capt.getValue().getURI().toString()); + } + + @Test + public void testGetConformance() throws Exception { + + String msg = IOUtils.toString(ClientR4Test.class.getResourceAsStream("/example-metadata.xml")); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + BaseConformance response = client.getServerConformanceStatement(); + + assertEquals("http://foo/metadata", capt.getValue().getURI().toString()); + assertEquals("Health Intersections", response.getPublisherElement().getValue()); + + } + + @SuppressWarnings("deprecation") + @Test + public void testHistoryResourceInstance() throws Exception { + + String msg = getHistoryBundleWithTwoResults(); + + ArgumentCaptor<HttpUriRequest> 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_ATOM_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + Bundle response = client.getHistoryPatientInstance(new IdType("111")); + + assertEquals("http://foo/Patient/111/_history", capt.getValue().getURI().toString()); + + assertEquals(2, response.getEntry().size()); + + verifyHistoryBundleWithTwoResults(response); + } + + @SuppressWarnings("deprecation") + @Test + public void testHistoryResourceType() throws Exception { + + String msg = getHistoryBundleWithTwoResults(); + ArgumentCaptor<HttpUriRequest> 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_ATOM_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + Bundle response = client.getHistoryPatientType(); + + assertEquals("http://foo/Patient/_history", capt.getValue().getURI().toString()); + + verifyHistoryBundleWithTwoResults(response); + } + + @SuppressWarnings("deprecation") + @Test + public void testHistoryServer() throws Exception { + String msg = getHistoryBundleWithTwoResults(); + + ArgumentCaptor<HttpUriRequest> 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_ATOM_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + Bundle response = client.getHistoryServer(); + + assertEquals("http://foo/_history", capt.getValue().getURI().toString()); + + assertEquals(2, response.getEntry().size()); + + verifyHistoryBundleWithTwoResults(response); + } + + @Test + public void testHistoryWithParams() throws Exception { + + final String msg = getHistoryBundleWithTwoResults(); + + ArgumentCaptor<HttpUriRequest> 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_ATOM_XML + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<InputStream>() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); + } + }); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + + // ensures the local timezone + String expectedDateString = new InstantType(new InstantType("2012-01-02T12:01:02").getValue()).getValueAsString(); + expectedDateString = expectedDateString.replace(":", "%3A").replace("+", "%2B"); + + client.getHistoryPatientInstance(new IdType("111"), new InstantType("2012-01-02T12:01:02"), new IntegerType(12)); + assertThat(capt.getAllValues().get(0).getURI().toString(), containsString("http://foo/Patient/111/_history?")); + assertThat(capt.getAllValues().get(0).getURI().toString(), containsString("_since=" + expectedDateString.replaceAll("\\..*", ""))); + assertThat(capt.getAllValues().get(0).getURI().toString(), containsString("_count=12")); + + client.getHistoryPatientInstance(new IdType("111"), new InstantType("2012-01-02T12:01:02").getValue(), new IntegerType(12).getValue()); + assertThat(capt.getAllValues().get(1).getURI().toString(), containsString("http://foo/Patient/111/_history?")); + assertThat(capt.getAllValues().get(1).getURI().toString(), containsString("_since=" + expectedDateString)); + assertThat(capt.getAllValues().get(1).getURI().toString(), containsString("_count=12")); + + client.getHistoryPatientInstance(new IdType("111"), null, new IntegerType(12)); + assertEquals("http://foo/Patient/111/_history?_count=12", capt.getAllValues().get(2).getURI().toString()); + + client.getHistoryPatientInstance(new IdType("111"), new InstantType("2012-01-02T00:01:02"), null); + assertEquals("http://foo/Patient/111/_history?_since=2012-01-02T00%3A01%3A02", capt.getAllValues().get(3).getURI().toString()); + + client.getHistoryPatientInstance(new IdType("111"), new InstantType(), new IntegerType(12)); + assertEquals("http://foo/Patient/111/_history?_count=12", capt.getAllValues().get(4).getURI().toString()); + + client.getHistoryPatientInstance(new IdType("111"), new InstantType("2012-01-02T00:01:02"), new IntegerType()); + assertEquals("http://foo/Patient/111/_history?_since=2012-01-02T00%3A01%3A02", capt.getAllValues().get(5).getURI().toString()); + + } + + @Test + public void testNonAnnotatedMethodFailsGracefully() { + + // TODO: remove the read annotation and make sure we get a sensible + // error message to tell the user why the method isn't working + FhirContext ctx = ourCtx; + ctx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); + + ClientWithoutAnnotation client = ctx.newRestfulClient(ClientWithoutAnnotation.class, "http://wildfhir.aegis.net/fhir"); + + try { + client.read(new IdType("8")); + fail(); + } catch (UnsupportedOperationException e) { + assertThat(e.getMessage(), containsString("annotation")); + } + + } + + @Test + public void testRead() throws Exception { + + String msg = getPatient(); + + ArgumentCaptor<HttpUriRequest> 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")); + Header[] headers = new Header[] { new BasicHeader(Constants.HEADER_LAST_MODIFIED, "Wed, 15 Nov 1995 04:58:08 GMT"), + new BasicHeader(Constants.HEADER_CONTENT_LOCATION, "http://foo.com/Patient/123/_history/2333"), + new BasicHeader(Constants.HEADER_CATEGORY, "http://foo/tagdefinition.html; scheme=\"http://hl7.org/fhir/tag\"; label=\"Some tag\"") }; + + when(myHttpResponse.getAllHeaders()).thenReturn(headers); + 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + // Patient response = client.findPatientByMrn(new + // IdentifierDt("urn:foo", "123")); + Patient response = client.getPatientById(new IdType("111")); + + assertEquals("http://foo/Patient/111", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + assertEquals("http://foo.com/Patient/123/_history/2333", response.getId()); + + InstantType lm = (InstantType) response.getMeta().getLastUpdatedElement(); + lm.setTimeZoneZulu(true); + assertEquals("1995-11-15T04:58:08.000Z", lm.getValueAsString()); + + List<Coding> tags = response.getMeta().getTag(); + assertNotNull(tags); + assertEquals(1, tags.size()); + assertEquals("http://foo/tagdefinition.html", tags.get(0).getCode()); + assertEquals("http://hl7.org/fhir/tag", tags.get(0).getSystem()); + assertEquals("Some tag", tags.get(0).getDisplay()); + + } + + @Test + public void testReadFailureInternalError() throws Exception { + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "INTERNAL")); + Header[] headers = new Header[1]; + headers[0] = new BasicHeader(Constants.HEADER_LAST_MODIFIED, "2011-01-02T22:01:02"); + when(myHttpResponse.getAllHeaders()).thenReturn(headers); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT)); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader("Internal Failure"), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + try { + client.getPatientById(new IdType("111")); + fail(); + } catch (InternalErrorException e) { + assertThat(e.getMessage(), containsString("INTERNAL")); + assertThat(e.getResponseBody(), containsString("Internal Failure")); + } + + } + + @Test + public void testReadFailureNoCharset() throws Exception { + + //@formatter:off + String msg = "<OperationOutcome xmlns=\"http://hl7.org/fhir\"></OperationOutcome>"; + //@formatter:on + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 404, "NOT FOUND")); + Header[] headers = new Header[1]; + headers[0] = new BasicHeader(Constants.HEADER_LAST_MODIFIED, "2011-01-02T22:01:02"); + when(myHttpResponse.getAllHeaders()).thenReturn(headers); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML)); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + try { + client.getPatientById(new IdType("111")); + fail(); + } catch (ResourceNotFoundException e) { + // good + } + + } + + @Test + public void testReadNoCharset() throws Exception { + + String msg = getPatient(); + + ArgumentCaptor<HttpUriRequest> 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")); + Header[] headers = new Header[1]; + headers[0] = new BasicHeader(Constants.HEADER_LAST_MODIFIED, "Wed, 15 Nov 1995 04:58:08 GMT"); + when(myHttpResponse.getAllHeaders()).thenReturn(headers); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML)); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + // Patient response = client.findPatientByMrn(new + // IdentifierDt("urn:foo", "123")); + Patient response = client.getPatientById(new IdType("111")); + + assertEquals("http://foo/Patient/111", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + InstantType lm = (InstantType) response.getMeta().getLastUpdatedElement(); + lm.setTimeZoneZulu(true); + assertEquals("1995-11-15T04:58:08.000Z", lm.getValueAsString()); + + } + + @Test + public void testResponseContainingOldStyleXmlContentType() throws Exception { + + String msg = getPatient(); + + ArgumentCaptor<HttpUriRequest> 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", "application/fhir+xml; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + // Patient response = client.findPatientByMrn(new + // IdentifierDt("urn:foo", "123")); + Patient response = client.getPatientById(new IdType("111")); + + assertEquals("http://foo/Patient/111", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchByCompartment() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + + 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"))); + + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + List<Patient> response = client.getPatientByCompartmentAndDob(new IdType("123"), new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + + assertEquals("http://foo/Patient/123/compartmentName?birthdate=ge2011-01-02", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.get(0).getIdentifier().get(0).getValueElement().getValue()); + + try { + client.getPatientByCompartmentAndDob(new IdType(""), new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + fail(); + } catch (InvalidRequestException e) { + assertThat(e.toString(), containsString("null or empty for compartment")); + } + + } + + @Test + public void testSearchByCompositeParam() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + StringParam str = new StringParam("FOO$BAR"); + DateParam date = new DateParam("2001-01-01"); + client.getObservationByNameValueDate(new CompositeParam<StringParam, DateParam>(str, date)); + + assertEquals("http://foo/Observation?" + Observation.SP_CODE_VALUE_DATE + "=" + URLEncoder.encode("FOO\\$BAR$2001-01-01", "UTF-8"), capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchByDateRange() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + DateRangeParam param = new DateRangeParam(); + param.setLowerBound(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-01")); + param.setUpperBound(new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, "2021-01-01")); + client.getPatientByDateRange(param); + + assertEquals("http://foo/Patient?dateRange=ge2011-01-01&dateRange=%3C%3D2021-01-01", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchByDob() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + + 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"))); + + // httpResponse = new BasicHttpResponse(statusline, catalog, locale) + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + List<Patient> response = client.getPatientByDob(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + + assertEquals("http://foo/Patient?birthdate=ge2011-01-02", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.get(0).getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchByQuantity() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + Patient response = client.findPatientQuantity(new QuantityParam(ParamPrefixEnum.GREATERTHAN, 123L, "foo", "bar")); + + assertEquals("http://foo/Patient?quantityParam=%3E123%7Cfoo%7Cbar", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchByToken() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + Patient response = client.findPatientByMrn(new TokenParam("urn:foo", "123")); + + assertEquals("http://foo/Patient?identifier=urn%3Afoo%7C123", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchNamedQueryNoParams() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.getPatientNoParams(); + + assertEquals("http://foo/Patient?_query=someQueryNoParams", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchNamedQueryOneParam() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.getPatientOneParam(new StringParam("BB")); + + assertEquals("http://foo/Patient?_query=someQueryOneParam¶m1=BB", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchOrList() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + TokenOrListParam identifiers = new TokenOrListParam(); + identifiers.add("foo", "bar"); + identifiers.add("baz", "boz"); + client.getPatientMultipleIdentifiers(identifiers); + + assertEquals("http://foo/Patient?ids=foo%7Cbar%2Cbaz%7Cboz", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchWithCustomType() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClientWithCustomType client = ourCtx.newRestfulClient(ITestClientWithCustomType.class, "http://foo"); + CustomPatient response = client.getPatientByDob(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + + assertEquals("http://foo/Patient?birthdate=ge2011-01-02", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchWithCustomTypeList() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClientWithCustomTypeList client = ourCtx.newRestfulClient(ITestClientWithCustomTypeList.class, "http://foo"); + List<CustomPatient> response = client.getPatientByDob(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + + assertEquals("http://foo/Patient?birthdate=ge2011-01-02", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.get(0).getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchWithElements() throws Exception { + + final String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + + 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<InputStream>() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); + } + }); + + // httpResponse = new BasicHttpResponse(statusline, catalog, locale) + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + + ITestClientWithElements client = ourCtx.newRestfulClient(ITestClientWithElements.class, "http://foo"); + + int idx = 0; + + client.getPatientWithIncludes((String) null); + assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes((Set<String>) null); + assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes("test"); + assertEquals("http://foo/Patient?_elements=test", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes("test,foo"); + assertEquals("http://foo/Patient?_elements=test%2Cfoo", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes(new HashSet<String>(Arrays.asList("test", "foo", ""))); + assertEquals("http://foo/Patient?_elements=test%2Cfoo", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + } + + @Test + public void testSearchWithEscapedValues() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + StringAndListParam andListParam = new StringAndListParam(); + StringOrListParam orListParam1 = new StringOrListParam().addOr(new StringParam("NE,NE", false)).addOr(new StringParam("NE,NE", false)); + StringOrListParam orListParam2 = new StringOrListParam().addOr(new StringParam("E$E", true)); + StringOrListParam orListParam3 = new StringOrListParam().addOr(new StringParam("NE\\NE", false)); + StringOrListParam orListParam4 = new StringOrListParam().addOr(new StringParam("E|E", true)); + client.findPatient(andListParam.addAnd(orListParam1).addAnd(orListParam2).addAnd(orListParam3).addAnd(orListParam4)); + + assertThat(capt.getValue().getURI().toString(), containsString("%3A")); + assertEquals("http://foo/Patient?param=NE\\,NE,NE\\,NE¶m=NE\\\\NE¶m:exact=E\\$E¶m:exact=E\\|E", UrlUtil.unescape(capt.getValue().getURI().toString())); + + } + + @Test + public void testSearchWithFormatAndPrettyPrint() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + // TODO: document this + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.getPatientByDob(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + assertEquals("http://foo/Patient?birthdate=ge2011-01-02", capt.getAllValues().get(0).getURI().toString()); + + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + client.setEncoding(EncodingEnum.JSON); // this needs to be actually + // implemented + client.getPatientByDob(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + assertEquals("http://foo/Patient?birthdate=ge2011-01-02&_format=json", capt.getAllValues().get(1).getURI().toString()); + + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + client.setPrettyPrint(true); + client.getPatientByDob(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + assertEquals("http://foo/Patient?birthdate=ge2011-01-02&_format=json&_pretty=true", capt.getAllValues().get(2).getURI().toString()); + + } + + @Test + public void testSearchWithGenericReturnType() throws Exception { + + Bundle bundle = new Bundle(); + + Patient patient = new Patient(); + patient.addIdentifier().setValue("PRP1660"); + bundle.addEntry().setResource(patient); + + Organization org = new Organization(); + org.setName("FOO"); + patient.getManagingOrganization().setResource(org); + + String msg = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(bundle); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + + 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"))); + + // httpResponse = new BasicHttpResponse(statusline, catalog, locale) + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + List<IBaseResource> response = client.getPatientByDobWithGenericResourceReturnType(new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, "2011-01-02")); + + assertEquals("http://foo/Patient?birthdate=ge2011-01-02", capt.getValue().getURI().toString()); + ExtendedPatient patientResp = (ExtendedPatient) response.get(0); + assertEquals("PRP1660", patientResp.getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchWithGlobalSummary() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.setSummary(SummaryEnum.DATA); + client.findPatientByMrn(new TokenParam("sysm", "val")); + + assertEquals("http://foo/Patient?identifier=sysm%7Cval&_summary=data", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchWithIncludes() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.getPatientWithIncludes(new StringParam("aaa"), Arrays.asList(new Include[] { new Include("inc1"), new Include("inc2", true), new Include("inc3", true) })); + + assertEquals("http://foo/Patient?withIncludes=aaa&_include=inc1&_include%3Arecurse=inc2&_include%3Arecurse=inc3", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchWithOptionalParam() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + Bundle response = client.findPatientByName(new StringParam("AAA"), null); + + assertEquals("http://foo/Patient?family=AAA", capt.getValue().getURI().toString()); + Patient resource = (Patient) response.getEntry().get(0).getResource(); + assertEquals("PRP1660", resource.getIdentifier().get(0).getValueElement().getValue()); + + /* + * Now with a first name + */ + + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); + client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + response = client.findPatientByName(new StringParam("AAA"), new StringParam("BBB")); + + assertEquals("http://foo/Patient?family=AAA&given=BBB", capt.getValue().getURI().toString()); + resource = (Patient) response.getEntry().get(0).getResource(); + assertEquals("PRP1660", resource.getIdentifier().get(0).getValueElement().getValue()); + + } + + @Test + public void testSearchWithStringIncludes() throws Exception { + + String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClientWithStringIncludes client = ourCtx.newRestfulClient(ITestClientWithStringIncludes.class, "http://foo"); + client.getPatientWithIncludes(new StringParam("aaa"), "inc1"); + + assertEquals("http://foo/Patient?withIncludes=aaa&_include=inc1", capt.getValue().getURI().toString()); + + } + + @Test + public void testSearchWithSummary() throws Exception { + + final String msg = getPatientFeedWithOneResult(); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + + 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<InputStream>() { + @Override + public InputStream answer(InvocationOnMock theInvocation) throws Throwable { + return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); + } + }); + + // httpResponse = new BasicHttpResponse(statusline, catalog, locale) + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + + ITestClientWithSummary client = ourCtx.newRestfulClient(ITestClientWithSummary.class, "http://foo"); + + int idx = 0; + + client.getPatientWithIncludes((SummaryEnum) null); + assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes(SummaryEnum.COUNT); + assertEquals("http://foo/Patient?_summary=count", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes(SummaryEnum.DATA); + assertEquals("http://foo/Patient?_summary=data", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes(Arrays.asList(SummaryEnum.DATA)); + assertEquals("http://foo/Patient?_summary=data", capt.getAllValues().get(idx).getURI().toString()); + idx++; + + client.getPatientWithIncludes(Arrays.asList(SummaryEnum.COUNT, SummaryEnum.DATA)); + assertThat(capt.getAllValues().get(idx).getURI().toString(), either(equalTo("http://foo/Patient?_summary=data&_summary=count")).or(equalTo("http://foo/Patient?_summary=count&_summary=data"))); + idx++; + + client.getPatientWithIncludes(new ArrayList<SummaryEnum>()); + assertEquals("http://foo/Patient", capt.getAllValues().get(idx).getURI().toString()); + idx++; + } + + @Test + public void testUpdate() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); + when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + MethodOutcome response = client.updatePatient(new IdType("100"), patient); + + assertEquals(HttpPut.class, capt.getValue().getClass()); + HttpPut post = (HttpPut) capt.getValue(); + assertThat(post.getURI().toASCIIString(), StringEndsWith.endsWith("/Patient/100")); + assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); + assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); + assertEquals("200", response.getId().getVersionIdPart()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(0).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); + } + + /** + * Return a FHIR content type, but no content and make sure we handle this without crashing + */ + @Test + public void testUpdateWithEmptyResponse() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "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(""), Charset.forName("UTF-8"))); + when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Content-Location", "http://example.com/fhir/Patient/100/_history/200")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.updatePatient(new IdType("Patient/100/_history/200"), patient); + + assertEquals(HttpPut.class, capt.getValue().getClass()); + HttpPut post = (HttpPut) capt.getValue(); + assertEquals("http://foo/Patient/100", post.getURI().toASCIIString()); + + Header h = post.getFirstHeader("content-location"); + assertEquals("Patient/100/_history/200", h.getValue()); + + } + + @Test(expected = ResourceVersionConflictException.class) + public void testUpdateWithResourceConflict() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + 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(""), Charset.forName("UTF-8"))); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_409_CONFLICT, "Conflict")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + client.updatePatient(new IdType("Patient/100/_history/200"), patient); + } + + @Test + public void testUpdateWithVersion() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); + when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + MethodOutcome response = client.updatePatient(new IdType("Patient/100/_history/200"), patient); + + assertEquals(HttpPut.class, capt.getValue().getClass()); + HttpPut post = (HttpPut) capt.getValue(); + assertThat(post.getURI().toASCIIString(), StringEndsWith.endsWith("/Patient/100")); + assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); + assertThat(post.getFirstHeader("Content-Location").getValue(), StringEndsWith.endsWith("Patient/100/_history/200")); + assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); + assertEquals("200", response.getId().getVersionIdPart()); + } + + @Test + public void testValidate() throws Exception { + + Patient patient = new Patient(); + patient.addIdentifier().setSystem("urn:foo").setValue("123"); + + ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); + when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); + when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 201, "OK")); + when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_TEXT + "; charset=UTF-8")); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"))); + when(myHttpResponse.getAllHeaders()).thenReturn(toHeaderArray("Location", "http://example.com/fhir/Patient/100/_history/200")); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + MethodOutcome response = client.validatePatient(patient); + + assertEquals(HttpPost.class, capt.getValue().getClass()); + HttpPost post = (HttpPost) capt.getValue(); + assertThat(post.getURI().toASCIIString(), StringEndsWith.endsWith("/Patient/_validate")); + assertThat(IOUtils.toString(post.getEntity().getContent()), StringContains.containsString("<Patient")); + assertEquals("http://example.com/fhir/Patient/100/_history/200", response.getId().getValue()); + assertEquals("200", response.getId().getVersionIdPart()); + + } + + @Test + public void testVRead() throws Exception { + + //@formatter:off + String msg = "<Patient xmlns=\"http://hl7.org/fhir\">" + + "<text><status value=\"generated\" /><div xmlns=\"http://www.w3.org/1999/xhtml\">John Cardinal: 444333333 </div></text>" + + "<identifier><label value=\"SSN\" /><system value=\"http://orionhealth.com/mrn\" /><value value=\"PRP1660\" /></identifier>" + + "<name><use value=\"official\" /><family value=\"Cardinal\" /><given value=\"John\" /></name>" + + "<name><family value=\"Kramer\" /><given value=\"Doe\" /></name>" + + "<telecom><system value=\"phone\" /><value value=\"555-555-2004\" /><use value=\"work\" /></telecom>" + + "<gender><coding><system value=\"http://hl7.org/fhir/v3/AdministrativeGender\" /><code value=\"M\" /></coding></gender>" + + "<address><use value=\"home\" /><line value=\"2222 Home Street\" /></address><active value=\"true\" />" + + "</Patient>"; + //@formatter:on + + ArgumentCaptor<HttpUriRequest> 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"))); + + ITestClient client = ourCtx.newRestfulClient(ITestClient.class, "http://foo"); + // Patient response = client.findPatientByMrn(new + // IdentifierDt("urn:foo", "123")); + Patient response = client.getPatientById(new IdType("Patient/111/_history/999")); + + assertEquals("http://foo/Patient/111/_history/999", capt.getValue().getURI().toString()); + assertEquals("PRP1660", response.getIdentifier().get(0).getValueElement().getValue()); + + } + + private Header[] toHeaderArray(String theName, String theValue) { + return new Header[] { new BasicHeader(theName, theValue) }; + } + + private void verifyHistoryBundleWithTwoResults(Bundle response) { + assertEquals(2, response.getEntry().size()); + // Older resource + { + BundleEntryComponent olderEntry = response.getEntry().get(0); + assertEquals("http://acme.com/Patient/111", olderEntry.getId()); + } + // Newer resource + { + BundleEntryComponent newerEntry = response.getEntry().get(1); + assertEquals("http://acme.com/Patient/222", newerEntry.getId()); + } + } + + @AfterClass + public static void afterClassClearContext() { + TestUtil.clearAllStaticFieldsForUnitTest(); + } + + private interface ClientWithoutAnnotation extends IBasicClient { + Patient read(@IdParam IdType theId); + } + + @ResourceDef(name = "Patient") + public static class CustomPatient extends Patient { + + private static final long serialVersionUID = 1L; + + // nothing + } + + public interface ITestClientWithCustomType extends IBasicClient { + @Search() + public CustomPatient getPatientByDob(@RequiredParam(name = Patient.SP_BIRTHDATE) DateParam theBirthDate); + } + + public interface ITestClientWithCustomTypeList extends IBasicClient { + @Search() + public List<CustomPatient> getPatientByDob(@RequiredParam(name = Patient.SP_BIRTHDATE) DateParam theBirthDate); + } + + public interface ITestClientWithElements extends IBasicClient { + @Search() + public List<Patient> getPatientWithIncludes(@Elements Set<String> theElements); + + @Search() + public List<Patient> getPatientWithIncludes(@Elements String theElements); + + } + + public interface ITestClientWithStringIncludes extends IBasicClient { + @Search() + public Patient getPatientWithIncludes(@RequiredParam(name = "withIncludes") StringParam theString, @IncludeParam String theInclude); + } + + public interface ITestClientWithSummary extends IBasicClient { + @Search() + public List<Patient> getPatientWithIncludes(List<SummaryEnum> theSummary); + + @Search() + public List<Patient> getPatientWithIncludes(SummaryEnum theSummary); + + } + +} diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientServerValidationDstu1Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientServerValidationDstu1Test.java index c4df0dcf03f..38019cd1816 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientServerValidationDstu1Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientServerValidationDstu1Test.java @@ -1,6 +1,6 @@ package ca.uhn.fhir.rest.client; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -15,9 +15,9 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicStatusLine; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.hl7.fhir.r4.model.CapabilityStatement; +import org.hl7.fhir.r4.model.Patient; +import org.junit.*; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; @@ -25,11 +25,11 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.dstu.resource.Conformance; -import ca.uhn.fhir.model.dstu.resource.Patient; import ca.uhn.fhir.model.primitive.UriDt; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.client.api.IGenericClient; +import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.rest.client.exceptions.FhirClientInappropriateForServerException; -import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.util.TestUtil; public class ClientServerValidationDstu1Test { @@ -45,13 +45,13 @@ public class ClientServerValidationDstu1Test { myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); myFirstResponse = true; - myCtx = FhirContext.forDstu1(); + myCtx = FhirContext.forR4(); myCtx.getRestfulClientFactory().setHttpClient(myHttpClient); } @Test public void testServerReturnsAppropriateVersionDstu() throws Exception { - Conformance conf = new Conformance(); + CapabilityStatement conf = new CapabilityStatement(); conf.setFhirVersion("0.0.8"); final String confResource = myCtx.newXmlParser().encodeResourceToString(conf); @@ -88,7 +88,7 @@ public class ClientServerValidationDstu1Test { @Test public void testServerReturnsWrongVersionDstu() throws Exception { - Conformance conf = new Conformance(); + CapabilityStatement conf = new CapabilityStatement(); conf.setFhirVersion("0.4.0"); String msg = myCtx.newXmlParser().encodeResourceToString(conf); @@ -105,7 +105,7 @@ public class ClientServerValidationDstu1Test { myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/1")); fail(); } catch (FhirClientInappropriateForServerException e) { - assertThat(e.toString(), containsString("The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.4.0\" which corresponds to DSTU2, but this client is configured to use DSTU1 (via the FhirContext)")); + assertThat(e.toString(), containsString("The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.4.0\" which corresponds to DSTU2, but this client is configured to use R4 (via the FhirContext)")); } } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ExceptionHandlingTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ExceptionHandlingTest.java index dc19963e8cf..251e74ced96 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ExceptionHandlingTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ExceptionHandlingTest.java @@ -1,7 +1,8 @@ package ca.uhn.fhir.rest.client; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.StringReader; import java.nio.charset.Charset; @@ -14,22 +15,17 @@ import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicStatusLine; import org.hamcrest.core.StringContains; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.hl7.fhir.r4.model.*; +import org.junit.*; import org.mockito.ArgumentCaptor; import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.base.resource.BaseOperationOutcome; -import ca.uhn.fhir.model.dstu.resource.OperationOutcome; -import ca.uhn.fhir.model.dstu.resource.Patient; -import ca.uhn.fhir.model.primitive.IdType; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.client.api.IRestfulClient; -import ca.uhn.fhir.rest.server.Constants; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.client.api.*; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.util.TestUtil; @@ -41,7 +37,7 @@ public class ExceptionHandlingTest { @BeforeClass public static void beforeClass() { - ourCtx = FhirContext.forDstu1(); + ourCtx = FhirContext.forR4(); } @Before @@ -49,7 +45,7 @@ public class ExceptionHandlingTest { myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs()); ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient); - ourCtx.getRestfulClientFactory().setServerValidationModeEnum(ServerValidationModeEnum.NEVER); + ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs()); } @@ -68,7 +64,7 @@ public class ExceptionHandlingTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); try { - client.read(Patient.class, new IdType("Patient/1234")); + client.read().resource(Patient.class).withId(new IdType("Patient/1234")).execute(); fail(); } catch (InternalErrorException e) { assertThat(e.getMessage(), StringContains.containsString("HTTP 500 Internal Error")); @@ -80,7 +76,7 @@ public class ExceptionHandlingTest { @Test public void testFail500WithOperationOutcomeMessage() throws Exception { OperationOutcome oo = new OperationOutcome(); - oo.getIssueFirstRep().getDetails().setValue("Help I'm a bug"); + oo.getIssueFirstRep().getDiagnosticsElement().setValue("Help I'm a bug"); String msg = ourCtx.newXmlParser().encodeResourceToString(oo); String contentType = Constants.CT_FHIR_XML; @@ -93,7 +89,7 @@ public class ExceptionHandlingTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); try { - client.read(Patient.class, new IdType("Patient/1234")); + client.read().resource(Patient.class).withId(new IdType("Patient/1234")).execute(); fail(); } catch (InternalErrorException e) { assertThat(e.getMessage(), StringContains.containsString("HTTP 500 Internal Error")); @@ -118,7 +114,7 @@ public class ExceptionHandlingTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); try { - client.read(Patient.class, new IdType("Patient/1234")); + client.read().resource(Patient.class).withId(new IdType("Patient/1234")).execute(); fail(); } catch (InternalErrorException e) { assertEquals("HTTP 500 Internal Error", e.getMessage()); @@ -130,7 +126,7 @@ public class ExceptionHandlingTest { @Test public void testFail500WithOperationOutcomeMessageJson() throws Exception { OperationOutcome oo = new OperationOutcome(); - oo.getIssueFirstRep().getDetails().setValue("Help I'm a bug"); + oo.getIssueFirstRep().getDiagnosticsElement().setValue("Help I'm a bug"); String msg = ourCtx.newJsonParser().encodeResourceToString(oo); String contentType = Constants.CT_FHIR_JSON; @@ -142,7 +138,7 @@ public class ExceptionHandlingTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); try { - client.read(Patient.class, new IdType("Patient/1234")); + client.read().resource(Patient.class).withId(new IdType("Patient/1234")).execute(); fail(); } catch (InternalErrorException e) { assertThat(e.getMessage(), StringContains.containsString("HTTP 500 Internal Error")); @@ -156,7 +152,7 @@ public class ExceptionHandlingTest { @Test public void testFail500WithOperationOutcomeMessageGeneric() throws Exception { OperationOutcome oo = new OperationOutcome(); - oo.getIssueFirstRep().getDetails().setValue("Help I'm a bug"); + oo.getIssueFirstRep().getDiagnosticsElement().setValue("Help I'm a bug"); String msg = ourCtx.newJsonParser().encodeResourceToString(oo); String contentType = Constants.CT_FHIR_JSON; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientTest.java index 2faddbb27f4..1d9e1ae4303 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/GenericClientTest.java @@ -28,6 +28,8 @@ import org.hamcrest.Matchers; import org.hamcrest.core.StringContains; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Bundle.BundleType; +import org.hl7.fhir.r4.model.Bundle.HTTPVerb; import org.junit.*; import org.mockito.ArgumentCaptor; import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; @@ -47,8 +49,7 @@ import ca.uhn.fhir.rest.client.impl.BaseClient; import ca.uhn.fhir.rest.client.impl.GenericClient; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import ca.uhn.fhir.util.TestUtil; -import ca.uhn.fhir.util.UrlUtil; +import ca.uhn.fhir.util.*; public class GenericClientTest { @@ -139,9 +140,7 @@ public class GenericClientTest { @Test public void testCreatePopulatesIsCreated() throws Exception { - Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); + Patient p1 = createPatientP1(); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -164,12 +163,17 @@ public class GenericClientTest { ourLog.info("lastResponseBody: {}", ((GenericClient)client).getLastResponseBody()); } + private Patient createPatientP1() { + Patient p1 = new Patient(); + p1.addIdentifier().setSystem("foo:bar").setValue("12345"); + p1.addName().setFamily("Smith").addGiven("John"); + return p1; + } + @Test public void testCreateWithStringAutoDetectsEncoding() throws Exception { - Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); + Patient p1 = createPatientP1(); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -218,12 +222,8 @@ public class GenericClientTest { @Test public void testCreateWithTag() throws Exception { - Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); - TagList list = new TagList(); - list.addTag("http://hl7.org/fhir/tag", "urn:happytag", "This is a happy resource"); - ResourceMetadataKeyEnum.TAG_LIST.put(p1, list); + Patient p1 = createPatientP1(); + p1.getMeta().addTag("http://hl7.org/fhir/tag", "urn:happytag", "This is a happy resource"); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -242,9 +242,6 @@ public class GenericClientTest { assertEquals("http://example.com/fhir/Patient", capt.getValue().getURI().toString()); assertEquals("POST", capt.getValue().getMethod()); - Header catH = capt.getValue().getFirstHeader("Category"); - assertNotNull(Arrays.asList(capt.getValue().getAllHeaders()).toString(), catH); - assertEquals("urn:happytag; label=\"This is a happy resource\"; scheme=\"http://hl7.org/fhir/tag\"", catH.getValue()); assertEquals(1, capt.getAllValues().get(count).getHeaders(Constants.HEADER_CONTENT_TYPE).length); assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(count).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); count++; @@ -272,12 +269,8 @@ public class GenericClientTest { @Test public void testCreateWithTagNonFluent() throws Exception { - Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); - TagList list = new TagList(); - list.addTag("http://hl7.org/fhir/tag", "urn:happytag", "This is a happy resource"); - ResourceMetadataKeyEnum.TAG_LIST.put(p1, list); + Patient p1 = createPatientP1(); + p1.getMeta().addTag("http://hl7.org/fhir/tag", "urn:happytag", "This is a happy resource"); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -295,8 +288,7 @@ public class GenericClientTest { assertEquals("http://example.com/fhir/Patient", capt.getValue().getURI().toString()); assertEquals("POST", capt.getValue().getMethod()); Header catH = capt.getValue().getFirstHeader("Category"); - assertNotNull(Arrays.asList(capt.getValue().getAllHeaders()).toString(), catH); - assertEquals("urn:happytag; label=\"This is a happy resource\"; scheme=\"http://hl7.org/fhir/tag\"", catH.getValue()); + assertNull(catH); } /** @@ -307,7 +299,7 @@ public class GenericClientTest { String name = "測試醫院"; Organization org = new Organization(); org.setName(name); - org.addIdentifier("urn:system", "testCreateWithUtf8Characters_01"); + org.addIdentifier().setSystem("urn:system").setValue("testCreateWithUtf8Characters_01"); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -330,7 +322,7 @@ public class GenericClientTest { @Test public void testDelete() throws Exception { OperationOutcome oo = new OperationOutcome(); - oo.addIssue().addLocation().setValue("testDelete01"); + oo.addIssue().addLocation("testDelete01"); String ooStr = ourCtx.newXmlParser().encodeResourceToString(oo); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); @@ -346,7 +338,7 @@ public class GenericClientTest { assertEquals("http://example.com/fhir/Patient/123", capt.getValue().getURI().toString()); assertEquals("DELETE", capt.getValue().getMethod()); - assertEquals("testDelete01", outcome.getIssueFirstRep().getLocationFirstRep().getValue()); + assertEquals("testDelete01", outcome.getIssueFirstRep().getLocation()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader("LKJHLKJGLKJKLL"), Charset.forName("UTF-8"))); outcome = (OperationOutcome) client.delete().resourceById(new IdType("Location", "123", "456")).prettyPrint().encodedJson().execute(); @@ -357,43 +349,6 @@ public class GenericClientTest { } - @Test - public void testGetTags() throws Exception { - - TagList tagList = new TagList(); - tagList.add(new Tag("CCC", "AAA", "BBB")); - String msg = ourCtx.newXmlParser().encodeTagListToString(tagList); - - ArgumentCaptor<HttpUriRequest> 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"))); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - - //@formatter:off - TagList response = client.getTags() - .execute(); - //@formatter:on - - assertEquals("http://example.com/fhir/_tags", capt.getValue().getURI().toString()); - assertEquals(1, response.size()); - assertEquals("CCC", response.get(0).getScheme()); - - // Now for patient - - when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - //@formatter:off - response = client.getTags().forResource(Patient.class) - .execute(); - //@formatter:on - - assertEquals("http://example.com/fhir/Patient/_tags", capt.getValue().getURI().toString()); - assertEquals(1, response.size()); - assertEquals("CCC", response.get(0).getScheme()); - - } @Test public void testHistory() throws Exception { @@ -416,37 +371,31 @@ public class GenericClientTest { int idx = 0; Bundle response; - //@formatter:off response = client .history() .onServer() - .andReturnDstu1Bundle() + .andReturnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/_history", capt.getAllValues().get(idx).getURI().toString()); - assertEquals(1, response.size()); + assertEquals(1, response.getEntry().size()); idx++; - //@formatter:off response = client .history() .onType(Patient.class) - .andReturnDstu1Bundle() + .andReturnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient/_history", capt.getAllValues().get(idx).getURI().toString()); - assertEquals(1, response.size()); + assertEquals(1, response.getEntry().size()); idx++; - //@formatter:off response = client .history() .onInstance(new IdType("Patient", "123")) - .andReturnDstu1Bundle() + .andReturnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient/123/_history", capt.getAllValues().get(idx).getURI().toString()); - assertEquals(1, response.size()); + assertEquals(1, response.getEntry().size()); idx++; } @@ -491,24 +440,26 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off - Patient response = client.read(Patient.class, new IdType("Patient/1234")); - //@formatter:on + Patient response = client + .read() + .resource(Patient.class) + .withId(new IdType("Patient/1234")) + .execute(); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); - assertEquals("http://foo.com/Patient/123/_history/2333", response.getId().getValue()); + assertEquals("http://foo.com/Patient/123/_history/2333", response.getIdElement().getValue()); - InstantDt lm = (InstantDt) response.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); + InstantType lm = response.getMeta().getLastUpdatedElement(); lm.setTimeZoneZulu(true); assertEquals("1995-11-15T04:58:08.000Z", lm.getValueAsString()); - TagList tags = ResourceMetadataKeyEnum.TAG_LIST.get(response); + List<Coding> tags = response.getMeta().getTag(); assertNotNull(tags); assertEquals(1, tags.size()); - assertEquals("http://foo/tagdefinition.html", tags.get(0).getTerm()); - assertEquals("http://hl7.org/fhir/tag", tags.get(0).getScheme()); - assertEquals("Some tag", tags.get(0).getLabel()); + assertEquals("http://hl7.org/fhir/tag", tags.get(0).getSystem()); + assertEquals("http://foo/tagdefinition.html", tags.get(0).getCode()); + assertEquals("Some tag", tags.get(0).getDisplay()); } @@ -531,27 +482,27 @@ public class GenericClientTest { int count = 0; Patient response = client.read().resource(Patient.class).withId(new IdType("Patient/1234")).execute(); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); assertEquals("http://example.com/fhir/Patient/1234", capt.getAllValues().get(count++).getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); response = (Patient) client.read().resource("Patient").withId("1234").execute(); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); assertEquals("http://example.com/fhir/Patient/1234", capt.getAllValues().get(count++).getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); response = (Patient) client.read().resource("Patient").withId(567L).execute(); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); assertEquals("http://example.com/fhir/Patient/567", capt.getAllValues().get(count++).getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); response = client.read().resource(Patient.class).withIdAndVersion("1234", "22").execute(); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); assertEquals("http://example.com/fhir/Patient/1234/_history/22", capt.getAllValues().get(count++).getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); response = client.read().resource(Patient.class).withUrl("http://foo/Patient/22").execute(); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); assertEquals("http://foo/Patient/22", capt.getAllValues().get(count++).getURI().toString()); } @@ -572,14 +523,22 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Patient response = client.read(Patient.class, new IdType("http://somebase.com/path/to/base/Patient/1234")); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); + Patient response = client + .read() + .resource(Patient.class) + .withUrl(new IdType("http://somebase.com/path/to/base/Patient/1234")) + .execute(); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); assertEquals("http://somebase.com/path/to/base/Patient/1234", capt.getAllValues().get(0).getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - response = client.read(Patient.class, new IdType("http://somebase.com/path/to/base/Patient/1234/_history/2222")); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); - assertEquals("http://somebase.com/path/to/base/Patient/1234", capt.getAllValues().get(1).getURI().toString()); + response = client + .read() + .resource(Patient.class) + .withUrl(new IdType("http://somebase.com/path/to/base/Patient/1234/_history/222")) + .execute(); + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); + assertEquals("http://somebase.com/path/to/base/Patient/1234/_history/222", capt.getAllValues().get(1).getURI().toString()); } @@ -597,12 +556,11 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forAllResources() .where(Patient.NAME.matches().value("james")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/?name=james", capt.getValue().getURI().toString()); @@ -624,12 +582,11 @@ public class GenericClientTest { String longValue = StringUtils.leftPad("", 20000, 'B'); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.NAME.matches().value(longValue)) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient/_search", capt.getValue().getURI().toString()); @@ -654,13 +611,11 @@ public class GenericClientTest { when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); IGenericClient client = ourCtx.newRestfulGenericClient("http://foo"); - //@formatter:off client .loadPage() .byUrl("http://example.com/page1") - .andReturnDstu1Bundle() + .andReturnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/page1", capt.getValue().getURI().toString()); } @@ -680,27 +635,26 @@ public class GenericClientTest { when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); IGenericClient client = ourCtx.newRestfulGenericClient("http://foo"); - //@formatter:off Bundle response = client .search() .forResource(Patient.class) .withIdAndCompartment("123", "fooCompartment") .where(Patient.BIRTHDATE.afterOrEquals().day("2011-01-02")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://foo/Patient/123/fooCompartment?birthdate=%3E%3D2011-01-02", capt.getValue().getURI().toString()); - assertEquals("PRP1660", response.getResources(Patient.class).get(0).getIdentifier().get(0).getValue().getValue()); + + assertEquals("PRP1660", BundleUtil.toListOfResourcesOfType(ourCtx, response, Patient.class).get(0).getIdentifier().get(0).getValue()); try { - //@formatter:off client .search() .forResource(Patient.class) .withIdAndCompartment("", "fooCompartment") .where(Patient.BIRTHDATE.afterOrEquals().day("2011-01-02")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on fail(); } catch (InvalidRequestException e) { assertThat(e.toString(), containsString("null or empty for compartment")); @@ -722,17 +676,16 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://foo"); - //@formatter:off Bundle response = client.search() .forResource("Observation") - .where(Observation.NAME_VALUE_DATE - .withLeft(Observation.NAME.exactly().code("FOO$BAR")) + .where(Observation.CODE_VALUE_DATE + .withLeft(Observation.CODE.exactly().code("FOO$BAR")) .withRight(Observation.VALUE_DATE.exactly().day("2001-01-01")) ) + .returnBundle(Bundle.class) .execute(); - //@formatter:on - assertEquals("http://foo/Observation?" + Observation.SP_NAME_VALUE_DATE + "=" + URLEncoder.encode("FOO\\$BAR$2001-01-01", "UTF-8"), capt.getValue().getURI().toString()); + assertEquals("http://foo/Observation?" + Observation.SP_CODE_VALUE_DATE + "=" + URLEncoder.encode("FOO\\$BAR$2001-01-01", "UTF-8"), capt.getValue().getURI().toString()); } @@ -756,48 +709,44 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); int idx = 0; - //@formatter:off @SuppressWarnings("deprecation") Bundle response = client.search() .forResource(Patient.class) .encodedJson() .where(Patient.BIRTHDATE.beforeOrEquals().day("2012-01-22")) .and(Patient.BIRTHDATE.after().day("2011-01-01")) - .include(Patient.INCLUDE_MANAGINGORGANIZATION) + .include(Patient.INCLUDE_ORGANIZATION) .sort().ascending(Patient.BIRTHDATE) .sort().descending(Patient.NAME) .sort().defaultOrder(Patient.ADDRESS) - .limitTo(123) + .count(123) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_sort=address&_count=123&_format=json", capt.getAllValues().get(idx++).getURI().toString()); - //@formatter:off response = client.search() .forResource(Patient.class) .encodedJson() .where(Patient.BIRTHDATE.beforeOrEquals().day("2012-01-22")) .and(Patient.BIRTHDATE.after().day("2011-01-01")) - .include(Patient.INCLUDE_MANAGINGORGANIZATION) + .include(Patient.INCLUDE_ORGANIZATION) .sort().ascending(Patient.BIRTHDATE) .sort().descending(Patient.NAME) .sort().defaultOrder(Patient.ADDRESS) .count(123) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_sort=address&_count=123&_format=json", capt.getAllValues().get(idx++).getURI().toString()); - - //@formatter:off response = client.search() .forResource(Patient.class) .encodedJson() .where(Patient.BIRTHDATE.beforeOrEquals().day("2012-01-22").orAfter().day("2020-01-01")) .and(Patient.BIRTHDATE.after().day("2011-01-01")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on String comma = "%2C"; assertEquals("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22" + comma + "%3E2020-01-01&birthdate=%3E2011-01-01&_format=json", capt.getAllValues().get(idx++).getURI().toString()); @@ -807,7 +756,7 @@ public class GenericClientTest { @Test public void testSearchByNumberExact() throws Exception { - String msg = ourCtx.newXmlParser().encodeBundleToString(new Bundle()); + String msg = ourCtx.newXmlParser().encodeResourceToString(new Bundle()); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -817,15 +766,13 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Observation.class) .where(Observation.VALUE_QUANTITY.greaterThan().number(123).andUnits("foo", "bar")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Observation?value-quantity=%3E123%7Cfoo%7Cbar", capt.getValue().getURI().toString()); - } @SuppressWarnings("unused") @@ -842,13 +789,12 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) .withProfile("http://1") .withProfile("http://2") + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?_profile=http%3A%2F%2F1&_profile=http%3A%2F%2F2", capt.getValue().getURI().toString()); @@ -868,12 +814,11 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) .where(Encounter.LENGTH.exactly().number(123)) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?length=123", capt.getValue().getURI().toString()); @@ -891,16 +836,15 @@ public class GenericClientTest { 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"); Bundle response = client.search() .forResource(Patient.class) - .where(Patient.PROVIDER.hasChainedProperty(Organization.NAME.matches().value("ORG0"))) + .where(Patient.GENERAL_PRACTITIONER.hasChainedProperty(Organization.NAME.matches().value("ORG0"))) + .returnBundle(Bundle.class) .execute(); - assertEquals("http://example.com/fhir/Patient?provider.name=ORG0", capt.getValue().getURI().toString()); - //@formatter:on + assertEquals("http://example.com/fhir/Patient?general-practitioner.name=ORG0", capt.getValue().getURI().toString()); } @@ -918,14 +862,13 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") - .where(Patient.PROVIDER.hasId("123")) + .where(Patient.GENERAL_PRACTITIONER.hasId("123")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on - assertEquals("http://example.com/fhir/Patient?provider=123", capt.getValue().getURI().toString()); + assertEquals("http://example.com/fhir/Patient?general-practitioner=123", capt.getValue().getURI().toString()); } @@ -943,13 +886,12 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) .withSecurity("urn:foo", "123") .withSecurity("urn:bar", "456") + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?_security=urn%3Afoo%7C123&_security=urn%3Abar%7C456", capt.getValue().getURI().toString()); @@ -969,22 +911,20 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.NAME.matches().value("james")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?name=james", capt.getValue().getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - //@formatter:off response = client.search() .forResource("Patient") .where(Patient.NAME.matches().values("AAA", "BBB", "C,C")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?name=" + URLEncoder.encode("AAA,BBB,C\\,C", "UTF-8"), capt.getAllValues().get(1).getURI().toString()); @@ -1004,12 +944,11 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.NAME.matchesExactly().value("james")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?name%3Aexact=james", capt.getValue().getURI().toString()); @@ -1029,13 +968,12 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) .withTag("urn:foo", "123") .withTag("urn:bar", "456") + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?_tag=urn%3Afoo%7C123&_tag=urn%3Abar%7C456", capt.getValue().getURI().toString()); @@ -1056,32 +994,29 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.exactly().systemAndCode("http://example.com/fhir", "ZZZ")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?identifier=http%3A%2F%2Fexample.com%2Ffhir%7CZZZ", capt.getValue().getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - //@formatter:off response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.exactly().code("ZZZ")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?identifier=ZZZ", capt.getAllValues().get(1).getURI().toString()); when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); - //@formatter:off response = client.search() .forResource("Patient") - .where(Patient.IDENTIFIER.exactly().identifiers(new ca.uhn.fhir.model.dstu.composite.IdentifierDt("A", "B"), new ca.uhn.fhir.model.dstu.composite.IdentifierDt("C", "D"))) + .where(Patient.IDENTIFIER.exactly().codings(new Coding("A", "B", "ZZZ"), new Coding("C", "D", "ZZZ"))) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?identifier=" + URLEncoder.encode("A|B,C|D", "UTF-8"), capt.getAllValues().get(2).getURI().toString()); @@ -1108,29 +1043,26 @@ public class GenericClientTest { int idx = 0; - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.hasSystemWithAnyCode("urn:foo")) + .returnBundle(Bundle.class) .execute(); assertEquals("http://example.com/fhir/Patient?identifier=urn%3Afoo%7C", capt.getAllValues().get(idx++).getURI().toString()); - //@formatter:on - //@formatter:off response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.exactly().systemAndCode("urn:foo", null)) + .returnBundle(Bundle.class) .execute(); assertEquals("http://example.com/fhir/Patient?identifier=urn%3Afoo%7C", capt.getAllValues().get(idx++).getURI().toString()); - //@formatter:on - //@formatter:off response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.exactly().systemAndCode("urn:foo", "")) + .returnBundle(Bundle.class) .execute(); assertEquals("http://example.com/fhir/Patient?identifier=urn%3Afoo%7C", capt.getAllValues().get(idx++).getURI().toString()); - //@formatter:on } /** @@ -1156,10 +1088,10 @@ public class GenericClientTest { int index = 0; String wantPrefix = "http://foo/Patient?identifier="; - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.exactly().systemAndCode("1", "2")) + .returnBundle(Bundle.class) .execute(); String wantValue = "1|2"; String url = capt.getAllValues().get(index).getURI().toString(); @@ -1167,12 +1099,11 @@ public class GenericClientTest { assertEquals(wantValue, UrlUtil.unescape(url.substring(wantPrefix.length()))); assertEquals(UrlUtil.escape(wantValue), url.substring(wantPrefix.length())); index++; - //@formatter:on - //@formatter:off response = client.search() .forResource("Patient") .where(Patient.IDENTIFIER.exactly().systemAndCode("1,2", "3,4")) + .returnBundle(Bundle.class) .execute(); wantValue = "1\\,2|3\\,4"; url = capt.getAllValues().get(index).getURI().toString(); @@ -1180,8 +1111,6 @@ public class GenericClientTest { assertEquals(wantValue, UrlUtil.unescape(url.substring(wantPrefix.length()))); assertEquals(UrlUtil.escape(wantValue), url.substring(wantPrefix.length())); index++; - //@formatter:on - } @SuppressWarnings("unused") @@ -1198,18 +1127,17 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) - .include(Patient.INCLUDE_MANAGINGORGANIZATION) - .include(Patient.INCLUDE_LINK_OTHER.asRecursive()) + .include(Patient.INCLUDE_ORGANIZATION) + .include(Patient.INCLUDE_LINK.asRecursive()) .include(Patient.INCLUDE_ALL.asNonRecursive()) - .execute(); - //@formatter:on + .returnBundle(Bundle.class) +.execute(); assertThat(capt.getValue().getURI().toString(), containsString("http://example.com/fhir/Patient?")); - assertThat(capt.getValue().getURI().toString(), containsString("_include=" + Patient.INCLUDE_MANAGINGORGANIZATION.getValue())); - assertThat(capt.getValue().getURI().toString(), containsString("_include%3Arecurse=" + Patient.INCLUDE_LINK_OTHER.getValue())); + assertThat(capt.getValue().getURI().toString(), containsString("_include=" + Patient.INCLUDE_ORGANIZATION.getValue())); + assertThat(capt.getValue().getURI().toString(), containsString("_include%3Arecurse=" + Patient.INCLUDE_LINK.getValue())); assertThat(capt.getValue().getURI().toString(), containsString("_include=*")); } @@ -1228,13 +1156,12 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.NAME.matches().value("james")) .usingStyle(SearchStyleEnum.GET_WITH_SEARCH) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient/_search?name=james", capt.getValue().getURI().toString()); } @@ -1253,13 +1180,12 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.NAME.matches().value("james")) .usingStyle(SearchStyleEnum.POST) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient/_search", capt.getValue().getURI().toString()); @@ -1283,32 +1209,15 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Bundle response = client.search(new UriDt("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_count=123&_format=json")); + Bundle response = client + .search() + .byUrl("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_count=123&_format=json") + .returnBundle(Bundle.class) + .execute(); - assertEquals("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_count=123&_format=json", capt.getValue().getURI().toString()); - - assertEquals(1, response.size()); + assertEquals(1, response.getEntry().size()); } - @Test - public void testSearchWithAbsoluteUrlAndType() throws Exception { - - String msg = getPatientFeedWithOneResult(); - - ArgumentCaptor<HttpUriRequest> 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"))); - - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - - Bundle response = client.search(Patient.class, new UriDt("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_count=123&_format=json")); - - assertEquals("http://example.com/fhir/Patient?birthdate=%3C%3D2012-01-22&birthdate=%3E2011-01-01&_include=Patient.managingOrganization&_sort%3Aasc=birthdate&_sort%3Adesc=name&_count=123&_format=json", capt.getValue().getURI().toString()); - - assertEquals(1, response.size()); - } @SuppressWarnings("unused") @Test @@ -1322,15 +1231,14 @@ public class GenericClientTest { 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"))); - GenericClient client = (GenericClient) ourCtx.newRestfulGenericClient("http://example.com/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); client.setPrettyPrint(true); client.setEncoding(EncodingEnum.JSON); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?_format=json&_pretty=true", capt.getValue().getURI().toString()); @@ -1350,15 +1258,14 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource("Patient") .where(Patient.NAME.matches().values("NE,NE", "NE,NE")) .where(Patient.NAME.matchesExactly().values("E$E")) .where(Patient.NAME.matches().values("NE\\NE")) .where(Patient.NAME.matchesExactly().values("E|E")) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertThat(capt.getValue().getURI().toString(), containsString("%3A")); assertEquals("http://example.com/fhir/Patient?name=NE\\,NE,NE\\,NE&name=NE\\\\NE&name:exact=E\\$E&name:exact=E\\|E", UrlUtil.unescape(capt.getValue().getURI().toString())); @@ -1425,13 +1332,12 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.search() .forResource(Patient.class) .encodedJson() .revInclude(Provenance.INCLUDE_TARGET) + .returnBundle(Bundle.class) .execute(); - //@formatter:on assertEquals("http://example.com/fhir/Patient?_revinclude=Provenance.target&_format=json", capt.getValue().getURI().toString()); @@ -1459,7 +1365,11 @@ public class GenericClientTest { (client).setEncoding(EncodingEnum.JSON); int count = 0; - client.read(Patient.class, new IdType("Patient/1234")); + client + .read() + .resource(Patient.class) + .withId(new IdType("Patient/1234")) + .execute(); assertEquals("http://example.com/fhir/Patient/1234?_format=json", capt.getAllValues().get(count).getURI().toString()); count++; @@ -1467,88 +1377,84 @@ public class GenericClientTest { @Test public void testTransaction() throws Exception { - String bundleStr = IOUtils.toString(getClass().getResourceAsStream("/bundle.json")); - Bundle bundle = ourCtx.newJsonParser().parseBundle(bundleStr); - + Bundle input = createTransactionBundleInput(); + Bundle output = createTransactionBundleOutput(); + + String msg = ourCtx.newJsonParser().encodeResourceToString(output); + ArgumentCaptor<HttpUriRequest> 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(bundleStr), Charset.forName("UTF-8"))); + when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - //@formatter:off Bundle response = client.transaction() - .withBundle(bundle) + .withBundle(input) .execute(); - //@formatter:on assertEquals("http://example.com/fhir", capt.getValue().getURI().toString()); - assertEquals(bundle.getEntries().get(0).getResource().getId(), response.getEntries().get(0).getResource().getId()); + assertEquals(input.getEntry().get(0).getResource().getId(), response.getEntry().get(0).getResource().getId()); assertEquals(EncodingEnum.XML.getBundleContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(0).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); } - @SuppressWarnings("deprecation") - @Test - public void testTransactionOldStyle() throws Exception { - String bundleStr = IOUtils.toString(getClass().getResourceAsStream("/bundle.json")); - Bundle bundle = ourCtx.newJsonParser().parseBundle(bundleStr); + @Test + public void testTransactionXml() throws Exception { + Bundle input = createTransactionBundleInput(); + Bundle output = createTransactionBundleOutput(); + + String msg = ourCtx.newXmlParser().encodeResourceToString(output); + + ArgumentCaptor<HttpUriRequest> 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"))); - ArgumentCaptor<HttpUriRequest> 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(bundleStr), Charset.forName("UTF-8"))); + IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + Bundle response = client.transaction() + .withBundle(input) + .execute(); - List<IBaseResource> input = new ArrayList<IBaseResource>(); - input.addAll(bundle.toListOfResources()); - client.transaction(input); - } + assertEquals("http://example.com/fhir", capt.getValue().getURI().toString()); + assertEquals(input.getEntry().get(0).getResource().getId(), response.getEntry().get(0).getResource().getId()); + assertEquals(EncodingEnum.XML.getBundleContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(0).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue()); - @Test - public void testTransactionJson() throws Exception { - String bundleStr = IOUtils.toString(getClass().getResourceAsStream("/bundle.json")); - Bundle bundle = ourCtx.newJsonParser().parseBundle(bundleStr); + } - ArgumentCaptor<HttpUriRequest> 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(bundleStr), Charset.forName("UTF-8"))); + private Bundle createTransactionBundleOutput() { + Bundle output = new Bundle(); + output.setType(BundleType.TRANSACTIONRESPONSE); + output + .addEntry() + .setResource(createPatientP1()) + .getResponse() + .setLocation(createPatientP1().getId()); + return output; + } - IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); + private Bundle createTransactionBundleInput() { + Bundle input = new Bundle(); + input.setType(BundleType.TRANSACTION); + input + .addEntry() + .setResource(createPatientP1()) + .getRequest() + .setMethod(HTTPVerb.POST); + return input; + } - //@formatter:off - Bundle response = client.transaction() - .withBundle(bundle) - .encodedJson() - .execute(); - //@formatter:on - HttpEntityEnclosingRequestBase value = (HttpEntityEnclosingRequestBase) capt.getValue(); - - Header ct = value.getFirstHeader(Constants.HEADER_CONTENT_TYPE); - assertNotNull(ct); - assertEquals(Constants.CT_FHIR_JSON + "; charset=UTF-8", ct.getValue()); - - assertEquals("http://example.com/fhir", value.getURI().toString()); - assertThat(IOUtils.toString(value.getEntity().getContent()), StringContains.containsString("\"resourceType\"")); - assertEquals(bundle.getEntries().get(0).getResource().getId(), response.getEntries().get(0).getResource().getId()); - } @Test public void testUpdate() throws Exception { Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); - TagList list = new TagList(); - list.addTag("http://hl7.org/fhir/tag", "urn:happytag", "This is a happy resource"); - ResourceMetadataKeyEnum.TAG_LIST.put(p1, list); + p1.addIdentifier().setSystem("foo:bar").setValue("12345"); + p1.addName().setFamily("Smith").addGiven("John"); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -1612,9 +1518,9 @@ public class GenericClientTest { @Test public void testUpdateWithStringAutoDetectsEncoding() throws Exception { - Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); + Patient p1 = new Patient(); + p1.addIdentifier().setSystem("foo:bar").setValue("12345"); + p1.addName().setFamily("Smith").addGiven("John"); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -1659,7 +1565,7 @@ public class GenericClientTest { public void testValidateNonFluent() throws Exception { OperationOutcome oo = new OperationOutcome(); - oo.addIssue().setDetails("OOOK"); + oo.addIssue().setDiagnostics("OOOK"); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); @@ -1670,14 +1576,14 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Patient p1 = new Patient(); - p1.addIdentifier("foo:bar", "12345"); - p1.addName().addFamily("Smith").addGiven("John"); + Patient p1 = new Patient(); + p1.addIdentifier().setSystem("foo:bar").setValue("12345"); + p1.addName().setFamily("Smith").addGiven("John"); MethodOutcome resp = client.validate(p1); assertEquals("http://example.com/fhir/Patient/_validate", capt.getValue().getURI().toString()); oo = (OperationOutcome) resp.getOperationOutcome(); - assertEquals("OOOK", oo.getIssueFirstRep().getDetails().getValue()); + assertEquals("OOOK", oo.getIssueFirstRep().getDiagnostics()); } @@ -1697,22 +1603,20 @@ public class GenericClientTest { IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); - Patient response = client.vread(Patient.class, new IdType("http://somebase.com/path/to/base/Patient/1234/_history/2222")); - assertThat(response.getNameFirstRep().getFamilyAsSingleString(), StringContains.containsString("Cardinal")); - assertEquals("http://somebase.com/path/to/base/Patient/1234/_history/2222", capt.getAllValues().get(0).getURI().toString()); + Patient response = client + .read() + .resource(Patient.class) + .withUrl("http://somebase.com/path/to/base/Patient/1234/_history/2222") + .execute(); - try { - client.vread(Patient.class, new IdType("http://somebase.com/path/to/base/Patient/1234")); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("No version specified in URL")); - } + assertThat(response.getNameFirstRep().getFamily(), StringContains.containsString("Cardinal")); + assertEquals("http://somebase.com/path/to/base/Patient/1234/_history/2222", capt.getAllValues().get(0).getURI().toString()); } @BeforeClass public static void beforeClass() { - ourCtx = FhirContext.forDstu1(); + ourCtx = FhirContext.forR4(); } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java index 30ad6ce7c4c..948dce39cef 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java @@ -1,6 +1,6 @@ package ca.uhn.fhir.rest.client; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.IOException; @@ -9,28 +9,18 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.EnumerationUtils; -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.ProxyAuthenticationStrategy; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.hl7.fhir.r4.model.IdType; +import org.hl7.fhir.r4.model.Patient; +import org.junit.*; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.IResource; -import ca.uhn.fhir.model.dstu.resource.Patient; -import ca.uhn.fhir.model.primitive.IdType; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.util.PortUtil; @@ -112,7 +102,7 @@ public class HttpProxyTest { IGenericClient client = ourCtx.newRestfulGenericClient(baseUri); IdType id = new IdType("Patient", "123"); - client.read(Patient.class, id); + client.read().resource(Patient.class).withId(id).execute(); assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", myAuthHeader); @@ -124,13 +114,13 @@ public class HttpProxyTest { @BeforeClass public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu1(); + ourCtx = FhirContext.forR4(); } public static class PatientResourceProvider implements IResourceProvider { @Override - public Class<? extends IResource> getResourceType() { + public Class<Patient> getResourceType() { return Patient.class; } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ITestClient.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ITestClient.java index 32d37998144..15f2d88c9c0 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ITestClient.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ITestClient.java @@ -3,11 +3,11 @@ package ca.uhn.fhir.rest.client; import java.util.Date; import java.util.List; +import org.hl7.fhir.instance.model.api.IAnyResource; +import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.*; -import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.Include; -import ca.uhn.fhir.model.primitive.*; import ca.uhn.fhir.rest.annotation.*; import ca.uhn.fhir.rest.annotation.Count; import ca.uhn.fhir.rest.api.MethodOutcome; @@ -29,9 +29,12 @@ public interface ITestClient extends IBasicClient { public List<Patient> getPatientByDob(@RequiredParam(name=Patient.SP_BIRTHDATE) DateParam theBirthDate); @Search(type=ExtendedPatient.class) - public List<IResource> getPatientByDobWithGenericResourceReturnType(@RequiredParam(name=Patient.SP_BIRTHDATE) DateParam theBirthDate); + public List<IBaseResource> getPatientByDobWithGenericResourceReturnType(@RequiredParam(name=Patient.SP_BIRTHDATE) DateParam theBirthDate); - @Search() + @Search(type=ExtendedPatient.class) + public List<IAnyResource> getPatientByDobWithGenericResourceReturnType2(@RequiredParam(name=Patient.SP_BIRTHDATE) DateParam theBirthDate); + + @Search() public List<Patient> getPatientMultipleIdentifiers(@RequiredParam(name = "ids") TokenOrListParam theIdentifiers); @Search(queryName="someQueryNoParams") @@ -65,7 +68,7 @@ public interface ITestClient extends IBasicClient { Bundle getHistoryPatientInstance(@IdParam IdType theId); @History(type=Patient.class) - Bundle getHistoryPatientInstance(@IdParam IdType theId, @Since InstantDt theSince, @Count IntegerDt theCount); + Bundle getHistoryPatientInstance(@IdParam IdType theId, @Since InstantType theSince, @Count IntegerType theCount); @History(type=Patient.class) Bundle getHistoryPatientInstance(@IdParam IdType theId, @Since Date theSince, @Count Integer theCount); @@ -83,7 +86,7 @@ public interface ITestClient extends IBasicClient { MethodOutcome validatePatient(@ResourceParam Patient thePatient); @Search(type=Patient.class) - Patient findPatientQuantity(@RequiredParam(name="quantityParam") QuantityParam theQuantityDt); + Patient findPatientQuantity(@RequiredParam(name="quantityParam") QuantityParam theQuantityType); @Search(compartmentName="compartmentName") public List<Patient> getPatientByCompartmentAndDob(@IdParam IdType theIdType, @RequiredParam(name=Patient.SP_BIRTHDATE) DateParam theBirthDate); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/IncludedResourceStitchingClientTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/IncludedResourceStitchingClientTest.java index e35217694ad..a5c1c180cd7 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/IncludedResourceStitchingClientTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/IncludedResourceStitchingClientTest.java @@ -23,8 +23,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.ExtensionDt; -import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; @@ -92,99 +90,112 @@ public class IncludedResourceStitchingClientTest { when(httpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(createLinkedBundle()), Charset.forName("UTF-8"))); IGenericClient client = ctx.newRestfulGenericClient( "http://foo"); - Bundle bundle = client.search().forResource(IncludeTest.ExtPatient.class).execute(); + Bundle bundle = client.search().forResource(IncludeTest.ExtPatient.class).returnBundle(Bundle.class).execute(); assertEquals(HttpGet.class, capt.getValue().getClass()); HttpGet get = (HttpGet) capt.getValue(); assertEquals("http://foo/Patient", get.getURI().toString()); - assertEquals(4, bundle.size()); + assertEquals(4, bundle.getEntry().size()); ExtPatient p = (ExtPatient) bundle.getEntry().get(0).getResource(); - ResourceReferenceDt ref = (ResourceReferenceDt) p.getSecondOrg(); - assertEquals("Organization/o1", ref.getReference().getValue()); + Reference ref = (Reference) p.getSecondOrg(); + assertEquals("Organization/o1", ref.getReferenceElement().getValue()); assertNotNull(ref.getResource()); Organization o1 = (Organization) ref.getResource(); - assertEquals("o2", o1.getPartOf().getReference().toUnqualifiedVersionless().getIdPart()); + assertEquals("o2", o1.getPartOf().getReferenceElement().toUnqualifiedVersionless().getIdPart()); assertNotNull(o1.getPartOf().getResource()); } private String createLinkedBundle() { - //@formatter:off - return "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n" + - " <title/>\n" + - " <id>6cfcd90e-877a-40c6-a11c-448006712979</id>\n" + - " <link rel=\"self\" href=\"http://localhost:49782/Patient?_query=declaredExtInclude&_pretty=true\"/>\n" + - " <link rel=\"fhir-base\" href=\"http://localhost:49782\"/>\n" + - " <os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults>\n" + - " <author>\n" + - " <name>HAPI FHIR Server</name>\n" + - " </author>\n" + - " <entry>\n" + - " <title>Patient p1\n" + - " http://localhost:49782/Patient/p1\n" + - " 2014-08-12T10:22:19-04:00\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " Patient p2\n" + - " http://localhost:49782/Patient/p2\n" + - " 2014-08-12T10:22:19-04:00\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " Organization o1\n" + - " http://localhost:49782/Organization/o1\n" + - " 2014-08-12T10:22:19-04:00\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " Organization o2\n" + - " http://localhost:49782/Organization/o2\n" + - " 2014-08-12T10:22:19-04:00\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - //@formatter:on + + Bundle bundle = new Bundle(); + + Patient p1 = new Patient(); + p1.addIdentifier().setValue("p1"); + bundle.addEntry().setResource(p1); + + Patient p2 = new Patient(); + p2.addIdentifier().setValue("p1"); + bundle.addEntry().setResource(p2); + + return ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(bundle); + +// //@formatter:off +// return "\n" + +// " \n" + +// " <id>6cfcd90e-877a-40c6-a11c-448006712979</id>\n" + +// " <link rel=\"self\" href=\"http://localhost:49782/Patient?_query=declaredExtInclude&_pretty=true\"/>\n" + +// " <link rel=\"fhir-base\" href=\"http://localhost:49782\"/>\n" + +// " <os:totalResults xmlns:os=\"http://a9.com/-/spec/opensearch/1.1/\">2</os:totalResults>\n" + +// " <author>\n" + +// " <name>HAPI FHIR Server</name>\n" + +// " </author>\n" + +// " <entry>\n" + +// " <title>Patient p1\n" + +// " http://localhost:49782/Patient/p1\n" + +// " 2014-08-12T10:22:19-04:00\n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " Patient p2\n" + +// " http://localhost:49782/Patient/p2\n" + +// " 2014-08-12T10:22:19-04:00\n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " Organization o1\n" + +// " http://localhost:49782/Organization/o1\n" + +// " 2014-08-12T10:22:19-04:00\n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " Organization o2\n" + +// " http://localhost:49782/Organization/o2\n" + +// " 2014-08-12T10:22:19-04:00\n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// " \n" + +// ""; +// //@formatter:on } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java index 11d04d1abb3..ca48c155139 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java @@ -404,12 +404,12 @@ public class IncludeTest { Patient p1 = new Patient(); p1.setId("p1"); p1.addIdentifier().setValue("p1"); - p1.addUndeclaredExtension(false, "http://foo", new Reference(o1)); + p1.addExtension(new org.hl7.fhir.r4.model.Extension("http://foo", new Reference(o1))); Patient p2 = new Patient(); p2.setId("p2"); p2.addIdentifier().setValue("p2"); - p2.addUndeclaredExtension(false, "http://foo", new Reference(o1)); + p2.addExtension(new org.hl7.fhir.r4.model.Extension( "http://foo", new Reference(o1))); return Arrays.asList(p1, p2); } @@ -419,13 +419,13 @@ public class IncludeTest { ArrayList retVal = new ArrayList(); Patient p = new Patient(); - p.addIdentifier("Mr", "Test"); + p.addIdentifier().setSystem("Mr").setValue("Test"); p.setId(theName.getValue()); if (theIncludes != null) { for (Include next : theIncludes) { - p.addName().setFamily().setValue(next.getValue()); + p.addName().setFamily(next.getValue()); } } retVal.add(p); @@ -434,7 +434,7 @@ public class IncludeTest { } @Override - public Class getResourceType() { + public Class getResourceType() { return Patient.class; }