Example usage for java.lang.reflect InvocationTargetException getTargetException

List of usage examples for java.lang.reflect InvocationTargetException getTargetException

Introduction

In this page you can find the example usage for java.lang.reflect InvocationTargetException getTargetException.

Prototype

public Throwable getTargetException() 

Source Link

Document

Get the thrown target exception.

Usage

From source file:org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor.java

/**
 * Retrieve the Connection via WebSphere's <code>getNativeConnection</code> method.
 *//*from   w w  w .  j  a  v a2  s  .c  om*/
protected Connection doGetNativeConnection(Connection con) throws SQLException {
    // WebSphere 5 connection?
    if (this.webSphere5ConnectionClass != null
            && this.webSphere5ConnectionClass.isAssignableFrom(con.getClass())) {
        try {
            // WebSphere 5's WSJdbcUtil.getNativeConnection(wsJdbcConnection)
            return (Connection) this.webSphere5NativeConnectionMethod.invoke(null, new Object[] { con });
        } catch (InvocationTargetException ex) {
            throw new DataAccessResourceFailureException("WebSphere5's getNativeConnection method failed",
                    ex.getTargetException());
        } catch (Exception ex) {
            throw new DataAccessResourceFailureException(
                    "Could not access WebSphere5's getNativeConnection method", ex);
        }
    }

    // WebSphere 4 connection (or version 4 connection on WebSphere 5)?
    else if (this.webSphere4ConnectionClass != null
            && this.webSphere4ConnectionClass.isAssignableFrom(con.getClass())) {
        try {
            // WebSphere 4's connectionProxy.getPhysicalConnection()
            return (Connection) this.webSphere4PhysicalConnectionMethod.invoke(con, (Object[]) null);
        } catch (InvocationTargetException ex) {
            throw new DataAccessResourceFailureException("WebSphere4's getPhysicalConnection method failed",
                    ex.getTargetException());
        } catch (Exception ex) {
            throw new DataAccessResourceFailureException(
                    "Could not access WebSphere4's getPhysicalConnection method", ex);
        }
    }

    // No known WebSphere connection -> return as-is.
    else {
        if (logger.isDebugEnabled()) {
            logger.debug("Connection [" + con + "] is not a WebSphere 5/4 connection, returning as-is");
        }
        return con;
    }
}

From source file:org.springframework.jms.listener.adapter.MessageListenerAdapter.java

/**
 * Invoke the specified listener method.
 * @param methodName the name of the listener method
 * @param arguments the message arguments to be passed in
 * @return the result returned from the listener method
 * @throws JMSException if thrown by JMS API methods
 * @see #getListenerMethodName/*w  w w. j a va 2 s  . c o m*/
 * @see #buildListenerArguments
 */
protected Object invokeListenerMethod(String methodName, Object[] arguments) throws JMSException {
    try {
        MethodInvoker methodInvoker = new MethodInvoker();
        methodInvoker.setTargetObject(getDelegate());
        methodInvoker.setTargetMethod(methodName);
        methodInvoker.setArguments(arguments);
        methodInvoker.prepare();
        return methodInvoker.invoke();
    } catch (InvocationTargetException ex) {
        Throwable targetEx = ex.getTargetException();
        if (targetEx instanceof JMSException) {
            throw (JMSException) targetEx;
        } else {
            throw new ListenerExecutionFailedException("Listener method '" + methodName + "' threw exception",
                    targetEx);
        }
    } catch (Throwable ex) {
        throw new ListenerExecutionFailedException("Failed to invoke target method '" + methodName
                + "' with arguments " + ObjectUtils.nullSafeToString(arguments), ex);
    }
}

