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:MethodTroubleReturns.java

public static void main(String... args) {
    try {/*  w  w  w . j a  v  a 2s .  c om*/
        MethodTroubleReturns mtr = new MethodTroubleReturns();
        Class<?> c = mtr.getClass();
        Method m = c.getDeclaredMethod("drinkMe", int.class);
        m.invoke(mtr, -1);

        // production code should handle these exceptions more gracefully
    } catch (InvocationTargetException x) {
        Throwable cause = x.getCause();
        System.err.format("drinkMe() failed: %s%n", cause.getMessage());
    } catch (Exception x) {
        x.printStackTrace();
    }
}

From source file:org.jetbrains.webdemo.executors.JavaExecutor.java

public static void main(String[] args) {
    PrintStream defaultOutputStream = System.out;
    try {//from w w  w . j  a va  2  s.c  o  m
        System.setOut(new PrintStream(standardOutputStream));
        System.setErr(new PrintStream(errorOutputStream));

        RunOutput outputObj = new RunOutput();
        String className;
        if (args.length > 0) {
            className = args[0];
            try {
                Method mainMethod = Class.forName(className).getMethod("main", String[].class);
                mainMethod.invoke(null, (Object) Arrays.copyOfRange(args, 1, args.length));
            } catch (InvocationTargetException e) {
                outputObj.exception = e.getCause();
            } catch (NoSuchMethodException e) {
                System.err.println("No main method found in project.");
            } catch (ClassNotFoundException e) {
                System.err.println("No main method found in project.");
            }
        } else {
            System.err.println("No main method found in project.");
        }

        System.out.flush();
        System.err.flush();
        System.setOut(defaultOutputStream);
        outputObj.text = outputStream.toString().replaceAll("</errStream><errStream>", "")
                .replaceAll("</outStream><outStream>", "");
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Throwable.class, new ThrowableSerializer());
        objectMapper.registerModule(module);
        System.out.print(objectMapper.writeValueAsString(outputObj));
    } catch (Throwable e) {
        System.setOut(defaultOutputStream);
        System.out.println("{\"text\":\"<errStream>" + e.getClass().getName() + ": " + e.getMessage());
        System.out.print("</errStream>\"}");
    }

}

From source file:Deet.java

