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.apache.struts.webapp.example2.SaveRegistrationAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*from  w  ww  .  j  a  va  2s.  co  m*/
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    RegistrationForm regform = (RegistrationForm) form;
    String action = regform.getAction();
    if (action == null) {
        action = "Create";
    }
    UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
    if (log.isDebugEnabled()) {
        log.debug("SaveRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user (unless creating)?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (!"Create".equals(action) && (user == null)) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("failure"));
    }

    // Validate the transactional control token
    ActionErrors errors = new ActionErrors();
    if (log.isTraceEnabled()) {
        log.trace(" Checking transactional control token");
    }
    if (!isTokenValid(request)) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.transaction.token"));
    }
    resetToken(request);

    // Validate the request parameters specified by the user
    if (log.isTraceEnabled()) {
        log.trace(" Performing extra validations");
    }
    String value = null;
    value = regform.getUsername();
    if (("Create".equals(action)) && (database.findUser(value) != null)) {
        errors.add("username", new ActionError("error.username.unique", regform.getUsername()));
    }
    if ("Create".equals(action)) {
        value = regform.getPassword();
        if ((value == null) || (value.length() < 1)) {
            errors.add("password", new ActionError("error.password.required"));
        }
        value = regform.getPassword2();
        if ((value == null) || (value.length() < 1)) {
            errors.add("password2", new ActionError("error.password2.required"));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        saveToken(request);
        return (mapping.getInputForward());
    }

    // Update the user's persistent profile information
    try {
        if ("Create".equals(action)) {
            user = database.createUser(regform.getUsername());
        }
        String oldPassword = user.getPassword();
        PropertyUtils.copyProperties(user, regform);
        if ((regform.getPassword() == null) || (regform.getPassword().length() < 1)) {
            user.setPassword(oldPassword);
        }
    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null) {
            t = e;
        }
        log.error("Registration.populate", t);
        throw new ServletException("Registration.populate", t);
    } catch (Throwable t) {
        log.error("Registration.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Log the user in if appropriate
    if ("Create".equals(action)) {
        session.setAttribute(Constants.USER_KEY, user);
        if (log.isTraceEnabled()) {
            log.trace(" User '" + user.getUsername() + "' logged on in session " + session.getId());
        }
    }

    // Remove the obsolete form bean
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }

    // Forward control to the specified success URI
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to success page");
    }
    return (mapping.findForward("success"));

}

From source file:org.apache.tapestry.listener.ListenerMap.java

/**
 *  Invoked by the inner listener/adaptor classes to
 *  invoke the method.// w ww.j av  a  2  s.  c  om
 *
 **/

private static void invokeTargetMethod(Object target, Method method, Object[] args) {
    if (LOG.isDebugEnabled())
        LOG.debug("Invoking listener method " + method + " on " + target);

    try {
        try {
            method.invoke(target, args);
        } catch (InvocationTargetException ex) {
            Throwable inner = ex.getTargetException();

            if (inner instanceof ApplicationRuntimeException)
                throw (ApplicationRuntimeException) inner;

            // Edit out the InvocationTargetException, if possible.

            if (inner instanceof RuntimeException)
                throw (RuntimeException) inner;

            throw ex;
        }
    } catch (ApplicationRuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        // Catch InvocationTargetException or, preferrably,
        // the inner exception here (if its a runtime exception).

        throw new ApplicationRuntimeException(Tapestry.format("ListenerMap.unable-to-invoke-method",
                method.getName(), target, ex.getMessage()), ex);
    }
}

From source file:org.apache.velocity.runtime.parser.node.ASTMethod.java

/**
 *  invokes the method.  Returns null if a problem, the
 *  actual return if the method returns something, or
 *  an empty string "" if the method returns void
 * @param o/*from   ww  w . j  a v  a2  s  . c om*/
 * @param context
 * @return Result or null.
 * @throws MethodInvocationException
 */