From source file:org.springframework.ldap.transaction.compensating.manager.TransactionAwareDirContextInvocationHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    String methodName = method.getName();
    if (methodName.equals("getTargetContext")) {
        return target;
    } else if (methodName.equals("equals")) {
        // Only consider equal when proxies are identical.
        return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
    } else if (methodName.equals("hashCode")) {
        // Use hashCode of Connection proxy.
        return new Integer(hashCode());
    } else if (methodName.equals("close")) {
        doCloseConnection(target, contextSource);
        return null;
    } else if (LdapTransactionUtils.isSupportedWriteTransactionOperation(methodName)) {
        // Store transaction data and allow operation to proceed.
        CompensatingTransactionUtils.performOperation(contextSource, target, method, args);
        return null;
    } else {//from  ww w.  j  a  v a  2s.  c o  m
        try {
            return method.invoke(target, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }
}

From source file:org.springframework.scheduling.support.MethodInvokingRunnable.java

@Override
public void run() {
    try {/*from w w  w . ja  v  a  2  s  .c o  m*/
        invoke();
    } catch (InvocationTargetException ex) {
        logger.error(getInvocationFailureMessage(), ex.getTargetException());
        // Do not throw exception, else the main loop of the scheduler might stop!
    } catch (Throwable ex) {
        logger.error(getInvocationFailureMessage(), ex);
        // Do not throw exception, else the main loop of the scheduler might stop!
    }
}

From source file:org.springframework.test.context.junit4.SpringMethodRoadie.java

/**
 * Runs the test method on the test instance, processing exceptions (both
 * expected and unexpected), assumptions, and registering failures as
 * necessary./*  w  w  w .  j  av  a2 s. c  om*/
 */
protected void runTestMethod() {
    this.testException = null;
    try {
        getTestMethod().invoke(getTestInstance());
        if (getTestMethod().expectsException()) {
            addFailure(new AssertionError(
                    "Expected exception: " + getTestMethod().getExpectedException().getName()));
        }
    } catch (final InvocationTargetException e) {
        this.testException = e.getTargetException();
        if (this.testException instanceof AssumptionViolatedException) {
            return;
        } else if (!getTestMethod().expectsException()) {
            addFailure(this.testException);
        } else if (getTestMethod().isUnexpected(this.testException)) {
            final String message = "Unexpected exception, expected<"
                    + getTestMethod().getExpectedException().getName() + "> but was<"
                    + this.testException.getClass().getName() + ">";
            addFailure(new Exception(message, this.testException));
        }
    } catch (final Throwable t) {
        addFailure(t);
    } finally {
        if (logger.isDebugEnabled()) {
            logger.debug("Test method [" + getTestMethod().getMethod() + "] threw exception ["
                    + this.testException + "].");
        }
    }
}

From source file:org.springframework.test.context.junit4.SpringMethodRoadie.java

/**
 * Calls {@link TestContextManager#beforeTestMethod(Object,Method)} and then
 * runs {@link org.junit.Before @Before methods}, registering failures and
 * throwing {@link FailedBefore} exceptions as necessary.
 *
 * @throws FailedBefore If an error occurs while executing a <em>before</em>
 *         method./*  w  w  w .  j  a  v a2  s.  c  o m*/
 */
protected void runBefores() throws FailedBefore {
    try {
        getTestContextManager().beforeTestMethod(getTestInstance(), getTestMethod().getMethod());
        final List<Method> befores = getTestMethod().getBefores();
        for (final Method before : befores) {
            before.invoke(getTestInstance());
        }
    } catch (final InvocationTargetException e) {
        addFailure(e.getTargetException());
        throw new FailedBefore();
    } catch (final Throwable t) {
        addFailure(t);
        throw new FailedBefore();
    }
}

From source file:org.springframework.test.context.junit4.SpringMethodRoadie.java

/**
 * Runs {@link org.junit.After @After methods}, registering failures as
 * necessary, and then calls//from www  .j a va2 s  .c o m
 * {@link TestContextManager#afterTestMethod(Object,Method,Throwable)}.
 */
protected void runAfters() {
    final List<Method> afters = getTestMethod().getAfters();
    for (final Method after : afters) {
        try {
            after.invoke(getTestInstance());
        } catch (final InvocationTargetException e) {
            addFailure(e.getTargetException());
        } catch (final Throwable t) {
            addFailure(t); // Untested, but seems impossible
        }
    }

    try {
        getTestContextManager().afterTestMethod(getTestInstance(), getTestMethod().getMethod(),
                getTestException());
    } catch (final Throwable t) {
        addFailure(t);
    }
}

From source file:org.springframework.test.context.transaction.TransactionalTestExecutionListener.java

/**
 * Run all {@link BeforeTransaction @BeforeTransaction} methods for the
 * specified {@linkplain 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  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);
            }
            ReflectionUtils.makeAccessible(method);
            method.invoke(testContext.getTestInstance());
        }
    } catch (InvocationTargetException ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Exception encountered while executing @BeforeTransaction methods for test context "
                    + testContext + ".", ex.getTargetException());
        }
        ReflectionUtils.rethrowException(ex.getTargetException());
    }
}

From source file:org.springframework.test.context.transaction.TransactionalTestExecutionListener.java

/**
 * Run all {@link AfterTransaction @AfterTransaction} methods for the
 * specified {@linkplain 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
 *///from  w w w  .  j  av a 2  s  .  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);
            }
            ReflectionUtils.makeAccessible(method);
            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.web.servlet.mvc.multiaction.MultiActionController.java

/**
 * Invokes the named method./* ww  w . j a v a 2  s .c  o m*/
 * <p>Uses a custom exception handler if possible; otherwise, throw an
 * unchecked exception; wrap a checked exception or Throwable.
 */
protected final ModelAndView invokeNamedMethod(String methodName, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Method method = this.handlerMethodMap.get(methodName);
    if (method == null) {
        throw new NoSuchRequestHandlingMethodException(methodName, getClass());
    }

    try {
        Class<?>[] paramTypes = method.getParameterTypes();
        List<Object> params = new ArrayList<Object>(4);
        params.add(request);
        params.add(response);

        if (paramTypes.length >= 3 && HttpSession.class == paramTypes[2]) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                throw new HttpSessionRequiredException(
                        "Pre-existing session required for handler method '" + methodName + "'");
            }
            params.add(session);
        }

        // If last parameter isn't of HttpSession type, it's a command.
        if (paramTypes.length >= 3 && HttpSession.class != paramTypes[paramTypes.length - 1]) {
            Object command = newCommandObject(paramTypes[paramTypes.length - 1]);
            params.add(command);
            bind(request, command);
        }

        Object returnValue = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
        return massageReturnValueIfNecessary(returnValue);
    } catch (InvocationTargetException ex) {
        // The handler method threw an exception.
        return handleException(request, response, ex.getTargetException());
    } catch (Exception ex) {
        // The binding process threw an exception.
        return handleException(request, response, ex);
    }
}