Example usage for java.lang.reflect InvocationTargetException getCause

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

Introduction

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

Prototype

public Throwable getCause() 

Source Link

Document

Returns the cause of this exception (the thrown target exception, which may be null ).

Usage

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @return the {@link Object} result of invoking method with given signature.
 *//*from  w ww. ja v a 2  s .co  m*/
public static Object invokeMethod(Object object, String signature, Object... arguments) throws Exception {
    Assert.isNotNull(object);
    Assert.isNotNull(arguments);
    // prepare class/object
    Class<?> refClass = getRefClass(object);
    Object refObject = getRefObject(object);
    // prepare method
    Method method = getMethodBySignature(refClass, signature);
    Assert.isNotNull(method, "Can not find method " + signature + " in " + refClass);
    // do invoke
    try {
        return method.invoke(refObject, arguments);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        }
        throw e;
    }
}

From source file:tools.xor.util.ClassUtil.java

public static RuntimeException wrapRun(Exception e) {
    if (InvocationTargetException.class.isAssignableFrom(e.getClass())) {
        InvocationTargetException ite = (InvocationTargetException) e;
        Throwable cause = ite.getCause();
        if (cause != null && Exception.class.isAssignableFrom(cause.getClass()))
            e = (Exception) cause;
    }// w  w  w .ja v a 2 s  .  c  o  m

    if (RuntimeException.class.isAssignableFrom(e.getClass()))
        return (RuntimeException) e;
    else
        return new RuntimeException(e);
}

From source file:org.opencms.jlan.CmsJlanRepository.java

/**
 * Creates a dynamic proxy for a disk interface which logs the method calls and their results.<p>
 *
 * @param impl the disk interface for which a logging proxy should be created
 *
 * @return the dynamic proxy which logs methods calls
 *//*from w  ww. ja  v  a2s  . c  o  m*/
public static DiskInterface createLoggingProxy(final DiskInterface impl) {

    return (DiskInterface) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] { DiskInterface.class }, new InvocationHandler() {

                @SuppressWarnings("synthetic-access")
                public Object invoke(Object target, Method method, Object[] params) throws Throwable {

                    // Just to be on the safe side performance-wise, we only log the parameters/result
                    // if the info channel is enabled
                    if (LOG.isInfoEnabled()) {
                        List<String> paramStrings = new ArrayList<String>();
                        for (Object param : params) {
                            paramStrings.add("" + param);
                        }
                        String paramsAsString = CmsStringUtil.listAsString(paramStrings, ", ");
                        LOG.info("Call: " + method.getName() + " " + paramsAsString);
                    }
                    try {
                        Object result = method.invoke(impl, params);
                        if (LOG.isInfoEnabled()) {
                            LOG.info("Returned from " + method.getName() + ": " + result);
                        }
                        return result;
                    } catch (InvocationTargetException e) {
                        Throwable cause = e.getCause();
                        if ((cause != null) && (cause instanceof CmsSilentWrapperException)) {
                            // not really an error
                            LOG.info(cause.getCause().getLocalizedMessage(), cause.getCause());
                        } else {
                            LOG.error(e.getLocalizedMessage(), e);
                        }
                        throw e.getCause();
                    }
                }
            });
}

From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Decorates an ImageInputStream so the flush*() methods are ignored and have no effect.
 * The decoration is implemented using a dynamic proxy.
 * @param in the ImageInputStream//from   w  w w .  ja v  a 2  s  . c  om
 * @return the decorated ImageInputStream
 */
public static ImageInputStream ignoreFlushing(final ImageInputStream in) {
    return (ImageInputStream) Proxy.newProxyInstance(in.getClass().getClassLoader(),
            new Class[] { ImageInputStream.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodName = method.getName();
                    //Ignore calls to flush*()
                    if (!methodName.startsWith("flush")) {
                        try {
                            return method.invoke(in, args);
                        } catch (InvocationTargetException ite) {
                            throw ite.getCause();
                        }
                    } else {
                        return null;
                    }
                }
            });
}

From source file:com.taobao.itest.spring.context.SpringContextManager.java

public static void findAnnotatedMethodsAndInjectBeanByName(Class<? extends Annotation> annotationType,
        Object object, ApplicationContext applicationContext) {
    Set<Method> methods = getMethodsAnnotatedWith(object.getClass(), annotationType);
    for (Method method : methods) {
        try {/*ww w.  ja  va 2s.c  om*/
            if (!isSetter(method)) {
                invokeMethod(object, method, getBean(method.getParameterTypes()[0], applicationContext));
            } else {
                invokeMethod(object, method, getBean(getPropertyName(method), applicationContext));
            }

        } catch (InvocationTargetException e) {
            throw new RuntimeException(
                    "Unable to assign the Spring bean value to method annotated with @"
                            + annotationType.getSimpleName() + ". Method " + "has thrown an exception.",
                    e.getCause());
        }
    }
}

From source file:org.azyva.dragom.tool.DragomToolInvoker.java

/**
 * Invokes a tool./*www .  ja va2 s .co  m*/
 *
 * @param toolInvocationInfo ToolInvocationInfo.
 * @param arrayArgs Array of arguments.
 */