public static void main(String... args) {
    if (args.length != 4) {
        err.format("Usage: java Deet <classname> <langauge> <country> <variant>%n");
        return;/*  w ww. j  a v a2  s . c  o  m*/
    }

    try {
        Class<?> c = Class.forName(args[0]);
        Object t = c.newInstance();

        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
            String mname = m.getName();
            if (!mname.startsWith("test") || (m.getGenericReturnType() != boolean.class)) {
                continue;
            }
            Type[] pType = m.getGenericParameterTypes();
            if ((pType.length != 1) || Locale.class.isAssignableFrom(pType[0].getClass())) {
                continue;
            }

            out.format("invoking %s()%n", mname);
            try {
                m.setAccessible(true);
                Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
                out.format("%s() returned %b%n", mname, (Boolean) o);

                // Handle any exceptions thrown by method to be invoked.
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
                err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
            }
        }

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (InstantiationException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:org.apache.commons.net.examples.Main.java

/**
 * Helper application for example classes.
 * Lists available classes, and provides shorthand invocation.
 * For example:<br>/*from  www  .j a  v  a2s.co m*/
 * <code>java -jar commons-net-examples-m.n.jar FTPClientExample -l host user password</code>
 *
 * @param args the first argument is used to name the class; remaining arguments
 * are passed to the target class.
 * @throws Throwable if an error occurs
 */
public static void main(String[] args) throws Throwable {
    final Properties fp = new Properties();
    final InputStream ras = Main.class.getResourceAsStream("examples.properties");
    if (ras != null) {
        fp.load(ras);
    } else {
        System.err.println("[Cannot find examples.properties file, so aliases cannot be used]");
    }
    if (args.length == 0) {
        if (Thread.currentThread().getStackTrace().length > 2) { // called by Maven
            System.out.println("Usage: mvn -q exec:java  -Dexec.arguments=<alias or"
                    + " exampleClass>,<exampleClass parameters> (comma-separated, no spaces)");
            System.out.println("Or   : mvn -q exec:java  -Dexec.args=\"<alias"
                    + " or exampleClass> <exampleClass parameters>\" (space separated)");
        } else {
            if (fromJar()) {
                System.out.println(
                        "Usage: java -jar commons-net-examples-m.n.jar <alias or exampleClass> <exampleClass parameters>");
            } else {
                System.out.println(
                        "Usage: java -cp target/classes examples/Main <alias or exampleClass> <exampleClass parameters>");
            }
        }
        @SuppressWarnings("unchecked") // property names are Strings
        List<String> l = (List<String>) Collections.list(fp.propertyNames());
        if (l.isEmpty()) {
            return;
        }
        Collections.sort(l);
        System.out.println("\nAliases and their classes:");
        for (String s : l) {
            System.out.printf("%-25s %s%n", s, fp.getProperty(s));
        }
        return;
    }

    String shortName = args[0];
    String fullName = fp.getProperty(shortName);
    if (fullName == null) {
        fullName = shortName;
    }
    fullName = fullName.replace('/', '.');
    try {
        Class<?> clazz = Class.forName(fullName);
        Method m = clazz.getDeclaredMethod("main", new Class[] { args.getClass() });
        String[] args2 = new String[args.length - 1];
        System.arraycopy(args, 1, args2, 0, args2.length);
        try {
            m.invoke(null, (Object) args2);
        } catch (InvocationTargetException ite) {
            Throwable cause = ite.getCause();
            if (cause != null) {
                throw cause;
            } else {
                throw ite;
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    }
}

From source file:Main.java

/**
 * Safe handling for the {@link SwingUtilities#invokeAndWait(Runnable)}
 * method. It is unsafe to call invokeAndWait on the dispatch thread due to
 * deadlocks. This method simply runs the given {@link Runnable} if this is
 * called in the dispatch thread./*from  w ww.j  av a  2 s.c o  m*/
 * 
 * @param r
 *            - the runnable to run
 * @throws Exception
 *             - any exceptions propagate, the possible
 *             {@link InvocationTargetException} is unwrapped.
 */
public static void runOnDispatch(Runnable r) throws Exception {
    if (SwingUtilities.isEventDispatchThread()) {
        r.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(r);
        } catch (InvocationTargetException iie) {
            if (iie.getCause() instanceof Exception) {
                throw (Exception) iie.getCause();
            } else {
                throw iie;
            }
        }
    }
}

From source file:Main.java

@SuppressWarnings("unused")
public static void unregisterMediaButtonEventReceiverCompat(AudioManager audioManager, ComponentName receiver) {
    if (sMethodUnregisterMediaButtonEventReceiver == null)
        return;/*w w  w . j av a 2 s  . c  o  m*/

    try {
        sMethodUnregisterMediaButtonEventReceiver.invoke(audioManager, receiver);
    } catch (InvocationTargetException e) {
        // Unpack original exception when possible
        Throwable cause = e.getCause();
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            // Unexpected checked exception; wrap and re-throw
            throw new RuntimeException(e);
        }
    } catch (IllegalAccessException e) {
        Log.e(TAG, "IllegalAccessException invoking unregisterMediaButtonEventReceiver.");
        e.printStackTrace();
    }
}

From source file:org.mule.module.magento.api.MagentoClientAdaptor.java

@SuppressWarnings("unchecked")
public static <T> T adapt(final Class<T> receptorClass, final T receptor) {
    Validate.isTrue(receptorClass.isInterface());
    return (T) Proxy.newProxyInstance(MagentoClientAdaptor.class.getClassLoader(),
            new Class[] { receptorClass }, new InvocationHandler() {
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws Throwable {
                    try {
                        if (log.isDebugEnabled()) {
                            log.debug("Entering {} with args {}", method.getName(), args);
                        }//www .java2  s .co  m
                        final Object ret = method.invoke(receptor, args);
                        if (log.isDebugEnabled()) {
                            log.debug("Returning from {} with value {}", method.getName(), ret);
                        }
                        return ret;
                    } catch (final InvocationTargetException e) {
                        if (e.getCause() instanceof AxisFault) {
                            if (log.isWarnEnabled()) {
                                log.warn("An exception was thrown while invoking {}: {}", method.getName(),
                                        e.getCause());
                            }
                            throw toMagentoException((AxisFault) e.getCause());
                        }
                        throw e;
                    }
                }

            });
}

From source file:Main.java

public static void runMain(Object main, String[] args, String defCommand) throws Exception {
    if (args.length > 0) {
        String command = args[0];
        Method[] methods = main.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method.getName().equals(command)) {
                String[] remaining = new String[args.length - 1];
                System.arraycopy(args, 1, remaining, 0, remaining.length);
                try {
                    method.invoke(main, bindParameters(method, remaining));
                } catch (InvocationTargetException e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof IllegalArgumentException) {
                        System.err.println("Syntax error: " + cause.getMessage());
                    } else if (cause instanceof Exception) {
                        throw (Exception) cause;
                    } else {
                        throw e;
                    }//from   w w  w.  j  a v  a2s. c  o  m
                }
                return;
            }
        }
    }
    if (defCommand != null) {
        runMain(main, new String[] { defCommand }, null);
    }
}

