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:password.pwm.util.Helper.java

public static <E extends Enum<E>> E readEnumFromString(Class<E> enumClass, E defaultValue, String input) {
    if (input == null) {
        return defaultValue;
    }/*from   ww  w .  ja  v a 2 s.c  o m*/

    try {
        Method valueOfMethod = enumClass.getMethod("valueOf", String.class);
        try {
            Object result = valueOfMethod.invoke(null, input);
            return (E) result;
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    } catch (IllegalArgumentException e) {
        /* noop */
        //LOGGER.trace("input=" + input + " does not exist in enumClass=" + enumClass.getSimpleName());
    } catch (Throwable e) {
        LOGGER.warn(
                "unexpected error translating input=" + input + " to enumClass=" + enumClass.getSimpleName());
    }

    return defaultValue;
}

From source file:azkaban.common.utils.Utils.java

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

From source file:org.eclipse.wb.tests.designer.core.util.ast.BindingsTest.java

/**
 * Checks that method with given name and arguments fails.
 *///from   w  w  w. ja  v a  2  s  .  c  o m
private static void assert_methodFails(Object actualObject, String methodName, Object... args)
        throws Exception {
    Method[] allMethods = actualObject.getClass().getMethods();
    for (Method method : allMethods) {
        method.setAccessible(true);
        if (method.getName().equals(methodName)) {
            try {
                method.invoke(actualObject, args);
                fail("Method " + method + " should throw exception.");
            } catch (InvocationTargetException e) {
                assertInstanceOf(IllegalArgumentException.class, e.getCause());
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.fs.HFileSystem.java

private static ClientProtocol createReorderingProxy(final ClientProtocol cp, final ReorderBlocks lrb,
        final Configuration conf) {
    return (ClientProtocol) Proxy.newProxyInstance(cp.getClass().getClassLoader(),
            new Class[] { ClientProtocol.class, Closeable.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        if ((args == null || args.length == 0) && "close".equals(method.getName())) {
                            RPC.stopProxy(cp);
                            return null;
                        } else {
                            Object res = method.invoke(cp, args);
                            if (res != null && args != null && args.length == 3
                                    && "getBlockLocations".equals(method.getName())
                                    && res instanceof LocatedBlocks && args[0] instanceof String
                                    && args[0] != null) {
                                lrb.reorderBlocks(conf, (LocatedBlocks) res, (String) args[0]);
                            }//from   w  ww.  ja v  a2  s. c o  m
                            return res;
                        }
                    } catch (InvocationTargetException ite) {
                        // We will have this for all the exception, checked on not, sent
                        //  by any layer, including the functional exception
                        Throwable cause = ite.getCause();
                        if (cause == null) {
                            throw new RuntimeException("Proxy invocation failed and getCause is null", ite);
                        }
                        if (cause instanceof UndeclaredThrowableException) {
                            Throwable causeCause = cause.getCause();
                            if (causeCause == null) {
                                throw new RuntimeException("UndeclaredThrowableException had null cause!");
                            }
                            cause = cause.getCause();
                        }
                        throw cause;
                    }
                }
            });
}

From source file:com.splicemachine.mrio.api.SpliceTableMapReduceUtil.java

/**
 * If org.apache.hadoop.util.JarFinder is available (0.23+ hadoop),
 * finds the Jar for a class or creates it if it doesn't exist. If
 * the class is in a directory in the classpath, it creates a Jar
 * on the fly with the contents of the directory and returns the path
 * to that Jar. If a Jar is created, it is created in
 * the system temporary directory./*from   w  w w. j a v  a 2 s.  c o m*/
 *
 * Otherwise, returns an existing jar that contains a class of the
 * same name.
 *
 * @param my_class the class to find.
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findOrCreateJar(Class my_class) throws IOException {
    try {
        Class<?> jarFinder = Class.forName("org.apache.hadoop.util.JarFinder");
        // hadoop-0.23 has a JarFinder class that will create the jar
        // if it doesn't exist.  Note that this is needed to run the mapreduce
        // unit tests post-0.23, because mapreduce v2 requires the relevant jars
        // to be in the mr cluster to do output, split, etc.  At unit test time,
        // the hbase jars do not exist, so we need to create some.  Note that we
        // can safely fall back to findContainingJars for pre-0.23 mapreduce.
        Method m = jarFinder.getMethod("getJar", Class.class);
        return (String) m.invoke(null, my_class);
    } catch (InvocationTargetException ite) {
        // function was properly called, but threw it's own exception
        throw new IOException(ite.getCause());
    } catch (Exception e) {
        // ignore all other exceptions. related to reflection failure
    }

    LOG.debug("New JarFinder: org.apache.hadoop.util.JarFinder.getJar "
            + "not available.  Using old findContainingJar");
    return findContainingJar(my_class);
}

From source file:hermes.impl.LoaderSupport.java

public static void populateBean(Object bean, PropertySetConfig propertySet)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
    if (propertySet != null) {
        Set appliedProperties = new HashSet();

        for (Iterator iter = propertySet.getProperty().iterator(); iter.hasNext();) {
            PropertyConfig propertyConfig = (PropertyConfig) iter.next();

            if (appliedProperties.contains(propertyConfig.getName())) {
                iter.remove();/*from ww  w . j  av  a  2  s.  c om*/
            } else {
                try {

                    BeanUtils.setProperty(bean, propertyConfig.getName(),
                            TextUtils.replaceClasspathVariables(propertyConfig.getValue()));

                    appliedProperties.add(propertyConfig.getName());

                    log.debug("set " + bean.getClass().getName() + " " + propertyConfig.getName() + "="
                            + TextUtils.replaceClasspathVariables(propertyConfig.getValue()));
                } catch (InvocationTargetException t) {
                    log.error(
                            "unable to set property name=" + propertyConfig.getName() + " value="
                                    + propertyConfig.getValue() + " on object of class "
                                    + bean.getClass().getName() + ": " + t.getCause().getMessage(),
                            t.getCause());
                }
            }
        }
    }
}

From source file:com.jk.util.JKObjectUtil.java

/**
 * Call method.//  w  ww. j av  a  2 s .  com
 *
 * @param obj
 *            the obj
 * @param methodName
 *            the method name
 * @param includePrivateMehtods
 *            the include private mehtods
 * @param args
 *            the args
 * @throws InvocationTargetException
 *             the invocation target exception
 */
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void callMethod(final Object obj, final String methodName, final boolean includePrivateMehtods,
        final Object... args) throws InvocationTargetException {
    final Class[] intArgsClass = initParamsClasses(args);
    try {
        Class<?> current = obj.getClass();
        Method method = null;
        while (current != Object.class) {
            try {
                method = current.getDeclaredMethod(methodName, intArgsClass);
                break;
            } catch (final NoSuchMethodException ex) {
                current = current.getSuperclass();
            }
        }
        if (method == null) {
            throw new NoSuchMethodException("Mehtod is not found in " + current);
        }
        method.setAccessible(true);
        method.invoke(obj, args);
    } catch (final InvocationTargetException e) {
        throw new InvocationTargetException(e.getCause());
    } catch (final Exception e) {
        throw new InvocationTargetException(e);
    }
}

From source file:org.apache.atlas.TestUtils.java

/**
 * Adds a proxy wrapper around the specified MetadataService that automatically
 * resets the request context before every call.
 *
 * @param delegate//www  . ja v a2  s .  c  o m
 * @return
 */
public static MetadataService addSessionCleanupWrapper(final MetadataService delegate) {

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

                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    try {
                        resetRequestContext();
                        Object result = method.invoke(delegate, args);

                        return result;
                    } catch (InvocationTargetException e) {
                        e.getCause().printStackTrace();
                        throw e.getCause();
                    } catch (Throwable t) {
                        t.printStackTrace();
                        throw t;
                    }
                }

            });
}

