예제 #1
1
  @Test
  public void testTwoInclude() throws Exception {
    HttpGet httpGet =
        new HttpGet(
            "http://localhost:"
                + ourPort
                + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info(responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals(2, p.getName().size());
    assertEquals("Hello", p.getId().getIdPart());

    Set<String> values = new HashSet<String>();
    values.add(p.getName().get(0).getFamilyFirstRep().getValue());
    values.add(p.getName().get(1).getFamilyFirstRep().getValue());
    assertThat(values, containsInAnyOrder("foo", "bar"));
  }
  @Test
  public void testServerReturnsWrongVersionForDstu2() throws Exception {
    Conformance conf = new Conformance();
    conf.setFhirVersion("0.80");
    String msg = myCtx.newXmlParser().encodeResourceToString(conf);

    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);

    myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE);
    try {
      myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123"));
      fail();
    } catch (FhirClientInappropriateForServerException e) {
      String out = e.toString();
      String want =
          "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2 (via the FhirContext)";
      ourLog.info(out);
      ourLog.info(want);
      assertThat(out, containsString(want));
    }
  }
  @Test
  public void testSchemaBundleValidatorFails() throws IOException {
    String res =
        IOUtils.toString(getClass().getClassLoader().getResourceAsStream("bundle-example.json"));
    Bundle b = ourCtx.newJsonParser().parseBundle(res);

    FhirValidator val = createFhirValidator();

    ValidationResult validationResult = val.validateWithResult(b);
    assertTrue(validationResult.isSuccessful());

    MedicationOrder p = (MedicationOrder) b.getEntries().get(0).getResource();
    TimingDt timing = new TimingDt();
    timing.getRepeat().setDuration(123);
    timing.getRepeat().setDurationUnits((UnitsOfTimeEnum) null);
    p.getDosageInstructionFirstRep().setTiming(timing);

    validationResult = val.validateWithResult(b);
    assertFalse(validationResult.isSuccessful());
    OperationOutcome operationOutcome = (OperationOutcome) validationResult.toOperationOutcome();
    String encoded =
        ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(operationOutcome);
    ourLog.info(encoded);
    assertThat(encoded, containsString("tim-1:"));
  }
예제 #4
0
  @Test
  public void testUpdate() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    OperationOutcome oo =
        ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent);
    assertEquals("OODETAILS", oo.getIssueFirstRep().getDetails().getValue());

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testSchemaResourceValidator() throws IOException {
    String res =
        IOUtils.toString(
            getClass().getClassLoader().getResourceAsStream("patient-example-dicom.json"));
    Patient p = ourCtx.newJsonParser().parseResource(Patient.class, res);

    ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p));

    FhirValidator val = ourCtx.newValidator();
    val.setValidateAgainstStandardSchema(true);
    val.setValidateAgainstStandardSchematron(false);

    val.validate(p);

    p.getAnimal().getBreed().setText("The Breed");
    try {
      val.validate(p);
      fail();
    } catch (ValidationFailureException e) {
      OperationOutcome operationOutcome = (OperationOutcome) e.getOperationOutcome();
      ourLog.info(
          ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(operationOutcome));
      assertEquals(1, operationOutcome.getIssue().size());
      assertThat(
          operationOutcome.getIssueFirstRep().getDetailsElement().getValue(),
          containsString("cvc-complex-type"));
    }
  }
