ca.uhn.fhir.rest.client.api.IGenericClient Java Examples

The following examples show how to use ca.uhn.fhir.rest.client.api.IGenericClient. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
Source File: Example09_Interceptors.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
      IGenericClient client = FhirContext.forDstu3().newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

      // Register some interceptors
      client.registerInterceptor(new CookieInterceptor("mycookie=Chips Ahoy"));
      client.registerInterceptor(new LoggingInterceptor());

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

		// Change the gender
		patient.setGender(patient.getGender() == AdministrativeGender.MALE ? AdministrativeGender.FEMALE : AdministrativeGender.MALE);

		// Update the patient
		MethodOutcome outcome = client.update().resource(patient).execute();
		
		System.out.println("Now have ID: " + outcome.getId());
	}
 
Example #7
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 #8
Source File: FhirUtil.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public static IGenericClient getGenericClient(String theServerBase) {
	// Create a logging interceptor
	LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
	loggingInterceptor.setLogRequestSummary(true);
	loggingInterceptor.setLogRequestBody(true);

	IGenericClient client = context.newRestfulGenericClient(theServerBase);
	client.registerInterceptor(loggingInterceptor);
	return client;
}
 
Example #9
Source File: FhirBundleCursor.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
public FhirBundleIterator(IGenericClient fhirClient, IBaseBundle results, String dataType) {
    this.fhirClient = fhirClient;
    this.results =  results;
    this.current = -1;
    this.dataType = dataType;

    if (dataType != null) {
        this.dataTypeClass = this.fhirClient.getFhirContext().getResourceDefinition(this.dataType).getImplementingClass();
    }

    this.currentEntry = this.getEntry();
}
 
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: CacheValueSetsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
private ValueSet resolveValueSet(IGenericClient client, String valuesetId) {
    ValueSet valueSet = client.fetchResourceFromUrl(ValueSet.class, client.getServerBase() + "/ValueSet/" + valuesetId);

    boolean expand = false;
    if (valueSet.hasCompose()) {
        for (ValueSet.ConceptSetComponent component : valueSet.getCompose().getInclude()) {
            if (!component.hasConcept() || component.getConcept() == null) {
                expand = true;
            }
        }
    }

    if (expand) {
        return getCachedValueSet(
                client
                        .operation()
                        .onInstance(new IdType("ValueSet", valuesetId))
                        .named("$expand")
                        .withNoParameters(Parameters.class)
                        .returnResourceType(ValueSet.class)
                        .execute()
        );
    }

    valueSet.setVersion(valueSet.getVersion() + "-cache");
    return valueSet;
}
 
Example #12
Source File: CacheValueSetsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
private ValueSet resolveValueSet(IGenericClient client, String valuesetId) {
    ValueSet valueSet = client.fetchResourceFromUrl(ValueSet.class, client.getServerBase() + "/ValueSet/" + valuesetId);

    boolean expand = false;
    if (valueSet.hasCompose()) {
        for (ValueSet.ConceptSetComponent component : valueSet.getCompose().getInclude()) {
            if (!component.hasConcept() || component.getConcept() == null) {
                expand = true;
            }
        }
    }

    if (expand) {
        return getCachedValueSet(
                client
                        .operation()
                        .onInstance(new IdType("ValueSet", valuesetId))
                        .named("$expand")
                        .withNoParameters(Parameters.class)
                        .returnResourceType(ValueSet.class)
                        .execute()
        );
    }

    valueSet.setVersion(valueSet.getVersion() + "-cache");
    return valueSet;
}
 
