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:com.ery.ertc.estorm.util.Methods.java

public static <T> Object call(Class<T> clazz, T instance, String methodName, Class[] types, Object[] args)
        throws Exception {
    try {//from   www . j a v  a 2  s .  com
        Method m = clazz.getMethod(methodName, types);
        return m.invoke(instance, args);
    } catch (IllegalArgumentException arge) {
        LOG.fatal("Constructed invalid call. class=" + clazz.getName() + " method=" + methodName + " types="
                + Classes.stringify(types), arge);
        throw arge;
    } catch (NoSuchMethodException nsme) {
        throw new IllegalArgumentException("Can't find method " + methodName + " in " + clazz.getName() + "!",
                nsme);
    } catch (InvocationTargetException ite) {
        // unwrap the underlying exception and rethrow
        if (ite.getTargetException() != null) {
            if (ite.getTargetException() instanceof Exception) {
                throw (Exception) ite.getTargetException();
            } else if (ite.getTargetException() instanceof Error) {
                throw (Error) ite.getTargetException();
            }
        }
        throw new UndeclaredThrowableException(ite,
                "Unknown exception invoking " + clazz.getName() + "." + methodName + "()");
    } catch (IllegalAccessException iae) {
        throw new IllegalArgumentException("Denied access calling " + clazz.getName() + "." + methodName + "()",
                iae);
    } catch (SecurityException se) {
        LOG.fatal("SecurityException calling method. class=" + clazz.getName() + " method=" + methodName
                + " types=" + Classes.stringify(types), se);
        throw se;
    }
}

From source file:ReflectionExecutor.java

/**
 * Execution of reflection with {@link ReflectionAction}.
 * //from  w  w w  .j  av a 2 s  .c  o  m
 * @param <T>
 * @param action
 * @return
 */
public static <T> T doSafeAction(final ReflectionAction<T> action) {
    final SecurityManager securityManager = System.getSecurityManager();
    if (securityManager == null) {
        try {
            return action.run();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {

            @Override
            public T run() throws Exception {
                return action.run();
            }

        });
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (InvocationTargetException.class.isInstance(cause)) {
            InvocationTargetException e1 = (InvocationTargetException) cause;
            throw new Exception(e1.getTargetException());
        }
        throw new Exception(cause);
    }
}

From source file:de.beyondjava.angularFaces.components.puiSync.JSONUtilities.java

@SuppressWarnings("unchecked")
public static Object readObjectFromJSONString(String json, Class beanType) {
    if (null != jackson) {
        try {// w  w  w  .  j a v  a  2 s.co m
            Method method = jackson.getClass().getMethod("readValue", String.class, Class.class);
            if (null != method) {
                return method.invoke(jackson, json, beanType);
            }
        } catch (InvocationTargetException e) {
            Throwable rootException = e.getTargetException();
            System.out.println("Jackson couldn't read the value: " + rootException);

        } catch (ReflectiveOperationException e) {
            System.out.println("Jackson couldn't read the value: " + e);
        }
    }
    if (null != gson) {
        try {
            Method method = gson.getClass().getMethod("fromJson", String.class, Class.class);
            if (null != method) {
                return method.invoke(gson, json, beanType);
            }
        } catch (ReflectiveOperationException e) {
        }
    }
    return null;
}

From source file:com.microsoft.tfs.client.common.ui.framework.diagnostics.InternalSupportUtils.java

