Class Middlewares

java.lang.Object
com.commercetools.docs.meta.Middlewares

public class Middlewares extends Object
Table of content

Middlewares

ErrorMiddleware

The ErrorMiddleware is used to react to erroneous HTTP responses. It will always be placed as first middleware in the HandlerStack. The default implementation converts responses with a status code 400 or higher to exceptions. For creating the exceptions it uses a HttpExceptionFactory.

if (exceptionMode == ExceptionMode.COMPLETION_EXCEPTION) {
    return next.apply(request).thenApply(response -> {
        if (response.getStatusCode() >= 400) {
            throw exceptionFactory.create(request, response);
        }
        return response;
    });
}

CompletableFuture<ApiHttpResponse<byte[]>> result = new CompletableFuture<>();
next.apply(request).whenComplete((response, throwable) -> {
    if (throwable != null) {
        Throwable unwrap = throwable instanceof CompletionException ? throwable.getCause() : throwable;
        result.completeExceptionally(unwrap);
    }
    if (response != null) {
        if (response.getStatusCode() >= 400) {
            try {
                result.completeExceptionally(exceptionFactory.create(request, response));
            }
            catch (Throwable e) {
                result.completeExceptionally(e);
            }
        }
    }
    result.complete(response);
});

return result;

See the test code.

OAuthMiddleware

An OAuthMiddleware is used to authenticate a request against the commercetools Composable Commerce APIs. The default implementation adds an auth header to the request instance. In case of an expired token it will try to reauthenticate automatically. To retrieve an AuthenticationToken the OAuthHandler is called.

return failsafeExecutor.getStageAsync(() -> {
    if (request.getHeaders().getFirst(ApiHttpHeaders.AUTHORIZATION) != null) {
        return next.apply(request);
    }
    return authHandler.getTokenAsync()
            .thenCompose(token -> next
                    .apply(request.addHeader(ApiHttpHeaders.AUTHORIZATION, OAuthHandler.authHeader(token))));
});

See the test code.

PolicyMiddleware

The PolicyMiddleware is used to act on a failed request returns with the configured policies e.g. retry on status code 503. For retrying an exponential backoff strategy is used which will increase the wait time before each try to avoid overwhelming the API. A jitter is also added to avoid reduce the possibility that parallel requests will be retried at the same time.

The policy implementations use the library failsafe

ConcurrentModificationMiddleware

The ConcurrentModificationMiddleware is used to retry a failed request which returns the status codes 409 (concurrent modification). For retrying an exponential backoff strategy is used which will increase the wait time before each try to avoid overwhelming the API. A jitter is also added to avoid reduce the possibility that parallel requests will be retried at the same time.

The retry implementation uses the library failsafe

UserAgentMiddleware

The UserAgentMiddleware adds an user agent header to every request. By default is submits the following data:

  • SDK version
  • JVM runtime version
  • Operating system name and version
return UserAgentUtils.obtainUserAgent();

See the test code.

AcceptGZipMiddleware

The AcceptGZipMiddleware adds an Accept-Encoding: gzip header, to enable the ability of an compressed response as this reduces the data transport time.

return next.apply(request.withHeader(ApiHttpHeaders.ACCEPT_ENCODING, "gzip"));

See the test code.

InternalLoggerMiddleware

The InternalLoggerMiddleware

logs every request send using the SDK. Depending on the configured logging level the default implementation logs the sent request and the returning response. The info level outputs the request method, url and the response status code. Using debug level the request and response instance will be logged. With trace level it will pretty print body of the request as well the response. To avoid leaking of sensitive data the logger redacts passwords, tokens and some other sensitive data.
  • Constructor Details

    • Middlewares

      public Middlewares()