예제 #6
0
  @Test
  public void testUpdateWithTagWithSchemeAndLabel() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\"");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    CloseableHttpResponse status = ourClient.execute(httpPost);
    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
    IOUtils.closeQuietly(status.getEntity().getContent());

    httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\";   ");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    status = ourClient.execute(httpPost);
    IOUtils.closeQuietly(status.getEntity().getContent());

    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
  }
  @Test
  public void testSchematronResourceValidator() throws IOException {
    String res =
        IOUtils.toString(
            getClass().getClassLoader().getResourceAsStream("patient-example-dicom.json"));
    Patient p = ourCtx.newJsonParser().parseResource(Patient.class, res);

    FhirValidator val = ourCtx.newValidator();
    val.setValidateAgainstStandardSchema(false);
    val.setValidateAgainstStandardSchematron(true);

    ValidationResult validationResult = val.validateWithResult(p);
    assertTrue(validationResult.isSuccessful());

    p.getTelecomFirstRep().setValue("123-4567");
    validationResult = val.validateWithResult(p);
    assertFalse(validationResult.isSuccessful());
    OperationOutcome operationOutcome = (OperationOutcome) validationResult.toOperationOutcome();
    ourLog.info(
        ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(operationOutcome));
    assertEquals(1, operationOutcome.getIssue().size());
    assertThat(operationOutcome.getIssueFirstRep().getDiagnostics(), containsString("cpt-2:"));

    p.getTelecomFirstRep().setSystem(ContactPointSystemEnum.EMAIL);
    validationResult = val.validateWithResult(p);
    assertTrue(validationResult.isSuccessful());
  }
  /** See issue #50 */
  @Test
  public void testOutOfBoundsDate() {
    Patient p = new Patient();
    p.setBirthDate(new DateDt("2000-15-31"));

    String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p);
    ourLog.info(encoded);

    assertThat(encoded, StringContains.containsString("2000-15-31"));

    p = ourCtx.newXmlParser().parseResource(Patient.class, encoded);
    assertEquals("2000-15-31", p.getBirthDateElement().getValueAsString());
    assertEquals("2001-03-31", new SimpleDateFormat("yyyy-MM-dd").format(p.getBirthDate()));

    ValidationResult result = ourCtx.newValidator().validateWithResult(p);
    String resultString =
        ourCtx
            .newXmlParser()
            .setPrettyPrint(true)
            .encodeResourceToString(result.toOperationOutcome());
    ourLog.info(resultString);

    assertEquals(2, ((OperationOutcome) result.toOperationOutcome()).getIssue().size());
    assertThat(resultString, StringContains.containsString("2000-15-31"));
  }
  @Test
  public void testTransaction() throws Exception {
    String retVal = ourCtx.newXmlParser().encodeBundleToString(new Bundle());

    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
    when(ourHttpClient.execute(capt.capture())).thenReturn(ourHttpResponse);
    when(ourHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(ourHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_ATOM_XML + "; charset=UTF-8"));
    when(ourHttpResponse.getEntity().getContent())
        .thenReturn(new ReaderInputStream(new StringReader(retVal), Charset.forName("UTF-8")));

    Patient p1 = new Patient();
    p1.addIdentifier().setSystem("urn:system").setValue("value");

    IGenericClient client = ourCtx.newRestfulGenericClient("http://foo");
    client.transaction().withResources(Arrays.asList((IBaseResource) p1)).execute();

    HttpUriRequest value = capt.getValue();

    assertTrue("Expected request of type POST on long params list", value instanceof HttpPost);
    HttpPost post = (HttpPost) value;
    String body = IOUtils.toString(post.getEntity().getContent());
    IOUtils.closeQuietly(post.getEntity().getContent());
    ourLog.info(body);

    assertThat(
        body, Matchers.containsString("<type value=\"" + BundleTypeEnum.TRANSACTION.getCode()));
  }
  @Test
  public void testSpecificallyNamedQueryGetsPrecedence() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?AAA=123");

    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals("AAA", p.getIdentifierFirstRep().getValue().getValue());

    // Now the named query

    httpGet =
        new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findPatientByAAA&AAA=123");

    status = ourClient.execute(httpGet);
    responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());

    p = bundle.getResources(Patient.class).get(0);
    assertEquals("AAANamed", p.getIdentifierFirstRep().getValue().getValue());
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testSchemaBundleValidator() throws IOException {
    String res =
        IOUtils.toString(getClass().getClassLoader().getResourceAsStream("bundle-example.json"));
    Bundle b = ourCtx.newJsonParser().parseBundle(res);

    FhirValidator val = createFhirValidator();

    val.validate(b);

    MedicationOrder p = (MedicationOrder) b.getEntries().get(0).getResource();
    TimingDt timing = new TimingDt();
    timing.getRepeat().setDuration(123);
    timing.getRepeat().setDurationUnits((UnitsOfTimeEnum) null);
    p.getDosageInstructionFirstRep().setTiming(timing);

    try {
      val.validate(b);
      fail();
    } catch (ValidationFailureException e) {
      String encoded =
          ourCtx
              .newXmlParser()
              .setPrettyPrint(true)
              .encodeResourceToString(e.getOperationOutcome());
      ourLog.info(encoded);
      assertThat(encoded, containsString("tim-1:"));
    }
  }
  @Before
  public void before() {
    myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs());
    myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs());

    myCtx = FhirContext.forDstu2();
    myCtx.getRestfulClientFactory().setHttpClient(myHttpClient);
    myFirstResponse = true;
  }
