Add original headers into new client

mail@pastecode.io avatar
unknown
java
a year ago
2.6 kB
1
Indexable
Never
public class MyRequestFilter implements ClientRequestFilter {
    private MultivaluedMap<String, Object> originalHeaders;

    public MyRequestFilter(MultivaluedMap<String, Object> originalHeaders) {
        this.originalHeaders = originalHeaders;
    }

    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        // Add the original headers to the new request
        for (Map.Entry<String, List<Object>> entry : originalHeaders.entrySet()) {
            requestContext.getHeaders().addAll(entry.getKey(), entry.getValue());
        }
    }
}

public interface MyEndpoint {
    @GET
    @Path("/my-resource")
    CompletionStage<Response> getMyResource(@QueryParam("param1") String param1,
                                            @QueryParam("param2") String param2);
}

MyEndpoint endpointWithHeader = RestClientBuilder.newBuilder()
        .baseUri("http://example.com")
        .build(MyEndpoint.class);

MyEndpoint endpointWithoutHeader = RestClientBuilder.newBuilder()
        .baseUri("http://example.com")
        .registerProvider(new MyRequestFilter(Collections.emptyMap()))
        .build(MyEndpoint.class);

String missingHeader = "value-from-mobile-app";

BiFunction<Response, Throwable, CompletionStage<Response>> handleStatus = (response, throwable) -> {
    if (response != null && response.getStatus() == 409) {
        MultivaluedMap<String, Object> headers = response.getHeaders();
        if (headers.containsKey("Missing-Header")) {
            headers.add("pin", missingHeader);

            // Register a new request filter with the original headers
            endpointWithoutHeader = RestClientBuilder.newBuilder()
                    .baseUri("http://example.com")
                    .registerProvider(new MyRequestFilter(headers))
                    .build(MyEndpoint.class);

            // Call the endpoint again with the missing header and original headers using the endpointWithHeader client
            return endpointWithHeader.getMyResource("value1", "value2", missingHeader);
        }
    }
    // Handle other response codes here using the endpointWithoutHeader client
    return CompletableFuture.completedFuture(response);
};

CompletionStage<Response> responseStage = endpointWithoutHeader.getMyResource("value1", "value2");
responseStage.thenCompose(handleStatus)
        .thenApply(response -> {
            if (response.getStatus() == 200) {
                return response.readEntity(MyResource.class);
            } else {
                throw new MyException("Failed to get resource");
            }
        });