From source file:org.apache.atlas.TestUtils.java

/**
 * Adds a proxy wrapper around the specified MetadataRepository that automatically
 * resets the request context before every call and either commits or rolls
 * back the graph transaction after every call.
 *
 * @param delegate//w  w w . j a  v a  2s.c o  m
 * @return
 */
public static MetadataRepository addTransactionWrapper(final MetadataRepository delegate) {
    return (MetadataRepository) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] { MetadataRepository.class }, new InvocationHandler() {

                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    boolean useTransaction = GraphBackedMetadataRepository.class
                            .getMethod(method.getName(), method.getParameterTypes())
                            .isAnnotationPresent(GraphTransaction.class);
                    try {
                        resetRequestContext();
                        Object result = method.invoke(delegate, args);
                        if (useTransaction) {
                            System.out.println("Committing changes");
                            getGraph().commit();
                            System.out.println("Commit succeeded.");
                        }
                        return result;
                    } catch (InvocationTargetException e) {
                        e.getCause().printStackTrace();
                        if (useTransaction) {
                            System.out.println("Rolling back changes due to exception.");
                            getGraph().rollback();
                        }
                        throw e.getCause();
                    } catch (Throwable t) {
                        t.printStackTrace();
                        if (useTransaction) {
                            System.out.println("Rolling back changes due to exception.");
                            getGraph().rollback();
                        }
                        throw t;
                    }
                }

            });
}

From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Try to instantiate a protocol buffer of the given message class
 * from the given input stream./*from w  w w .j a  va 2s  .c  om*/
 *
 * @param protoClass the class of the generated protocol buffer
 * @param dataIn the input stream to read from
 * @return the instantiated Message instance
 * @throws IOException if an IO problem occurs
 */
private static Message tryInstantiateProtobuf(Class<?> protoClass, DataInput dataIn) throws IOException {

    try {
        if (dataIn instanceof InputStream) {
            // We can use the built-in parseDelimitedFrom and not have to re-copy
            // the data
            Method parseMethod = getStaticProtobufMethod(protoClass, "parseDelimitedFrom", InputStream.class);
            return (Message) parseMethod.invoke(null, (InputStream) dataIn);
        } else {
            // Have to read it into a buffer first, since protobuf doesn't deal
            // with the DataInput interface directly.

            // Read the size delimiter that writeDelimitedTo writes
            int size = ProtoUtil.readRawVarint32(dataIn);
            if (size < 0) {
                throw new IOException("Invalid size: " + size);
            }

            byte[] data = new byte[size];
            dataIn.readFully(data);
            Method parseMethod = getStaticProtobufMethod(protoClass, "parseFrom", byte[].class);
            return (Message) parseMethod.invoke(null, data);
        }
    } catch (InvocationTargetException e) {

        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        } else {
            throw new IOException(e.getCause());
        }
    } catch (IllegalAccessException iae) {
        throw new AssertionError("Could not access parse method in " + protoClass);
    }
}