001package org.hl7.fhir.r4.utils.client.network; 002 003import okhttp3.*; 004import org.apache.commons.lang3.StringUtils; 005import org.hl7.fhir.r4.formats.IParser; 006import org.hl7.fhir.r4.formats.JsonParser; 007import org.hl7.fhir.r4.formats.XmlParser; 008import org.hl7.fhir.r4.model.Bundle; 009import org.hl7.fhir.r4.model.OperationOutcome; 010import org.hl7.fhir.r4.model.Resource; 011import org.hl7.fhir.r4.utils.ResourceUtilities; 012import org.hl7.fhir.r4.utils.client.EFhirClientException; 013import org.hl7.fhir.r4.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.r4.model.OperationOutcome.OperationOutcomeIssueComponent} within the 108 * provided {@link OperationOutcome} have an {@link org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity} of 109 * {@link org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity#ERROR} or 110 * {@link org.hl7.fhir.r4.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 .addInterceptor(new RetryInterceptor(retryCount)) 170 .connectTimeout(timeout, timeoutUnit) 171 .writeTimeout(timeout, timeoutUnit) 172 .readTimeout(timeout, timeoutUnit) 173 .proxyAuthenticator(proxyAuthenticator) 174 .build(); 175 } 176 177 public FhirRequestBuilder withResourceFormat(String resourceFormat) { 178 this.resourceFormat = resourceFormat; 179 return this; 180 } 181 182 public FhirRequestBuilder withHeaders(Headers headers) { 183 this.headers = headers; 184 return this; 185 } 186 187 public FhirRequestBuilder withMessage(String message) { 188 this.message = message; 189 return this; 190 } 191 192 public FhirRequestBuilder withRetryCount(int retryCount) { 193 this.retryCount = retryCount; 194 return this; 195 } 196 197 public FhirRequestBuilder withLogger(FhirLoggingInterceptor logger) { 198 this.logger = logger; 199 return this; 200 } 201 202 public FhirRequestBuilder withTimeout(long timeout, TimeUnit unit) { 203 this.timeout = timeout; 204 this.timeoutUnit = unit; 205 return this; 206 } 207 208 protected Request buildRequest() { 209 return httpRequest.build(); 210 } 211 212 public <T extends Resource> ResourceRequest<T> execute() throws IOException { 213 formatHeaders(httpRequest, resourceFormat, headers); 214 Response response = getHttpClient().newCall(httpRequest.build()).execute(); 215 T resource = unmarshalReference(response, resourceFormat); 216 return new ResourceRequest<T>(resource, response.code(), getLocationHeader(response.headers())); 217 } 218 219 public Bundle executeAsBatch() throws IOException { 220 formatHeaders(httpRequest, resourceFormat, null); 221 Response response = getHttpClient().newCall(httpRequest.build()).execute(); 222 return unmarshalFeed(response, resourceFormat); 223 } 224 225 /** 226 * Unmarshalls a resource from the response stream. 227 */ 228 @SuppressWarnings("unchecked") 229 protected <T extends Resource> T unmarshalReference(Response response, String format) { 230 T resource = null; 231 OperationOutcome error = null; 232 233 if (response.body() != null) { 234 try { 235 byte[] body = response.body().bytes(); 236 resource = (T) getParser(format).parse(body); 237 if (resource instanceof OperationOutcome && hasError((OperationOutcome) resource)) { 238 error = (OperationOutcome) resource; 239 } 240 } catch (IOException ioe) { 241 throw new EFhirClientException("Error reading Http Response: " + ioe.getMessage(), ioe); 242 } catch (Exception e) { 243 throw new EFhirClientException("Error parsing response message: " + e.getMessage(), e); 244 } 245 } 246 247 if (error != null) { 248 throw new EFhirClientException("Error from server: " + ResourceUtilities.getErrorDescription(error), error); 249 } 250 251 return resource; 252 } 253 254 /** 255 * Unmarshalls Bundle from response stream. 256 */ 257 protected Bundle unmarshalFeed(Response response, String format) { 258 Bundle feed = null; 259 OperationOutcome error = null; 260 try { 261 byte[] body = response.body().bytes(); 262 String contentType = response.header("Content-Type"); 263 if (body != null) { 264 if (contentType.contains(ResourceFormat.RESOURCE_XML.getHeader()) || contentType.contains("text/xml+fhir")) { 265 Resource rf = getParser(format).parse(body); 266 if (rf instanceof Bundle) 267 feed = (Bundle) rf; 268 else if (rf instanceof OperationOutcome && hasError((OperationOutcome) rf)) { 269 error = (OperationOutcome) rf; 270 } else { 271 throw new EFhirClientException("Error reading server response: a resource was returned instead"); 272 } 273 } 274 } 275 } catch (IOException ioe) { 276 throw new EFhirClientException("Error reading Http Response", ioe); 277 } catch (Exception e) { 278 throw new EFhirClientException("Error parsing response message", e); 279 } 280 if (error != null) { 281 throw new EFhirClientException("Error from server: " + ResourceUtilities.getErrorDescription(error), error); 282 } 283 return feed; 284 } 285 286 /** 287 * Returns the appropriate parser based on the format type passed in. Defaults to XML parser if a blank format is 288 * provided...because reasons. 289 * <p> 290 * Currently supports only "json" and "xml" formats. 291 * 292 * @param format One of "json" or "xml". 293 * @return {@link JsonParser} or {@link XmlParser} 294 */ 295 protected IParser getParser(String format) { 296 if (StringUtils.isBlank(format)) { 297 format = ResourceFormat.RESOURCE_XML.getHeader(); 298 } 299 if (format.equalsIgnoreCase("json") || format.equalsIgnoreCase(ResourceFormat.RESOURCE_JSON.getHeader())) { 300 return new JsonParser(); 301 } else if (format.equalsIgnoreCase("xml") || format.equalsIgnoreCase(ResourceFormat.RESOURCE_XML.getHeader())) { 302 return new XmlParser(); 303 } else { 304 throw new EFhirClientException("Invalid format: " + format); 305 } 306 } 307}