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.lilyproject.avro.LilySpecificResponder.java

@Override
public Object respond(Protocol.Message message, Object request) throws Exception {
    int numParams = message.getRequest().getFields().size();
    Object[] params = new Object[numParams];
    Class[] paramTypes = new Class[numParams];
    int i = 0;/*from   w  ww.j a va2  s  .co m*/
    try {
        for (Schema.Field param : message.getRequest().getFields()) {
            params[i] = ((GenericRecord) request).get(param.name());
            paramTypes[i] = data.getClass(param.schema());
            i++;
        }
        Method method = impl.getClass().getMethod(message.getName(), paramTypes);
        method.setAccessible(true);
        return method.invoke(impl, params);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof SpecificRecord) {
            throw (Exception) e.getTargetException();
        } else {
            throw AvroConverter.convertOtherException(e.getTargetException());
        }
    } catch (NoSuchMethodException e) {
        throw new AvroRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new AvroRuntimeException(e);
    }
}

From source file:org.lilyproject.repository.avro.LilySpecificResponder.java

@Override
public Object respond(Protocol.Message message, Object request) throws Exception {
    Class[] paramTypes = new Class[message.getRequest().getFields().size()];
    int i = 0;//from ww  w. j ava2s . c o  m
    try {
        for (Schema.Field param : message.getRequest().getFields())
            paramTypes[i++] = data.getClass(param.schema());
        Method method = impl.getClass().getMethod(message.getName(), paramTypes);
        return method.invoke(impl, (Object[]) request);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof SpecificRecord) {
            throw (Exception) e.getTargetException();
        } else {
            throw converter.convertOtherException(e.getTargetException());
        }
    } catch (NoSuchMethodException e) {
        throw new AvroRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new AvroRuntimeException(e);
    }
}

From source file:org.mule.component.DefaultComponentLifecycleAdapter.java

/**
 * Propagates dispose() life-cycle to component object implementations if they
 * implement the mule {@link Disposable} interface. NOT: It is up to component
 * implementations to ensure their implementation of dispose() is thread-safe.
 */// w  ww.j ava 2  s .  c o  m
public void dispose() {
    try {
        if (isDisposable) {
            // make sure we haven't lost the reference to the object
            Object o = componentObject;
            if (o != null) {
                try {
                    disposeMethod.invoke(o);
                } catch (InvocationTargetException e) {
                    //unwrap
                    throw e.getTargetException();
                }
            }
        }
        componentObject = null;

    } catch (Throwable e) {
        logger.error("failed to dispose: " + flowConstruct.getName(), e);
    }
    disposed = true;
}

From source file:org.mypsycho.beans.DefaultInvoker.java

public Object get(Object bean, PropertyDescriptor prop, int index)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    // Call the indexed getter method if there is one
    if (prop instanceof IndexedPropertyDescriptor) {
        Method readMethod = ((IndexedPropertyDescriptor) prop).getIndexedReadMethod();
        readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod);
        if (readMethod != null) {
            try {
                return (invokeMethod(readMethod, bean, new Object[] { index }));
            } catch (InvocationTargetException e) {
                if (e.getTargetException() instanceof IndexOutOfBoundsException) {
                    throw (IndexOutOfBoundsException) e.getTargetException();
                } else {
                    throw e;
                }/*  w  w w. j  a v  a 2  s . c o  m*/
            }
        }
    }

    // Otherwise, the underlying property must be an array
    Method readMethod = getReadMethod(bean.getClass(), prop);
    required(bean, prop, readMethod, "getter");

    // Call the property getter and return the value
    Object invokeResult = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
    try {
        return getIndexed(invokeResult, index);
    } catch (IndexOutOfBoundsException e) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + getSize(invokeResult)
                + " for property '" + prop.getName() + "'");
    }
}

From source file:org.mypsycho.beans.DefaultInvoker.java

