Examples: FHIR Client
This page contains example interceptors that can be registered with the FHIR Client.
The following example shows an interceptor that can be used as a starter Client interceptor, implementing a hook method for each available pointcut.
/*-
* #%L
* Smile CDR - CDR
* %%
* Copyright (C) 2016 - 2023 Smile CDR, Inc.
* %%
* All rights reserved.
* #L%
*/
package com.smilecdr.demo.fhirclient;
import ca.uhn.fhir.interceptor.api.Hook;
import ca.uhn.fhir.interceptor.api.Interceptor;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.client.api.IRestfulClient;
import ca.uhn.fhir.util.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This interceptor is intended to be used with a FHIR client (IRestfulClient, or its implementations)
* and must be registered with it, before being called.
* <p>
* Example:
* IGenericClient fhirClient = FhirContext.forR4().newRestfulGenericClient("http://localhost:8000/");
* fhirClient.registerInterceptor(new ClientInterceptorTemplate());
* Afterward, calls done using 'fhirClient' will be intercepted by 'ClientInterceptorTemplate'
* and CLIENT_REQUEST and CLIENT_RESPONSE hook methods will be called.
* </p><p>
* Client interceptor can be useful to change the behaviour of a FHIR client before it send requests to a FHIR Endpoint,
* by changing the url/headers/content for example,
* or by doing some checks (on http status, headers, etc.) on the response received from a FHIR Endpoint.
* Currently, the response received cannot be modified by the CLIENT_RESPONSE hook.
* </p><p>
* In fact, this is how the FHIR client BasicAuthInterceptor, BearerTokenAuthInterceptor, LoggingInterceptor,
* and others are actually implemented.
* </p>
* Can be used as a starting point for your client interceptor.
*/
@SuppressWarnings({"unused", "EmptyTryBlock"})
@Interceptor
public class ClientInterceptorTemplate {
private static final Logger ourLog = LoggerFactory.getLogger(ClientInterceptorTemplate.class);
@Hook(Pointcut.CLIENT_REQUEST)
public void clientRequest(
IHttpRequest theHttpRequest,
IRestfulClient theRestfulClient) {
ourLog.info("Interceptor CLIENT_REQUEST - started");
StopWatch stopWatch = new StopWatch();
try {
// your implementation goes here
} finally {
ourLog.info("Interceptor CLIENT_REQUEST - ended, execution took {}", stopWatch);
}
}
@Hook(Pointcut.CLIENT_RESPONSE)
public void clientResponse(
IHttpRequest theHttpRequest,
IHttpResponse theHttpResponse,
IRestfulClient theRestfulClient) {
ourLog.info("Interceptor CLIENT_RESPONSE - started");
StopWatch stopWatch = new StopWatch();
try {
// your implementation goes here
} finally {
ourLog.info("Interceptor CLIENT_RESPONSE - ended, execution took {}", stopWatch);
}
}
}