public static boolean doExport(final Shell shell, final DataProviderCollection dataProviderCollection,
        final File outputFile) {
    final ExportRunnable runnable = new ExportRunnable(dataProviderCollection, outputFile);

    Throwable error = null;//from  w w w  . j a  v a  2s .  co m

    final DeferredProgressMonitorDialogContext context = new DeferredProgressMonitorDialogContext(shell, 500);

    try {
        context.run(true, true, runnable);
        error = runnable.getError();
    } catch (final InvocationTargetException e) {
        error = e.getTargetException();
    } catch (final InterruptedException e) {
        return false;
    }

    if (runnable.wasCancelled()) {
        return false;
    }

    if (error != null) {
        log.error(error);

        final String messageFormat = Messages.getString("InternalSupportUtils.ExportErrorStatusFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, error.getMessage());

        final Status status = new Status(IStatus.ERROR, TFSCommonUIClientPlugin.PLUGIN_ID, IStatus.OK, message,
                error);

        ErrorDialog.openError(shell, Messages.getString("InternalSupportUtils.ErrorDialogTitle"), //$NON-NLS-1$
                error.getMessage(), status);
        return false;
    }

    return true;
}

From source file:com.github.yongchristophertang.engine.java.LoggerProxyHelper.java

static Object addLogger(Logger logger, Method method, Object[] args, Object client) throws Throwable {
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(client, args);
    }/* www  . j  ava2s.c o  m*/

    String formatter = "\n\tAPI: " + method.getName() + "\n\n";
    formatter += "\tInput:\n";
    for (int i = 0; i < method.getParameterCount(); i++) {
        formatter += "\t\t" + method.getParameters()[i].getName() + " ("
                + method.getParameters()[i].getType().getSimpleName() + "): ";
        if (args[i] == null) {
            formatter += "NULL";
        } else if (args[i] instanceof Iterable) {
            int cnt = 0;
            Iterator iter = ((Iterable) args[i]).iterator();
            while (iter.hasNext()) {
                formatter += "\n\t\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), false);
            }
        } else {
            formatter += toPrinterString(args[i], false);
        }
        formatter += "\n";
    }

    long bf = System.nanoTime();
    Object result;
    try {
        result = method.invoke(client, args);
    } catch (InvocationTargetException e) {
        formatter += "\n\tException: \n\t\t" + e.getTargetException();
        formatter += "\n=======================================================================\n";
        logger.info(formatter);
        throw e.getTargetException();
    }
    long af = System.nanoTime();

    formatter += "\n\tResponse Time(ms): " + (af - bf) / 1000000 + "\n\n\tOutput:\n";

    if (result == null) {
        formatter += "\t\tNULL\n";
    } else if (result instanceof Iterable) {
        Iterator iter = ((Iterable) result).iterator();
        int cnt = 0;
        while (iter.hasNext()) {
            formatter += "\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), true) + "\n";
        }
        if (cnt == 0) {
            formatter += "\t\tEmpty Collection []\n";
        }
    } else {
        formatter += "\t\t" + toPrinterString(result, true) + "\n";
    }

    formatter += "=======================================================================\n";
    logger.info(formatter);
    return result;
}

From source file:eu.unifiedviews.plugins.extractor.filesdownload.ReflectionSocketFactory.java

/**
 * This method attempts to execute Socket method available since Java 1.4
 * using reflection. If the methods are not available or could not be executed <tt>null</tt> is returned
 * //  w  w w  .  jav a  2  s .  c o  m
 * @param socketfactoryName
 *            name of the socket factory class
 * @param host
 *            the host name/IP
 * @param port
 *            the port on the host
 * @param localAddress
 *            the local host name/IP to bind the socket to
 * @param localPort
 *            the port on the local machine
 * @param timeout
 *            the timeout value to be used in milliseconds. If the socket cannot be
 *            completed within the given time limit, it will be abandoned
 * @return a connected Socket
 * @throws IOException
 *             if an I/O error occurs while creating the socket
 * @throws UnknownHostException
 *             if the IP address of the host cannot be
 *             determined
 * @throws ConnectTimeoutException
 *             if socket cannot be connected within the
 *             given time limit
 */