public void set(Object bean, PropertyDescriptor prop, int index, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    // Call the indexed setter method if there is one
    if (prop instanceof IndexedPropertyDescriptor) {
        Method writeMethod = ((IndexedPropertyDescriptor) prop).getIndexedWriteMethod();
        writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod);
        if (writeMethod != null) {
            try {
                invokeMethod(writeMethod, bean, new Object[] { index, value });
            } catch (InvocationTargetException e) {
                if (e.getTargetException() instanceof IndexOutOfBoundsException) {
                    throw (IndexOutOfBoundsException) e.getTargetException();
                }//ww  w.  j  a  v  a  2  s .  c o m
                throw e;
            }
            return;
        }
    }

    // Otherwise, the underlying property must be an array or a list
    Method readMethod = getReadMethod(bean.getClass(), prop);
    required(bean, prop, readMethod, "getter");

    // Call the property getter to get the array or list
    Object invokeResult = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
    try {
        setIndexed(invokeResult, index, value);
    } catch (IndexOutOfBoundsException e) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + getSize(invokeResult)
                + " for property '" + prop.getName() + "'");
    }
}

From source file:org.mypsycho.beans.DefaultInvoker.java

/** This just catches and wraps IllegalArgumentException. */
private Object invokeMethod(Method method, Object bean, Object[] values)
        throws IllegalAccessException, InvocationTargetException {
    if (bean == null) {
        throw new IllegalArgumentException(
                "No bean specified " + "- this should have been checked before reaching this method");
    }/* w  ww.  ja  v a  2s  . com*/

    Exception cause = null;
    try {
        return method.invoke(bean, values);
    } catch (InvocationTargetException ite) {
        if (ite.getTargetException() instanceof Error) {
            throw (Error) ite.getTargetException();
        } else if (ite.getTargetException() instanceof RuntimeException) {
            throw (RuntimeException) ite.getTargetException();
        }
        throw ite;

    } catch (NullPointerException npe) {
        // JDK 1.3 and JDK 1.4 throw NullPointerException if an argument is
        // null for a primitive value (JDK 1.5+ throw
        // IllegalArgumentException)
        cause = npe;
    } catch (IllegalArgumentException iae) {
        cause = iae;
    }

    String valueString = "";
    if (values != null) {
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                valueString += ", ";
            }
            if (values[i] == null) {
                valueString += "<null>";
            } else {
                valueString += (values[i]).getClass().getName();
            }
        }
    }
    String expectedString = "";
    Class<?>[] parTypes = method.getParameterTypes();
    for (int i = 0; i < parTypes.length; i++) {
        if (i > 0) {
            expectedString += ", ";
        }
        expectedString += parTypes[i].getName();
    }

    IllegalArgumentException e = new IllegalArgumentException(
            "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName()
                    + " on bean class '" + bean.getClass() + "' - " + cause.getMessage()
                    // as per
                    // https://issues.apache.org/jira/browse/BEANUTILS-224
                    + " - had objects of type \"" + valueString + "\" but expected signature \""
                    + expectedString + "\"");
    BeanUtils.initCause(e, cause);
    throw e;
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Invokes the named method.//from w w  w .j a  va 2s.  c om
 * <p>
 * Uses a custom exception handler if possible; otherwise, throw an
 * unchecked exception; wrap a checked exception or Throwable.
 * @param useCommand 
 */
