Example usage for org.springframework.util ReflectionUtils rethrowException

List of usage examples for org.springframework.util ReflectionUtils rethrowException

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils rethrowException.

Prototype

public static void rethrowException(Throwable ex) throws Exception 

Source Link

Document

Rethrow the given Throwable exception , which is presumably the target exception of an InvocationTargetException .

Usage

From source file:dk.clanie.actor.ActorExecutionInterceptor.java

public Object invoke(final MethodInvocation invocation) throws Throwable {
    @SuppressWarnings("rawtypes")
    Future result = this.executor.submit(new Callable<Object>() {
        public Object call() throws Exception {
            try {
                Object result = invocation.proceed();
                if (result instanceof Future) {
                    return ((Future) result).get();
                }//from  w  ww. ja v  a  2 s  . co  m
            } catch (Throwable ex) {
                ReflectionUtils.rethrowException(ex);
            }
            return null;
        }
    });
    Class<?> returnType = invocation.getMethod().getReturnType();
    if (Future.class.isAssignableFrom(returnType)) {
        return result;
    } else if (Void.TYPE != returnType) {
        try {
            return result.get();
        } catch (Throwable ex) {
            ReflectionUtils.rethrowException(ex);
        }
    }
    return null;
}

From source file:com.crossbusiness.resiliency.aspect.AbstractAsyncAspect.java

/**
 * Intercept the given method invocation, submit the actual calling of the method to
 * the correct task executor and return immediately to the caller.
 * @return {@link Future} if the original method returns {@code Future}; {@code null}
 * otherwise./*from   w  w  w .ja  v a2s.  c  o m*/
 */
// @Around("asyncMethodExecution()")
private Object doAsync(final ProceedingJoinPoint point, Async asyncConfig) throws Throwable {
    log.debug(point + " -> " + asyncConfig);

    String qualifier = asyncConfig.value();
    MethodSignature targetMethodSig = (MethodSignature) point.getSignature();
    AsyncTaskExecutor executor = getExecutor(targetMethodSig.getMethod(), qualifier);

    if (executor == null) {
        return point.proceed();
    }

    Callable<Object> callable = new Callable<Object>() {
        public Object call() throws Exception {
            try {
                Object result = point.proceed();
                if (result instanceof Future) {
                    return ((Future<?>) result).get();
                }
            } catch (Throwable ex) {
                ReflectionUtils.rethrowException(ex);
            }
            return null;
        }
    };

    Future<?> result = executor.submit(callable);

    if (Future.class.isAssignableFrom(targetMethodSig.getMethod().getReturnType())) {
        return result;
    } else {
        return null;
    }
}

From source file:py.una.pol.karaku.test.cucumber.TransactionalTestCucumberExecutionListener.java

/**
 * Run all {@link BeforeTransaction &#064;BeforeTransaction methods} for the
 * specified {@link TestContext test context}. If one of the methods fails,
 * however, the caught exception will be rethrown in a wrapped
 * {@link RuntimeException}, and the remaining methods will
 * <strong>not</strong> be given a chance to execute.
 * /*  www  . j a v a  2 s .c o m*/
 * @param testContext
 *            the current test context
 */
protected void runBeforeTransactionMethods(TestContext testContext) throws Exception {

    try {
        List<Method> methods = getAnnotatedMethods(testContext.getTestClass(), BeforeTransaction.class);
        Collections.reverse(methods);
        for (Method method : methods) {
            if (logger.isDebugEnabled()) {
                logger.debug("Executing @BeforeTransaction method [" + method + "] for test context ["
                        + testContext + "]");
            }
            method.invoke(testContext.getTestInstance());
        }
    } catch (InvocationTargetException ex) {
        logger.error("Exception encountered while executing @BeforeTransaction methods for test context ["
                + testContext + "]", ex.getTargetException());
        ReflectionUtils.rethrowException(ex.getTargetException());
    }
}

From source file:py.una.pol.karaku.test.cucumber.TransactionalTestCucumberExecutionListener.java

/**
 * Run all {@link AfterTransaction &#064;AfterTransaction methods} for the
 * specified {@link TestContext test context}. If one of the methods fails,
 * the caught exception will be logged as an error, and the remaining
 * methods will be given a chance to execute. After all methods have
 * executed, the first caught exception, if any, will be rethrown.
 * /*from  ww w.  j  a  v  a 2s  . c o  m*/
 * @param testContext
 *            the current test context
 */