From source file:com.github.wnameless.factorextractor.FactorExtractor.java

/**
 * Returns a Map{@literal <String, Object>} which is extracted from annotated
 * methods of input objects./* www .ja v  a2 s .co  m*/
 * 
 * @param objects
 *          an array of objects
 * @return a Map{@literal <String, Object>}
 */
public static Map<String, Object> extract(Object... objects) {
    for (Object o : objects) {
        if (o == null)
            throw new NullPointerException("Null object is not allowed");
    }

    Map<String, Object> factors = new HashMap<String, Object>();
    for (Object o : objects) {
        Class<?> testClass = o.getClass();
        for (Method m : testClass.getMethods()) {
            Factor factor = AnnotationUtils.findAnnotation(m, Factor.class);
            if (factor != null) {
                try {
                    factors.put(factor.value(), m.invoke(o));
                } catch (InvocationTargetException wrappedExc) {
                    Throwable exc = wrappedExc.getCause();
                    Logger.getLogger(FactorExtractor.class.getName()).log(Level.SEVERE, m + " failed: " + exc,
                            wrappedExc);
                } catch (Exception exc) {
                    Logger.getLogger(FactorExtractor.class.getName()).log(Level.SEVERE,
                            "INVALID @Factor: " + m + exc, exc);
                }
            }
        }
    }

    return factors;
}

From source file:Main.java

/**
 * Invoke the specified <code>Callable</code> on the AWT event dispatching thread now and return
 * the result.<br>/*from  ww  w  .j a  v a 2s .c o m*/
 * The returned result can be <code>null</code> when a {@link Throwable} exception happen.<br>
 * Use this method carefully as it may lead to dead lock.
 * 
 * @throws InterruptedException
 *         if the current thread was interrupted while waiting
 * @throws Exception
 *         if the computation threw an exception
 */
public static <T> T invokeNow(Callable<T> callable) throws InterruptedException, Exception {
    if (SwingUtilities.isEventDispatchThread())
        return callable.call();

    final FutureTask<T> task = new FutureTask<T>(callable);

    try {
        EventQueue.invokeAndWait(task);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof Exception)
            throw (Exception) e.getCause();

        // not an exception --> handle it
        //IcyExceptionHandler.showErrorMessage(e, true);
        return null;
    }

    try {
        return task.get();
    } catch (ExecutionException e) {
        if (e.getCause() instanceof Exception)
            throw (Exception) e.getCause();

        // not an exception --> handle it
        //IcyExceptionHandler.showErrorMessage(e, true);
        return null;
    }
}