Class HttpUtils


  • public final class HttpUtils
    extends Object

    A class providing static utility functions related to the usage of HttpClient objects.

    • Method Detail

      • waitFor

        public static <T> T waitFor​(Future<? extends T> future)
                             throws IOException
        Blocks until the given future is completed, returns its result, and handles occurring exceptions. HttpClient has an asynchronous API, but this method offers an easy way to transform this to a blocking programming model by just waiting for the result to become available. To simplify exception handling for the caller, the various checked exceptions thrown by Future.get() are wrapped into IOException exceptions.
        Type Parameters:
        T - the result type of the future
        Parameters:
        future - the future to wait for
        Returns:
        the result produced by the future
        Throws:
        IOException - if the future failed or waiting was interrupted
      • unwrapCompletionException

        public static Throwable unwrapCompletionException​(Throwable ex)
        Returns the first exception in a chain that is not a CompletionException. When dealing with CompletableFuture objects that have been completed with an exception (for instance by processing futures via methods like whenComplete() or handle()), the representation of these exceptions is not always consistent. They are sometimes wrapped in a CompletionException and sometimes not. This method can be used to obtain the actual cause of a failure by removing all enclosing CompletionException instances.
        Parameters:
        ex - the exception to be unwrapped
        Returns:
        the unwrapped exception or null if none can be found
      • isSuccessStatus

        public static boolean isSuccessStatus​(int status)
        Returns a flag whether the passed in response status code indicates a successful response. This is the case if the status code is in the range of [200, 300).
        Parameters:
        status - the status code to check
        Returns:
        true if the status code indicates a successful response; false otherwise
      • checkResponse

        public static <T> ResponseProcessor<T> checkResponse​(ResponseProcessor<T> processor,
                                                             Predicate<Response> successPredicate,
                                                             String tag)
        Returns a ResponseProcessor that checks whether a request was successful based on a given predicate and allows tagging the request. The resulting processor invokes the given predicate on the response received from the server. If the predicate yields false, a FailedRequestException is thrown that is initialized with the tag and the response status code. Otherwise, the original ResponseProcessor is invoked, which can now safely generate its result.
        Type Parameters:
        T - the result type of the ResponseProcessor
        Parameters:
        processor - the ResponseProcessor to wrap
        successPredicate - a predicate to determine whether the response is successful
        tag - a tag to identify the request
        Returns:
        the ResponseProcessor checking the response
      • checkResponse

        public static <T> ResponseProcessor<T> checkResponse​(ResponseProcessor<T> processor,
                                                             Predicate<Response> successPredicate)
        Returns a ResponseProcessor that checks whether a request was successful based on a given predicate. This variant does not add a tag to the request.
        Type Parameters:
        T - the result type of the ResponseProcessor
        Parameters:
        processor - the ResponseProcessor to wrap
        successPredicate - a predicate to determine whether the response is successful
        Returns:
        the ResponseProcessor checking the response
      • checkResponse

        public static <T> ResponseProcessor<T> checkResponse​(ResponseProcessor<T> processor,
                                                             String tag)
        Returns a ResponseProcessor that checks the HTTP status code to determine whether a request was successful and allows tagging the request. This method is equivalent to the overloaded checkResponse() method using SUCCESS_STATUS as predicate.
        Type Parameters:
        T - the result type of the ResponseProcessor
        Parameters:
        processor - the ResponseProcessor to wrap
        tag - a tag to identify the request
        Returns:
        the ResponseProcessor checking the response
      • checkResponse

        public static <T> ResponseProcessor<T> checkResponse​(ResponseProcessor<T> processor)
        Returns a ResponseProcessor that checks the HTTP status code to determine whether a request was successful. This method is equivalent to the overloaded checkResponse() method using SUCCESS_STATUS as predicate. This variant does not add a tag to the request.
        Type Parameters:
        T - the result type of the ResponseProcessor
        Parameters:
        processor - the ResponseProcessor to wrap
        Returns:
        the ResponseProcessor checking the response
      • hasStatus

        public static Predicate<Response> hasStatus​(int status)
        Returns a predicate that checks a response for a specific status code. The response is considered successful if and only if the status code matches exactly the expected code.
        Parameters:
        status - the expected status code for the response
        Returns:
        a predicate checking for this response status code
      • createExceptionForResponse

        public static FailedRequestException createExceptionForResponse​(Response response,
                                                                        String tag)
        Creates a FailedRequestException based on the passed in response and request tag. The properties of the exception are initialized accordingly. The response entity is read as well and stored in the exception.
        Parameters:
        response - the failing response
        tag - a tag to identify the request
        Returns:
        the exception reporting a failed request
      • jsonResult

        public static <T> ResponseProcessor<T> jsonResult​(com.fasterxml.jackson.databind.ObjectMapper mapper,
                                                          Class<T> resultClass)
        Returns a ResponseProcessor that uses the ObjectMapper specified to map the JSON payload of a response to an object of the given result class. The resulting processor directly accesses the payload of the response; it can be combined with one of the checkResponse() methods to make sure that the response is successful before it is processed.
        Type Parameters:
        T - the type of the resulting object
        Parameters:
        mapper - the JSON mapper
        resultClass - the result class
        Returns:
        the ResponseProcessor doing a JSON de-serialization
      • jsonResultNew

        public static <T> ResponseProcessor<T> jsonResultNew​(com.fasterxml.jackson.databind.ObjectMapper mapper,
                                                             Class<T> resultClass)
        Returns a ResponseProcessor that uses the ObjectMapper specified to map the JSON payload of a response to an object of the given result class. The resulting processor directly accesses the payload of the response; it can be combined with one of the checkResponse() methods to make sure that the response is successful before it is processed.
        Type Parameters:
        T - the type of the resulting object
        Parameters:
        mapper - the JSON mapper
        resultClass - the result class
        Returns:
        the ResponseProcessor doing a JSON de-serialization
      • jsonResult

        public static <T> ResponseProcessor<T> jsonResult​(com.fasterxml.jackson.databind.ObjectMapper mapper,
                                                          com.fasterxml.jackson.core.type.TypeReference<T> typeReference)
        Returns a ResponseProcessor that uses the ObjectMapper specified to map the JSON payload of a response to an object of the type defined by the given reference. This is analogous to the overloaded method, but allows for more flexibility to specify the result type.
        Type Parameters:
        T - the type of the resulting object
        Parameters:
        mapper - the JSON mapper
        typeReference - the reference defining the target type
        Returns:
        the ResponseProcessor doing a JSON de-serialization
      • get

        public static Consumer<RequestBuilder> get​(String uri)
        Returns a very simple Consumer for a RequestBuilder that just configures the builder with the given URI. This causes an HTTP GET request to this URI without further properties.
        Parameters:
        uri - the URI to be retrieved
        Returns:
        the Consumer generating this GET request
      • nullProcessor

        public static <T> ResponseProcessor<T> nullProcessor()
        Returns a special ResponseProcessor that does not do any processing, but just returns the value null. Such a processor can be useful for requests that do not return a response body, e.g. POST requests to create or manipulate entities. When combined with a processor produced by one of the checkResponse() methods it is possible to have some error handling, but skip the evaluation of the response body.
        Returns:
        a ResponseProcessor returning null
      • urlEncode

        public static String urlEncode​(String src)
        Performs URL encoding on the given string.
        Parameters:
        src - the string to be encoded
        Returns:
        the encoded string (null if the input string was null)
      • addQueryParameters

        public static String addQueryParameters​(String url,
                                                Map<String,​?> params)
        Adds the given query parameters to a URL without applying any filtering.
        Parameters:
        url - the URL
        params - a map with the query parameters to append
        Returns:
        the resulting URL string with query parameters
        Throws:
        NullPointerException - if the URL or the map with parameters is null
        See Also:
        addQueryParameters(String, Map, boolean)
      • addQueryParameters

        public static String addQueryParameters​(String url,
                                                Map<String,​?> params,
                                                boolean filterUndefined)
        Adds the given query parameters to a URL. Each parameter value is encoded. The parameters are appended to the URL string using the correct separator characters. If the filterUndefined flag is set to true, parameters having a null or empty string value are filtered out.
        Parameters:
        url - the URL
        params - a map with the query parameters to append
        filterUndefined - flag whether undefined parameters should be ignored
        Returns:
        the resulting URL string with query parameters
        Throws:
        NullPointerException - if the URL or the map with parameters is null
      • addQueryParameter

        public static String addQueryParameter​(String url,
                                               String key,
                                               Object value)
        Adds a single query parameter to a URL. This is a convenience function for the case that there is only a single query parameter needed. Note that this method does not filter out undefined parameters.
        Parameters:
        url - the URL
        key - the parameter key
        value - the parameter value
        Returns:
        the URL with the query parameter added
        Throws:
        NullPointerException - if the URL is null