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