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