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.openqa.grid.internal.BaseRemoteProxy.java

/**
 * Takes a registration request and return the RemoteProxy associated to it. It can be any class
 * extending RemoteProxy.//from   www.  ja v a 2s .co m
 *
 * @param request  The request
 * @param registry The registry to use
 * @return a new instance built from the request.
 */
@SuppressWarnings("unchecked")
public static <T extends RemoteProxy> T getNewInstance(RegistrationRequest request, Registry registry) {
    try {
        String proxyClass = request.getRemoteProxyClass();
        if (proxyClass == null) {
            log.fine("No proxy class. Using default");
            proxyClass = BaseRemoteProxy.class.getCanonicalName();
        }
        Class<?> clazz = Class.forName(proxyClass);
        log.fine("Using class " + clazz.getName());
        Object[] args = new Object[] { request, registry };
        Class<?>[] argsClass = new Class[] { RegistrationRequest.class, Registry.class };
        Constructor<?> c = clazz.getConstructor(argsClass);
        Object proxy = c.newInstance(args);
        if (proxy instanceof RemoteProxy) {
            ((RemoteProxy) proxy).setupTimeoutListener();
            return (T) proxy;
        } else {
            throw new InvalidParameterException("Error: " + proxy.getClass() + " isn't a remote proxy");
        }

    } catch (InvocationTargetException e) {
        log.log(Level.SEVERE, e.getTargetException().getMessage(), e.getTargetException());
        throw new InvalidParameterException("Error: " + e.getTargetException().getMessage());

    } catch (Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new InvalidParameterException("Error: " + e.getMessage());
    }
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns the index'th element of the bean's property represented by
 * the supplied property descriptor./*from  w  ww.j  a  v a  2 s.  co m*/
 * @param bean to read
 * @param propertyDescriptor indicating what to read
 * @param index int
 * @return Object
 */
public static Object getValue(Object bean, PropertyDescriptor propertyDescriptor, int index) {
    if (propertyDescriptor instanceof IndexedPropertyDescriptor) {
        try {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) propertyDescriptor;
            Method method = ipd.getIndexedReadMethod();
            if (method != null) {
                return method.invoke(bean, new Object[] { new Integer(index) });
            }
        } catch (InvocationTargetException ex) {
            Throwable t = ex.getTargetException();
            if (t instanceof IndexOutOfBoundsException) {
                return null;
            }
            throw new JXPathException("Cannot access property: " + propertyDescriptor.getName(), t);
        } catch (Throwable ex) {
            throw new JXPathException("Cannot access property: " + propertyDescriptor.getName(), ex);
        }
    }

    // We will fall through if there is no indexed read

    return getValue(getValue(bean, propertyDescriptor), index);
}

From source file:net.iaeste.iws.core.transformers.CSVTransformer.java

/**
 * <p>Reflective invocation of the Object Setter methods. To enforce the
 * Setter Validation checks on the values. Required to avoid that illegal
 * values is being processed.</p>//w  ww.j  a va 2 s  .c om
 *
 * <p>The method will also catch any thrown IllegalArgument Exceptions and
 * add the result to the error map given.</p>
 *
 * @param errors   Validation Error Map
 * @param obj      The Object to invoke the Setter on
 * @param field    The Object field to be set
 * @param argument Argument to the Setter
 * @throws IWSException If a Reflection Error occurred.
 */