예제 #13
0
  public Throwable fhir(SparseArray<GlucoseRecord> records) {

    try {
      Patient p = getPatient();
      Log.d(TAG, "converting glucoserecrods to observations now");

      Device d = initializeDevice(p);
      // do conditional update here so the device is updated if needed

      String ident = getConditionalUrl(d, d.getIdentifierFirstRep());
      String a = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(d);
      IdDt id = (IdDt) client.update().resource(d).conditionalByUrl(ident).execute().getId();
      d.setId(id);

      DeviceMetric metric = initializeDeviceMetric(d);
      metric.setId(
          client
              .create()
              .resource(metric)
              .conditionalByUrl(getConditionalUrl(metric, metric.getIdentifier()))
              .execute()
              .getId());

      for (int i = 0; i < records.size(); i++) {
        int j = records.keyAt(i);
        GlucoseRecord r = records.get(j);

        Log.d(TAG, "creating quantity");

        QuantityDt qdt = initializeQuantityDt(r);

        Observation o = initializeObservation(p, metric, r, qdt);

        Log.d(TAG, "submitting to server...");
        // client.update().resource(o).conditionalByUrl("Observation?identifier=http://...%7Cid").encodedJson().execute();
        IdDt did =
            (IdDt)
                client
                    .update()
                    .resource(o)
                    .conditionalByUrl(getConditionalUrl(o, o.getIdentifierFirstRep()))
                    .execute()
                    .getId();

        o.setId(did);

        String s = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(o);

        Log.d(TAG, "... done");
      }
    } catch (Throwable e) {
      return e;
    }

    return null;
  }
  @Before
  public void before() {
    ourCtx = FhirContext.forDstu2();

    ourHttpClient = mock(HttpClient.class, new ReturnsDeepStubs());
    ourCtx.getRestfulClientFactory().setHttpClient(ourHttpClient);
    ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);

    ourHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs());
  }
  @Test
  public void testForceConformanceCheck() throws Exception {
    Conformance conf = new Conformance();
    conf.setFhirVersion("0.5.0");
    final String confResource = myCtx.newXmlParser().encodeResourceToString(conf);

    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 {
                if (myFirstResponse) {
                  myFirstResponse = false;
                  return new ReaderInputStream(
                      new StringReader(confResource), Charset.forName("UTF-8"));
                } else {
                  Patient resource = new Patient();
                  resource.addName().addFamily().setValue("FAM");
                  return new ReaderInputStream(
                      new StringReader(myCtx.newXmlParser().encodeResourceToString(resource)),
                      Charset.forName("UTF-8"));
                }
              }
            });

    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE);

    IGenericClient client = myCtx.newRestfulGenericClient("http://foo");
    client.registerInterceptor(new BasicAuthInterceptor("USER", "PASS"));

    client.forceConformanceCheck();

    assertEquals(1, capt.getAllValues().size());

    Patient pt = (Patient) client.read(new UriDt("http://foo/Patient/123"));
    assertEquals("FAM", pt.getNameFirstRep().getFamilyAsSingleString());

    assertEquals(2, capt.getAllValues().size());

    Header auth = capt.getAllValues().get(0).getFirstHeader("Authorization");
    assertNotNull(auth);
    assertEquals("Basic VVNFUjpQQVNT", auth.getValue());
    auth = capt.getAllValues().get(1).getFirstHeader("Authorization");
    assertNotNull(auth);
    assertEquals("Basic VVNFUjpQQVNT", auth.getValue());
  }
