protected Object around()

in safeguard-impl/src/main/java/org/apache/safeguard/impl/asynchronous/BaseAsynchronousInterceptor.java [45:101]


    protected Object around(final InvocationContext context) {
        final Class<?> returnType = context.getMethod().getReturnType();
        if (CompletionStage.class.isAssignableFrom(returnType)) {
            final ExtendedCompletableFuture<Object> future = newCompletableFuture(context);
            getExecutor(context).execute(() -> {
                try {
                    future.before();
                    final Object proceed = context.proceed();
                    final CompletionStage<?> stage = CompletionStage.class.cast(proceed);
                    stage.handle((r, e) -> {
                        future.after();
                        if (e != null) {
                            ofNullable(getErrorHandler(context.getContextData()))
                                .map(eh -> {
                                    if (Exception.class.isInstance(e)) {
                                        try {
                                            eh.apply(Exception.class.cast(e));
                                        } catch (final Exception e1) {
                                            future.completeExceptionally(e1);
                                        }
                                    } else {
                                        future.completeExceptionally(e);
                                    }
                                    return true;
                                })
                                .orElseGet(() -> future.completeExceptionally(e));
                        } else {
                            future.complete(r);
                        }
                        return null;
                    });
                } catch (final Exception e) {
                    future.completeExceptionally(e);
                }
            });
            return future;
        }
        if (Future.class.isAssignableFrom(returnType)) {
            final FutureWrapper<Object> facade = newFuture(context, context.getContextData());
            getExecutor(context).execute(() -> {
                final Object proceed;
                try {
                    facade.before();
                    proceed = context.proceed();
                    facade.setDelegate(Future.class.cast(proceed));
                } catch (final Exception e) {
                    final CompletableFuture<Object> failingFuture = new CompletableFuture<>();
                    failingFuture.completeExceptionally(e);
                    facade.setDelegate(failingFuture);
                }
            });
            return facade;
        }
        throw new FaultToleranceDefinitionException(
                "Unsupported return type: " + returnType + " (from: " + context.getMethod() + ")." +
                        "Should be Future or CompletionStage.");
    }