Fix $everything operation in generic client if the server returns JSON

This commit is contained in:
James Agnew 2015-05-29 17:50:18 -04:00
parent 11d22b1b1f
commit 3280375486
12 changed files with 1362 additions and 1262 deletions

View File

@ -1221,15 +1221,8 @@ public class JsonParser extends BaseParser implements IParser {
assertObjectOfType(resourceTypeObj, JsonValue.ValueType.STRING, "resourceType");
String resourceType = ((JsonString) resourceTypeObj).getString();
RuntimeResourceDefinition def;
if (theResourceType != null) {
def = myContext.getResourceDefinition(theResourceType);
} else {
def = myContext.getResourceDefinition(resourceType);
}
ParserState<? extends IBaseResource> state = ParserState.getPreResourceInstance(def.getImplementingClass(), myContext, true, getErrorHandler());
state.enteringNewElement(null, def.getName());
ParserState<? extends IBaseResource> state = ParserState.getPreResourceInstance(theResourceType, myContext, true, getErrorHandler());
state.enteringNewElement(null, resourceType);
parseChildren(object, state);

View File

@ -488,7 +488,7 @@ class ParserState<T> {
} else if ("author".equals(theLocalPart)) {
push(new AtomAuthorState(myEntry));
} else if ("content".equals(theLocalPart)) {
push(new PreResourceStateHapi(myEntry, myResourceType));
push(new PreResourceStateHapi(myEntry, myResourceType).setRequireResourceType(false));
} else if ("summary".equals(theLocalPart)) {
push(new XhtmlState(getPreResourceState(), myEntry.getSummary(), false));
} else if ("category".equals(theLocalPart)) {
@ -794,7 +794,6 @@ class ParserState<T> {
myPreResourceState = thePreResourceState;
}
@SuppressWarnings("unused")
public void attributeValue(String theName, String theValue) throws DataFormatException {
myErrorHandler.unknownAttribute(null, theName);
}
@ -803,7 +802,6 @@ class ParserState<T> {
// ignore by default
}
@SuppressWarnings("unused")
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
myErrorHandler.unknownElement(null, theLocalPart);
}
@ -1053,7 +1051,7 @@ class ParserState<T> {
} else if ("score".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getScore()));
} else if ("resource".equals(theLocalPart)) {
push(new PreResourceStateHapi(myEntry, myResourceType));
push(new PreResourceStateHapi(myEntry, myResourceType).setRequireResourceType(false));
} else if ("deleted".equals(theLocalPart)) {
push(new BundleEntryDeletedState(getPreResourceState(), myEntry));
} else {
@ -1987,6 +1985,12 @@ class ParserState<T> {
private IBaseResource myInstance;
private FhirVersionEnum myParentVersion;
private Class<? extends IBaseResource> myResourceType;
private boolean myRequireResourceType = true;
public ParserState<T>.PreResourceState setRequireResourceType(boolean theRequireResourceType) {
myRequireResourceType = theRequireResourceType;
return this;
}
public PreResourceState(Class<? extends IBaseResource> theResourceType) {
super(null);
@ -2020,6 +2024,9 @@ class ParserState<T> {
} else {
definition = myContext.getResourceDefinition(myResourceType);
if (!StringUtils.equals(theLocalPart, definition.getName())) {
if (myRequireResourceType) {
throw new DataFormatException(myContext.getLocalizer().getMessage(ParserState.class, "wrongResourceTypeFound", definition.getName(), theLocalPart));
}
definition = myContext.getResourceDefinition(theLocalPart);
if (!(definition instanceof RuntimeResourceDefinition)) {
throw new DataFormatException("Element '" + theLocalPart + "' is not a resource, expected a resource at this position");
@ -2573,13 +2580,19 @@ class ParserState<T> {
return myDt;
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
// IGNORE - don't handle this as an error, we process these as XML events
}
@Override
public void attributeValue(String theName, String theValue) throws DataFormatException {
if (myJsonMode) {
myDt.setValueAsString(theValue);
return;
} else {
// IGNORE - don't handle this as an error, we process these as XML events
}
super.attributeValue(theName, theValue);
}
protected void doPop() {

View File

@ -1144,7 +1144,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
BaseHttpClientInvocation invocation = OperationMethodBinding.createOperationInvocation(myContext, resourceName, id, myOperationName, myParameters, myUseHttpGet);
IClientResponseHandler handler;
handler = new ResourceResponseHandler(myParameters.getClass(), null);
handler = new ResourceResponseHandler(null, null);
Object retVal = invoke(null, handler, invocation);
if (myContext.getResourceDefinition((IBaseResource) retVal).getName().equals("Parameters")) {

View File

@ -25,6 +25,8 @@ ca.uhn.fhir.rest.method.SearchMethodBinding.invalidSpecialParamName=Method [{0}]
ca.uhn.fhir.rest.method.SearchMethodBinding.idWithoutCompartment=Method [{0}] in provider [{1}] has an @IdParam parameter. This is only allowable for compartment search (e.g. @Search(compartment="foo") )
ca.uhn.fhir.rest.method.SearchMethodBinding.idNullForCompartmentSearch=ID parameter can not be null or empty for compartment search
ca.uhn.fhir.parser.ParserState.wrongResourceTypeFound=Incorrect resource type found, expected "{0}" but found "{1}"
ca.uhn.fhir.rest.server.RestfulServer.getPagesNonHttpGet=Requests for _getpages must use HTTP GET
ca.uhn.fhir.validation.FhirValidator.noPhlocWarningOnStartup=Phloc-schematron library not found on classpath, will not attempt to perform schematron validation

View File

@ -76,6 +76,7 @@ import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.client.ServerValidationModeEnum;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.gclient.StringClientParam;
import ca.uhn.fhir.rest.gclient.TokenClientParam;
@ -388,6 +389,7 @@ public class ResourceProviderDstu2Test {
assertEquals(Patient.class, found.getEntries().get(0).getResource().getClass());
assertEquals(BundleEntrySearchModeEnum.MATCH, found.getEntries().get(0).getSearchMode().getValueAsEnum());
assertEquals(BundleEntrySearchModeEnum.MATCH, found.getEntries().get(0).getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE));
assertThat(found.getEntries().get(0).getResource().getText().getDiv().getValueAsString(), containsString("<table class=\"hapiPropertyTable"));
assertEquals(Organization.class, found.getEntries().get(1).getResource().getClass());
assertEquals(BundleEntrySearchModeEnum.INCLUDE, found.getEntries().get(1).getSearchMode().getValueAsEnum());
assertEquals(BundleEntrySearchModeEnum.INCLUDE, found.getEntries().get(1).getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE));
@ -981,6 +983,7 @@ public class ResourceProviderDstu2Test {
ourServer.setHandler(proxyHandler);
ourServer.start();
ourFhirCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourFhirCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
ourClient = ourFhirCtx.newRestfulGenericClient(ourServerBase);
// ourClient.registerInterceptor(new LoggingInterceptor(true));

View File

@ -76,77 +76,6 @@ public class XmlParserTest {
private static FhirContext ourCtx;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(XmlParserTest.class);
@Test
public void testParseErrorHandlerNoError() {
String input = "<Patient></Patient>";
ourCtx.newXmlParser().setParserErrorHandler(new StrictErrorHandler()).parseResource(Patient.class, input);
}
@Test
public void testParseErrorHandlerUnexpectedElement() {
String input = "<Patient><foo><bar/></foo><name><family value=\"AAA\"/></name></Patient>";
try {
ourCtx.newXmlParser().setParserErrorHandler(new StrictErrorHandler()).parseResource(Patient.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("'foo'"));
}
Patient p = ourCtx.newXmlParser().setParserErrorHandler(new LenientErrorHandler()).parseResource(Patient.class, input);
assertEquals(p.getName().get(0).getFamily().get(0).getValue(), "AAA");
}
@Test
public void testParseErrorHandlerUnexpectedAttribute() {
String input = "<Patient><name><family foo=\"FOO\" value=\"AAA\" bar=\"BAR\"/></name></Patient>";
try {
ourCtx.newXmlParser().setParserErrorHandler(new StrictErrorHandler()).parseResource(Patient.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("'foo'"));
}
Patient p = ourCtx.newXmlParser().setParserErrorHandler(new LenientErrorHandler()).parseResource(Patient.class, input);
assertEquals(p.getName().get(0).getFamily().get(0).getValue(), "AAA");
}
/**
* see #144 and #146
*/
@Test
public void testParseContained() {
FhirContext c = FhirContext.forDstu1();
IParser parser = c.newXmlParser().setPrettyPrint(true);
Observation o = new Observation();
o.getName().setText("obs text");
Patient p = new Patient();
p.addName().addFamily("patient family");
o.getSubject().setResource(p);
String enc = parser.encodeResourceToString(o);
ourLog.info(enc);
//@formatter:off
assertThat(enc, stringContainsInOrder(
"<Observation xmlns=\"http://hl7.org/fhir\">",
"<contained>",
"<Patient xmlns=\"http://hl7.org/fhir\" id=\"1\">",
"</contained>",
"<reference value=\"#1\"/>"
));
//@formatter:on
o = parser.parseResource(Observation.class, enc);
assertEquals("obs text", o.getName().getText().getValue());
assertNotNull(o.getSubject().getResource());
p = (Patient) o.getSubject().getResource();
assertEquals("patient family", p.getNameFirstRep().getFamilyAsSingleString());
}
@Test
public void testComposition() {
@ -163,39 +92,76 @@ public class XmlParserTest {
}
/**
* See #131
* Test for #82 - Not yet enabled because the test won't pass
*/
@Test
public void testParseAndReencodeCondition() {
FhirContext ctx = FhirContext.forDstu1();
ctx.setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());
InputStreamReader reader = new InputStreamReader(XmlParserTest.class.getResourceAsStream("/condition.xml"));
Condition cond = ctx.newXmlParser().parseResource(Condition.class, reader);
// @Test
public void testCustomTypeInExtension() throws DataFormatException {
String enc = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(cond);
ourLog.info(enc);
MyPatient patient = new MyPatient();
patient.addName().addFamily("PatientName");
assertThat(enc, not(containsString("generated")));
MyOrganization org = new MyOrganization();
org.setName("OrgName");
patient.getSomeOrganization().setResource(org);
String str = ourCtx.newXmlParser().encodeResourceToString(patient);
ourLog.info(str);
assertThat(
str,
Matchers.stringContainsInOrder("<Patient xmlns=\"http://hl7.org/fhir\"><extension url=\"http://foo/someOrg\"><valueResource><reference value=\"#1\"/></valueResource></extension><contained><Organization xmlns=\"http://hl7.org/fhir\" id=\"1\"><name value=\"OrgName\"/></Organization></contained><name><family value=\"PatientName\"/></name></Patient>"));
MyPatient parse = ourCtx.newXmlParser().parseResource(MyPatient.class, str);
assertEquals("PatientName", parse.getNameFirstRep().getFamilyAsSingleString());
assertEquals("OrgName", ((MyOrganization) parse.getSomeOrganization().getResource()).getName().getValue());
}
/**
* Test for #82 - Not yet enabled because the test won't pass
*/
// @Test
public void testCustomTypeInReplaceParent() throws DataFormatException {
MyPatient patient = new MyPatient();
patient.addName().addFamily("PatientName");
MyOrganization org = new MyOrganization();
org.setName("OrgName");
patient.getManagingOrganization().setResource(org);
String str = ourCtx.newXmlParser().encodeResourceToString(patient);
ourLog.info(str);
assertThat(
str,
Matchers.stringContainsInOrder("<Patient xmlns=\"http://hl7.org/fhir\"><contained><Organization xmlns=\"http://hl7.org/fhir\" id=\"1\"><name value=\"OrgName\"/></Organization></contained><name><family value=\"PatientName\"/></name><managingOrganization><reference value=\"#1\"/></managingOrganization></Patient>"));
MyPatient parse = ourCtx.newXmlParser().parseResource(MyPatient.class, str);
assertEquals("PatientName", parse.getNameFirstRep().getFamilyAsSingleString());
assertEquals("OrgName", ((MyOrganization) parse.getManagingOrganization().getResource()).getName().getValue());
}
/**
* See #91
*/
@Test
public void testEncodeOmitsVersionAndBase() {
Patient p = new Patient();
p.getManagingOrganization().setReference("http://example.com/base/Patient/1/_history/2");
public void testCustomTypeWithUnoderedExtensions() {
MyPatientWithUnorderedExtensions pat = new MyPatientWithUnorderedExtensions();
pat.getExtAtt1().setValue(true);
pat.getExtAtt2().setValue("val2");
pat.getExtAtt3().setValueAsString("20110102");
String enc;
String string = ourCtx.newXmlParser().encodeResourceToString(pat);
ourLog.info(string);
enc = ourCtx.newXmlParser().encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
//@formatter:off
assertThat(string, stringContainsInOrder(Arrays.asList(
"<extension url=\"urn:ex1\"><valueBoolean value=\"true\"/></extension>",
"<extension url=\"urn:ex2\"><valueString value=\"val2\"/></extension>",
"<extension url=\"urn:ex3\"><valueDate value=\"20110102\"/></extension>"
)));
//@formatter:on
enc = ourCtx.newXmlParser().setServerBaseUrl("http://example.com/base").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"Patient/1\""));
enc = ourCtx.newXmlParser().setServerBaseUrl("http://example.com/base2").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
}
@Test
@ -217,43 +183,6 @@ public class XmlParserTest {
}
@Test
public void testEncodeBinaryResource() {
Binary patient = new Binary();
patient.setContentType("foo");
patient.setContent(new byte[] { 1, 2, 3, 4 });
String val = ourCtx.newXmlParser().encodeResourceToString(patient);
assertEquals("<Binary xmlns=\"http://hl7.org/fhir\" contentType=\"foo\">AQIDBA==</Binary>", val);
}
@Test
public void testEncodeBinaryWithNoContentType() {
Binary b = new Binary();
b.setContent(new byte[] { 1, 2, 3, 4 });
String output = ourCtx.newXmlParser().encodeResourceToString(b);
ourLog.info(output);
assertEquals("<Binary xmlns=\"http://hl7.org/fhir\">AQIDBA==</Binary>", output);
}
@Test
public void testEncodeBoundCode() {
Patient patient = new Patient();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.getGender().setValueAsEnum(AdministrativeGenderCodesEnum.M);
String val = ourCtx.newXmlParser().encodeResourceToString(patient);
ourLog.info(val);
}
@Test
public void testEncodeAndParseExtensions() throws Exception {
@ -301,7 +230,9 @@ public class XmlParserTest {
enc,
containsString("<extension url=\"http://example.com#parent\"><extension url=\"http://example.com#child\"><valueString value=\"value1\"/></extension><extension url=\"http://example.com#child\"><valueString value=\"value2\"/></extension></extension>"));
assertThat(enc, containsString("<given value=\"Joe\"><extension url=\"http://examples.com#givenext\"><valueString value=\"given\"/></extension></given>"));
assertThat(enc, containsString("<given value=\"Shmoe\"><extension url=\"http://examples.com#givenext_parent\"><extension url=\"http://examples.com#givenext_child\"><valueString value=\"CHILD\"/></extension></extension></given>"));
assertThat(
enc,
containsString("<given value=\"Shmoe\"><extension url=\"http://examples.com#givenext_parent\"><extension url=\"http://examples.com#givenext_child\"><valueString value=\"CHILD\"/></extension></extension></given>"));
/*
* Now parse this back
@ -341,6 +272,91 @@ public class XmlParserTest {
}
/**
* See #103
*/
@Test
public void testEncodeAndReEncodeContainedJson() {
Composition comp = new Composition();
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
IParser parser = ourCtx.newJsonParser().setPrettyPrint(true);
String string = parser.encodeResourceToString(comp);
ourLog.info(string);
Composition parsed = parser.parseResource(Composition.class, string);
parsed.getSection().remove(0);
string = parser.encodeResourceToString(parsed);
ourLog.info(string);
parsed = parser.parseResource(Composition.class, string);
assertEquals(2, parsed.getContained().getContainedResources().size());
}
/**
* See #103
*/
@Test
public void testEncodeAndReEncodeContainedXml() {
Composition comp = new Composition();
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
IParser parser = ourCtx.newXmlParser().setPrettyPrint(true);
String string = parser.encodeResourceToString(comp);
ourLog.info(string);
Composition parsed = parser.parseResource(Composition.class, string);
parsed.getSection().remove(0);
string = parser.encodeResourceToString(parsed);
ourLog.info(string);
parsed = parser.parseResource(Composition.class, string);
assertEquals(2, parsed.getContained().getContainedResources().size());
}
@Test
public void testEncodeBinaryResource() {
Binary patient = new Binary();
patient.setContentType("foo");
patient.setContent(new byte[] { 1, 2, 3, 4 });
String val = ourCtx.newXmlParser().encodeResourceToString(patient);
assertEquals("<Binary xmlns=\"http://hl7.org/fhir\" contentType=\"foo\">AQIDBA==</Binary>", val);
}
@Test
public void testEncodeBinaryWithNoContentType() {
Binary b = new Binary();
b.setContent(new byte[] { 1, 2, 3, 4 });
String output = ourCtx.newXmlParser().encodeResourceToString(b);
ourLog.info(output);
assertEquals("<Binary xmlns=\"http://hl7.org/fhir\">AQIDBA==</Binary>", output);
}
@Test
public void testEncodeBoundCode() {
Patient patient = new Patient();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.getGender().setValueAsEnum(AdministrativeGenderCodesEnum.M);
String val = ourCtx.newXmlParser().encodeResourceToString(patient);
ourLog.info(val);
}
@Test
public void testEncodeBundle() throws InterruptedException {
@ -761,6 +777,26 @@ public class XmlParserTest {
}
@Test
public void testEncodeOmitsVersionAndBase() {
Patient p = new Patient();
p.getManagingOrganization().setReference("http://example.com/base/Patient/1/_history/2");
String enc;
enc = ourCtx.newXmlParser().encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
enc = ourCtx.newXmlParser().setServerBaseUrl("http://example.com/base").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"Patient/1\""));
enc = ourCtx.newXmlParser().setServerBaseUrl("http://example.com/base2").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
}
@Test
public void testEncodePrettyPrint() throws DataFormatException {
@ -940,56 +976,6 @@ public class XmlParserTest {
}
/**
* Test for #82 - Not yet enabled because the test won't pass
*/
// @Test
public void testCustomTypeInReplaceParent() throws DataFormatException {
MyPatient patient = new MyPatient();
patient.addName().addFamily("PatientName");
MyOrganization org = new MyOrganization();
org.setName("OrgName");
patient.getManagingOrganization().setResource(org);
String str = ourCtx.newXmlParser().encodeResourceToString(patient);
ourLog.info(str);
assertThat(
str,
Matchers.stringContainsInOrder("<Patient xmlns=\"http://hl7.org/fhir\"><contained><Organization xmlns=\"http://hl7.org/fhir\" id=\"1\"><name value=\"OrgName\"/></Organization></contained><name><family value=\"PatientName\"/></name><managingOrganization><reference value=\"#1\"/></managingOrganization></Patient>"));
MyPatient parse = ourCtx.newXmlParser().parseResource(MyPatient.class, str);
assertEquals("PatientName", parse.getNameFirstRep().getFamilyAsSingleString());
assertEquals("OrgName", ((MyOrganization) parse.getManagingOrganization().getResource()).getName().getValue());
}
/**
* Test for #82 - Not yet enabled because the test won't pass
*/
// @Test
public void testCustomTypeInExtension() throws DataFormatException {
MyPatient patient = new MyPatient();
patient.addName().addFamily("PatientName");
MyOrganization org = new MyOrganization();
org.setName("OrgName");
patient.getSomeOrganization().setResource(org);
String str = ourCtx.newXmlParser().encodeResourceToString(patient);
ourLog.info(str);
assertThat(
str,
Matchers.stringContainsInOrder("<Patient xmlns=\"http://hl7.org/fhir\"><extension url=\"http://foo/someOrg\"><valueResource><reference value=\"#1\"/></valueResource></extension><contained><Organization xmlns=\"http://hl7.org/fhir\" id=\"1\"><name value=\"OrgName\"/></Organization></contained><name><family value=\"PatientName\"/></name></Patient>"));
MyPatient parse = ourCtx.newXmlParser().parseResource(MyPatient.class, str);
assertEquals("PatientName", parse.getNameFirstRep().getFamilyAsSingleString());
assertEquals("OrgName", ((MyOrganization) parse.getSomeOrganization().getResource()).getName().getValue());
}
@Test
public void testLoadAndAncodeMessage() throws SAXException, IOException {
@ -1246,14 +1232,14 @@ public class XmlParserTest {
INarrativeGenerator gen = new INarrativeGenerator() {
@Override
public void generateNarrative(String theProfile, IBaseResource theResource, BaseNarrativeDt<?> theNarrative) throws DataFormatException {
theNarrative.getDiv().setValueAsString("<div>help</div>");
theNarrative.getStatus().setValueAsString("generated");
public void generateNarrative(IBaseResource theResource, BaseNarrativeDt<?> theNarrative) {
throw new UnsupportedOperationException();
}
@Override
public void generateNarrative(IBaseResource theResource, BaseNarrativeDt<?> theNarrative) {
throw new UnsupportedOperationException();
public void generateNarrative(String theProfile, IBaseResource theResource, BaseNarrativeDt<?> theNarrative) throws DataFormatException {
theNarrative.getDiv().setValueAsString("<div>help</div>");
theNarrative.getStatus().setValueAsString("generated");
}
@Override
@ -1325,6 +1311,22 @@ public class XmlParserTest {
}
/**
* See #131
*/
@Test
public void testParseAndReencodeCondition() {
FhirContext ctx = FhirContext.forDstu1();
ctx.setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());
InputStreamReader reader = new InputStreamReader(XmlParserTest.class.getResourceAsStream("/condition.xml"));
Condition cond = ctx.newXmlParser().parseResource(Condition.class, reader);
String enc = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(cond);
ourLog.info(enc);
assertThat(enc, not(containsString("generated")));
}
@Test
public void testParseBinaryResource() {
@ -1515,6 +1517,43 @@ public class XmlParserTest {
assertEquals(Organization.class, b.getEntries().get(2).getResource().getClass());
}
/**
* see #144 and #146
*/
@Test
public void testParseContained() {
FhirContext c = FhirContext.forDstu1();
IParser parser = c.newXmlParser().setPrettyPrint(true);
Observation o = new Observation();
o.getName().setText("obs text");
Patient p = new Patient();
p.addName().addFamily("patient family");
o.getSubject().setResource(p);
String enc = parser.encodeResourceToString(o);
ourLog.info(enc);
//@formatter:off
assertThat(enc, stringContainsInOrder(
"<Observation xmlns=\"http://hl7.org/fhir\">",
"<contained>",
"<Patient xmlns=\"http://hl7.org/fhir\" id=\"1\">",
"</contained>",
"<reference value=\"#1\"/>"
));
//@formatter:on
o = parser.parseResource(Observation.class, enc);
assertEquals("obs text", o.getName().getText().getValue());
assertNotNull(o.getSubject().getResource());
p = (Patient) o.getSubject().getResource();
assertEquals("patient family", p.getNameFirstRep().getFamilyAsSingleString());
}
/**
* Thanks to Alexander Kley!
*/
@ -1597,6 +1636,40 @@ public class XmlParserTest {
}
@Test
public void testParseErrorHandlerNoError() {
String input = "<Patient></Patient>";
ourCtx.newXmlParser().setParserErrorHandler(new StrictErrorHandler()).parseResource(Patient.class, input);
}
@Test
public void testParseErrorHandlerUnexpectedAttribute() {
String input = "<Patient><name><family foo=\"FOO\" value=\"AAA\" bar=\"BAR\"/></name></Patient>";
try {
ourCtx.newXmlParser().setParserErrorHandler(new StrictErrorHandler()).parseResource(Patient.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("'foo'"));
}
Patient p = ourCtx.newXmlParser().setParserErrorHandler(new LenientErrorHandler()).parseResource(Patient.class, input);
assertEquals(p.getName().get(0).getFamily().get(0).getValue(), "AAA");
}
@Test
public void testParseErrorHandlerUnexpectedElement() {
String input = "<Patient><foo><bar/></foo><name><family value=\"AAA\"/></name></Patient>";
try {
ourCtx.newXmlParser().setParserErrorHandler(new StrictErrorHandler()).parseResource(Patient.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("'foo'"));
}
Patient p = ourCtx.newXmlParser().setParserErrorHandler(new LenientErrorHandler()).parseResource(Patient.class, input);
assertEquals(p.getName().get(0).getFamily().get(0).getValue(), "AAA");
}
@Test
public void testParseFeedWithListResource() throws ConfigurationException, DataFormatException, IOException {
@ -1646,6 +1719,17 @@ public class XmlParserTest {
}
@Test
public void testParseWithIncorrectResourceType() {
String input = "<Patient><foo><bar/></foo><name><family value=\"AAA\"/></name></Patient>";
try {
ourCtx.newXmlParser().parseResource(Organization.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("expected \"Organization\" but found \"Patient\""));
}
}
@Test
public void testParseWithXmlHeader() throws ConfigurationException, DataFormatException {
IParser p = ourCtx.newXmlParser();
@ -1695,29 +1779,6 @@ public class XmlParserTest {
}
/**
* See #91
*/
@Test
public void testCustomTypeWithUnoderedExtensions() {
MyPatientWithUnorderedExtensions pat = new MyPatientWithUnorderedExtensions();
pat.getExtAtt1().setValue(true);
pat.getExtAtt2().setValue("val2");
pat.getExtAtt3().setValueAsString("20110102");
String string = ourCtx.newXmlParser().encodeResourceToString(pat);
ourLog.info(string);
//@formatter:off
assertThat(string, stringContainsInOrder(Arrays.asList(
"<extension url=\"urn:ex1\"><valueBoolean value=\"true\"/></extension>",
"<extension url=\"urn:ex2\"><valueString value=\"val2\"/></extension>",
"<extension url=\"urn:ex3\"><valueDate value=\"20110102\"/></extension>"
)));
//@formatter:on
}
@Test
public void testSimpleResourceEncodeWithCustomType() throws IOException, SAXException {
@ -1822,54 +1883,4 @@ public class XmlParserTest {
System.setProperty("file.encoding", "ISO-8859-1");
}
/**
* See #103
*/
@Test
public void testEncodeAndReEncodeContainedXml() {
Composition comp = new Composition();
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
IParser parser = ourCtx.newXmlParser().setPrettyPrint(true);
String string = parser.encodeResourceToString(comp);
ourLog.info(string);
Composition parsed = parser.parseResource(Composition.class, string);
parsed.getSection().remove(0);
string = parser.encodeResourceToString(parsed);
ourLog.info(string);
parsed = parser.parseResource(Composition.class, string);
assertEquals(2, parsed.getContained().getContainedResources().size());
}
/**
* See #103
*/
@Test
public void testEncodeAndReEncodeContainedJson() {
Composition comp = new Composition();
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
comp.addSection().getContent().setResource(new AllergyIntolerance().addIdentifier("foo", "bar"));
IParser parser = ourCtx.newJsonParser().setPrettyPrint(true);
String string = parser.encodeResourceToString(comp);
ourLog.info(string);
Composition parsed = parser.parseResource(Composition.class, string);
parsed.getSection().remove(0);
string = parser.encodeResourceToString(parsed);
ourLog.info(string);
parsed = parser.parseResource(Composition.class, string);
assertEquals(2, parsed.getContained().getContainedResources().size());
}
}

File diff suppressed because one or more lines are too long

View File

@ -16,6 +16,7 @@ import org.apache.commons.io.input.ReaderInputStream;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
@ -37,9 +38,11 @@ import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.model.dstu2.resource.Observation;
import ca.uhn.fhir.model.dstu2.resource.Parameters;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.EncodingEnum;
@ -48,11 +51,6 @@ public class GenericClientDstu2Test {
private HttpClient myHttpClient;
private HttpResponse myHttpResponse;
@BeforeClass
public static void beforeClass() {
ourCtx = FhirContext.forDstu2();
}
@Before
public void before() {
myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs());
@ -61,30 +59,9 @@ public class GenericClientDstu2Test {
myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs());
}
@SuppressWarnings("unused")
@Test
public void testSearchWithReverseInclude() 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");
//@formatter:off
Bundle response = client.search()
.forResource(Patient.class)
.encodedJson()
.revInclude(new Include("Provenance:target"))
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", capt.getValue().getURI().toString());
private String extractBody(ArgumentCaptor<HttpUriRequest> capt, int count) throws IOException {
String body = IOUtils.toString(((HttpEntityEnclosingRequestBase) capt.getAllValues().get(count)).getEntity().getContent(), "UTF-8");
return body;
}
private String getPatientFeedWithOneResult() {
@ -108,6 +85,122 @@ public class GenericClientDstu2Test {
return msg;
}
@Test
public void testCreate() 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), Constants.STATUS_HTTP_204_NO_CONTENT, ""));
when(myHttpResponse.getEntity().getContent()).then(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
Patient p = new Patient();
p.addName().addFamily("FOOFAMILY");
client.create().resource(p).execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertThat(extractBody(capt, idx), containsString("<family value=\"FOOFAMILY\"/>"));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
p.setId("123");
client.create().resource(p).execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
String body = extractBody(capt, idx);
assertThat(body, containsString("<family value=\"FOOFAMILY\"/>"));
assertThat(body, not(containsString("123")));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
}
@Test
public void testCreateConditional() 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), Constants.STATUS_HTTP_204_NO_CONTENT, ""));
when(myHttpResponse.getEntity().getContent()).then(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
Patient p = new Patient();
p.addName().addFamily("FOOFAMILY");
client.create().resource(p).conditionalByUrl("Patient?name=foo").execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertThat(extractBody(capt, idx), containsString("<family value=\"FOOFAMILY\"/>"));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
client.create().resource(p).conditional().where(Patient.NAME.matches().value("foo")).execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertThat(extractBody(capt, idx), containsString("<family value=\"FOOFAMILY\"/>"));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
}
@Test
public void testDeleteConditional() 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), Constants.STATUS_HTTP_204_NO_CONTENT, ""));
// when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type",
// Constants.CT_TEXT + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).then(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
client.delete().resourceById(new IdDt("Patient/123")).execute();
assertEquals("DELETE", capt.getAllValues().get(idx).getMethod());
assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString());
idx++;
client.delete().resourceConditionalByUrl("Patient?name=foo").execute();
assertEquals("DELETE", capt.getAllValues().get(idx).getMethod());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString());
idx++;
client.delete().resourceConditionalByType("Patient").where(Patient.NAME.matches().value("foo")).execute();
assertEquals("DELETE", capt.getAllValues().get(idx).getMethod());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString());
idx++;
}
@Test
public void testHistory() throws Exception {
@ -164,27 +257,253 @@ public class GenericClientDstu2Test {
}
@Test
public void testSearchByString() throws Exception {
String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
public void testOperationAsGetWithInParameters() throws Exception {
IParser p = ourCtx.newXmlParser();
Parameters inParams = new Parameters();
inParams.addParameter().setName("param1").setValue(new StringDt("STRINGVALIN1"));
inParams.addParameter().setName("param1").setValue(new StringDt("STRINGVALIN1b"));
inParams.addParameter().setName("param2").setValue(new StringDt("STRINGVALIN2"));
Parameters outParams = new Parameters();
outParams.addParameter().setValue(new StringDt("STRINGVALOUT1"));
outParams.addParameter().setValue(new StringDt("STRINGVALOUT2"));
final String respString = p.encodeResourceToString(outParams);
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()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
Parameters resp = client
.operation()
.onServer()
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
//@formatter:off
resp = client
.operation()
.onType(Patient.class)
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
//@formatter:off
resp = client
.operation()
.onInstance(new IdDt("Patient", "123"))
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
// @formatter:off
resp = client
.operation()
.onInstance(new IdDt("http://foo.com/bar/baz/Patient/123/_history/22"))
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
// @formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
}
@Test
public void testOperationAsGetWithNoInParameters() throws Exception {
IParser p = ourCtx.newXmlParser();
Parameters outParams = new Parameters();
outParams.addParameter().setValue(new StringDt("STRINGVALOUT1"));
outParams.addParameter().setValue(new StringDt("STRINGVALOUT2"));
final String respString = p.encodeResourceToString(outParams);
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()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
Parameters resp = client
.operation()
.onServer()
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
//@formatter:off
resp = client
.operation()
.onType(Patient.class)
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
//@formatter:off
resp = client
.operation()
.onInstance(new IdDt("Patient", "123"))
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
// @formatter:off
resp = client
.operation()
.onInstance(new IdDt("http://foo.com/bar/baz/Patient/123/_history/22"))
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
// @formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
}
@Test
public void testOperationWithBundleResponseXml() throws Exception {
IParser p = ourCtx.newXmlParser();
Parameters inParams = new Parameters();
inParams.addParameter().setValue(new StringDt("STRINGVALIN1"));
inParams.addParameter().setValue(new StringDt("STRINGVALIN2"));
String reqString = p.encodeResourceToString(inParams);
ca.uhn.fhir.model.dstu2.resource.Bundle outParams = new ca.uhn.fhir.model.dstu2.resource.Bundle();
outParams.setTotal(123);
final String respString = p.encodeResourceToString(outParams);
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()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
Parameters resp = client
.operation()
.onServer()
.named("$SOMEOPERATION")
.withParameters(inParams).execute();
//@formatter:on
assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertEquals(extractBody(capt, idx), reqString);
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
assertEquals(1, resp.getParameter().size());
assertEquals(ca.uhn.fhir.model.dstu2.resource.Bundle.class, resp.getParameter().get(0).getResource().getClass());
idx++;
}
@Test
public void testOperationWithBundleResponseJson() throws Exception {
final String resp = "{\n" +
" \"resourceType\":\"Bundle\",\n" +
" \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" +
" \"base\":\"http://fhirtest.uhn.ca/baseDstu2\"\n" +
"}";
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(msg), Charset.forName("UTF-8")));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(resp), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
IGenericClient client = ourCtx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu2");
//@formatter:off
Bundle response = client.search()
.forResource("Patient")
.where(Patient.NAME.matches().value("james"))
.execute();
//@formatter:on
client.registerInterceptor(new LoggingInterceptor(true));
assertEquals("http://example.com/fhir/Patient?name=james", capt.getValue().getURI().toString());
assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass());
// Create the input parameters to pass to the server
Parameters inParams = new Parameters();
inParams.addParameter().setName("start").setValue(new DateDt("2001-01-01"));
inParams.addParameter().setName("end").setValue(new DateDt("2015-03-01"));
// Invoke $everything on "Patient/1"
Parameters outParams = client.operation().onInstance(new IdDt("Patient", "18066")).named("$everything").withParameters(inParams).execute();
/*
* Note that the $everything operation returns a Bundle instead of a Parameters resource. The client operation methods return a Parameters instance however, so HAPI creates a Parameters object
* with a single parameter containing the value.
*/
ca.uhn.fhir.model.dstu2.resource.Bundle responseBundle = (ca.uhn.fhir.model.dstu2.resource.Bundle) outParams.getParameter().get(0).getResource();
// Print the response bundle
assertEquals("8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19", responseBundle.getId().getIdPart());
}
@Test
@ -352,14 +671,7 @@ public class GenericClientDstu2Test {
}
@Test
public void testOperationAsGetWithNoInParameters() throws Exception {
IParser p = ourCtx.newXmlParser();
Parameters outParams = new Parameters();
outParams.addParameter().setValue(new StringDt("STRINGVALOUT1"));
outParams.addParameter().setValue(new StringDt("STRINGVALOUT2"));
final String respString = p.encodeResourceToString(outParams);
public void testPageNext() 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), 200, "OK"));
@ -367,7 +679,7 @@ public class GenericClientDstu2Test {
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
return new ReaderInputStream(new StringReader(getPatientFeedWithOneResult()), Charset.forName("UTF-8"));
}
});
@ -375,158 +687,37 @@ public class GenericClientDstu2Test {
int idx = 0;
//@formatter:off
Parameters resp = client
.operation()
.onServer()
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl("http://foo.bar/prev");
sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl("http://foo.bar/next");
//@formatter:off
resp = client
.operation()
.onType(Patient.class)
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
ca.uhn.fhir.model.dstu2.resource.Bundle resp = client
.loadPage()
.next(sourceBundle)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
assertEquals(1, resp.getEntry().size());
assertEquals("http://foo.bar/next", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
//@formatter:off
resp = client
.operation()
.onInstance(new IdDt("Patient", "123"))
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
// @formatter:off
resp = client
.operation()
.onInstance(new IdDt("http://foo.com/bar/baz/Patient/123/_history/22"))
.named("$SOMEOPERATION")
.withNoParameters(Parameters.class)
.useHttpGet()
.execute();
// @formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
}
@Test
public void testOperationAsGetWithInParameters() throws Exception {
IParser p = ourCtx.newXmlParser();
Parameters inParams = new Parameters();
inParams.addParameter().setName("param1").setValue(new StringDt("STRINGVALIN1"));
inParams.addParameter().setName("param1").setValue(new StringDt("STRINGVALIN1b"));
inParams.addParameter().setName("param2").setValue(new StringDt("STRINGVALIN2"));
Parameters outParams = new Parameters();
outParams.addParameter().setValue(new StringDt("STRINGVALOUT1"));
outParams.addParameter().setValue(new StringDt("STRINGVALOUT2"));
final String respString = p.encodeResourceToString(outParams);
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()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
public void testPageNextNoLink() throws Exception {
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
Parameters resp = client
.operation()
.onServer()
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
//@formatter:off
resp = client
.operation()
.onType(Patient.class)
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
//@formatter:off
resp = client
.operation()
.onInstance(new IdDt("Patient", "123"))
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(respString, p.encodeResourceToString(resp));
assertEquals("GET", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
// @formatter:off
resp = client
.operation()
.onInstance(new IdDt("http://foo.com/bar/baz/Patient/123/_history/22"))
.named("$SOMEOPERATION")
.withParameters(inParams)
.useHttpGet()
.execute();
// @formatter:on
assertEquals("http://example.com/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1&param1=STRINGVALIN1b&param2=STRINGVALIN2", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
try {
client.loadPage().next(sourceBundle).execute();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("Can not perform paging operation because no link was found in Bundle with relation \"next\""));
}
}
@Test
public void testOperationWithBundleResponse() throws Exception {
IParser p = ourCtx.newXmlParser();
Parameters inParams = new Parameters();
inParams.addParameter().setValue(new StringDt("STRINGVALIN1"));
inParams.addParameter().setValue(new StringDt("STRINGVALIN2"));
String reqString = p.encodeResourceToString(inParams);
ca.uhn.fhir.model.dstu2.resource.Bundle outParams = new ca.uhn.fhir.model.dstu2.resource.Bundle();
outParams.setTotal(123);
final String respString = p.encodeResourceToString(outParams);
public void testPagePrev() 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), 200, "OK"));
@ -534,7 +725,7 @@ public class GenericClientDstu2Test {
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
return new ReaderInputStream(new StringReader(getPatientFeedWithOneResult()), Charset.forName("UTF-8"));
}
});
@ -542,21 +733,88 @@ public class GenericClientDstu2Test {
int idx = 0;
ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
sourceBundle.getLinkOrCreate("previous").setUrl("http://foo.bar/prev");
//@formatter:off
Parameters resp = client
.operation()
.onServer()
.named("$SOMEOPERATION")
.withParameters(inParams).execute();
ca.uhn.fhir.model.dstu2.resource.Bundle resp = client
.loadPage()
.previous(sourceBundle)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/$SOMEOPERATION", capt.getAllValues().get(idx).getURI().toASCIIString());
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertEquals(extractBody(capt, idx), reqString);
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
assertEquals(1, resp.getParameter().size());
assertEquals(ca.uhn.fhir.model.dstu2.resource.Bundle.class, resp.getParameter().get(0).getResource().getClass());
assertEquals(1, resp.getEntry().size());
assertEquals("http://foo.bar/prev", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
/*
* Try with "prev" instead of "previous"
*/
sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
sourceBundle.getLinkOrCreate("prev").setUrl("http://foo.bar/prev");
//@formatter:off
resp = client
.loadPage()
.previous(sourceBundle)
.execute();
//@formatter:on
assertEquals(1, resp.getEntry().size());
assertEquals("http://foo.bar/prev", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
}
@Test
public void testSearchByString() throws Exception {
String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
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(msg), Charset.forName("UTF-8")));
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
//@formatter:off
Bundle response = client.search()
.forResource("Patient")
.where(Patient.NAME.matches().value("james"))
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name=james", capt.getValue().getURI().toString());
assertEquals(Patient.class, response.getEntries().get(0).getResource().getClass());
}
@SuppressWarnings("unused")
@Test
public void testSearchWithReverseInclude() 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");
//@formatter:off
Bundle response = client.search()
.forResource(Patient.class)
.encodedJson()
.revInclude(new Include("Provenance:target"))
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", capt.getValue().getURI().toString());
}
@Test
@ -709,122 +967,6 @@ public class GenericClientDstu2Test {
assertEquals("Patient/2/_history/2", response.getEntry().get(1).getTransactionResponse().getLocation());
}
@Test
public void testDeleteConditional() 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), Constants.STATUS_HTTP_204_NO_CONTENT, ""));
// when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type",
// Constants.CT_TEXT + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).then(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
client.delete().resourceById(new IdDt("Patient/123")).execute();
assertEquals("DELETE", capt.getAllValues().get(idx).getMethod());
assertEquals("http://example.com/fhir/Patient/123", capt.getAllValues().get(idx).getURI().toString());
idx++;
client.delete().resourceConditionalByUrl("Patient?name=foo").execute();
assertEquals("DELETE", capt.getAllValues().get(idx).getMethod());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString());
idx++;
client.delete().resourceConditionalByType("Patient").where(Patient.NAME.matches().value("foo")).execute();
assertEquals("DELETE", capt.getAllValues().get(idx).getMethod());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getURI().toString());
idx++;
}
@Test
public void testCreateConditional() throws Exception {
ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), Constants.STATUS_HTTP_204_NO_CONTENT, ""));
when(myHttpResponse.getEntity().getContent()).then(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
Patient p = new Patient();
p.addName().addFamily("FOOFAMILY");
client.create().resource(p).conditionalByUrl("Patient?name=foo").execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertThat(extractBody(capt, idx), containsString("<family value=\"FOOFAMILY\"/>"));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
client.create().resource(p).conditional().where(Patient.NAME.matches().value("foo")).execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertThat(extractBody(capt, idx), containsString("<family value=\"FOOFAMILY\"/>"));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("http://example.com/fhir/Patient?name=foo", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_IF_NONE_EXIST).getValue());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
}
@Test
public void testCreate() 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), Constants.STATUS_HTTP_204_NO_CONTENT, ""));
when(myHttpResponse.getEntity().getContent()).then(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(""), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
Patient p = new Patient();
p.addName().addFamily("FOOFAMILY");
client.create().resource(p).execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
assertThat(extractBody(capt, idx), containsString("<family value=\"FOOFAMILY\"/>"));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
p.setId("123");
client.create().resource(p).execute();
assertEquals(1, capt.getAllValues().get(idx).getHeaders(Constants.HEADER_CONTENT_TYPE).length);
assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue());
String body = extractBody(capt, idx);
assertThat(body, containsString("<family value=\"FOOFAMILY\"/>"));
assertThat(body, not(containsString("123")));
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).getURI().toString());
assertEquals("POST", capt.getAllValues().get(idx).getRequestLine().getMethod());
idx++;
}
@Test
public void testUpdateConditional() throws Exception {
ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
@ -878,106 +1020,9 @@ public class GenericClientDstu2Test {
}
private String extractBody(ArgumentCaptor<HttpUriRequest> capt, int count) throws IOException {
String body = IOUtils.toString(((HttpEntityEnclosingRequestBase) capt.getAllValues().get(count)).getEntity().getContent(), "UTF-8");
return body;
}
@Test
public void testPageNext() 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), 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<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(getPatientFeedWithOneResult()), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl("http://foo.bar/prev");
sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl("http://foo.bar/next");
//@formatter:off
ca.uhn.fhir.model.dstu2.resource.Bundle resp = client
.loadPage()
.next(sourceBundle)
.execute();
//@formatter:on
assertEquals(1, resp.getEntry().size());
assertEquals("http://foo.bar/next", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
}
@Test
public void testPagePrev() 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), 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<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(getPatientFeedWithOneResult()), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
sourceBundle.getLinkOrCreate("previous").setUrl("http://foo.bar/prev");
//@formatter:off
ca.uhn.fhir.model.dstu2.resource.Bundle resp = client
.loadPage()
.previous(sourceBundle)
.execute();
//@formatter:on
assertEquals(1, resp.getEntry().size());
assertEquals("http://foo.bar/prev", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
/*
* Try with "prev" instead of "previous"
*/
sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
sourceBundle.getLinkOrCreate("prev").setUrl("http://foo.bar/prev");
//@formatter:off
resp = client
.loadPage()
.previous(sourceBundle)
.execute();
//@formatter:on
assertEquals(1, resp.getEntry().size());
assertEquals("http://foo.bar/prev", capt.getAllValues().get(idx).getURI().toASCIIString());
idx++;
}
@Test
public void testPageNextNoLink() throws Exception {
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
try {
client.loadPage().next(sourceBundle).execute();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("Can not perform paging operation because no link was found in Bundle with relation \"next\""));
}
@BeforeClass
public static void beforeClass() {
ourCtx = FhirContext.forDstu2();
}
}