예제 #16
0
  @Test
  public void testExtendedClass() {
    FhirContext ctx = new FhirContext();
    ctx.getResourceDefinition(MyPatient.class);

    RuntimeResourceDefinition patient = ctx.getResourceDefinition("Patient");
    assertEquals(Patient.class, patient.getImplementingClass());

    RuntimeResourceDefinition def = ctx.getResourceDefinition(MyPatient.class);
    RuntimeResourceDefinition baseDef = def.getBaseDefinition();
    assertEquals(Patient.class, baseDef.getImplementingClass());
  }
예제 #17
0
  public FHIRService(
      String url,
      Context context,
      DeviceInformation deviceInfo,
      no.nordicsemi.android.nrftoolbox.gls.Patient p) {
    this.context = context;
    this.deviceInfo = deviceInfo;
    this.patient = p;

    // initialize context and client
    ctx = FhirContext.forDstu2();
    ctx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
    client = ctx.newRestfulGenericClient(url);
  }
  public static BaseHttpClientInvocation createValidateInvocation(
      FhirContext theContext, IBaseResource theResource) {
    IBaseParameters parameters =
        (IBaseParameters) theContext.getResourceDefinition("Parameters").newInstance();
    ParametersUtil.addParameterToParameters(theContext, parameters, theResource, "resource");

    String resourceName = theContext.getResourceDefinition(theResource).getName();
    String resourceId = theResource.getIdElement().getIdPart();

    BaseHttpClientInvocation retVal =
        createOperationInvocation(
            theContext, resourceName, resourceId, Constants.EXTOP_VALIDATE, parameters, false);
    return retVal;
  }
  @Override
  public ValueSet expandByIdentifier(String theUri, String theFilter) {
    if (isBlank(theUri)) {
      throw new InvalidRequestException("URI must not be blank or missing");
    }
    ValueSet source;

    org.hl7.fhir.instance.model.ValueSet defaultValueSet =
        myDefaultProfileValidationSupport.fetchResource(
            myRiCtx, org.hl7.fhir.instance.model.ValueSet.class, theUri);
    if (defaultValueSet != null) {
      source =
          getContext()
              .newJsonParser()
              .parseResource(
                  ValueSet.class, myRiCtx.newJsonParser().encodeResourceToString(defaultValueSet));
    } else {
      IBundleProvider ids = search(ValueSet.SP_URL, new UriParam(theUri));
      if (ids.size() == 0) {
        throw new InvalidRequestException("Unknown ValueSet URI: " + theUri);
      }
      source = (ValueSet) ids.getResources(0, 1).get(0);
    }

    return expand(source, theFilter);
  }
예제 #20
0
  @Test
  public void testIIncludedResourcesNonContainedInExtensionJson() throws Exception {
    HttpGet httpGet =
        new HttpGet(
            "http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true&_format=json");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newJsonParser().parseBundle(responseContent);

    ourLog.info(responseContent);

    assertEquals(3, bundle.size());
    assertEquals(
        new IdDt("Patient/p1"),
        bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless());
    assertEquals(
        new IdDt("Patient/p2"),
        bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless());
    assertEquals(
        new IdDt("Organization/o1"),
        bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless());
    assertEquals(
        BundleEntrySearchModeEnum.INCLUDE,
        bundle.getEntries().get(2).getSearchMode().getValueAsEnum());

    Patient p1 = (Patient) bundle.toListOfResources().get(0);
    assertEquals(0, p1.getContained().getContainedResources().size());

    Patient p2 = (Patient) bundle.toListOfResources().get(1);
    assertEquals(0, p2.getContained().getContainedResources().size());
  }