protected void runAfterTransactionMethods(TestContext testContext) throws Exception {

    Throwable afterTransactionException = null;

    List<Method> methods = getAnnotatedMethods(testContext.getTestClass(), AfterTransaction.class);
    for (Method method : methods) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Executing @AfterTransaction method [" + method + "] for test context ["
                        + testContext + "]");
            }
            method.invoke(testContext.getTestInstance());
        } catch (InvocationTargetException ex) {
            Throwable targetException = ex.getTargetException();
            if (afterTransactionException == null) {
                afterTransactionException = targetException;
            }
            logger.error("Exception encountered while executing @AfterTransaction method [" + method
                    + "] for test context [" + testContext + "]", targetException);
        } catch (Exception ex) {
            if (afterTransactionException == null) {
                afterTransactionException = ex;
            }
            logger.error("Exception encountered while executing @AfterTransaction method [" + method
                    + "] for test context [" + testContext + "]", ex);
        }
    }

    if (afterTransactionException != null) {
        ReflectionUtils.rethrowException(afterTransactionException);
    }
}

From source file:org.broadleafcommerce.test.MergeTransactionalTestExecutionListener.java

/**
 * Run all {@link BeforeTransaction @BeforeTransaction methods} for the
 * specified {@link TestContext test context}. If one of the methods fails,
 * however, the caught exception will be rethrown in a wrapped
 * {@link RuntimeException}, and the remaining methods will <strong>not</strong>
 * be given a chance to execute./*from  w ww.  j  a va 2s  . com*/
 * @param testContext the current test context
 */
protected void runBeforeTransactionMethods(TestContext testContext) throws Exception {
    try {
        List<Method> methods = getAnnotatedMethods(testContext.getTestClass(), BeforeTransaction.class);
        Collections.reverse(methods);
        for (Method method : methods) {
            if (logger.isDebugEnabled()) {
                logger.debug("Executing @BeforeTransaction method [" + method + "] for test context ["
                        + testContext + "]");
            }
            method.invoke(testContext.getTestInstance());
        }
    } catch (InvocationTargetException ex) {
        logger.error("Exception encountered while executing @BeforeTransaction methods for test context ["
                + testContext + "]", ex.getTargetException());
        ReflectionUtils.rethrowException(ex.getTargetException());
    }
}

From source file:org.broadleafcommerce.test.MergeTransactionalTestExecutionListener.java

/**
 * Run all {@link AfterTransaction @AfterTransaction methods} for the
 * specified {@link TestContext test context}. If one of the methods fails,
 * the caught exception will be logged as an error, and the remaining
 * methods will be given a chance to execute. After all methods have
 * executed, the first caught exception, if any, will be rethrown.
 * @param testContext the current test context
 *///ww  w .  j a v a2s  .  co  m
protected void runAfterTransactionMethods(TestContext testContext) throws Exception {
    Throwable afterTransactionException = null;

    List<Method> methods = getAnnotatedMethods(testContext.getTestClass(), AfterTransaction.class);
    for (Method method : methods) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Executing @AfterTransaction method [" + method + "] for test context ["
                        + testContext + "]");
            }
            method.invoke(testContext.getTestInstance());
        } catch (InvocationTargetException ex) {
            Throwable targetException = ex.getTargetException();
            if (afterTransactionException == null) {
                afterTransactionException = targetException;
            }
            logger.error("Exception encountered while executing @AfterTransaction method [" + method
                    + "] for test context [" + testContext + "]", targetException);
        } catch (Exception ex) {
            if (afterTransactionException == null) {
                afterTransactionException = ex;
            }
            logger.error("Exception encountered while executing @AfterTransaction method [" + method
                    + "] for test context [" + testContext + "]", ex);
        }
    }

    if (afterTransactionException != null) {
        ReflectionUtils.rethrowException(afterTransactionException);
    }
}

From source file:org.springframework.aop.interceptor.AsyncExecutionAspectSupport.java

/**
 * Handles a fatal error thrown while asynchronously invoking the specified
 * {@link Method}./*from w w w. j a  va 2  s. c o  m*/
 * <p>If the return type of the method is a {@link Future} object, the original
 * exception can be propagated by just throwing it at the higher level. However,
 * for all other cases, the exception will not be transmitted back to the client.
 * In that later case, the current {@link AsyncUncaughtExceptionHandler} will be
 * used to manage such exception.
 * @param ex the exception to handle
 * @param method the method that was invoked
 * @param params the parameters used to invoke the method
 */
protected void handleError(Throwable ex, Method method, Object... params) throws Exception {
    if (Future.class.isAssignableFrom(method.getReturnType())) {
        ReflectionUtils.rethrowException(ex);
    } else {
        // Could not transmit the exception to the caller with default executor
        try {
            this.exceptionHandler.handleUncaughtException(ex, method, params);
        } catch (Throwable ex2) {
            logger.error("Exception handler for async method '" + method.toGenericString()
                    + "' threw unexpected exception itself", ex2);
        }
    }
}

From source file:org.springframework.aop.interceptor.AsyncExecutionInterceptor.java