public static Socket createSocket(final Object socketfactory, final String host, final int port,
        final InetAddress localAddress, final int localPort, int timeout)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (REFLECTION_FAILED) {
        //This is known to have failed before. Do not try it again
        return null;
    }
    // This code uses reflection to essentially do the following:
    //
    //  SocketFactory socketFactory = Class.forName(socketfactoryName).getDefault();
    //  Socket socket = socketFactory.createSocket();
    //  SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    //  SocketAddress remoteaddr = new InetSocketAddress(host, port);
    //  socket.bind(localaddr);
    //  socket.connect(remoteaddr, timeout);
    //  return socket;
    try {
        Class socketfactoryClass = socketfactory.getClass();//Class.forName(socketfactoryName);
        Method method = socketfactoryClass.getMethod("getDefault", new Class[] {});
        //            Object socketfactory = method.invoke(null, 
        //                new Object[] {});
        method = socketfactoryClass.getMethod("createSocket", new Class[] {});
        Socket socket = (Socket) method.invoke(socketfactory, new Object[] {});

        if (INETSOCKETADDRESS_CONSTRUCTOR == null) {
            Class addressClass = Class.forName("java.net.InetSocketAddress");
            INETSOCKETADDRESS_CONSTRUCTOR = addressClass
                    .getConstructor(new Class[] { InetAddress.class, Integer.TYPE });
        }

        Object remoteaddr = INETSOCKETADDRESS_CONSTRUCTOR
                .newInstance(new Object[] { InetAddress.getByName(host), new Integer(port) });

        Object localaddr = INETSOCKETADDRESS_CONSTRUCTOR
                .newInstance(new Object[] { localAddress, new Integer(localPort) });

        if (SOCKETCONNECT_METHOD == null) {
            SOCKETCONNECT_METHOD = Socket.class.getMethod("connect",
                    new Class[] { Class.forName("java.net.SocketAddress"), Integer.TYPE });
        }

        if (SOCKETBIND_METHOD == null) {
            SOCKETBIND_METHOD = Socket.class.getMethod("bind",
                    new Class[] { Class.forName("java.net.SocketAddress") });
        }
        SOCKETBIND_METHOD.invoke(socket, new Object[] { localaddr });
        SOCKETCONNECT_METHOD.invoke(socket, new Object[] { remoteaddr, new Integer(timeout) });
        return socket;
    } catch (InvocationTargetException e) {
        Throwable cause = e.getTargetException();
        if (SOCKETTIMEOUTEXCEPTION_CLASS == null) {
            try {
                SOCKETTIMEOUTEXCEPTION_CLASS = Class.forName("java.net.SocketTimeoutException");
            } catch (ClassNotFoundException ex) {
                // At this point this should never happen. Really.
                REFLECTION_FAILED = true;
                return null;
            }
        }
        if (SOCKETTIMEOUTEXCEPTION_CLASS.isInstance(cause)) {
            throw new ConnectTimeoutException(
                    "The host did not accept the connection within timeout of " + timeout + " ms", cause);
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        return null;
    } catch (Exception e) {
        REFLECTION_FAILED = true;
        return null;
    }
}

From source file:com.dalabs.droop.util.password.CredentialProviderHelper.java

public static String resolveAlias(Configuration conf, String alias) throws IOException {
    LOG.debug("Resolving alias with credential provider path set to " + conf.get(CREDENTIAL_PROVIDER_PATH));
    try {//ww  w  .  j a v a2  s. c o m
        char[] cred = (char[]) methGetPassword.invoke(conf, new Object[] { alias });
        if (cred == null) {
            throw new IOException("The provided alias cannot be resolved");
        }
        String pass = new String(cred);
        return pass;
    } catch (InvocationTargetException ite) {
        throw new RuntimeException("Error resolving password " + " from the credential providers ",
                ite.getTargetException());
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Error invoking the credential provider method", iae);
    }
}

From source file:com.dalabs.droop.util.password.CredentialProviderHelper.java

/**
 * Test utility to create an entry/*from w w w .ja v  a 2 s  .com*/
 */
public static void createCredentialEntry(Configuration conf,

        String alias, String credential) throws IOException {

    if (!isProviderAvailable()) {
        throw new RuntimeException("CredentialProvider facility not available " + "in the hadoop environment");
    }

    try {
        List<?> result = (List<?>) methGetProviders.invoke(null, new Object[] { conf });
        Object provider = result.get(0);
        LOG.debug("Using credential provider " + provider);

        methCreateCredEntry.invoke(provider, new Object[] { alias, credential.toCharArray() });
        methFlush.invoke(provider, new Object[] {});
    } catch (InvocationTargetException ite) {
        throw new RuntimeException("Error creating credential entry " + " using the credentail provider",
                ite.getTargetException());
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Error accessing the credential create method", iae);
    }
}

From source file:com.stimulus.struts.BeanAction.java

public final static String callMethod(ActionForm form, String methodName) throws Exception {
    Method method = null;/*from  ww  w.  j  ava  2 s .c  om*/
    String forward = null;
    try {
        method = form.getClass().getMethod(methodName, null);
        forward = (String) method.invoke(form, null);
    } catch (InvocationTargetException ite) {
        throw new BeanActionException("failed to execute method. Cause:" + ite.getTargetException(), ite,
                logger);
    }
    return forward;
}

From source file:com.javaetmoi.core.spring.vfs.Vfs2Utils.java

protected static Object invokeVfsMethod(Method method, Object target, Object... args) throws IOException {
    try {//from   w  w w  . ja  va 2  s . com
        return method.invoke(target, args);
    } catch (InvocationTargetException ex) {
        Throwable targetEx = ex.getTargetException();
        if (targetEx instanceof IOException) {
            throw (IOException) targetEx;
        }
        ReflectionUtils.handleInvocationTargetException(ex);
    } catch (Exception ex) {
        ReflectionUtils.handleReflectionException(ex);
    }

    throw new IllegalStateException("Invalid code path reached");
}