예제 #21
0
public class ModelExtensionTest {
  private static final org.slf4j.Logger ourLog =
      org.slf4j.LoggerFactory.getLogger(ModelExtensionTest.class);
  private FhirContext ourCtx = FhirContext.forDstu1();

  @Test
  public void testModelExtension() throws DataFormatException {
    MyOrganization org = new MyOrganization();
    org.getName().setValue("org0");

    MyPatient patient = new MyPatient();
    patient.addIdentifier("foo", "bar");
    patient.getManagingOrganization().setResource(org);

    IParser p = ourCtx.newXmlParser().setPrettyPrint(true);
    String str = p.encodeResourceToString(patient);

    ourLog.info(str);

    MyPatient parsed = ourCtx.newXmlParser().parseResource(MyPatient.class, str);
    assertEquals("foo", parsed.getIdentifierFirstRep().getSystem().getValueAsString());

    //		assertEquals(MyOrganization.class,
    // parsed.getManagingOrganization().getResource().getClass());
    //		MyOrganization parsedOrg = (MyOrganization) parsed.getManagingOrganization().getResource();
    //		assertEquals("arg0", parsedOrg.getName().getValue());
  }

  @AfterClass
  public static void afterClassClearContext() {
    TestUtil.clearAllStaticFieldsForUnitTest();
  }
}
  /** See #164 */
  @Test
  public void testSearchByPostWithParamsInBodyAndUrl() throws Exception {
    HttpPost filePost =
        new HttpPost("http://localhost:" + ourPort + "/Patient/_search?name=Central");

    // add parameters to the post method
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("_id", "aaa"));

    UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, "UTF-8");
    filePost.setEntity(sendentity);

    HttpResponse status = ourClient.execute(filePost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(200, status.getStatusLine().getStatusCode());

    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals("idaaa", p.getName().get(0).getFamilyAsSingleString());
    assertEquals("nameCentral", p.getName().get(1).getFamilyAsSingleString());
  }
예제 #23
0
  @Test
  public void testUpdateNoResponse() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    String encoded = ourCtx.newXmlParser().encodeResourceToString(dr);
    ourLog.info("OUT: {}", encoded);

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.setEntity(
        new StringEntity(encoded, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);
    try {
      ourLog.info(IOUtils.toString(status.getEntity().getContent()));
      assertEquals(200, status.getStatusLine().getStatusCode());
      assertEquals(
          "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
          status.getFirstHeader("location").getValue());
    } finally {
      IOUtils.closeQuietly(status.getEntity().getContent());
    }
  }
예제 #24
0
  @Test
  public void testUpdateWithVersion() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.getIdentifier().setValue("001");

    HttpPut httpPut = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPut.addHeader("Content-Location", "/DiagnosticReport/001/_history/004");
    httpPut.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPut);
    IOUtils.closeQuietly(status.getEntity().getContent());

    // String responseContent =
    // IOUtils.toString(status.getEntity().getContent());
    // ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
        status.getFirstHeader("Location").getValue());
  }
예제 #25
0
  @Test
  public void testUpdateWithWrongResourceType() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/AAAAAA");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(400, status.getStatusLine().getStatusCode());

    String expected =
        "<OperationOutcome xmlns=\"http://hl7.org/fhir\"><issue><severity value=\"error\"/><details value=\"Failed to parse request body as XML resource. Error was: DataFormatException at [[row,col {unknown-source}]: [1,1]]: Incorrect resource type found, expected &quot;DiagnosticReport&quot; but found &quot;Patient&quot;\"/></issue></OperationOutcome>";
    assertEquals(expected, responseContent);
  }
  @Test
  public void testUpdateWithoutConditionalUrl() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());

    assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue());
    assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue());
    assertNull(ourLastConditionalUrl);
  }
  @Test
  public void testServerReturnsAnHttp401() throws Exception {
    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);

    when(myHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 401, "Unauthorized"));
    when(myHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_TEXT));
    when(myHttpResponse.getEntity().getContent())
        .thenAnswer(
            new Answer<InputStream>() {
              @Override
              public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
                return new ReaderInputStream(
                    new StringReader("Unauthorized"), Charset.forName("UTF-8"));
              }
            });
    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    IGenericClient client = myCtx.newRestfulGenericClient("http://foo");
    try {
      client.read().resource(Patient.class).withId("123").execute();
      fail();
    } catch (AuthenticationException e) {
      // good
    }
  }
