Java Code Examples for ca.uhn.fhir.context.FhirContext#newRestfulGenericClient()

The following examples show how to use ca.uhn.fhir.context.FhirContext#newRestfulGenericClient() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestApplication.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * This is the Java main method, which gets executed
 */
public static void main(String[] args) {

   // Create a context
   FhirContext ctx = FhirContext.forR4();

   // Create a client
   IGenericClient client = ctx.newRestfulGenericClient("https://hapi.fhir.org/baseR4");

   // Read a patient with the given ID
   Patient patient = client.read().resource(Patient.class).withId("example").execute();

   // Print the output
   String string = ctx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
   System.out.println(string);

}
 
Example 2
Source File: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public static void step1_read_a_resource() {

		FhirContext ctx = FhirContext.forDstu3();
		IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

		Patient patient;
		try {
			// Try changing the ID from 952975 to 999999999999
			patient = client.read().resource(Patient.class).withId("952975").execute();
		} catch (ResourceNotFoundException e) {
			System.out.println("Resource not found!");
			return;
		}

		String string = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient);
		System.out.println(string);

	}
 
Example 3
Source File: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public static void step2_search_for_patients_named_test() {
	FhirContext ctx = FhirContext.forDstu3();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

	org.hl7.fhir.r4.model.Bundle results = client
		.search()
		.forResource(Patient.class)
		.where(Patient.NAME.matches().value("test"))
		.returnBundle(org.hl7.fhir.r4.model.Bundle.class)
		.execute();

	System.out.println("First page: ");
	System.out.println(ctx.newXmlParser().encodeResourceToString(results));

	// Load the next page
	org.hl7.fhir.r4.model.Bundle nextPage = client
		.loadPage()
		.next(results)
		.execute();

	System.out.println("Next page: ");
	System.out.println(ctx.newXmlParser().encodeResourceToString(nextPage));

}
 
Example 4
Source File: Example08_ClientSearch.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public static void main(String[] theArgs) {
   FhirContext ctx = FhirContext.forDstu3();
   IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

   // Build a search and execute it
   Bundle response = client.search()
      .forResource(Patient.class)
      .where(Patient.NAME.matches().value("Test"))
      .and(Patient.BIRTHDATE.before().day("2014-01-01"))
      .count(100)
      .returnBundle(Bundle.class)
      .execute();

   // How many resources did we find?
   System.out.println("Responses: " + response.getTotal());

   // Print the ID of the first one
   System.out.println("First response ID: " + response.getEntry().get(0).getResource().getId());
}
 
Example 5
Source File: TestFhirLibrary.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
public void TestCMS9v4_CQM() throws IOException, JAXBException {
      File xmlFile = new File(URLDecoder.decode(TestFhirLibrary.class.getResource("CMS9v4_CQM.xml").getFile(), "UTF-8"));
      Library library = CqlLibraryReader.read(xmlFile);

      Context context = new Context(library);

      FhirContext fhirContext = FhirContext.forDstu3();

Dstu3FhirModelResolver modelResolver = new Dstu3FhirModelResolver();
RestFhirRetrieveProvider retrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(fhirContext),  fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"));
CompositeDataProvider provider = new CompositeDataProvider(modelResolver, retrieveProvider);
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3");
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://fhir3.healthintersections.com.au/open/");
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://wildfhir.aegis.net/fhir");
      context.registerDataProvider("http://hl7.org/fhir", provider);

      Object result = context.resolveExpressionRef("Breastfeeding Intention Assessment").evaluate(context);
      assertThat(result, instanceOf(Iterable.class));
      for (Object element : (Iterable)result) {
          assertThat(element, instanceOf(RiskAssessment.class));
      }
  }
 
Example 6
Source File: Example06_ClientCreate.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] theArgs) {

      Patient pat = new Patient();
      pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("J");
      pat.addIdentifier().setSystem("http://acme.org/MRNs").setValue("7000135");
      pat.setGender(AdministrativeGender.MALE);

      // Create a context
      FhirContext ctx = FhirContext.forR4();

      // Create a client
      String serverBaseUrl = "http://hapi.fhir.org/baseR4";
      IGenericClient client = ctx.newRestfulGenericClient(serverBaseUrl);

      // Use the client to store a new resource instance
      MethodOutcome outcome = client
         .create()
         .resource(pat)
         .execute();

      // Print the ID of the newly created resource
      System.out.println(outcome.getId());
   }
 
Example 7
Source File: Example07_ClientReadAndUpdate.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] theArgs) {
   // Create a client
	FhirContext ctx = FhirContext.forR4();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/R4");

	Patient patient = new Patient();
	patient.setId("Patient/example"); // Give the patient an ID
	patient.addName().setFamily("Simpson").addGiven("Homer");
	patient.setGender(Enumerations.AdministrativeGender.MALE);

	// Update the patient
	MethodOutcome outcome = client
        .update()
        .resource(patient)
        .execute();
	
	System.out.println("Now have ID: " + outcome.getId());
}
 
