List of usage examples for java.lang.reflect InvocationTargetException getTargetException
public Throwable getTargetException()
From source file:org.sonatype.nexus.extdirect.internal.ExtDirectServlet.java
@Override protected Dispatcher createDispatcher(final Class<? extends Dispatcher> cls) { return new SsmDispatcher() { @Override/*ww w. j ava2s.com*/ protected Object createInvokeInstanceForMethodWithDefaultConstructor(final RegisteredMethod method) throws Exception { if (log.isDebugEnabled()) { log.debug("Creating instance of action class '{}' mapped to '{}", method.getActionClass().getName(), method.getActionName()); } @SuppressWarnings("unchecked") Iterable<BeanEntry<Annotation, Object>> actionInstance = beanLocator .locate(Key.get((Class) method.getActionClass())); return actionInstance.iterator().next().getValue(); } @Override protected Object invokeMethod(final RegisteredMethod method, final Object actionInstance, final Object[] parameters) throws Exception { if (log.isDebugEnabled()) { log.debug("Invoking action method: {}, java-method: {}", method.getFullName(), method.getFullJavaMethodName()); } Response response = null; EventDataBuilder builder = null; EventRecorder recorder = recorderProvider.get(); // Maybe record analytics events if (recorder != null && recorder.isEnabled()) { builder = new EventDataBuilder("Ext.Direct").set("type", method.getType().name()) .set("name", method.getName()).set("action", method.getActionName()); } MDC.put(getClass().getName(), method.getFullName()); try { response = asResponse(super.invokeMethod(method, actionInstance, parameters)); } catch (InvocationTargetException e) { response = handleException(method, e.getTargetException()); } catch (Throwable e) { response = handleException(method, e); } finally { // Record analytics event if (recorder != null && builder != null) { if (response != null) { builder.set("success", response.isSuccess()); } recorder.record(builder.build()); } MDC.remove(getClass().getName()); } return response; } private Response handleException(final RegisteredMethod method, final Throwable e) { // debug logging for sanity (without stacktrace for suppressed exception) log.debug("Failed to invoke action method: {}, java-method: {}, exception message: {}", method.getFullName(), method.getFullJavaMethodName(), e.getMessage(), isSuppressedException(e) ? null : e); // handle validation message responses which have contents if (e instanceof ConstraintViolationException) { ConstraintViolationException cause = (ConstraintViolationException) e; Set<ConstraintViolation<?>> violations = cause.getConstraintViolations(); if (violations != null && !violations.isEmpty()) { return asResponse(invalid(cause)); } } // exception logging for all non-suppressed exceptions if (!isSuppressedException(e)) { log.error("Failed to invoke action method: {}, java-method: {}", method.getFullName(), method.getFullJavaMethodName(), e); } return asResponse(error(e)); } private boolean isSuppressedException(final Throwable e) { return SUPPRESSED_EXCEPTIONS.stream().anyMatch(ex -> ex.isInstance(e)); } private Response asResponse(final Object result) { Response response; if (result == null) { response = success(); } else { if (result instanceof Response) { response = (Response) result; } else { response = success(result); } } return response; } }; }
From source file:org.springframework.amqp.rabbit.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 Exception if thrown by Rabbit API methods * @see #getListenerMethodName/*from ww w . j a va 2 s. co m*/ * @see #buildListenerArguments */ protected Object invokeListenerMethod(String methodName, Object[] arguments) throws Exception { 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 IOException) { throw new AmqpIOException((IOException) targetEx); } else { throw new ListenerExecutionFailedException("Listener method '" + methodName + "' threw exception", targetEx); } } catch (Throwable ex) { ArrayList<String> arrayClass = new ArrayList<String>(); if (arguments != null) { for (int i = 0; i < arguments.length; i++) { arrayClass.add(arguments[i].getClass().toString()); } } throw new ListenerExecutionFailedException("Failed to invoke target method '" + methodName + "' with argument type = [" + StringUtils.collectionToCommaDelimitedString(arrayClass) + "], value = [" + ObjectUtils.nullSafeToString(arguments) + "]", ex); } }
From source file:org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.java
private void invokeHandlerMethod(MethodInvocation mi, Throwable ex, Method method) throws Throwable { Object[] handlerArgs;//from ww w .j a va 2 s . c o m if (method.getParameterCount() == 1) { handlerArgs = new Object[] { ex }; } else { handlerArgs = new Object[] { mi.getMethod(), mi.getArguments(), mi.getThis(), ex }; } try { method.invoke(this.throwsAdvice, handlerArgs); } catch (InvocationTargetException targetEx) { throw targetEx.getTargetException(); } }
From source file:org.springframework.aop.support.AopUtils.java
/** * Invoke the target directly via reflection. * @param target the target object//from www . j a v a 2 s.c o m * @param method the method to invoke * @param args the arguments for the method * @throws Throwable if thrown by the target method * @throws org.aopalliance.aop.AspectException if encountering a reflection error */ public static Object invokeJoinpointUsingReflection(Object target, Method method, Object[] args) throws Throwable { // Use reflection to invoke the method. try { if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) { method.setAccessible(true); } return method.invoke(target, args); } catch (InvocationTargetException ex) { // Invoked method threw a checked exception. // We must rethrow it. The client won't see the interceptor. throw ex.getTargetException(); } catch (IllegalArgumentException ex) { throw new AspectException("AOP configuration seems to be invalid: tried calling method [" + method + "] on target [" + target + "]: " + ex); } catch (IllegalAccessException ex) { throw new AspectException("Couldn't access method [" + method + "]: " + ex); } }
From source file:org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.java
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); try {/*from w w w . j av a2 s. c om*/ metadata.invokeInitMethods(bean, beanName); } catch (InvocationTargetException ex) { throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Failed to invoke init method", ex); } return bean; }
From source file:org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.java
@Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); try {//from ww w . j ava 2 s . c om metadata.invokeDestroyMethods(bean, beanName); } catch (InvocationTargetException ex) { String msg = "Invocation of destroy method failed on bean with name '" + beanName + "'"; if (logger.isDebugEnabled()) { logger.warn(msg, ex.getTargetException()); } else { logger.warn(msg + ": " + ex.getTargetException()); } } catch (Throwable ex) { logger.error("Failed to invoke destroy method on bean with name '" + beanName + "'", ex); } }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Invoke the specified custom init method on the given bean. * Called by invokeInitMethods./*from w w w. ja v a 2 s . co m*/ * <p>Can be overridden in subclasses for custom resolution of init * methods with arguments. * @see #invokeInitMethods */ protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { String initMethodName = mbd.getInitMethodName(); Assert.state(initMethodName != null, "No init method set"); final Method initMethod = (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); if (initMethod == null) { if (mbd.isEnforceInitMethod()) { throw new BeanDefinitionValidationException("Couldn't find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { if (logger.isTraceEnabled()) { logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } } if (logger.isTraceEnabled()) { logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(initMethod); return null; }); try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> initMethod.invoke(bean), getAccessControlContext()); } catch (PrivilegedActionException pae) { InvocationTargetException ex = (InvocationTargetException) pae.getException(); throw ex.getTargetException(); } } else { try { ReflectionUtils.makeAccessible(initMethod); initMethod.invoke(bean); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }
From source file:org.springframework.beans.factory.support.AbstractBeanFactory.java
/** * Invoke the specified custom destroy method on the given bean. * <p>This implementation invokes a no-arg method if found, else checking * for a method with a single boolean argument (passing in "true", * assuming a "force" parameter), else logging an error. * <p>Can be overridden in subclasses for custom resolution of destroy * methods with arguments.//from w w w .j ava2s. c om * @param beanName the bean has in the factory. Used for debug output. * @param bean new bean instance we may need to notify of destruction * @param destroyMethodName the name of the custom destroy method * @param enforceDestroyMethod indicates whether the defined destroy method needs to exist */ protected void invokeCustomDestroyMethod(String beanName, Object bean, String destroyMethodName, boolean enforceDestroyMethod) { Method destroyMethod = BeanUtils.findDeclaredMethodWithMinimalParameters(bean.getClass(), destroyMethodName); if (destroyMethod == null) { if (enforceDestroyMethod) { logger.error("Couldn't find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'"); } } else { Class[] paramTypes = destroyMethod.getParameterTypes(); if (paramTypes.length > 1) { logger.error("Method '" + destroyMethodName + "' of bean '" + beanName + "' has more than one parameter - not supported as destroy method"); } else if (paramTypes.length == 1 && !paramTypes[0].equals(boolean.class)) { logger.error("Method '" + destroyMethodName + "' of bean '" + beanName + "' has a non-boolean parameter - not supported as destroy method"); } else { Object[] args = new Object[paramTypes.length]; if (paramTypes.length == 1) { args[0] = Boolean.TRUE; } if (!Modifier.isPublic(destroyMethod.getModifiers())) { destroyMethod.setAccessible(true); } try { destroyMethod.invoke(bean, args); } catch (InvocationTargetException ex) { logger.error("Couldn't invoke destroy method '" + destroyMethodName + "' of bean with name '" + beanName + "'", ex.getTargetException()); } catch (Throwable ex) { logger.error("Couldn't invoke destroy method '" + destroyMethodName + "' of bean with name '" + beanName + "'", ex); } } } }
From source file:org.springframework.beans.factory.support.DisposableBeanAdapter.java
/** * Invoke the specified custom destroy method on the given bean. * <p>This implementation invokes a no-arg method if found, else checking * for a method with a single boolean argument (passing in "true", * assuming a "force" parameter), else logging an error. *//*w w w . ja v a 2s . co m*/ private void invokeCustomDestroyMethod(final Method destroyMethod) { Class<?>[] paramTypes = destroyMethod.getParameterTypes(); final Object[] args = new Object[paramTypes.length]; if (paramTypes.length == 1) { args[0] = Boolean.TRUE; } if (logger.isDebugEnabled()) { logger.debug("Invoking destroy method '" + this.destroyMethodName + "' on bean with name '" + this.beanName + "'"); } try { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(destroyMethod); return null; }); try { AccessController.doPrivileged( (PrivilegedExceptionAction<Object>) () -> destroyMethod.invoke(bean, args), acc); } catch (PrivilegedActionException pax) { throw (InvocationTargetException) pax.getException(); } } else { ReflectionUtils.makeAccessible(destroyMethod); destroyMethod.invoke(bean, args); } } catch (InvocationTargetException ex) { String msg = "Invocation of destroy method '" + this.destroyMethodName + "' failed on bean with name '" + this.beanName + "'"; if (logger.isDebugEnabled()) { logger.warn(msg, ex.getTargetException()); } else { logger.warn(msg + ": " + ex.getTargetException()); } } catch (Throwable ex) { logger.error("Couldn't invoke destroy method '" + this.destroyMethodName + "' on bean with name '" + this.beanName + "'", ex); } }
From source file:org.springframework.binding.method.MethodInvoker.java
/** * Invoke the method on the bean provided. Argument values are pulled from the provided argument source. * @param signature the definition of the method to invoke, including the method name and the method argument types * @param bean the bean to invoke/*from www . j av a 2 s . co m*/ * @param argumentSource the source for method arguments * @return the invoked method's return value * @throws MethodInvocationException the method could not be invoked */ public Object invoke(MethodSignature signature, Object bean, Object argumentSource) throws MethodInvocationException { Parameters parameters = signature.getParameters(); Object[] arguments = new Object[parameters.size()]; for (int i = 0; i < parameters.size(); i++) { Parameter parameter = parameters.getParameter(i); Object argument = parameter.evaluateArgument(argumentSource); arguments[i] = applyTypeConversion(argument, parameter.getType()); } Class<?>[] parameterTypes = parameters.getTypesArray(); for (int i = 0; i < parameterTypes.length; i++) { if (parameterTypes[i] == null) { Object argument = arguments[i]; if (argument != null) { parameterTypes[i] = argument.getClass(); } } } MethodKey key = new MethodKey(bean.getClass(), signature.getMethodName(), parameterTypes); try { Method method = methodCache.get(key); if (logger.isDebugEnabled()) { logger.debug("Invoking method with signature [" + key + "] with arguments " + StylerUtils.style(arguments) + " on bean [" + bean + "]"); } Object returnValue = method.invoke(bean, arguments); if (logger.isDebugEnabled()) { logger.debug("Invoked method with signature [" + key + "] returned value [" + returnValue + "]"); } return returnValue; } catch (InvocationTargetException e) { throw new MethodInvocationException(signature, arguments, e.getTargetException()); } catch (Exception e) { throw new MethodInvocationException(signature, arguments, e); } }