예제 #28
0
  private void encodeUndeclaredExtensions(
      IBaseResource theResource,
      XMLStreamWriter theWriter,
      List<? extends IBaseExtension<?>> theExtensions,
      String tagName,
      boolean theIncludedResource)
      throws XMLStreamException, DataFormatException {
    for (IBaseExtension<?> next : theExtensions) {
      if (next == null) {
        continue;
      }

      theWriter.writeStartElement(tagName);

      String url = next.getUrl();
      theWriter.writeAttribute("url", url);

      if (next.getValue() != null) {
        IBaseDatatype value = next.getValue();
        RuntimeChildUndeclaredExtensionDefinition extDef =
            myContext.getRuntimeChildUndeclaredExtensionDefinition();
        String childName = extDef.getChildNameByDatatype(value.getClass());
        BaseRuntimeElementDefinition<?> childDef;
        if (childName == null) {
          childDef = myContext.getElementDefinition(value.getClass());
          if (childDef == null) {
            throw new ConfigurationException(
                "Unable to encode extension, unrecognized child element type: "
                    + value.getClass().getCanonicalName());
          } else {
            childName =
                RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef);
          }
        } else {
          childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
        }
        encodeChildElementToStreamWriter(
            theResource, theWriter, value, childName, childDef, null, theIncludedResource);
      }

      // child extensions
      encodeExtensionsIfPresent(theResource, theWriter, next, theIncludedResource);

      theWriter.writeEndElement();
    }
  }
  @Test
  public void testSchemaBundleValidatorIsSuccessful() throws IOException {
    String res =
        IOUtils.toString(getClass().getClassLoader().getResourceAsStream("bundle-example.json"));
    Bundle b = ourCtx.newJsonParser().parseBundle(res);

    ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(b));

    FhirValidator val = createFhirValidator();

    ValidationResult result = val.validateWithResult(b);

    OperationOutcome operationOutcome = (OperationOutcome) result.toOperationOutcome();

    assertTrue(result.toString(), result.isSuccessful());
    assertNotNull(operationOutcome);
    assertEquals(1, operationOutcome.getIssue().size());
  }
  @Test
  public void testServerReturnsAppropriateVersionForDstu2_050() throws Exception {
    Conformance conf = new Conformance();
    conf.setFhirVersion("0.5.0");
    final String confResource = myCtx.newXmlParser().encodeResourceToString(conf);

    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 {
                if (myFirstResponse) {
                  myFirstResponse = false;
                  return new ReaderInputStream(
                      new StringReader(confResource), Charset.forName("UTF-8"));
                } else {
                  return new ReaderInputStream(
                      new StringReader(myCtx.newXmlParser().encodeResourceToString(new Patient())),
                      Charset.forName("UTF-8"));
                }
              }
            });

    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE);
    IGenericClient client = myCtx.newRestfulGenericClient("http://foo");

    // don't load the conformance until the first time the client is actually used
    assertTrue(myFirstResponse);
    client.read(new UriDt("http://foo/Patient/123"));
    assertFalse(myFirstResponse);
    myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123"));
    myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123"));

    // Conformance only loaded once, then 3 reads
    verify(myHttpClient, times(4)).execute(Matchers.any(HttpUriRequest.class));
  }