2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.aai.restclient.client;
23 import java.io.ByteArrayOutputStream;
24 import java.text.SimpleDateFormat;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.UUID;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33 import java.util.stream.Collectors;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.Invocation.Builder;
37 import javax.ws.rs.client.WebTarget;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.MultivaluedHashMap;
40 import javax.ws.rs.core.MultivaluedMap;
41 import javax.ws.rs.core.Response;
42 import org.onap.aai.cl.api.LogFields;
43 import org.onap.aai.cl.api.LogLine;
44 import org.onap.aai.cl.api.Logger;
45 import org.onap.aai.cl.eelf.LoggerFactory;
46 import org.onap.aai.cl.mdc.MdcContext;
47 import org.onap.aai.cl.mdc.MdcOverride;
48 import org.onap.aai.restclient.enums.RestAuthenticationMode;
49 import org.onap.aai.restclient.logging.RestClientMsgs;
50 import org.onap.aai.restclient.rest.RestClientBuilder;
55 * This class provides a general client implementation that micro services can use for communicating with the endpoints
56 * via their exposed REST interfaces.
60 public class RestClient {
63 * This is a generic builder that is used for constructing the REST client that we will use to communicate with the
66 private RestClientBuilder clientBuilder;
68 private final ConcurrentMap<String, InitializedClient> CLIENT_CACHE = new ConcurrentHashMap<>();
69 private static final String REST_CLIENT_INSTANCE = "REST_CLIENT_INSTANCE";
71 /** Standard logger for producing log statements. */
72 private Logger logger = LoggerFactory.getInstance().getLogger("AAIRESTClient");
74 /** Standard logger for producing metric statements. */
75 private Logger metricsLogger = LoggerFactory.getInstance().getMetricsLogger("AAIRESTClient");
77 private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
79 /** Reusable function call for GET REST operations. */
80 private final RestOperation getOp = new GetRestOperation();
82 /** Reusable function call for PUT REST operations. */
83 private final RestOperation putOp = new PutRestOperation();
85 /** Reusable function call for POST REST operations. */
86 private final RestOperation postOp = new PostRestOperation();
88 /** Reusable function call for DELETE REST operations. */
89 private final RestOperation deleteOp = new DeleteRestOperation();
91 /** Reusable function call for HEAD REST operations. */
92 private final RestOperation headOp = new HeadRestOperation();
94 /** Reusable function call for PATCH REST operations. */
95 private final RestOperation patchOp = new PatchRestOperation();
98 * Creates a new instance of the {@link RestClient}.
100 public RestClient() {
101 clientBuilder = new RestClientBuilder();
105 * Creates a new instance of the {@link RestClient} using the supplied {@link RestClientBuilder}.
107 * @param rcBuilder - The REST client builder that this instance of the {@link RestClient} should use.
109 public RestClient(RestClientBuilder rcBuilder) {
110 clientBuilder = rcBuilder;
113 public RestClient authenticationMode(RestAuthenticationMode mode) {
114 logger.debug("Set rest authentication mode= " + mode);
115 clientBuilder.setAuthenticationMode(mode);
119 public RestClient basicAuthUsername(String username) {
120 logger.debug("Set SSL BasicAuth username = " + username);
121 clientBuilder.setBasicAuthUsername(username);
125 public RestClient basicAuthPassword(String password) {
127 * purposely not logging out the password, I guess we could obfuscate it if we really want to see it in the logs
129 clientBuilder.setBasicAuthPassword(password);
134 * Sets the flag to indicate whether or not validation should be performed against the host name of the server we
135 * are trying to communicate with.
137 * @parameter validate - Set to true to enable validation, false to disable
139 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
141 public RestClient validateServerHostname(boolean validate) {
142 logger.debug("Set validate server hostname = " + validate);
143 clientBuilder.setValidateServerHostname(validate);
148 * Sets the flag to indicate whether or not validation should be performed against the certificate chain.
150 * @parameter validate - Set to true to enable validation, false to disable.
152 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
154 public RestClient validateServerCertChain(boolean validate) {
155 logger.debug("Set validate server certificate chain = " + validate);
156 clientBuilder.setValidateServerCertChain(validate);
161 * Assigns the client certificate file to use.
163 * @param filename - The name of the certificate file.
165 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
167 public RestClient clientCertFile(String filename) {
168 logger.debug("Set client certificate filename = " + filename);
169 clientBuilder.setClientCertFileName(filename);
174 * Assigns the client certificate password to use.
176 * @param password - The certificate password.
178 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
180 public RestClient clientCertPassword(String password) {
181 clientBuilder.setClientCertPassword(password);
186 * Assigns the name of the trust store file to use.
188 * @param filename - the name of the trust store file.
190 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
192 public RestClient trustStore(String filename) {
193 logger.debug("Set trust store filename = " + filename);
194 clientBuilder.setTruststoreFilename(filename);
199 * Assigns the connection timeout (in ms) to use when connecting to the target server.
201 * @param timeout - The length of time to wait in ms before timing out.
203 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
205 public RestClient connectTimeoutMs(int timeout) {
206 logger.debug("Set connection timeout = " + timeout + " ms");
207 clientBuilder.setConnectTimeoutInMs(timeout);
212 * Assigns the read timeout (in ms) to use when communicating with the target server.
214 * @param timeout The read timeout in milliseconds.
216 * @return The AAIRESTClient instance. This is useful for chaining parameter assignments.
218 public RestClient readTimeoutMs(int timeout) {
219 logger.debug("Set read timeout = " + timeout + " ms");
220 clientBuilder.setReadTimeoutInMs(timeout);
225 * Configures the client for a specific SSL protocol
227 * @param sslProtocol - protocol string constant such as TLS, TLSv1, TLSv1.1, TLSv1.2
229 * @return The AAIRESTClient instance.
231 public RestClient sslProtocol(String sslProtocol) {
232 logger.debug("Set sslProtocol = " + sslProtocol);
233 clientBuilder.setSslProtocol(sslProtocol);
237 private boolean shouldRetry(OperationResult operationResult) {
239 if (operationResult == null) {
243 int resultCode = operationResult.getResultCode();
245 if (resultCode == 200) {
249 if (resultCode == 404) {
258 * This method operates on a REST endpoint by submitting an HTTP operation request against the supplied URL. This
259 * variant of the method will perform a requested number of retries in the event that the first request is
262 * @param operation - the REST operation type to send to the url
263 * @param url - The REST endpoint to submit the REST request to.
264 * @param payload - They payload to provide in the REST request, if applicable
265 * @param headers - The headers that should be passed in the request
266 * @param contentType - The content type of the payload
267 * @param responseType - The expected format of the response.
269 * @return The result of the REST request.
271 protected OperationResult processRequest(RestOperation operation, String url, String payload,
272 Map<String, List<String>> headers, MediaType contentType, MediaType responseType, int numRetries) {
275 OperationResult result = null;
277 long startTimeInMs = System.currentTimeMillis();
278 for (int retryCount = 0; retryCount < numRetries; retryCount++) {
280 logger.info(RestClientMsgs.HTTP_REQUEST_WITH_RETRIES, operation.getRequestType().toString(), url,
281 Integer.toString(retryCount + 1));
283 // Submit our query to the AAI.
284 result = processRequest(operation, url, payload, headers, contentType, responseType);
286 // If the submission was successful then we're done.
288 if (!shouldRetry(result)) {
290 logger.info(RestClientMsgs.HTTP_REQUEST_TIME_WITH_RETRIES, operation.getRequestType().toString(), url,
291 Long.toString(System.currentTimeMillis() - startTimeInMs), Integer.toString(retryCount));
293 result.setNumRetries(retryCount);
298 // Our submission was unsuccessful...
300 // Sleep between re-tries to be nice to the target system.
303 } catch (InterruptedException e) {
304 logger.error(RestClientMsgs.HTTP_REQUEST_INTERRUPTED, url, e.getLocalizedMessage());
305 Thread.currentThread().interrupt();
310 // If we've gotten this far, then we failed all of our retries.
311 if (result == null) {
312 result = new OperationResult();
315 result.setNumRetries(numRetries);
316 result.setResultCode(504);
317 result.setFailureCause("Failed to get a successful result after multiple retries to target server.");
324 * This method operates on a REST endpoint by submitting an HTTP operation request against the supplied URL.
326 * @param operation - the REST operation type to send to the url
327 * @param url - The REST endpoint to submit the REST request to.
328 * @param payload - They payload to provide in the REST request, if applicable
329 * @param headers - The headers that should be passed in the request
330 * @param contentType - The content type of the payload
331 * @param responseType - The expected format of the response.
333 * @return The result of the REST request.
335 protected OperationResult processRequest(RestOperation operation, String url, String payload,
336 Map<String, List<String>> headers, MediaType contentType, MediaType responseType) {
338 Response clientResponse = null;
339 OperationResult operationResult = new OperationResult();
340 ByteArrayOutputStream baos = new ByteArrayOutputStream();
342 String requestType = operation.getRequestType().name();
344 // Grab the current time so that we can log how long the
345 // query took once we are done.
346 long startTimeInMs = System.currentTimeMillis();
347 MdcOverride override = new MdcOverride();
348 override.addAttribute(MdcContext.MDC_START_TIME, formatter.format(startTimeInMs));
350 logger.info(RestClientMsgs.HTTP_REQUEST, requestType, url);
354 // Get a REST client instance for our request.
355 Client client = getClient();
357 // Debug log the request
358 debugRequest(url, payload, headers, responseType);
360 // Get a client request builder, and submit our GET request.
361 Builder builder = getClientBuilder(client, url, headers, responseType);
362 clientResponse = operation.processOperation(builder, payload, contentType);
364 populateOperationResult(clientResponse, operationResult);
366 // Debug log the response
367 if (clientResponse != null) {
368 debugResponse(operationResult, clientResponse.getHeaders());
371 } catch (Exception ex) {
373 logger.error(RestClientMsgs.HTTP_REQUEST_ERROR, requestType, url, ex.getLocalizedMessage());
374 operationResult.setResultCode(500);
376 .setFailureCause("Error during GET operation to AAI with message = " + ex.getLocalizedMessage());
380 if (logger.isDebugEnabled()) {
381 logger.debug(baos.toString());
384 // Not every valid response code is actually represented by the Response.Status
385 // object, so we need to guard against missing codes, otherwise we throw null
386 // pointer exceptions when we try to generate our metrics logs...
387 Response.Status responseStatus = Response.Status.fromStatusCode(operationResult.getResultCode());
388 String responseStatusCodeString = "";
389 if (responseStatus != null) {
390 responseStatusCodeString = responseStatus.toString();
393 metricsLogger.info(RestClientMsgs.HTTP_REQUEST_TIME,
394 new LogFields().setField(LogLine.DefinedFields.STATUS_CODE, responseStatusCodeString)
395 .setField(LogLine.DefinedFields.RESPONSE_CODE, operationResult.getResultCode())
396 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, operationResult.getResult()),
397 override, requestType, Long.toString(System.currentTimeMillis() - startTimeInMs), url);
398 logger.info(RestClientMsgs.HTTP_REQUEST_TIME, requestType,
399 Long.toString(System.currentTimeMillis() - startTimeInMs), url);
400 logger.info(RestClientMsgs.HTTP_RESPONSE, url,
401 operationResult.getResultCode() + " " + responseStatusCodeString);
404 return operationResult;
408 * This method submits an HTTP PUT request against the supplied URL.
410 * @param url - The REST endpoint to submit the PUT request to.
411 * @param payload - the payload to send to the supplied URL
412 * @param headers - The headers that should be passed in the request
413 * @param contentType - The content type of the payload
414 * @param responseType - The expected format of the response.
416 * @return The result of the PUT request.
418 public OperationResult put(String url, String payload, Map<String, List<String>> headers, MediaType contentType,
419 MediaType responseType) {
420 return processRequest(putOp, url, payload, headers, contentType, responseType);
424 * This method submits an HTTP POST request against the supplied URL.
426 * @param url - The REST endpoint to submit the POST request to.
427 * @param payload - the payload to send to the supplied URL
428 * @param headers - The headers that should be passed in the request
429 * @param contentType - The content type of the payload
430 * @param responseType - The expected format of the response.
432 * @return The result of the POST request.
434 public OperationResult post(String url, String payload, Map<String, List<String>> headers, MediaType contentType,
435 MediaType responseType) {
436 return processRequest(postOp, url, payload, headers, contentType, responseType);
440 * This method submits an HTTP POST request against the supplied URL, and emulates a PATCH operation by setting a
441 * special header value
443 * @param url - The REST endpoint to submit the POST request to.
444 * @param payload - the payload to send to the supplied URL
445 * @param headers - The headers that should be passed in the request
446 * @param contentType - The content type of the payload
447 * @param responseType - The expected format of the response.
449 * @return The result of the PATCH request.
451 public OperationResult patch(String url, String payload, Map<String, List<String>> headers, MediaType contentType,
452 MediaType responseType) {
453 return processRequest(patchOp, url, payload, headers, contentType, responseType);
457 * This method submits an HTTP HEAD request against the supplied URL
459 * @param url - The REST endpoint to submit the POST request to.
460 * @param headers - The headers that should be passed in the request
461 * @param responseType - The expected format of the response.
463 * @return The result of the HEAD request.
465 public OperationResult head(String url, Map<String, List<String>> headers, MediaType responseType) {
466 return processRequest(headOp, url, null, headers, null, responseType);
470 * This method submits an HTTP GET request against the supplied URL.
472 * @param url - The REST endpoint to submit the GET request to.
473 * @param headers - The headers that should be passed in the request
474 * @param responseType - The expected format of the response.
476 * @return The result of the GET request.
478 public OperationResult get(String url, Map<String, List<String>> headers, MediaType responseType) {
479 return processRequest(getOp, url, null, headers, null, responseType);
483 * This method submits an HTTP GET request against the supplied URL. This variant of the method will perform a
484 * requested number of retries in the event that the first request is unsuccessful.
486 * @param url - The REST endpoint to submit the GET request to.
487 * @param headers - The headers that should be passed in the request
488 * @param responseType - The expected format of the response.
489 * @param numRetries - The number of times to try resubmitting the request in the event of a failure.
491 * @return The result of the GET request.
493 public OperationResult get(String url, Map<String, List<String>> headers, MediaType responseType, int numRetries) {
494 return processRequest(getOp, url, null, headers, null, responseType, numRetries);
498 * This method submits an HTTP DELETE request against the supplied URL.
500 * @param url - The REST endpoint to submit the DELETE request to.
501 * @param headers - The headers that should be passed in the request
502 * @param responseType - The expected format of the response.
504 * @return The result of the DELETE request.
506 public OperationResult delete(String url, Map<String, List<String>> headers, MediaType responseType) {
507 return processRequest(deleteOp, url, null, headers, null, responseType);
511 * This method does a health check ("ping") against the supplied URL.
513 * @param url - The REST endpoint to attempt a health check.
514 * @param srcAppName - The name of the application using this client.
515 * @param destAppName - The name of the destination app.
517 * @return A boolean value. True if connection attempt was successful, false otherwise.
520 public boolean healthCheck(String url, String srcAppName, String destAppName) {
521 return healthCheck(url, srcAppName, destAppName, MediaType.TEXT_PLAIN_TYPE);
526 * This method does a health check ("ping") against the supplied URL.
528 * @param url - The REST endpoint to attempt a health check.
529 * @param srcAppName - The name of the application using this client.
530 * @param destAppName - The name of the destination app.
531 * @param responseType - The response type.
533 * @return A boolean value. True if connection attempt was successful, false otherwise.
536 public boolean healthCheck(String url, String srcAppName, String destAppName, MediaType responseType) {
537 Map<String, List<String>> headers = new HashMap<>();
538 headers.put(Headers.FROM_APP_ID, Arrays.asList(new String[] {srcAppName}));
539 headers.put(Headers.TRANSACTION_ID, Arrays.asList(new String[] {UUID.randomUUID().toString()}));
542 logger.info(RestClientMsgs.HEALTH_CHECK_ATTEMPT, destAppName, url);
543 OperationResult result = get(url, headers, responseType);
545 if (result != null && result.getFailureCause() == null) {
546 logger.info(RestClientMsgs.HEALTH_CHECK_SUCCESS, destAppName, url);
549 logger.error(RestClientMsgs.HEALTH_CHECK_FAILURE, destAppName, url,
550 result != null ? result.getFailureCause() : null);
553 } catch (Exception e) {
554 logger.error(RestClientMsgs.HEALTH_CHECK_FAILURE, destAppName, url, e.getMessage());
560 * This method constructs a client request builder that can be used for submitting REST requests to the supplied URL
563 * @param client - The REST client we will be using to talk to the server.
564 * @param url - The URL endpoint that our request will be submitted to.
565 * @param headers - The headers that should be passed in the request
566 * @param responseType - The expected format of the response.
568 * @return A client request builder.
570 private Builder getClientBuilder(Client client, String url, Map<String, List<String>> headers,
571 MediaType responseType) {
573 WebTarget target = client.target(url);
575 Builder builder = target.request().accept(responseType);
577 if (headers != null) {
578 for (Entry<String, List<String>> header : headers.entrySet()) {
579 builder.header(header.getKey(), String.join(";", header.getValue()));
582 // Added additional check to prevent adding duplicate authorization header if client is already sending the
583 // authorization header
584 // AAI-1097 - For AAI calls when Rest authentication mode is selected as SSL_BASIC getting 403 error
585 if (clientBuilder.getAuthenticationMode() == RestAuthenticationMode.SSL_BASIC
586 && headers.get(Headers.AUTHORIZATION) == null) {
587 builder = builder.header(Headers.AUTHORIZATION, clientBuilder.getBasicAuthenticationCredentials());
595 private void debugRequest(String url, String payload, Map<String, List<String>> headers, MediaType responseType) {
596 if (!logger.isDebugEnabled()) {
600 StringBuilder debugRequest = new StringBuilder("REQUEST:\n");
601 debugRequest.append("URL: ").append(url).append("\n");
602 debugRequest.append("Payload: ").append(payload).append("\n");
603 debugRequest.append("Response Type: ").append(responseType).append("\n");
605 if (headers == null) {
606 logger.debug(debugRequest.toString());
610 debugRequest.append("Headers: ");
611 for (Entry<String, List<String>> header : headers.entrySet()) {
612 debugRequest.append("\n\t").append(header.getKey()).append(":");
613 for (String headerEntry : header.getValue()) {
614 debugRequest.append("\"").append(headerEntry).append("\" ");
618 logger.debug(debugRequest.toString());
622 private void debugResponse(OperationResult operationResult, MultivaluedMap<String, Object> headers) {
624 if (!logger.isDebugEnabled()) {
628 StringBuilder debugResponse = new StringBuilder("RESPONSE:\n");
629 debugResponse.append("Result: ").append(operationResult.getResultCode()).append("\n");
630 debugResponse.append("Failure Cause: ").append(operationResult.getFailureCause()).append("\n");
631 debugResponse.append("Payload: ").append(operationResult.getResult()).append("\n");
633 if (headers == null) {
634 logger.debug(debugResponse.toString());
638 debugResponse.append("Headers: ");
639 for (Entry<String, List<Object>> header : headers.entrySet()) {
640 debugResponse.append("\n\t").append(header.getKey()).append(":");
641 for (Object headerEntry : header.getValue()) {
642 debugResponse.append("\"").append(headerEntry).append("\" ");
646 logger.debug(debugResponse.toString());
650 * This method creates an instance of the low level REST client to use for communicating with the AAI, if one has
651 * not already been created, otherwise it returns the already created instance.
653 * @return A {@link Client} instance.
655 protected Client getClient() throws Exception {
658 * Attempting a new way of doing non-blocking thread-safe lazy-initialization by using Java 1.8 computeIfAbsent
659 * functionality. A null value will not be stored, but once a valid mapping has been established, then the same
660 * value will be returned.
662 * One awkwardness of the computeIfAbsent is the lack of support for thrown exceptions, which required a bit of
663 * hoop jumping to preserve the original exception for the purpose of maintaining the pre-existing this API
667 final InitializedClient clientInstance =
668 CLIENT_CACHE.computeIfAbsent(REST_CLIENT_INSTANCE, k -> loggedClientInitialization());
670 if (clientInstance.getCaughtException() != null) {
671 throw new InstantiationException(clientInstance.getCaughtException().getMessage());
674 return clientInstance.getClient();
679 * This method will only be called if computerIfAbsent is true. The return value is null, then the result is not
682 * @return a new client instance or null
684 private InitializedClient loggedClientInitialization() {
686 if (logger.isDebugEnabled()) {
687 logger.debug("Instantiating REST client with following parameters:");
688 logger.debug(clientBuilder.toString());
691 InitializedClient initClient = new InitializedClient();
694 initClient.setClient(clientBuilder.getClient());
695 } catch (Exception error) {
696 initClient.setCaughtException(error);
705 * This method populates the fields of an {@link OperationResult} instance based on the contents of a
706 * {@link Response} received in response to a REST request.
708 private void populateOperationResult(Response response, OperationResult opResult) {
710 // If we got back a NULL response, then just produce a generic
711 // error code and result indicating this.
712 if (response == null) {
713 opResult.setResultCode(500);
714 opResult.setFailureCause("Client response was null");
718 int statusCode = response.getStatus();
719 opResult.setResultCode(statusCode);
721 if (opResult.wasSuccessful()) {
722 if (statusCode != Response.Status.NO_CONTENT.getStatusCode()) {
723 opResult.setResult(response.readEntity(String.class));
726 opResult.setFailureCause(response.readEntity(String.class));
729 opResult.setHeaders(convertHeaderObjectsToString(response.getHeaders()));
732 private MultivaluedMap<String, String> convertHeaderObjectsToString(MultivaluedMap<String, Object> headers) {
733 MultivaluedMap<String, String> result = new MultivaluedHashMap<>();
734 headers.forEach((k, v) -> result.addAll(k, v.stream().map(Object::toString).collect(Collectors.toList())));
738 private class GetRestOperation implements RestOperation {
740 public Response processOperation(Builder builder, String payload, MediaType contentType) {
741 return builder.get();
745 public RequestType getRequestType() {
746 return RequestType.GET;
750 private class PutRestOperation implements RestOperation {
752 public Response processOperation(Builder builder, String payload, MediaType contentType) {
753 return builder.put(Entity.entity(payload, contentType));
757 public RequestType getRequestType() {
758 return RequestType.PUT;
762 private class PostRestOperation implements RestOperation {
764 public Response processOperation(Builder builder, String payload, MediaType contentType) {
765 return builder.post(Entity.entity(payload, contentType));
769 public RequestType getRequestType() {
770 return RequestType.POST;
774 private class DeleteRestOperation implements RestOperation {
776 public Response processOperation(Builder builder, String payload, MediaType contentType) {
777 return builder.delete();
781 public RequestType getRequestType() {
782 return RequestType.DELETE;
786 private class HeadRestOperation implements RestOperation {
788 public Response processOperation(Builder builder, String payload, MediaType contentType) {
789 return builder.head();
793 public RequestType getRequestType() {
794 return RequestType.HEAD;
798 private class PatchRestOperation implements RestOperation {
801 * Technically there is no standarized PATCH operation for the jersey client, but we can use the method-override
805 public Response processOperation(Builder builder, String payload, MediaType contentType) {
806 builder = builder.header("X-HTTP-Method-Override", "PATCH");
807 return builder.post(Entity.entity(payload, contentType));
811 public RequestType getRequestType() {
812 return RequestType.PATCH;
818 * Interface used wrap a Jersey REST call using a functional interface.
820 private interface RestOperation {
823 * Method used to wrap the functionality of making a REST call out to the endpoint.
825 * @param builder the Jersey builder used to make the request
826 * @param payload the request payload
827 * @param contentType the content type of the payload
828 * @return the response from the REST endpoint
830 public Response processOperation(Builder builder, String payload, MediaType contentType);
833 * Returns the REST request type.
835 public RequestType getRequestType();
838 * The supported REST request types.
840 public enum RequestType {
841 GET, PUT, POST, DELETE, PATCH, HEAD
846 * An entity to encapsulate an expected result and a potential failure cause when returning from a functional
847 * interface during the computeIfAbsent call.
849 private class InitializedClient {
850 private Client client;
851 private Throwable caughtException;
853 public InitializedClient() {
855 caughtException = null;
858 public Client getClient() {
862 public void setClient(Client client) {
863 this.client = client;
866 public Throwable getCaughtException() {
867 return caughtException;
870 public void setCaughtException(Throwable caughtException) {
871 this.caughtException = caughtException;