/**
 * Handles a fatal error thrown while asynchronously invoking the specified
 * {@link Method}./*  ww w .j a  v  a2  s  .  co m*/
 * <p>If the return type of the method is a {@link Future} object, the original
 * exception can be propagated by just throwing it at the higher level. However,
 * for all other cases, the exception will not be transmitted back to the client.
 * In that later case, the current {@link AsyncUncaughtExceptionHandler} will be
 * used to manage such exception.
 * @param ex the exception to handle
 * @param method the method that was invoked
 * @param params the parameters used to invoke the method
 */
protected void handleError(Throwable ex, Method method, Object... params) throws Exception {
    if (method.getReturnType().isAssignableFrom(Future.class)) {
        ReflectionUtils.rethrowException(ex);
    } else {
        // Could not transmit the exception to the caller with default executor
        try {
            this.exceptionHandler.handleUncaughtException(ex, method, params);
        } catch (Throwable ex2) {
            logger.error("Exception handler for async method '" + method.toGenericString()
                    + "' threw unexpected exception itself", ex2);
        }
    }
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

public final Object invokeHandlerMethod(Method handlerMethod, Object handler, NativeWebRequest webRequest,
        ExtendedModelMap implicitModel) throws Exception {

    Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod);
    try {//from w  ww. jav a2 s . c  o m
        boolean debug = logger.isDebugEnabled();
        for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
            Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName);
            if (attrValue != null) {
                implicitModel.addAttribute(attrName, attrValue);
            }
        }
        for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) {
            Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod);
            Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest,
                    implicitModel);
            if (debug) {
                logger.debug("Invoking model attribute method: " + attributeMethodToInvoke);
            }
            String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value();
            if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) {
                continue;
            }
            ReflectionUtils.makeAccessible(attributeMethodToInvoke);
            Object attrValue = attributeMethodToInvoke.invoke(handler, args);
            if ("".equals(attrName)) {
                Class resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke,
                        handler.getClass());
                attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType,
                        attrValue);
            }
            if (!implicitModel.containsAttribute(attrName)) {
                implicitModel.addAttribute(attrName, attrValue);
            }
        }
        Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
        if (debug) {
            logger.debug("Invoking request handler method: " + handlerMethodToInvoke);
        }
        ReflectionUtils.makeAccessible(handlerMethodToInvoke);
        return handlerMethodToInvoke.invoke(handler, args);
    } catch (IllegalStateException ex) {
        // Internal assertion failed (e.g. invalid signature):
        // throw exception with full handler method context...
        throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex);
    } catch (InvocationTargetException ex) {
        // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception...
        ReflectionUtils.rethrowException(ex.getTargetException());
        return null;
    }
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

public final void updateModelAttributes(Object handler, Map<String, Object> mavModel,
        ExtendedModelMap implicitModel, NativeWebRequest webRequest) throws Exception {

    if (this.methodResolver.hasSessionAttributes() && this.sessionStatus.isComplete()) {
        for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
            this.sessionAttributeStore.cleanupAttribute(webRequest, attrName);
        }//from  w  ww .  j  a  va  2s .c  o m
    }

    // Expose model attributes as session attributes, if required.
    // Expose BindingResults for all attributes, making custom editors available.
    Map<String, Object> model = (mavModel != null ? mavModel : implicitModel);
    if (model != null) {
        try {
            String[] originalAttrNames = model.keySet().toArray(new String[model.size()]);
            for (String attrName : originalAttrNames) {
                Object attrValue = model.get(attrName);
                boolean isSessionAttr = this.methodResolver.isSessionAttribute(attrName,
                        (attrValue != null ? attrValue.getClass() : null));
                if (isSessionAttr) {
                    if (this.sessionStatus.isComplete()) {
                        implicitModel.put(MODEL_KEY_PREFIX_STALE + attrName, Boolean.TRUE);
                    } else if (!implicitModel.containsKey(MODEL_KEY_PREFIX_STALE + attrName)) {
                        this.sessionAttributeStore.storeAttribute(webRequest, attrName, attrValue);
                    }
                }
                if (!attrName.startsWith(BindingResult.MODEL_KEY_PREFIX)
                        && (isSessionAttr || isBindingCandidate(attrValue))) {
                    String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + attrName;
                    if (mavModel != null && !model.containsKey(bindingResultKey)) {
                        WebDataBinder binder = createBinder(webRequest, attrValue, attrName);
                        initBinder(handler, attrName, binder, webRequest);
                        mavModel.put(bindingResultKey, binder.getBindingResult());
                    }
                }
            }
        } catch (InvocationTargetException ex) {
            // User-defined @InitBinder method threw an exception...
            ReflectionUtils.rethrowException(ex.getTargetException());
        }
    }
}