private static <O extends Verifiable> void invokeMethodOnObject(final Map<String, String> errors, final O obj,
        final OfferFields field, final Object argument) {
    if ((field.getMethod() != null) && field.useField(OfferFields.Type.DOMESTIC)) {
        try {
            final Method implementation = obj.getClass().getMethod(field.getMethod(), field.getArgumentClass());
            implementation.invoke(obj, argument);
        } catch (InvocationTargetException e) {
            // The Reflection Framework is wrapping all caught Exceptions
            // inside the Invocation Target Exception. Since our setters
            // is throwing an IllegalArgument Exception, we have to see if
            // this occurs.
            if (e.getTargetException() instanceof IllegalArgumentException) {
                LOG.debug("Setter {} Invocation Error: {}", field.getMethod(), e.getTargetException(),
                        e.getTargetException());
                errors.put(field.getField(), e.getTargetException().getMessage());
            } else {
                LOG.debug("Setter {} Invocation Error: {}", field.getMethod(), e.getMessage(), e);
                errors.put(field.getField(), e.getMessage());
            }
        } catch (SecurityException | NoSuchMethodException | IllegalArgumentException
                | IllegalAccessException e) {
            // The Reflection framework forces a check for the
            // NoSuchMethodException. Additionally, if the Java Security
            // Manager is used, we may also see a SecurityException.
            //   Invoking the method may also result in either an
            // IllegalArgumentException or IllegalAccessException.
            LOG.error(e.getMessage(), e);
            throw new IWSException(IWSErrors.FATAL, e.getMessage(), e);
        }
    } else {
        LOG.warn("Cannot set field {}, as there is no method associated with it.", field.getField());
    }
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Handle the given invocation target exception. Should only be called if no
 * checked exception is expected to be thrown by the target method.
 * <p>/*from w w  w  .  j  ava2 s  . c om*/
 * Throws the underlying RuntimeException or Error in case of such a root
 * cause. Throws an IllegalStateException else.
 * 
 * @param ex the invocation target exception to handle
 */
public static void handleInvocationTargetException(final InvocationTargetException ex) {
    rethrowRuntimeException(ex.getTargetException());
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Handle the given invocation target exception. Should only be called if no
 * checked exception is expected to be thrown by the target method.
 * <p>Throws the underlying RuntimeException or Error in case of such a root
 * cause. Throws an IllegalStateException else.
 * @param ex the invocation target exception to handle
 *///from   ww w  .j  a  v a2s  . c o  m
public static void handleInvocationTargetException(InvocationTargetException ex) {
    rethrowRuntimeException(ex.getTargetException());
}

From source file:com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils.java

/**
 * Not really a generic method for printing random object graphs. But it
 * works for events and decisions.// w  ww .jav  a 2s.  c o m
 */
private static String prettyPrintObject(Object object, String methodToSkip,
        boolean skipNullsAndEmptyCollections, String indentation, boolean skipLevel) {
    StringBuffer result = new StringBuffer();
    if (object == null) {
        return "null";
    }
    Class<? extends Object> clz = object.getClass();
    if (Number.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (Boolean.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (clz.equals(String.class)) {
        return (String) object;
    }
    if (clz.equals(Date.class)) {
        return String.valueOf(object);
    }
    if (Map.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (Collection.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (!skipLevel) {
        result.append(" {");
    }
    Method[] eventMethods = object.getClass().getMethods();
    boolean first = true;
    for (Method method : eventMethods) {
        String name = method.getName();
        if (!name.startsWith("get")) {
            continue;
        }
        if (name.equals(methodToSkip) || name.equals("getClass")) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        Object value;
        try {
            value = method.invoke(object, (Object[]) null);
            if (value != null && value.getClass().equals(String.class) && name.equals("getDetails")) {
                value = printDetails((String) value);
            }
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e.getTargetException());
        } catch (RuntimeException e) {
            throw (RuntimeException) e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (skipNullsAndEmptyCollections) {
            if (value == null) {
                continue;
            }
            if (value instanceof Map && ((Map<?, ?>) value).isEmpty()) {
                continue;
            }
            if (value instanceof Collection && ((Collection<?>) value).isEmpty()) {
                continue;
            }
        }
        if (!skipLevel) {
            if (first) {
                first = false;
            } else {
                result.append(";");
            }
            result.append("\n");
            result.append(indentation);
            result.append("    ");
            result.append(name.substring(3));
            result.append(" = ");
            result.append(prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections,
                    indentation + "    ", false));
        } else {
            result.append(
                    prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation, false));
        }
    }
    if (!skipLevel) {
        result.append("\n");
        result.append(indentation);
        result.append("}");
    }
    return result.toString();
}

From source file:biz.bokhorst.xprivacy.Util.java

public static void bug(XHook hook, Throwable ex) {
    if (ex instanceof InvocationTargetException) {
        InvocationTargetException exex = (InvocationTargetException) ex;
        if (exex.getTargetException() != null)
            ex = exex.getTargetException();
    }//from w  w w  .  j av a2s  .c  o m

    int priority;
    if (ex instanceof ActivityShare.AbortException)
        priority = Log.WARN;
    else if (ex instanceof ActivityShare.ServerException)
        priority = Log.WARN;
    else if (ex instanceof ConnectTimeoutException)
        priority = Log.WARN;
    else if (ex instanceof FileNotFoundException)
        priority = Log.WARN;
    else if (ex instanceof HttpHostConnectException)
        priority = Log.WARN;
    else if (ex instanceof NameNotFoundException)
        priority = Log.WARN;
    else if (ex instanceof NoClassDefFoundError)
        priority = Log.WARN;
    else if (ex instanceof OutOfMemoryError)
        priority = Log.WARN;
    else if (ex instanceof RuntimeException)
        priority = Log.WARN;
    else if (ex instanceof SecurityException)
        priority = Log.WARN;
    else if (ex instanceof SocketTimeoutException)
        priority = Log.WARN;
    else if (ex instanceof SSLPeerUnverifiedException)
        priority = Log.WARN;
    else if (ex instanceof StackOverflowError)
        priority = Log.WARN;
    else if (ex instanceof TransactionTooLargeException)
        priority = Log.WARN;
    else if (ex instanceof UnknownHostException)
        priority = Log.WARN;
    else if (ex instanceof UnsatisfiedLinkError)
        priority = Log.WARN;
    else
        priority = Log.ERROR;

    boolean xprivacy = false;
    for (StackTraceElement frame : ex.getStackTrace())
        if (frame.getClassName() != null && frame.getClassName().startsWith("biz.bokhorst.xprivacy")) {
            xprivacy = true;
            break;
        }
    if (!xprivacy)
        priority = Log.WARN;

    log(hook, priority, ex.toString() + " uid=" + Process.myUid() + "\n" + Log.getStackTraceString(ex));
}

From source file:demo.config.PropertyConverter.java

/**
 * Tries to convert the specified object into a number object. This method
 * is used by the conversion methods for number types. Note that the return
 * value is not in always of the specified target class, but only if a new
 * object has to be created.//from   w  w  w . j a  v  a  2s  .c o m
 * 
 * @param value
 *            the value to be converted (must not be <b>null</b>)
 * @param targetClass
 *            the target class of the conversion (must be derived from
 *            {@code java.lang.Number})
 * @return the converted number
 * @throws ConversionException
 *             if the object cannot be converted
 */
static Number toNumber(Object value, Class<?> targetClass) throws ConversionException {
    if (value instanceof Number) {
        return (Number) value;
    } else {
        String str = value.toString();
        if (str.startsWith(HEX_PREFIX)) {
            try {
                return new BigInteger(str.substring(HEX_PREFIX.length()), HEX_RADIX);
            } catch (NumberFormatException nex) {
                throw new ConversionException(
                        "Could not convert " + str + " to " + targetClass.getName() + "! Invalid hex number.",
                        nex);
            }
        }

        if (str.startsWith(BIN_PREFIX)) {
            try {
                return new BigInteger(str.substring(BIN_PREFIX.length()), BIN_RADIX);
            } catch (NumberFormatException nex) {
                throw new ConversionException("Could not convert " + str + " to " + targetClass.getName()
                        + "! Invalid binary number.", nex);
            }
        }

        try {
            Constructor<?> constr = targetClass.getConstructor(CONSTR_ARGS);
            return (Number) constr.newInstance(new Object[] { str });
        } catch (InvocationTargetException itex) {
            throw new ConversionException("Could not convert " + str + " to " + targetClass.getName(),
                    itex.getTargetException());
        } catch (Exception ex) {
            // Treat all possible exceptions the same way
            throw new ConversionException(
                    "Conversion error when trying to convert " + str + " to " + targetClass.getName(), ex);
        }
    }
}

From source file:ch.sourcepond.maven.release.providers.BaseProvider.java

@SuppressWarnings("unchecked")
@Override/*  w ww . ja va  2  s  .  co  m*/
public T get() {
    return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { getDelegateType() },
            new InvocationHandler() {

                @Override
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws Throwable {
                    notNull(getDelegate(), "Delegate object is not available!");
                    try {
                        return method.invoke(getDelegate(), args);
                    } catch (final InvocationTargetException e) {
                        throw e.getTargetException();
                    }
                }
            });
}

From source file:org.bytesoft.bytetcc.supports.spring.SpringContainerContextImpl.java

public void confirm(CompensableInvocation invocation) throws RuntimeException {
    Method method = invocation.getMethod();
    Object[] args = invocation.getArgs();
    String beanName = invocation.getConfirmableKey();
    Object instance = this.applicationContext.getBean(beanName);
    try {/*from w w w  . j a  v  a2 s .com*/
        method.invoke(instance, args);
    } catch (InvocationTargetException itex) {
        throw new RuntimeException(itex.getTargetException());
    } catch (RuntimeException rex) {
        throw rex;
    } catch (Throwable throwable) {
        throw new RuntimeException(throwable);
    }
}