Skip to content

Commit

Permalink
Experiment 2 : Reimplement MP REST Client AsyncInvocationInterceptor …
Browse files Browse the repository at this point in the history
…support

Quite straightforward, the only thing that keeps the implementation complex is,
that PreInvocationInterceptor doesn't know what kind of invocation is going to happen,
therefore it cannot be registered on top level, and the decision to register interceptor
needs to be postponed until we know we're about to call async.

We could use one more flag in request context to signal that, but still we'd still
need to act in MethodModel.
  • Loading branch information
pdudits committed Oct 28, 2019
1 parent 7ff7e84 commit e9397cf
Show file tree
Hide file tree
Showing 4 changed files with 153 additions and 167 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) [2019] Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/

package org.glassfish.jersey.microprofile.restclient;

import org.eclipse.microprofile.rest.client.ext.AsyncInvocationInterceptor;
import org.eclipse.microprofile.rest.client.ext.AsyncInvocationInterceptorFactory;
import org.glassfish.jersey.client.spi.PostInvocationInterceptor;
import org.glassfish.jersey.client.spi.PreInvocationInterceptor;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.core.Configurable;
import java.util.List;

class AsyncInterceptorSupport {
private final List<AsyncInvocationInterceptorFactory> factories;
private static final String KEY = AsyncInterceptorSupport.class.getName();

AsyncInterceptorSupport(List<AsyncInvocationInterceptorFactory> factories) {
this.factories = factories;
}

private PreInvocationInterceptor preSubmit() {
return this::preSubmit;
}

private ClientRequestFilter preInvoke() {
return this::preInvoke;
}

private PostInvocationInterceptor postInvoke() {
return new PostInvoke();
}

private void preSubmit(ClientRequestContext requestContext) {
AsyncInvocationInterceptor[] interceptors = factories.stream().map(AsyncInvocationInterceptorFactory::newInterceptor)
.toArray(AsyncInvocationInterceptor[]::new);
requestContext.setProperty(KEY, interceptors);
//applyContext methods need to be called in reverse ordering of priority
for (AsyncInvocationInterceptor interceptor : interceptors) {
interceptor.prepareContext();
}
}

private void preInvoke(ClientRequestContext requestContext) {
AsyncInvocationInterceptor[] interceptors = readInterceptors(requestContext);
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
AsyncInvocationInterceptor interceptor = interceptors[i];
interceptor.applyContext();
}
}
}

private AsyncInvocationInterceptor[] readInterceptors(ClientRequestContext requestContext) {
Object interceptors = requestContext.getProperty(KEY);
if (interceptors instanceof AsyncInvocationInterceptor[]) {
return (AsyncInvocationInterceptor[]) interceptors;
}
return null;
}

static void register(List<AsyncInvocationInterceptorFactory> interceptorFactories,
Configurable<? extends Configurable> config) {
if (interceptorFactories != null && !interceptorFactories.isEmpty()) {
AsyncInterceptorSupport support = new AsyncInterceptorSupport(interceptorFactories);
config.register(support.preSubmit()).register(support.preInvoke()).register(support.postInvoke());
}
}

private class PostInvoke implements PostInvocationInterceptor {

@Override
public void afterRequest(ClientRequestContext requestContext, ClientResponseContext responseContext) {
AsyncInvocationInterceptor[] interceptors = readInterceptors(requestContext);
if (interceptors == null) {
return;
}
for (AsyncInvocationInterceptor interceptor : interceptors) {
interceptor.removeContext();
}
}

@Override
public void onException(ClientRequestContext requestContext, ExceptionContext exceptionContext) {
AsyncInvocationInterceptor[] interceptors = readInterceptors(requestContext);
if (interceptors == null) {
return;
}
for (AsyncInvocationInterceptor interceptor : interceptors) {
try {
interceptor.removeContext();
} catch (Throwable t) {
exceptionContext.getThrowables().add(t);
}
}
}


}


}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,11 @@ Object invokeMethod(WebTarget classLevelTarget, Method method, Object[] args) {
customHeaders.remove(HttpHeaders.CONTENT_TYPE);
}