public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException {
    /*
     *  new strategy (strategery!) for introspection. Since we want
     *  to be thread- as well as context-safe, we *must* do it now,
     *  at execution time.  There can be no in-node caching,
     *  but if we are careful, we can do it in the context.
     */
    Object[] params = new Object[paramCount];

    /*
     * sadly, we do need recalc the values of the args, as this can
     * change from visit to visit
     */
    final Class[] paramClasses = paramCount > 0 ? new Class[paramCount] : ArrayUtils.EMPTY_CLASS_ARRAY;

    for (int j = 0; j < paramCount; j++) {
        params[j] = jjtGetChild(j + 1).value(context);
        if (params[j] != null) {
            paramClasses[j] = params[j].getClass();
        }
    }

    VelMethod method = ClassUtils.getMethod(methodName, params, paramClasses, o, context, this, strictRef);
    if (method == null)
        return null;

    try {
        /*
         *  get the returned object.  It may be null, and that is
         *  valid for something declared with a void return type.
         *  Since the caller is expecting something to be returned,
         *  as long as things are peachy, we can return an empty
         *  String so ASTReference() correctly figures out that
         *  all is well.
         */

        Object obj = method.invoke(o, params);

        if (obj == null) {
            if (method.getReturnType() == Void.TYPE) {
                return "";
            }
        }

        return obj;
    } catch (InvocationTargetException ite) {
        return handleInvocationException(o, context, ite.getTargetException());
    }

    /** Can also be thrown by method invocation **/
    catch (IllegalArgumentException t) {
        return handleInvocationException(o, context, t);
    }

    /**
     * pass through application level runtime exceptions
     */
    catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        String msg = "ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.getClass();
        Logger.error(this, msg, e);
        throw new VelocityException(msg, e);
    }
}

From source file:org.blocks4j.feature.toggle.proxy.Feature.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object _this;
    if (this.isOn(method, args)) {
        _this = this.featureOn;
    } else {/*from  ww w .  j  a va  2  s  .c  om*/
        _this = this.featureOff;
    }
    try {
        return method.invoke(_this, args);
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}

From source file:org.broadleafcommerce.common.cache.HydratedSetup.java

