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 -> System.out.println("Success:" + res.toString()))
.onFailure(response -> System.out.println("Failure:" + res.toString()))
.onResponse(response -> 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.
|
| Modifier and Type | Field and Description |
|---|---|
protected java.util.Set<java.lang.String> |
blacklistParams
Never forward these params.
|
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 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 blacklisted headers.
|
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.lang.String |
name |
protected int |
requestTimeout
Parameter for default HttpClient configuration
|
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 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".
|
protected java.util.Set<java.lang.String> |
whitelistParams
Always forward these params.
|
| 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.
|
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() |
RestClient.Executor |
getExecutor()
Gets
executor and calling buildExecutor to construct a new one if executor is null. |
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.lang.String |
getName() |
int |
getRequestTimeout() |
int |
getRetryMax() |
int |
getRetryTimeoutMax() |
RestClient |
getRetryTimeoutMax(int retryTimeoutMax) |
int |
getRetryTimeoutMin() |
int |
getSocketTimeout() |
java.util.Set |
getWhitelistParams() |
boolean |
isForwardHeaders() |
boolean |
isForwardParams() |
boolean |
isUseCompression() |
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 |
removeIncludeForwardHeader(java.lang.String headerKey) |
RestClient |
removeWhitelistParam(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 |
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 |
withName(java.lang.String name) |
RestClient |
withRequestTimeout(int requestTimeout) |
RestClient |
withRetryMax(int retryMax) |
RestClient |
withRetryTimeoutMin(int retryTimeoutMin) |
RestClient |
withSocketTimeout(int socketTimeout) |
RestClient |
withUrl(java.lang.String url) |
RestClient |
withUseCompression(boolean useCompression) |
RestClient |
withWhitelistedParams(java.lang.String... paramNames) |
protected java.lang.String name
protected java.lang.String url
protected boolean forwardHeaders
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 java.util.Set includeForwardHeaders
shouldForwardHeader(String)protected java.util.Set excludeForwardHeaders
shouldForwardHeader(String)protected 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.
protected boolean forwardParams
protected java.util.Set<java.lang.String> whitelistParams
shouldForwardParam(String)protected java.util.Set<java.lang.String> blacklistParams
shouldForwardParam(String)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)protected int retryTimeoutMax
#computeTimeout(Request)protected int socketTimeout
org.apache.http.client.config.RequstConfig.setSocketTimeoutprotected int connectTimeout
org.apache.http.client.config.RequstConfig.setConnectTimeoutprotected int requestTimeout
org.apache.http.client.config.RequstConfig.setConnectionRequestTimeoutprotected org.apache.http.client.HttpClient httpClient
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&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 forcedHeadersprotected 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"){request - protected long computeTimeout(Request request, Response response)
You can override this to provide your own timeout policy.
request - response - protected 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 - response - isNetworkException(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.Exceptionhttp://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/public 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 and calling buildExecutor to construct a new one if executor is null.public RestClient withExecutor(RestClient.Executor executor)
protected RestClient.Executor buildExecutor()
You can dependency inject your Executor or override this method to provide advanced customizations.
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 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 getWhitelistParams()
public RestClient withWhitelistedParams(java.lang.String... paramNames)
public RestClient removeWhitelistParam(java.lang.String param)
public int getRetryTimeoutMin()
public RestClient withRetryTimeoutMin(int retryTimeoutMin)
public int getRetryTimeoutMax()
public RestClient getRetryTimeoutMax(int retryTimeoutMax)
Copyright © 2024 Rocket Partners, LLC. All rights reserved.