Example 8
Source File: TestFhirPath.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Test
public void testFhirHelpersStu3() throws UcumException {
    String cql = getStringFromResourceStream("stu3/TestFHIRHelpers.cql");
    Library library = translate(cql);
    Context context = new Context(library);
    context.registerLibraryLoader(getLibraryLoader());

    Dstu3FhirModelResolver modelResolver = new Dstu3FhirModelResolver();
    FhirContext fhirContext = FhirContext.forDstu3();
    RestFhirRetrieveProvider retrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(fhirContext),
            fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"));
    CompositeDataProvider provider = new CompositeDataProvider(modelResolver, retrieveProvider);
    // BaseFhirDataProvider provider = new
    // FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3");
    context.registerDataProvider("http://hl7.org/fhir", provider);

    Object result = context.resolveExpressionRef("TestPeriodToInterval").getExpression().evaluate(context);
    // TODO - fix
    // Assert.assertEquals(((DateTime)((Interval) result).getStart()).getPartial(),
    // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 18, 8, 0}));
    // Assert.assertEquals(((DateTime)((Interval) result).getEnd()).getPartial(),
    // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 19, 8, 0}));
    result = context.resolveExpressionRef("TestToQuantity").getExpression().evaluate(context);
    // TODO: ModelInfo bug. Not aware of SimpleQuantity
    result = context.resolveExpressionRef("TestRangeToInterval").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToCode").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToConcept").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToString").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestRequestStatusToString").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToDateTime").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToTime").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToInteger").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToDecimal").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToBoolean").getExpression().evaluate(context);
}
 
Example 9
Source File: FhirExecutionTestBase.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup() {
    dstu2ModelResolver = new Dstu2FhirModelResolver();
    FhirContext dstu2Context = FhirContext.forDstu2();
    dstu2RetrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(dstu2Context),
            dstu2Context.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu2"));
    dstu2Provider = new CompositeDataProvider(dstu2ModelResolver, dstu2RetrieveProvider);
    
    dstu3ModelResolver = new Dstu3FhirModelResolver();
    FhirContext dstu3Context = FhirContext.forDstu3();
    dstu3RetrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(dstu3Context), 
    dstu3Context.newRestfulGenericClient("http://measure.eval.kanvix.com/cqf-ruler/baseDstu3"));
    dstu3Provider = new CompositeDataProvider(dstu3ModelResolver, dstu3RetrieveProvider);

}
 
Example 10
Source File: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void step3_create_patient() {
	// Create a patient
	Patient newPatient = new Patient();

	// Populate the patient with fake information
	newPatient
		.addName()
			.setFamily("DevDays2015")
			.addGiven("John")
			.addGiven("Q");
	newPatient
		.addIdentifier()
			.setSystem("http://acme.org/mrn")
			.setValue("1234567");
	newPatient.setGender(Enumerations.AdministrativeGender.MALE);
	newPatient.setBirthDateElement(new DateType("2015-11-18"));

	// Create a client
	FhirContext ctx = FhirContext.forDstu3();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

	// Create the resource on the server
	MethodOutcome outcome = client
		.create()
		.resource(newPatient)
		.execute();

	// Log the ID that the server assigned
	IIdType id = outcome.getId();
	System.out.println("Created patient, got ID: " + id);
}
 
Example 11
Source File: FhirVerifierExtension.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static void verifyConnection(ResultBuilder builder, Map<String, Object> parameters) {
    if (!builder.build().getErrors().isEmpty()) {
        return;
    }
    final String serverUrl = ConnectorOptions.extractOption(parameters, SERVER_URL);
    final FhirVersionEnum fhirVersion = ConnectorOptions.extractOptionAsType(
        parameters, FHIR_VERSION, FhirVersionEnum.class);
    final String username = ConnectorOptions.extractOption(parameters, "username");
    final String password = ConnectorOptions.extractOption(parameters, "password");
    final String accessToken = ConnectorOptions.extractOption(parameters, "accessToken");

    LOG.debug("Validating FHIR connection to {} with FHIR version {}", serverUrl, fhirVersion);

    if (ObjectHelper.isNotEmpty(serverUrl)) {
        try {
            FhirContext fhirContext = new FhirContext(fhirVersion);
            IGenericClient iGenericClient = fhirContext.newRestfulGenericClient(serverUrl);

            if (ObjectHelper.isNotEmpty(username) || ObjectHelper.isNotEmpty(password)) {
                if (ObjectHelper.isEmpty(username) || ObjectHelper.isEmpty(password)) {
                    builder.error(
                        ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_GROUP_COMBINATION,
                            "Both username and password must be provided to enable basic authentication")
                            .parameterKey("username")
                            .parameterKey("password")
                            .build());
                } else if (ObjectHelper.isNotEmpty(accessToken)) {
                    builder.error(
                        ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_GROUP_COMBINATION,
                            "You must provide either username and password or bearer token to enable authentication")
                            .parameterKey("accessToken")
                            .build());
                } else {
                    iGenericClient.registerInterceptor(new BasicAuthInterceptor(username, password));
                }
            } else if (ObjectHelper.isNotEmpty(accessToken)) {
                iGenericClient.registerInterceptor(new BearerTokenAuthInterceptor(accessToken));
            }
            iGenericClient.forceConformanceCheck();
        } catch (Exception e) {
            builder.error(
                ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_GROUP_COMBINATION, "Unable to connect to FHIR server")
                    .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e)
                    .parameterKey(SERVER_URL)
                    .parameterKey(FHIR_VERSION)
                    .build()
            );
        }
    } else {
        builder.error(
            ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE, "Invalid blank FHIR server URL")
                .parameterKey(SERVER_URL)
                .build()
        );
    }
}