public class RestClient
extends java.lang.Object
io.inversion.Action with some superpowers.
RestClient gives you easy or built in:
doRequest(Request)
Transforming requests / responses
You can easily override the doRequest(Request) method to potentially short circuit calls or perform request/response transforms.
For example:
protected RestClient client = new RestClient("myservice")
{
protected Response doRequest(Request request)
{
if(checkMyCondition(request))
{
//-- short circuit the remote call "faking" a
//-- remote 200 response (the default status code for a Response)
return new Response(request.getUrl());
}
else
{
doMyRequestTransformation(request);
Response response = super.getResponse(request);
doMyResponseTransformation(response);
return response;
}
}
}
client.get("/some/relative/path")
.onSuccess(response -@gt; System.out.println("Success:" + res.toString()))
.onFailure(response -@gt; System.out.println("Failure:" + res.toString()))
.onResponse(response -@gt; System.out.println(res.getStatus()));
//-- instead of using the success/failure callbacks as above
//-- you can wait for the async process to complete by calling 'get()'
FutureResponse future = client.post("/some/relative/path", new JSNode("hello", "world"));
//-- request is asynchronously executing here
//-- the call to get() blocks indefinitely until the async execution completes
//-- the fact that this method is called 'get()' is not related to HTTP get.
Response response = future.get();
//-- now do whatever you want with the Response
| Modifier and Type | Class and Description |
|---|---|
static class |
RestClient.Executor
An asynchronous thread pool task runner.
|
class |
RestClient.FutureResponse
A RunnableFuture that blocks on get() until the execution of the Request has returned the Response.
|
static interface |
RestClient.RequestListener |
| Modifier and Type | Field and Description |
|---|---|
protected int |
compressionMinSize
If
useCompression is true, anything over this size in bytes will be compressed. |
protected int |
connectTimeout
Parameter for default HttpClient configuration
|
protected java.util.Set |
excludeForwardHeaders
Never forward these headers.
|
protected java.util.Set<java.lang.String> |
excludeParams
Never forward these params.
|
protected RestClient.Executor |
executor
The thread pool executor used to make asynchronous requests
|
protected org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> |
forcedHeaders
Headers that are always sent regardless of
forwardHeaders, includeForwardHeaders and excludeForwardHeaders state. |
protected boolean |
forwardHeaders
Indicates the headers from the root inbound Request being handled on this Chain should be included on this request minus any
excludeForwardHeaders. |
protected boolean |
forwardParams
Indicates the params from the root inbound Request being handled on this Chain should be included on this request minus any blacklisted params.
|
protected org.apache.http.client.HttpClient |
httpClient
The underlying HttpClient use for all network comms.
|
protected java.util.Set |
includeForwardHeaders
Always forward these headers.
|
protected java.util.Set<java.lang.String> |
includeParams
Always forward these params.
|
protected java.lang.String |
name
The RestClient name that will be for property decoding.
|
protected java.util.List<RestClient.RequestListener> |
requestListeners |
protected int |
requestTimeout
Parameter for default HttpClient configuration
|
protected java.util.List<java.util.function.Consumer<Response>> |
responseListeners |
protected int |
retryMax
The default maximum number of times to retry a request
|
protected int |
retryTimeoutMax
The maximum amount of time to wait before a single retry.
|
protected int |
retryTimeoutMin
The length of time before the first retry.
|
protected int |
socketTimeout
Parameter for default HttpClient configuration
|
protected int |
threadsMax
The number of background executor threads.
|
protected java.lang.String |
url
Optional base url that will be prepended to the url arg of any calls assuming that the url arg supplied is a relative path and not an absolute url.
|
protected boolean |
useCompression
Indicates that a request body should be gzipped and the content-encoding header should be sent with value "gzip".
|
| Constructor and Description |
|---|
RestClient() |
RestClient(java.lang.String name) |
| Modifier and Type | Method and Description |
|---|---|
protected RestClient.Executor |
buildExecutor()
Build an executor if one was not wired in.
|
protected org.apache.http.client.HttpClient |
buildHttpClient()
Factory method for building an HttpClient if one was not configured via withHttpClient.
|
Request |
buildRequest(java.lang.String method,
java.lang.String fullUrlOrRelativePath,
java.util.Map<java.lang.String,java.lang.String> params,
JSNode body,
org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> headers,
int retryMax)
Builds a request with the supplied information merged with the url, query param, and header options configured
on this reset client and potentially pulled from the Chain request.
|
RestClient.FutureResponse |
call(Request request)
Executes the request as provided without modification.
|
RestClient.FutureResponse |
call(java.lang.String method,
java.lang.String fullUrlOrRelativePath,
java.util.Map<java.lang.String,java.lang.String> params,
JSNode body,
int retryMax,
org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> headers)
Makes an HTTP request.
|
protected long |
computeTimeout(Request request,
Response response)
Computes an incremental retry backoff time between retryTimeoutMin and retryTimeoutMax.
|
RestClient.FutureResponse |
delete(java.lang.String fullUrlOrRelativePath)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a DELETE request. |
protected Response |
doRequest(Request request)
The work of executing the remote call is done here.
|
RestClient.FutureResponse |
get(java.lang.String fullUrlOrRelativePath)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request. |
RestClient.FutureResponse |
get(java.lang.String fullUrlOrRelativePath,
java.util.Map<java.lang.String,java.lang.String> params)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request. |
RestClient.FutureResponse |
get(java.lang.String fullUrlOrRelativePath,
java.lang.String... queryStringNameValuePairs)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request. |
RestClient.FutureResponse |
get(java.lang.String fullUrlOrRelativePath,
java.lang.String queryString)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request. |
int |
getCompressionMinSize() |
int |
getConnectTimeout() |
java.util.Set |
getExcludeForwardHeaders() |
java.util.Set |
getExcludeParams() |
RestClient.Executor |
getExecutor() |
org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> |
getForcedHeaders() |
protected org.apache.http.client.HttpClient |
getHttpClient() |
java.util.Set<java.lang.String> |
getIncludeForwardHeaders() |
java.util.Set |
getIncludeParams() |
java.lang.String |
getName() |
int |
getRequestTimeout() |
int |
getRetryMax() |
int |
getRetryTimeoutMax() |
RestClient |
getRetryTimeoutMax(int retryTimeoutMax) |
int |
getRetryTimeoutMin() |
int |
getSocketTimeout() |
int |
getThreadsMax() |
boolean |
isForwardHeaders() |
boolean |
isForwardParams() |
boolean |
isUseCompression() |
RestClient |
onRequest(RestClient.RequestListener requestListener) |
RestClient |
onResponse(java.util.function.Consumer<Response> responseListener) |
RestClient.FutureResponse |
patch(java.lang.String fullUrlOrRelativePath,
JSNode body)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a PATCH request. |
RestClient.FutureResponse |
post(java.lang.String fullUrlOrRelativePath,
JSNode body)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a POST request. |
RestClient.FutureResponse |
put(java.lang.String fullUrlOrRelativePath,
JSNode body)
Convenience overloading of
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a PUT request. |
RestClient |
removeExcludeForwardHeader(java.lang.String headerKey) |
RestClient |
removeExcludeParam(java.lang.String param) |
RestClient |
removeIncludeForwardHeader(java.lang.String headerKey) |
RestClient |
removeIncludeParam(java.lang.String param) |
protected boolean |
shouldForwardHeader(java.lang.String headerKey) |
protected boolean |
shouldForwardParam(java.lang.String param) |
protected boolean |
shouldRetry(Request request,
Response response)
Determines if the Request should be retried.
|
RestClient |
withCompressionMinSize(int compressionMinSize) |
RestClient |
withConnectTimeout(int connectTimeout) |
RestClient |
withExcludeForwardHeaders(java.lang.String... headerKeys) |
RestClient |
withExcludeParams(java.lang.String... paramNames) |
RestClient |
withExecutor(RestClient.Executor executor) |
RestClient |
withForcedHeader(java.lang.String name,
java.lang.String value) |
RestClient |
withForcedHeaders(java.lang.String... headers) |
RestClient |
withForwardedHeaders(boolean forwardHeaders) |
RestClient |
withForwardedParams(boolean forwardParams) |
RestClient |
withForwardHeaders(boolean forwardHeaders) |
RestClient |
withForwardParams(boolean forwardParams) |
RestClient |
withHttpClient(org.apache.http.client.HttpClient httpClient) |
RestClient |
withIncludeForwardHeaders(java.lang.String... headerKeys) |
RestClient |
withIncludeParams(java.lang.String... paramNames) |
RestClient |
withName(java.lang.String name) |
RestClient |
withRequestTimeout(int requestTimeout) |
RestClient |
withRetryMax(int retryMax) |
RestClient |
withRetryTimeoutMin(int retryTimeoutMin) |
RestClient |
withSocketTimeout(int socketTimeout) |
RestClient |
withThreadsMax(int threadsMax) |
RestClient |
withUrl(java.lang.String url) |
RestClient |
withUseCompression(boolean useCompression) |
RestClient |
withWhitelistedHeaders(java.lang.String... headerKeys)
Deprecated.
Replaced by
getIncludeForwardHeaders() |
protected final java.util.Set includeForwardHeaders
protected final java.util.Set excludeForwardHeaders
shouldForwardHeader(String)protected final org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> forcedHeaders
forwardHeaders, includeForwardHeaders and excludeForwardHeaders state.
These headers will overwrite any caller supplied or forwarded header with the same key, not append to the value list.
This list is initially empty.
protected final java.util.Set<java.lang.String> includeParams
shouldForwardParam(String)protected final java.util.Set<java.lang.String> excludeParams
shouldForwardParam(String)protected final java.util.List<RestClient.RequestListener> requestListeners
protected final java.util.List<java.util.function.Consumer<Response>> responseListeners
protected java.lang.String name
Configuratorprotected boolean forwardHeaders
excludeForwardHeaders.
Default value is true.
protected java.lang.String url
protected boolean useCompression
Default value is true.
protected int compressionMinSize
useCompression is true, anything over this size in bytes will be compressed.
Default value is 1024.
protected boolean forwardParams
protected RestClient.Executor executor
protected int retryMax
The default value is zero meaning by default, failed requests will not be retried
protected int retryTimeoutMin
Incremental retries receive progressively more of a timeout up to retryTimeoutMax.
computeTimeout(Request, Response)protected int retryTimeoutMax
computeTimeout(Request, Response)protected int socketTimeout
RequestConfig.Builder.setSocketTimeout(int)protected int connectTimeout
RequestConfig.Builder.setConnectTimeout(int)protected int requestTimeout
RequestConfig.Builder.setConnectionRequestTimeout(int)protected org.apache.http.client.HttpClient httpClient
protected int threadsMax
A value < 1 will cause all tasks to execute synchronously on the calling thread meaning the FutureResponse will always be complete upon return.
The default value is 5.
public RestClient()
public RestClient(java.lang.String name)
name - the prefix used to look up property values from the environment if they have not already been wiredpublic RestClient.FutureResponse get(java.lang.String fullUrlOrRelativePath)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request.fullUrlOrRelativePath - may be a full url or relative to the url property if set, can have a query string or notpublic RestClient.FutureResponse get(java.lang.String fullUrlOrRelativePath, java.lang.String queryString)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request.fullUrlOrRelativePath - may be a full url or relative to the url property if set, can have a query string or notqueryString - additional query string params in name=value@amp;name2=value2 stylepublic RestClient.FutureResponse get(java.lang.String fullUrlOrRelativePath, java.util.Map<java.lang.String,java.lang.String> params)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request.fullUrlOrRelativePath - may be a full url or relative to the url property if set, can have a query string or notparams - query strings passed in as a mappublic RestClient.FutureResponse get(java.lang.String fullUrlOrRelativePath, java.lang.String... queryStringNameValuePairs)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a GET request.fullUrlOrRelativePath - may be a full url or relative to the url property if set, can have a query string or notqueryStringNameValuePairs - additional query string name/value pairspublic RestClient.FutureResponse post(java.lang.String fullUrlOrRelativePath, JSNode body)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a POST request.fullUrlOrRelativePath - may be a full url or relative to the url property if setbody - the optional JSON to postpublic RestClient.FutureResponse put(java.lang.String fullUrlOrRelativePath, JSNode body)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a PUT request.fullUrlOrRelativePath - may be a full url or relative to the url property if setbody - the optional JSON to putpublic RestClient.FutureResponse patch(java.lang.String fullUrlOrRelativePath, JSNode body)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a PATCH request.fullUrlOrRelativePath - may be a full url or relative to the url property if setbody - the optional JSON patchpublic RestClient.FutureResponse delete(java.lang.String fullUrlOrRelativePath)
call(String, String, Map, JSNode, int, ArrayListValuedHashMap) to perform a DELETE request.fullUrlOrRelativePath - may be a full url or relative to the url property if setpublic RestClient.FutureResponse call(java.lang.String method, java.lang.String fullUrlOrRelativePath, java.util.Map<java.lang.String,java.lang.String> params, JSNode body, int retryMax, org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> headers)
method - the HTTP method to invokefullUrlOrRelativePath - optional may be a full url or only additional relative path parts if the url property if set, may contain a query stringparams - optional additional query string params that will overwrite any that may be on url as composed from buildUrl(String)body - optional json bodyretryMax - how many times the client should retry if the Request is not successful, if less than zero then this.retriesMax is usedheaders - headers that will always be sent regardless of includeForwardHeaders, excludeForwardHeaders but may be overwritten by forcedHeaderspublic RestClient.FutureResponse call(Request request)
All of the other 'get/post/put/patch/delete/call' methods will construct a Request based on the configured properties of this RestClient and optionally the data in Request on the top of the Chain if operating inside an Engine.
Those methods ultimately delegate to this method and no further modification of the Request is made from here out.
request - public Request buildRequest(java.lang.String method, java.lang.String fullUrlOrRelativePath, java.util.Map<java.lang.String,java.lang.String> params, JSNode body, org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> headers, int retryMax)
method - - the http methodfullUrlOrRelativePath - - a full url or a relative path that will be appended to this.urlparams - - query params to passbody - - the request body to passheaders - - request headers to passretryMax - - the number of times to retry this call if it fails.protected Response doRequest(Request request)
Override this method to intercept the remote call and change anything about the Request or Response that you want.
All of the Request url/header/param configuration has already been done on the Request.
You don't need to do anything related to threading here. This method is already executing asynchronously within the Executor's thread pool. Simply handle/transform the Request/Response as desired. Simply returning a Response will cause the FutureResponse to transition to done and allow calls blocking on FutureResponse.get() to receive the Response.
Overriding this method can be really helpful when you what your RestClient calling algorithm to say clean, hiding some of the Request/Response customization details or otherwise need to make sure Requests/Responses are always handled in a specific way.
A typical override of this method might look like the following:
protected RestClient client = new RestClient("myservice"){
protected Response doRequest(Request request)
{
if(checkMyCondition(request))
{
//-- short circuit the remote call "faking" a
//-- remote 200 response (the default status code for a Response)
return new Response(request.getUrl());
}
else
{
doMyRequestTransformation(request);
Response response = super.getResponse(request);
doMyResponseTransformation(response);
return response;
}
}
}
request - the request to makepublic RestClient onRequest(RestClient.RequestListener requestListener)
public RestClient onResponse(java.util.function.Consumer<Response> responseListener)
protected long computeTimeout(Request request, Response response)
You can override this to provide your own timeout policy.
request - the Request being maderesponse - the Response being computedprotected boolean shouldRetry(Request request, Response response)
You can override this to provide your own retry policy.
The default algorithm will only retry if the Request is not successful due to a network error and the current request.retryCount is less than reqest.retryMax.
request - the Request being maderesponse - the Response being computedisNetworkException(Throwable)protected org.apache.http.client.HttpClient buildHttpClient()
throws java.lang.Exception
The default HttpClient constructed here basically SSL cert and hostname verification assuming that you will be calling clients you control.
If you need to adopt a tighter security posture just override this method or call withHttpClient(HttpClient) to supply your own HttpClient and security configuration.
Use of this method is wrapped by getHttpClient() which controls concurrency so this method should not be called more than once per instance if an error is not thrown.
java.lang.Exception - if HttpClient construction failspublic RestClient withUrl(java.lang.String url)
public org.apache.commons.collections4.multimap.ArrayListValuedHashMap<java.lang.String,java.lang.String> getForcedHeaders()
public RestClient withForcedHeader(java.lang.String name, java.lang.String value)
public RestClient withForcedHeaders(java.lang.String... headers)
public RestClient withForwardedHeaders(boolean forwardHeaders)
public RestClient withForwardedParams(boolean forwardParams)
public java.lang.String getName()
public RestClient withName(java.lang.String name)
public boolean isUseCompression()
public RestClient withUseCompression(boolean useCompression)
public int getCompressionMinSize()
public RestClient withCompressionMinSize(int compressionMinSize)
public int getRetryMax()
public RestClient withRetryMax(int retryMax)
public int getSocketTimeout()
public RestClient withSocketTimeout(int socketTimeout)
public int getConnectTimeout()
public RestClient withConnectTimeout(int connectTimeout)
public int getRequestTimeout()
public RestClient withRequestTimeout(int requestTimeout)
public RestClient withHttpClient(org.apache.http.client.HttpClient httpClient)
protected org.apache.http.client.HttpClient getHttpClient()
public RestClient.Executor getExecutor()
executor if necessary.public RestClient withExecutor(RestClient.Executor executor)
protected RestClient.Executor buildExecutor()
You can dependency inject your Executor or override this method to provide advanced customizations.
As a convenience RestClient.threadsMax is configured on the default executor.
public boolean isForwardHeaders()
protected boolean shouldForwardHeader(java.lang.String headerKey)
public RestClient withForwardHeaders(boolean forwardHeaders)
public java.util.Set<java.lang.String> getIncludeForwardHeaders()
public RestClient withIncludeForwardHeaders(java.lang.String... headerKeys)
public RestClient withWhitelistedHeaders(java.lang.String... headerKeys)
getIncludeForwardHeaders()public RestClient removeIncludeForwardHeader(java.lang.String headerKey)
public java.util.Set getExcludeForwardHeaders()
public RestClient withExcludeForwardHeaders(java.lang.String... headerKeys)
public RestClient removeExcludeForwardHeader(java.lang.String headerKey)
public boolean isForwardParams()
protected boolean shouldForwardParam(java.lang.String param)
public RestClient withForwardParams(boolean forwardParams)
public java.util.Set getIncludeParams()
public RestClient withIncludeParams(java.lang.String... paramNames)
public RestClient removeIncludeParam(java.lang.String param)
public java.util.Set getExcludeParams()
public RestClient withExcludeParams(java.lang.String... paramNames)
public RestClient removeExcludeParam(java.lang.String param)
public int getRetryTimeoutMin()
public RestClient withRetryTimeoutMin(int retryTimeoutMin)
public int getRetryTimeoutMax()
public RestClient getRetryTimeoutMax(int retryTimeoutMax)
public int getThreadsMax()
public RestClient withThreadsMax(int threadsMax)
Copyright © 2021 Rocket Partners, LLC. All rights reserved.