View File

@ -465,6 +465,9 @@
<copy todir="target/site/apidocs-dstu">
<fileset dir="hapi-fhir-structures-dstu/target/site/apidocs"/>
</copy>
<copy todir="target/site/apidocs-hl7org-dstu2">
<fileset dir="hapi-fhir-structures-hl7org-dstu2/target/site/apidocs"/>
</copy>
<copy todir="target/site/apidocs-dstu2">
<fileset dir="hapi-fhir-structures-dstu2/target/site/apidocs"/>
</copy>
@ -833,6 +836,7 @@
<module>hapi-fhir-base</module>
<module>hapi-fhir-structures-dstu</module>
<module>hapi-fhir-structures-dstu2</module>
<module>hapi-fhir-structures-hl7org-dstu2</module>
<module>hapi-fhir-jpaserver-base</module>
<module>examples</module>
</modules>

View File

@ -42,6 +42,16 @@
used to validate resources as they are being parsed, and optionally fail if invalid/unexpected
elements are found in resource bodies during parsing.
</action>
<action type="fix">
IParser#parseResource(Class, String) method, which is used to parse a resource into the given
structure will now throw a DataFormatException if the structure is for the wrong type of
resource for the one actually found in the input String (or Reader). For example, if a Patient
resource is being parsed into Organization.class this will now cause an error. Previously,
the XML parser would ignore the type and the JSON parser would fail. This also caused
operations to not parse correctly if they returned a resource type other than
parameters with JSON encoding (e.g. the $everything operation on UHN's test server).
Thanks to Avinash Shanbhag for reporting!
</action>
</release>
<release version="1.0" date="2015-May-8">
<action type="add">

View File

@ -107,6 +107,7 @@
<item name="Core API" href="./apidocs/index.html" />
<item name="Model API (DSTU1)" href="./apidocs-dstu/index.html" />
<item name="Model API (DSTU2)" href="./apidocs-dstu2/index.html" />
<item name="Model API (RI DSTU2)" href="./apidocs-hl7org-dstu2/index.html" />
<item name="JPA Server API" href="./apidocs-jpaserver/index.html" />
</item>
<item name="Maven Plugin (hapi-tinder-plugin)" href="./doc_tinder.html" />