Example #13
Source File: CacheValueSetsProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
@Operation(name="cache-valuesets", idempotent = true, type = Endpoint.class)
public Resource cacheValuesets(
        RequestDetails details,
        @IdParam IdType theId,
        @RequiredParam(name="valuesets") StringAndListParam valuesets,
        @OptionalParam(name="user") String userName,
        @OptionalParam(name="pass") String password
) {

    Endpoint endpoint = this.endpointDao.read(theId);

    if (endpoint == null) {
        return Helper.createErrorOutcome("Could not find Endpoint/" + theId);
    }

    IGenericClient client = this.systemDao.getContext().newRestfulGenericClient(endpoint.getAddress());

    if (userName != null || password != null) {
        if (userName == null) {
            Helper.createErrorOutcome("Password was provided, but not a user name.");
        }
        else if (password == null) {
            Helper.createErrorOutcome("User name was provided, but not a password.");
        }

        BasicAuthInterceptor basicAuth = new BasicAuthInterceptor(userName, password);
        client.registerInterceptor(basicAuth);

        // TODO - more advanced security like bearer tokens, etc...
    }

    try {
        Bundle bundleToPost = new Bundle();
        for (StringOrListParam params : valuesets.getValuesAsQueryTokens()) {
            for (StringParam valuesetId : params.getValuesAsQueryTokens()) {
                bundleToPost.addEntry()
                        .setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl("ValueSet/" + valuesetId.getValue()))
                        .setResource(resolveValueSet(client, valuesetId.getValue()));
            }
        }

        return (Resource) systemDao.transaction(details, bundleToPost);
    } catch (Exception e) {
        return Helper.createErrorOutcome(e.getMessage());
    }
}
 
Example #14
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()
        );
    }
}
 
Example #15
Source File: CacheValueSetsProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
@Operation(name="cache-valuesets", idempotent = true, type = Endpoint.class)
public Resource cacheValuesets(
        RequestDetails details,
        @IdParam IdType theId,
        @RequiredParam(name="valuesets") StringAndListParam valuesets,
        @OptionalParam(name="user") String userName,
        @OptionalParam(name="pass") String password
) {

    Endpoint endpoint = this.endpointDao.read(theId);

    if (endpoint == null) {
        return Helper.createErrorOutcome("Could not find Endpoint/" + theId);
    }

    IGenericClient client = this.systemDao.getContext().newRestfulGenericClient(endpoint.getAddress());

    if (userName != null || password != null) {
        if (userName == null) {
            Helper.createErrorOutcome("Password was provided, but not a user name.");
        }
        else if (password == null) {
            Helper.createErrorOutcome("User name was provided, but not a password.");
        }

        BasicAuthInterceptor basicAuth = new BasicAuthInterceptor(userName, password);
        client.registerInterceptor(basicAuth);

        // TODO - more advanced security like bearer tokens, etc...
    }

    try {
        Bundle bundleToPost = new Bundle();
        for (StringOrListParam params : valuesets.getValuesAsQueryTokens()) {
            for (StringParam valuesetId : params.getValuesAsQueryTokens()) {
                bundleToPost.addEntry()
                        .setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl("ValueSet/" + valuesetId.getValue()))
                        .setResource(resolveValueSet(client, valuesetId.getValue()));
            }
        }

        return (Resource) systemDao.transaction(details, bundleToPost);
    } catch (Exception e) {
        return Helper.createErrorOutcome(e.getMessage());
    }
}
 
Example #16
Source File: R4FhirTerminologyProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public IGenericClient getFhirClient() {
    return fhirClient;
}
 
Example #17
Source File: R4FhirTerminologyProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public R4FhirTerminologyProvider(IGenericClient fhirClient) {
    this(fhirClient.getFhirContext());
    this.fhirClient = fhirClient;
}
 
Example #18
Source File: Dstu3FhirTerminologyProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public IGenericClient getFhirClient() {
    return fhirClient;
}
 
Example #19
Source File: Dstu3FhirTerminologyProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public Dstu3FhirTerminologyProvider(IGenericClient fhirClient) {
    this(fhirClient.getFhirContext());
    this.fhirClient = fhirClient;
}
 
Example #20
Source File: FhirBundleCursor.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public FhirBundleCursor(IGenericClient fhirClient, IBaseBundle results, String dataType) {
    this.fhirClient = fhirClient;
    this.results = results;
    this.dataType = dataType;
}
 
Example #21
Source File: FhirBundleCursor.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public FhirBundleCursor(IGenericClient fhirClient, IBaseBundle results)
{
    this(fhirClient, results, null);
}
 
Example #22
Source File: RestFhirRetrieveProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public RestFhirRetrieveProvider(SearchParameterResolver searchParameterResolver, IGenericClient fhirClient) {
	super(searchParameterResolver);
	this.fhirClient = fhirClient;
	// TODO: Figure out how to validate that the searchParameterResolver and the context are on the same version of FHIR.
}