boolean isAsync = CompletionStage.class.isAssignableFrom(method.getReturnType());

if (isAsync) {
AsyncInterceptorSupport.register(interfaceModel.getAsyncInterceptorFactories(), webTarget);
}
Invocation.Builder builder = webTarget
.request(produces)
.property(INVOKED_METHOD, method)
Expand All @@ -197,7 +202,7 @@ Object invokeMethod(WebTarget classLevelTarget, Method method, Object[] args) {

Object response;

if (CompletionStage.class.isAssignableFrom(method.getReturnType())) {
if (isAsync) {
response = asynchronousCall(builder, entityToUse, method, customHeaders);
} else {
response = synchronousCall(builder, entityToUse, method, customHeaders);
Expand Down Expand Up @@ -245,13 +250,6 @@ private CompletableFuture asynchronousCall(Invocation.Builder builder,
Method method,
MultivaluedMap<String, Object> customHeaders) {

//AsyncInterceptors initialization
List<AsyncInvocationInterceptor> asyncInterceptors = interfaceModel.getAsyncInterceptorFactories().stream()
.map(AsyncInvocationInterceptorFactory::newInterceptor)
.collect(Collectors.toList());
asyncInterceptors.forEach(AsyncInvocationInterceptor::prepareContext);
ExecutorServiceWrapper.asyncInterceptors.set(asyncInterceptors);

CompletableFuture<Object> result = new CompletableFuture<>();
Future<Response> theFuture;
if (entity != null
Expand All @@ -264,7 +262,6 @@ private CompletableFuture asynchronousCall(Invocation.Builder builder,

CompletableFuture<Response> completableFuture = (CompletableFuture<Response>) theFuture;
completableFuture.thenAccept(response -> {
asyncInterceptors.forEach(AsyncInvocationInterceptor::removeContext);
try {
evaluateResponse(response, method);
if (returnType.getType().equals(Void.class)) {
Expand All @@ -278,15 +275,6 @@ private CompletableFuture asynchronousCall(Invocation.Builder builder,
result.completeExceptionally(e);
}
}).exceptionally(throwable -> {
// Since it could have been the removeContext method causing exception, we need to be more careful
// to assure, that the future completes
asyncInterceptors.forEach(interceptor -> {
try {
interceptor.removeContext();
} catch (Throwable e) {
throwable.addSuppressed(e);
}
});
result.completeExceptionally(throwable);
return null;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ class RestClientBuilderImpl implements RestClientBuilder {
private final ConfigWrapper configWrapper;
private URI uri;
private ClientBuilder clientBuilder;
private Supplier<ExecutorService> executorService;
private ExecutorService executorService;
private HostnameVerifier sslHostnameVerifier;
private SSLContext sslContext;
private KeyStore sslTrustStore;
Expand All @@ -100,7 +100,6 @@ class RestClientBuilderImpl implements RestClientBuilder {
asyncInterceptorFactories = new ArrayList<>();
config = ConfigProvider.getConfig();
configWrapper = new ConfigWrapper(clientBuilder.getConfiguration());
executorService = Executors::newCachedThreadPool;
}

@Override
Expand Down Expand Up @@ -130,7 +129,7 @@ public RestClientBuilder executorService(ExecutorService executor) {
if (executor == null) {
throw new IllegalArgumentException("ExecutorService cannot be null.");
}
executorService = () -> executor;
executorService = executor;
return this;
}

Expand All @@ -156,7 +155,9 @@ public <T> T build(Class<T> interfaceClass) throws IllegalStateException, RestCl
//sort all AsyncInvocationInterceptorFactory by priority
asyncInterceptorFactories.sort(Comparator.comparingInt(AsyncInvocationInterceptorFactoryPriorityWrapper::getPriority));

clientBuilder.executorService(new ExecutorServiceWrapper(executorService.get()));
if (executorService != null) {
clientBuilder.executorService(executorService);
}

if (null != sslContext) {
clientBuilder.sslContext(sslContext);
Expand Down

0 comments on commit e9397cf

Please sign in to comment.