public static void populateFromCache(Object entity, String propertyName) {
    HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager();
    HydrationDescriptor descriptor = ((HydratedAnnotationManager) manager).getHydrationDescriptor(entity);
    if (!MapUtils.isEmpty(descriptor.getHydratedMutators())) {
        Method[] idMutators = descriptor.getIdMutators();
        String cacheRegion = descriptor.getCacheRegion();
        for (String field : descriptor.getHydratedMutators().keySet()) {
            if (StringUtils.isEmpty(propertyName) || field.equals(propertyName)) {
                try {
                    Serializable entityId = (Serializable) idMutators[0].invoke(entity);
                    Object hydratedItem = manager.getHydratedCacheElementItem(cacheRegion,
                            getInheritanceHierarchyRoot(entity.getClass()), entityId, field);
                    if (hydratedItem == null) {
                        Method factoryMethod = entity.getClass().getMethod(
                                descriptor.getHydratedMutators().get(field).getFactoryMethod(), new Class[] {});
                        Object fieldVal = factoryMethod.invoke(entity);
                        manager.addHydratedCacheElementItem(cacheRegion,
                                getInheritanceHierarchyRoot(entity.getClass()), entityId, field, fieldVal);
                        hydratedItem = fieldVal;
                    }/*  w ww  .  j  a va 2s. c  o m*/
                    descriptor.getHydratedMutators().get(field).getMutators()[1].invoke(entity, hydratedItem);
                } catch (InvocationTargetException e) {
                    if (e.getTargetException() != null
                            && e.getTargetException() instanceof CacheFactoryException) {
                        LOG.warn("Unable to setup the hydrated cache for an entity. "
                                + e.getTargetException().getMessage());
                    } else {
                        throw new RuntimeException(
                                "There was a problem while replacing a hydrated cache item - field(" + field
                                        + ") : entity(" + entity.getClass().getName() + ')',
                                e);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(
                            "There was a problem while replacing a hydrated cache item - field(" + field
                                    + ") : entity(" + entity.getClass().getName() + ')',
                            e);
                }
            }
        }
    }
}

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.//  w ww .j a va 2  s .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
 */// w w  w. j  a v  a 2 s. com
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.brutusin.instrumentation.InstrumentatorTest.java

@Test
public void testException() throws Exception {
    final Bean<String> executionIdBean = new Bean<String>();
    final Bean<Integer> counterBean = new Bean<Integer>();
    final Bean<Throwable> thBean = new Bean<Throwable>();
    final Bean<AssertionError> assertionBean = new Bean<AssertionError>();

    Interceptor interceptor = new VoidInterceptor() {
        @Override/*from  w  w  w .j  a  va 2  s. co  m*/
        public void doOnStart(Object source, Object[] arg, String executionId) {
            try {
                assertNull(executionIdBean.getValue());
                assertNull(counterBean.getValue());
                assertNull(thBean.getValue());
                executionIdBean.setValue(executionId);
                counterBean.setValue(1);
            } catch (AssertionError e) {
                if (assertionBean.getValue() == null) {
                    assertionBean.setValue(e);
                } else {
                    //assertionBean.getValue().addSuppressed(e);
                    assertionBean.setValue(e); // JDK 6 comp
                }
            }
        }

        @Override
        public void doOnThrowableThrown(Object source, Throwable th, String executionId) {
            try {
                assertNotNull(executionIdBean.getValue());
                assertEquals(executionId, executionIdBean.getValue());
                assertEquals(new Integer(1), counterBean.getValue());
                assertNull(thBean.getValue());
                counterBean.setValue(counterBean.getValue() + 1);
                thBean.setValue(th);
            } catch (AssertionError e) {
                if (assertionBean.getValue() == null) {
                    assertionBean.setValue(e);
                } else {
                    //assertionBean.getValue().addSuppressed(e);
                    assertionBean.setValue(e); // JDK 6 comp
                }
            }
        }

        @Override
        public void doOnThrowableUncatched(Object source, Throwable th, String executionId) {
            try {
                assertNotNull(executionIdBean.getValue());
                assertNotNull(thBean.getValue());
                assertEquals(executionId, executionIdBean.getValue());
                assertEquals(th, thBean.getValue());
                assertEquals(new Integer(2), counterBean.getValue());
            } catch (AssertionError e) {
                if (assertionBean.getValue() == null) {
                    assertionBean.setValue(e);
                } else {
                    //assertionBean.getValue().addSuppressed(e);
                    assertionBean.setValue(e); // JDK 6 comp
                }
            }
        }

        @Override
        public void doOnFinish(Object source, Object o, String executionId) {
            AssertionError e = new AssertionError();
            if (assertionBean.getValue() == null) {
                assertionBean.setValue(e);
            } else {
                //assertionBean.getValue().addSuppressed(e);
                assertionBean.setValue(e); // JDK 6 comp
            }
        }
    };

    try {
        Class instrumentedClass = instrumentClass(interceptor);
        instrumentedClass.getMethod("throwHello").invoke(null);
    } catch (InvocationTargetException ite) {
        assertEquals(ite.getTargetException(), thBean.getValue());
    }
    if (assertionBean.getValue() != null) {
        throw assertionBean.getValue();
    }
    assertTrue(thBean.getValue() instanceof RuntimeException
            && thBean.getValue().getMessage().equals(SimpleClass.GREETING));
}

From source file:org.castor.cache.distributed.OsCache.java

/**
 * {@inheritDoc}/*from w w w  .  j ava  2s  .co  m*/
 */
@SuppressWarnings("unchecked")
public V get(final Object key) {
    try {
        return (V) _getMethod.invoke(_cache, new Object[] { String.valueOf(key) });
    } catch (InvocationTargetException e) {
        String cause = e.getTargetException().getClass().getName();
        if (cause.equals(NEEDS_REFRESH_EXCEPTION)) {
            invokeCacheMethod(_cancelMethod, new Object[] { String.valueOf(key) });
            return null;
        }

        String msg = "Failed to call method on OSCache instance: " + e.getMessage();
        LOG.error(msg, e);
        throw new IllegalStateException(e.getMessage());
    } catch (Exception e) {
        String msg = "Failed to call method on OSCache instance: " + e.getMessage();
        LOG.error(msg, e);
        throw new IllegalStateException(e.getMessage());
    }
}

From source file:org.chiba.xml.xforms.core.UpdateSequencer.java

/**
 * Performs the next deferred update if any.
 * <p/>//from   ww w.j a  v  a2s  .  co m
 * The update method name is removed from the sequence of updates to be
 * deferred further.
 *
 * @return <code>true</code> if an deferred update has been performed,
 *         otherwise <code>false</code>.
 * @throws Exception if any error occurred during the update.
 */
public boolean perform() throws Exception {
    this.updateRunning = false;

    if (this.updateSequence.size() > 0) {
        String name = this.updateSequence.removeFirst().toString();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("performing sequenced " + name);
        }

        try {
            this.model.getClass().getDeclaredMethod(name, (Class[]) null).invoke(this.model, (Object[]) null);
        } catch (InvocationTargetException e) {
            throw new Exception(e.getTargetException());
        }

        return true;
    }

    return false;
}