private static void invokeTool(ToolInvocationInfo toolInvocationInfo, String[] arrayArgs) {
    Method method;
    String[] arrayRealArgs;

    if (toolInvocationInfo.arrayFixedArgs != null) {
        arrayRealArgs = new String[toolInvocationInfo.arrayFixedArgs.length + arrayArgs.length];
        System.arraycopy(toolInvocationInfo.arrayFixedArgs, 0, arrayRealArgs, 0,
                toolInvocationInfo.arrayFixedArgs.length);
        System.arraycopy(arrayArgs, 0, arrayRealArgs, toolInvocationInfo.arrayFixedArgs.length,
                arrayArgs.length);
    } else {
        arrayRealArgs = arrayArgs;
    }

    try {
        method = toolInvocationInfo.classTool.getMethod("main", String[].class);
        method.invoke(null, new Object[] { arrayRealArgs });
    } catch (InvocationTargetException ite) {
        // This is to support integration tests which prevent System.exit() from
        // terminating the JVM by causing it to throw an ExitException instead.
        if (ite.getCause().getClass().getName().contains("ExitException")) {
            throw (RuntimeException) ite.getCause();
        }

        throw new RuntimeException(ite);
    } catch (NoSuchMethodException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.codesourcery.jasm16.ide.ui.utils.UIUtils.java

public static void invokeAndWait(Runnable r) {
    if (SwingUtilities.isEventDispatchThread()) {
        r.run();//from   ww  w  . jav a2 s .c o  m
    } else {
        try {
            SwingUtilities.invokeAndWait(r);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e.getCause());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.github.riking.dropcontrol.ItemStringInterpreter.java

public static BasicItemMatcher valueOf(String itemString) throws IllegalArgumentException {
    itemString = itemString.toUpperCase();
    if (itemString.equals("ANY")) {
        return new BasicItemMatcher(null, null, null);
    }/*from w  ww  .  ja  v  a  2s.  c  o  m*/
    String[] split = itemString.split(":");
    Validate.isTrue(split.length <= 2,
            "Unable to parse item string - too many colons (maximum 1). Please correct the format and reload the config. Input: "
                    + itemString);
    Material mat = getMaterial(split[0]);
    Validate.notNull(mat,
            "Unable to parse item string - unrecognized material. Please correct the format and reload the config. Input: "
                    + itemString);
    if (split.length == 1) {
        return new BasicItemMatcher(mat, null, null);
    }
    String dataString = split[1];
    short data;
    try {
        data = Short.parseShort(dataString);
        return new BasicItemMatcher(mat, data, null); // the datastring is not passed if it was just a number
    } catch (NumberFormatException ignored) {
    }
    if (materialData.containsKey(mat.getData())) {
        Class<? extends MaterialData> matClass = mat.getData();
        Class<? extends Enum> enumClass = materialData.get(mat.getData());
        Enum enumValue;
        try {
            enumValue = (Enum) enumClass.getMethod("valueOf", String.class).invoke(null, dataString);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("Unable to parse item string - " + dataString
                    + " is not a valid member of " + enumClass.getSimpleName(), e.getCause());
        } catch (Exception rethrow) {
            throw new RuntimeException("Unexpected exception when parsing item string", rethrow);
        }
        MaterialData matData;
        try {
            matData = matClass.getConstructor(enumClass).newInstance(enumValue);
        } catch (Exception rethrow) {
            throw new RuntimeException("Unexpected exception when parsing item string", rethrow);
        }
        data = (short) matData.getData();
        return new BasicItemMatcher(mat, data, dataString);
    }
    if (workarounds.containsKey(mat)) {
        StringInterpreter interp = workarounds.get(mat);
        data = interp.interpret(dataString);
        return new BasicItemMatcher(mat, data, dataString);
    }
    throw new IllegalArgumentException(
            "Unable to parse item string - I don't know how to parse a word-data for " + mat);
}

From source file:io.coala.factory.ClassUtil.java

/**
 * @param returnType the type of the stored property value
 * @param args the arguments for construction
 * @return the property value's class instantiated
 * @throws CoalaException if the property's value is no instance of
 *             valueClass/*from  w  w w  . jav a2s.c o  m*/
 */
@SuppressWarnings("unchecked")
public static <T> T instantiate(final Class<T> returnType, final Object... args) throws CoalaException {
    if (returnType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.create("returnType");

    final Class<?>[] argTypes = new Class<?>[args.length];
    for (int i = 0; i < args.length; i++)
        argTypes[i] = args[i] == null ? null : args[i].getClass();

    for (Constructor<?> constructor : returnType.getConstructors()) {
        final Class<?>[] paramTypes = constructor.getParameterTypes();
        if (paramTypes.length != args.length) // different argument count,
        // try next constructor
        {
            continue;
        }

        boolean match = true;
        for (int i = 0; match && i < paramTypes.length; i++) {
            if (args[i] == null && !paramTypes[i].isPrimitive())
                argTypes[i] = paramTypes[i];
            else if (!isAssignableFrom(paramTypes[i], argTypes[i]))
                match = false;
        }

        if (!match) // no matching parameter types, try next constructor
        {
            continue;
        }

        try {
            return (T) constructor.newInstance(args);
        } catch (final InvocationTargetException exception) {
            // exception caused by the constructor itself, pass cause thru
            throw exception.getCause() instanceof CoalaException ? (CoalaException) exception.getCause()
                    : CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType,
                            Arrays.asList(argTypes));
        } catch (final Exception exception) {
            throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType, Arrays.asList(argTypes));
        }
    }
    throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(returnType, Arrays.asList(argTypes));
}

From source file:com.cenrise.test.azkaban.Utils.java

/**
 * Get the root cause of the Exception//  w  ww  . j  a  v  a  2s. co  m
 *
 * @param e The Exception
 * @return The root cause of the Exception
 */
private static RuntimeException getCause(final InvocationTargetException e) {
    final Throwable cause = e.getCause();
    if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
    } else {
        throw new IllegalStateException(e.getCause());
    }
}