001package org.hl7.fhir.r5.utils.client.network;
002
003import okhttp3.*;
004import org.apache.commons.lang3.StringUtils;
005import org.hl7.fhir.r5.formats.IParser;
006import org.hl7.fhir.r5.formats.JsonParser;
007import org.hl7.fhir.r5.formats.XmlParser;
008import org.hl7.fhir.r5.model.Bundle;
009import org.hl7.fhir.r5.model.OperationOutcome;
010import org.hl7.fhir.r5.model.Resource;
011import org.hl7.fhir.r5.utils.ResourceUtilities;
012import org.hl7.fhir.r5.utils.client.EFhirClientException;
013import org.hl7.fhir.r5.utils.client.ResourceFormat;
014import org.hl7.fhir.utilities.ToolingClientLogger;
015
016import java.io.IOException;
017import java.util.ArrayList;
018import java.util.Collections;
019import java.util.List;
020import java.util.Map;
021import java.util.concurrent.TimeUnit;
022
023public class FhirRequestBuilder {
024
025  protected static final String HTTP_PROXY_USER = "http.proxyUser";
026  protected static final String HTTP_PROXY_PASS = "http.proxyPassword";
027  protected static final String HEADER_PROXY_AUTH = "Proxy-Authorization";
028  protected static final String LOCATION_HEADER = "location";
029  protected static final String CONTENT_LOCATION_HEADER = "content-location";
030  protected static final String DEFAULT_CHARSET = "UTF-8";
031  /**
032   * The singleton instance of the HttpClient, used for all requests.
033   */
034  private static OkHttpClient okHttpClient;
035  private final Request.Builder httpRequest;
036  private String resourceFormat = null;
037  private Headers headers = null;
038  private String message = null;
039  private int retryCount = 1;
040  /**
041   * The timeout quantity. Used in combination with {@link FhirRequestBuilder#timeoutUnit}.
042   */
043  private long timeout = 5000;
044  /**
045   * Time unit for {@link FhirRequestBuilder#timeout}.
046   */
047  private TimeUnit timeoutUnit = TimeUnit.MILLISECONDS;
048
049  /**
050   * {@link FhirLoggingInterceptor} for log output.
051   */
052  private FhirLoggingInterceptor logger = null;
053
054  public FhirRequestBuilder(Request.Builder httpRequest) {
055    this.httpRequest = httpRequest;
056  }
057
058  /**
059   * Adds necessary default headers, formatting headers, and any passed in {@link Headers} to the passed in
060   * {@link okhttp3.Request.Builder}
061   *
062   * @param request {@link okhttp3.Request.Builder} to add headers to.
063   * @param format  Expected {@link Resource} format.
064   * @param headers Any additional {@link Headers} to add to the request.
065   */
066  protected static void formatHeaders(Request.Builder request, String format, Headers headers) {
067    addDefaultHeaders(request, headers);
068    if (format != null) addResourceFormatHeaders(request, format);
069    if (headers != null) addHeaders(request, headers);
070  }
071
072  /**
073   * Adds necessary headers for all REST requests.
074   * <li>User-Agent : hapi-fhir-tooling-client</li>
075   * <li>Accept-Charset : {@link FhirRequestBuilder#DEFAULT_CHARSET}</li>
076   *
077   * @param request {@link Request.Builder} to add default headers to.
078   */
079  protected static void addDefaultHeaders(Request.Builder request, Headers headers) {
080    if (headers == null || !headers.names().contains("User-Agent")) {
081      request.addHeader("User-Agent", "hapi-fhir-tooling-client");
082    }
083    request.addHeader("Accept-Charset", DEFAULT_CHARSET);
084  }
085
086  /**
087   * Adds necessary headers for the given resource format provided.
088   *
089   * @param request {@link Request.Builder} to add default headers to.
090   */
091  protected static void addResourceFormatHeaders(Request.Builder request, String format) {
092    request.addHeader("Accept", format);
093    request.addHeader("Content-Type", format + ";charset=" + DEFAULT_CHARSET);
094  }
095
096  /**
097   * Iterates through the passed in {@link Headers} and adds them to the provided {@link Request.Builder}.
098   *
099   * @param request {@link Request.Builder} to add headers to.
100   * @param headers {@link Headers} to add to request.
101   */
102  protected static void addHeaders(Request.Builder request, Headers headers) {
103    headers.forEach(header -> request.addHeader(header.getFirst(), header.getSecond()));
104  }
105
106  /**
107   * Returns true if any of the {@link org.hl7.fhir.r5.model.OperationOutcome.OperationOutcomeIssueComponent} within the
108   * provided {@link OperationOutcome} have an {@link org.hl7.fhir.r5.model.OperationOutcome.IssueSeverity} of
109   * {@link org.hl7.fhir.r5.model.OperationOutcome.IssueSeverity#ERROR} or
110   * {@link org.hl7.fhir.r5.model.OperationOutcome.IssueSeverity#FATAL}
111   *
112   * @param oo {@link OperationOutcome} to evaluate.
113   * @return {@link Boolean#TRUE} if an error exists.
114   */
115  protected static boolean hasError(OperationOutcome oo) {
116    return (oo.getIssue().stream()
117      .anyMatch(issue -> issue.getSeverity() == OperationOutcome.IssueSeverity.ERROR
118        || issue.getSeverity() == OperationOutcome.IssueSeverity.FATAL));
119  }
120
121  /**
122   * Extracts the 'location' header from the passes in {@link Headers}. If no value for 'location' exists, the
123   * value for 'content-location' is returned. If neither header exists, we return null.
124   *
125   * @param headers {@link Headers} to evaluate
126   * @return {@link String} header value, or null if no location headers are set.
127   */
128  protected static String getLocationHeader(Headers headers) {
129    Map<String, List<String>> headerMap = headers.toMultimap();
130    if (headerMap.containsKey(LOCATION_HEADER)) {
131      return headerMap.get(LOCATION_HEADER).get(0);
132    } else if (headerMap.containsKey(CONTENT_LOCATION_HEADER)) {
133      return headerMap.get(CONTENT_LOCATION_HEADER).get(0);
134    } else {
135      return null;
136    }
137  }
138
139  /**
140   * We only ever want to have one copy of the HttpClient kicking around at any given time. If we need to make changes
141   * to any configuration, such as proxy settings, timeout, caches, etc, we can do a per-call configuration through
142   * the {@link OkHttpClient#newBuilder()} method. That will return a builder that shares the same connection pool,
143   * dispatcher, and configuration with the original client.
144   * </p>
145   * The {@link OkHttpClient} uses the proxy auth properties set in the current system properties. The reason we don't
146   * set the proxy address and authentication explicitly, is due to the fact that this class is often used in conjunction
147   * with other http client tools which rely on the system.properties settings to determine proxy settings. It's easier
148   * to keep the method consistent across the board. ...for now.
149   *
150   * @return {@link OkHttpClient} instance
151   */
152  protected OkHttpClient getHttpClient() {
153    if (okHttpClient == null) {
154      okHttpClient = new OkHttpClient();
155    }
156
157    Authenticator proxyAuthenticator = (route, response) -> {
158      String credential = Credentials.basic(System.getProperty(HTTP_PROXY_USER), System.getProperty(HTTP_PROXY_PASS));
159      return response.request().newBuilder()
160        .header(HEADER_PROXY_AUTH, credential)
161        .build();
162    };
163
164    OkHttpClient.Builder builder = okHttpClient.newBuilder();
165    if (logger != null) builder.addInterceptor(logger);
166    builder.addInterceptor(new RetryInterceptor(retryCount));
167
168    return builder.connectTimeout(timeout, timeoutUnit)
169      .writeTimeout(timeout, timeoutUnit)
170      .readTimeout(timeout, timeoutUnit)
171      .proxyAuthenticator(proxyAuthenticator)
172      .build();
173  }
174
175  public FhirRequestBuilder withResourceFormat(String resourceFormat) {
176    this.resourceFormat = resourceFormat;
177    return this;
178  }
179
180  public FhirRequestBuilder withHeaders(Headers headers) {
181    this.headers = headers;
182    return this;
183  }
184
185  public FhirRequestBuilder withMessage(String message) {
186    this.message = message;
187    return this;
188  }
189
190  public FhirRequestBuilder withRetryCount(int retryCount) {
191    this.retryCount = retryCount;
192    return this;
193  }
194
195  public FhirRequestBuilder withLogger(FhirLoggingInterceptor logger) {
196    this.logger = logger;
197    return this;
198  }
199
200  public FhirRequestBuilder withTimeout(long timeout, TimeUnit unit) {
201    this.timeout = timeout;
202    this.timeoutUnit = unit;
203    return this;
204  }
205
206  protected Request buildRequest() {
207    return httpRequest.build();
208  }
209
210  public <T extends Resource> ResourceRequest<T> execute() throws IOException {
211    formatHeaders(httpRequest, resourceFormat, headers);
212    Response response = getHttpClient().newCall(httpRequest.build()).execute();
213    T resource = unmarshalReference(response, resourceFormat);
214    return new ResourceRequest<T>(resource, response.code(), getLocationHeader(response.headers()));
215  }
216
217  public Bundle executeAsBatch() throws IOException {
218    formatHeaders(httpRequest, resourceFormat, null);
219    Response response = getHttpClient().newCall(httpRequest.build()).execute();
220    return unmarshalFeed(response, resourceFormat);
221  }
222
223  /**
224   * Unmarshalls a resource from the response stream.
225   */
226  @SuppressWarnings("unchecked")
227  protected <T extends Resource> T unmarshalReference(Response response, String format) {
228    T resource = null;
229    OperationOutcome error = null;
230
231    if (response.body() != null) {
232      try {
233        byte[] body = response.body().bytes();
234        resource = (T) getParser(format).parse(body);
235        if (resource instanceof OperationOutcome && hasError((OperationOutcome) resource)) {
236          error = (OperationOutcome) resource;
237        }
238      } catch (IOException ioe) {
239        throw new EFhirClientException("Error reading Http Response: " + ioe.getMessage(), ioe);
240      } catch (Exception e) {
241        throw new EFhirClientException("Error parsing response message: " + e.getMessage(), e);
242      }
243    }
244
245    if (error != null) {
246      throw new EFhirClientException("Error from server: " + ResourceUtilities.getErrorDescription(error), error);
247    }
248
249    return resource;
250  }
251
252  /**
253   * Unmarshalls Bundle from response stream.
254   */
255  protected Bundle unmarshalFeed(Response response, String format) {
256    Bundle feed = null;
257    OperationOutcome error = null;
258    try {
259      byte[] body = response.body().bytes();
260      String contentType = response.header("Content-Type");
261      if (body != null) {
262        if (contentType.contains(ResourceFormat.RESOURCE_XML.getHeader()) || contentType.contains("text/xml+fhir")) {
263          Resource rf = getParser(format).parse(body);
264          if (rf instanceof Bundle)
265            feed = (Bundle) rf;
266          else if (rf instanceof OperationOutcome && hasError((OperationOutcome) rf)) {
267            error = (OperationOutcome) rf;
268          } else {
269            throw new EFhirClientException("Error reading server response: a resource was returned instead");
270          }
271        }
272      }
273    } catch (IOException ioe) {
274      throw new EFhirClientException("Error reading Http Response", ioe);
275    } catch (Exception e) {
276      throw new EFhirClientException("Error parsing response message", e);
277    }
278    if (error != null) {
279      throw new EFhirClientException("Error from server: " + ResourceUtilities.getErrorDescription(error), error);
280    }
281    return feed;
282  }
283
284  /**
285   * Returns the appropriate parser based on the format type passed in. Defaults to XML parser if a blank format is
286   * provided...because reasons.
287   * <p>
288   * Currently supports only "json" and "xml" formats.
289   *
290   * @param format One of "json" or "xml".
291   * @return {@link JsonParser} or {@link XmlParser}
292   */
293  protected IParser getParser(String format) {
294    if (StringUtils.isBlank(format)) {
295      format = ResourceFormat.RESOURCE_XML.getHeader();
296    }
297    if (format.equalsIgnoreCase("json") || format.equalsIgnoreCase(ResourceFormat.RESOURCE_JSON.getHeader())) {
298      return new JsonParser();
299    } else if (format.equalsIgnoreCase("xml") || format.equalsIgnoreCase(ResourceFormat.RESOURCE_XML.getHeader())) {
300      return new XmlParser();
301    } else {
302      throw new EFhirClientException("Invalid format: " + format);
303    }
304  }
305}