@SuppressWarnings("deprecation")
protected final ModelAndView invokeNamedMethod(Method method, WebRequestContext request, Object useCommand)
        throws Exception {
    //TODO TRATAMENTO DE LOOP ETERNO (REFERENCIA CIRCULAR)

    do {
        Input input = null;
        boolean fromErrors = false;
        try {
            List<Object> params = new ArrayList<Object>(2);
            boolean hasRequestParameter = method.getParameterTypes().length > 0
                    && method.getParameterTypes()[0].isAssignableFrom(WebRequestContext.class)
                    && !method.getParameterTypes()[0].equals(Object.class);
            if (hasRequestParameter) {
                params.add(request);
            }

            if (useCommand == null) {
                input = getAnnotation(method, Input.class);//modificado em 22/10/2010, esse cdigo ficava dentro do if.. e s funcionava caso existissem commands
                if ((hasRequestParameter && method.getParameterTypes().length == 2)
                        || (!hasRequestParameter && method.getParameterTypes().length == 1)) {
                    Class<?> commandClass = getCommandClass(method, hasRequestParameter ? 1 : 0);
                    CommandInfo commandInfo = getCommandInfo(method);

                    Object command;
                    ServletRequestDataBinder binder;

                    if (!fromErrors) {
                        command = getCommandObject(request, commandClass, commandInfo);
                        binder = bind(request, command, commandInfo.validate);
                    } else {
                        command = getCommandObject(request, commandClass, commandInfo);
                        //se veio de erros nao fazer o bind novamente
                        binder = new ServletRequestDataBinder(command, getCommandName(command));
                    }

                    params.add(command);

                    if (binder.getBindingResult().hasErrors()) {
                        String inputAction = null;

                        if (input != null) {
                            inputAction = input.value();
                        } else {
                            logger.warn("No @Input specified for method " + method.getDeclaringClass().getName()
                                    + "." + method.getName() + ". Bind errors.");
                            new BindException(binder.getBindingResult()).printStackTrace();
                            if (commandInfo.session) {
                                //should reset the command
                                command = instantiateNewSessionCommand(request, commandClass,
                                        getSessionCommandName(commandClass, commandInfo));
                                inputAction = method.getName();
                            }
                        }
                        if (inputAction != null) {
                            ((DefaultWebRequestContext) request).setLastAction(inputAction);
                            Method handlerMethod = this.methodNameResolver.getHandlerMethod(inputAction);
                            ((DefaultWebRequestContext) request)
                                    .setBindException(new BindException(binder.getBindingResult()));
                            if (!handlerMethod.getName().equals(method.getName())) {
                                //o input deve ter o mesmo command do mtodo que declarou o input .. ento deixaremos o mtodo de input.. fazer o handling como o mesmo command
                                ((DefaultWebRequestContext) request)
                                        .setBindException(new BindException(binder.getBindingResult()));
                                method = handlerMethod;
                            }
                        } else {
                            binder.close();
                        }
                    }
                }
            } else {
                params.add(useCommand);
            }
            Object result = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
            return convertActionResultToModelAndView(method, result);
        } catch (NoSuchRequestHandlingMethodException e) {
            throw e;
        } catch (NextException e) {
            throw e;
        } catch (InvocationTargetException ex) {
            // the invoked method threw exception
            if (input == null) {
                OnErrors onErrors = getAnnotation(method, OnErrors.class);
                if (onErrors != null) {
                    fromErrors = true;
                    ((DefaultWebRequestContext) request).setLastAction(onErrors.value());
                    Method methodErrors = this.methodNameResolver.getHandlerMethod(onErrors.value());
                    request.addError(ex.getTargetException());
                    logger.error("Erro ao invocar mtodo " + method.getName() + " da classe "
                            + this.getClass().getName() + ". Redirecionando para onErrors: " + onErrors.value(),
                            ex.getTargetException());
                    method = methodErrors;
                    continue;
                } else {
                    // nao tem input e no tem onerrors.. deixar a exceo vazar para algum handler se for o caso
                }
            } else {
                //se tem input.. redirecionar para input
                boolean sameMethod = false;
                String inputName = input.value();

                Method handlerMethod = this.methodNameResolver.getHandlerMethod(inputName);
                sameMethod = handlerMethod.getName().equals(method.getName());

                //   se for o mesmo mtodo.. deixar a excecao vazar (se mandar para o mtodo denovo vai dar loop eterno porque a excecao vai ocorrer novamente
                if (!sameMethod) {
                    // se nao for o mesmo mtodo.. redirecionar
                    // poderiamos mandar um flag j que o mtodo a ser invocado tem o mesmo command .. nesse caso economizariamos o bind
                    // mas vamos deixar fazer o bind novamente porque j pode ter ocorrido algum processamento que alterou os valores do command 
                    method = handlerMethod;
                    request.addError(ex.getTargetException());
                    ((DefaultWebRequestContext) request).setLastAction(inputName);
                    logger.error(
                            "Erro ao invocar mtodo " + method.getName() + " da classe "
                                    + this.getClass().getName() + ". Redirecionando para input: " + inputName,
                            ex.getTargetException());
                    continue;
                }
            }
            return handleException(request, ex.getTargetException());
        } catch (IllegalArgumentException ex) {
            throw new NextException(
                    "No foi possvel invocar o mtodo. Se estiver utilizando o mtodo continueToAction verifique se o mtodo que pede o redirecionamento e o mtodo de destino possuem a mesma classe de command",
                    ex);
        } catch (Exception ex) {
            // The binding process threw an exception.
            return handleException(request, ex);
        }
    } while (true);
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Invoke the selected exception handler.
 * /*from   ww  w.  j a  va2  s .  c om*/
 * @param handler
 *            handler method to invoke
 */
private ModelAndView invokeExceptionHandler(Method handler, WebRequestContext request, Throwable ex)
        throws Exception {

    if (handler == null) {
        throw new ServletException("No handler for exception", ex);
    }

    // If we get here, we have a handler.
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking exception handler [" + handler + "] for exception [" + ex + "]");
    }
    try {
        Object result = handler.invoke(this.delegate, new Object[] { request, ex });
        ModelAndView mv = convertActionResultToModelAndView(handler, result);
        while (mv != null && mv.getViewName() != null && mv.getViewName().startsWith("action:")) {
            String actionName = mv.getViewName().substring("action:".length(), mv.getViewName().length());
            Method method = this.methodNameResolver.getHandlerMethod(actionName);
            mv = invokeNamedMethod(method, request, null);
        }
        return mv;
    } catch (InvocationTargetException ex2) {
        Throwable targetEx = ex2.getTargetException();
        if (targetEx instanceof Exception) {
            throw (Exception) targetEx;
        }
        if (targetEx instanceof Error) {
            throw (Error) targetEx;
        }
        // shouldn't happen
        throw new ServletException("Unknown Throwable type encountered", targetEx);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LdapRetryHandler.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    int attempts = attemptsNumber;
    Throwable e = null;//from www .  j  a v  a 2 s .co m
    while (attempts-- > 0) {
        try {
            return method.invoke(dirContext, args);
        } catch (InvocationTargetException sue) {
            e = sue.getTargetException();
            if (!(e instanceof ServiceUnavailableException)) {
                throw sue.getTargetException();
            } else {
                log.debug("Retrying ...", e);
            }
        }
    }
    throw e;
}

From source file:org.oclc.oai.server.OAIHandler.java

public static String getResult(Map attributes, HttpServletRequest request, HttpServletResponse response,
        Transformer serverTransformer, Map serverVerbs, Map extensionVerbs, String extensionPath)
        throws Throwable {
    try {//from w  ww.j a  va  2  s . c  om
        boolean isExtensionVerb = extensionPath.equals(request.getPathInfo());
        String verb = request.getParameter("verb");
        if (debug) {
            System.out.println("OAIHandler.g<etResult: verb=>" + verb + "<");
        }

        String result;
        Class verbClass;
        if (isExtensionVerb) {
            verbClass = (Class) extensionVerbs.get(verb);
        } else {
            verbClass = (Class) serverVerbs.get(verb);
        }
        if (verbClass == null) {
            verbClass = (Class) attributes.get("OAIHandler.missingVerbClass");
        }

        Method construct = verbClass.getMethod("construct", new Class[] { HashMap.class,
                HttpServletRequest.class, HttpServletResponse.class, Transformer.class });
        try {
            result = (String) construct.invoke(null, attributes, request, response, serverTransformer);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
        if (debug) {
            System.out.println(result);
        }
        return result;
    }

    catch (NoSuchMethodException e) {
        throw new OAIInternalServerError(e.getMessage());
    }

    catch (IllegalAccessException e) {
        throw new OAIInternalServerError(e.getMessage());
    }

}