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.metasys.cmis.stages.Stage.java

public void execute(Tag root) throws OperationFailedException {
    List<Tag> children = root.getChildren();

    for (Tag c : children) {
        if (!methodMappings.containsKey(c.getName())) {
            logger.error("Invalid action specified: " + c.getName());
            continue;
        }/* ww  w  . j av a 2  s  .c  o m*/
        boolean failed = false;
        String errorMessage = "";
        try {
            MethodUtils.invokeMethod(this, methodMappings.get(c.getName()), c);
        } catch (NoSuchMethodException noMethod) {
            logger.error("Error:", noMethod);
            failed = true;
        } catch (IllegalAccessException illegalMethod) {
            logger.error("Error:", illegalMethod);
            failed = true;
        } catch (InvocationTargetException invocationMethod) {
            logger.error("Error:", invocationMethod);
            Throwable cause = invocationMethod.getCause();
            if (cause != null && cause instanceof CmisBaseException) {
                errorMessage = ExceptionParser.parseException(connector,
                        ((CmisBaseException) cause).getErrorContent());
                if (errorMessage == null)
                    errorMessage = cause.getLocalizedMessage();
            } else
                errorMessage = cause.getMessage();
            failed = true;
        }

        String exceptionMessage = "Failed during operation '" + c.getName() + "' with error: " + errorMessage;
        if (CMISInBatch.stopOnFail && failed)
            throw new OperationFailedException(exceptionMessage);
        else if (failed)
            logger.error(exceptionMessage);
    }
}

From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java

public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener,
        final Plugin plugin) {
    Validate.notNull(plugin, "Plugin can not be null");
    Validate.notNull(listener, "Listener can not be null");

    boolean useTimings = Loader.getEventBus().useTimings();
    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>();
    Set<Method> methods;
    try {//  w ww.  j  a v  a2 s . c  o m
        Method[] publicMethods = listener.getClass().getMethods();
        methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE);
        for (Method method : publicMethods) {
            methods.add(method);
        }
        for (Method method : listener.getClass().getDeclaredMethods()) {
            methods.add(method);
        }
    } catch (NoClassDefFoundError e) {
        PluginManager.getLogger()
                .severe("Plugin " + plugin.getDescription().getFullName()
                        + " has failed to register events for " + listener.getClass() + " because "
                        + e.getMessage() + " does not exist.");
        return ret;
    }

    for (final Method method : methods) {
        final EventHandler eh = method.getAnnotation(EventHandler.class);
        if (eh == null)
            continue;
        final Class<?> checkClass;
        if (method.getParameterTypes().length != 1
                || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
            PluginManager.getLogger()
                    .severe(plugin.getDescription().getFullName()
                            + " attempted to register an invalid EventHandler method signature \""
                            + method.toGenericString() + "\" in " + listener.getClass());
            continue;
        }
        final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
        method.setAccessible(true);
        Set<RegisteredListener> eventSet = ret.get(eventClass);
        if (eventSet == null) {
            eventSet = new HashSet<RegisteredListener>();
            ret.put(eventClass, eventSet);
        }

        for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
            // This loop checks for extending deprecated events
            if (clazz.getAnnotation(Deprecated.class) != null) {
                Warning warning = clazz.getAnnotation(Warning.class);
                WarningState warningState = Loader.getInstance().getWarningState();
                if (!warningState.printFor(warning)) {
                    break;
                }
                PluginManager.getLogger().log(Level.WARNING, String.format(
                        "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated."
                                + " \"%s\"; please notify the authors %s.",
                        plugin.getDescription().getFullName(), clazz.getName(), method.toGenericString(),
                        (warning != null && warning.reason().length() != 0) ? warning.reason()
                                : "Server performance will be affected",
                        Arrays.toString(plugin.getDescription().getAuthors().toArray())),
                        warningState == WarningState.ON ? new AuthorNagException(null) : null);
                break;
            }
        }

        EventExecutor executor = new EventExecutor() {
            public void execute(Listener listener, Event event) throws EventException {
                try {
                    if (!eventClass.isAssignableFrom(event.getClass())) {
                        return;
                    }
                    method.invoke(listener, event);
                } catch (InvocationTargetException ex) {
                    throw new EventException(ex.getCause());
                } catch (Throwable t) {
                    throw new EventException(t);
                }
            }
        };
        if (useTimings) {
            eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin,
                    eh.ignoreCancelled()));
        } else {
            eventSet.add(
                    new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
        }
    }
    return ret;
}

From source file:org.Microsoft.Telemetry.IntermediateHistoryStore.java

@Override
protected void serviceStop() throws Exception {

    Method m;//from   www.  j ava 2 s  .c o m
    try {
        m = originalStorage.getClass().getDeclaredMethod("serviceStop", null);
        m.setAccessible(true);
        m.invoke(originalStorage, null);

    } catch (NoSuchMethodException noSuchMethodException) {

        LOG.error(PATTERN_LOG_ERROR + "no Such Method Exception :", noSuchMethodException);

    } catch (SecurityException securityException) {

        LOG.error(PATTERN_LOG_ERROR + "Security Exception :", securityException);

    } catch (IllegalAccessException illegalAccessException) {

        LOG.error(PATTERN_LOG_ERROR + "Illegal Access Exception :", illegalAccessException);

    } catch (IllegalArgumentException illegalArgumentException) {

        LOG.error(PATTERN_LOG_ERROR + "Illegal Argument Exception :", illegalArgumentException);

    } catch (InvocationTargetException invocationTargetException) {

        Throwable cause = invocationTargetException.getCause();
        LOG.error(PATTERN_LOG_ERROR + "Invocation Target Exception failed because of:" + cause.getMessage(),
                invocationTargetException);

    }
}

From source file:org.Microsoft.Telemetry.IntermediateHistoryStore.java

@Override
protected void serviceInit(Configuration conf) throws Exception {

    try {/*from   ww  w.jav a2 s  . c  o m*/

        //Method m = originalStorage.getClass().getDeclaredMethod("serviceInit", Configuration.class);
        Method m = originalStorage.getClass().getMethod("serviceInit", Configuration.class);
        m.setAccessible(true);
        m.invoke(originalStorage, (Object) conf);

    } catch (NoSuchMethodException noSuchMethodException) {

        LOG.error(PATTERN_LOG_ERROR + "no Such Method Exception :", noSuchMethodException);
        noSuchMethodException.printStackTrace();

    } catch (SecurityException securityException) {

        LOG.error(PATTERN_LOG_ERROR + "Security Exception :", securityException);
        securityException.printStackTrace();

    } catch (IllegalAccessException illegalAccessException) {

        LOG.error(PATTERN_LOG_ERROR + "Illegal Access Exception :", illegalAccessException);
        illegalAccessException.printStackTrace();

    } catch (IllegalArgumentException illegalArgumentException) {

        LOG.error(PATTERN_LOG_ERROR + "Illegal Argument Exception :", illegalArgumentException);
        illegalArgumentException.printStackTrace();

    } catch (InvocationTargetException invocationTargetException) {

        Throwable cause = invocationTargetException.getCause();
        LOG.error(PATTERN_LOG_ERROR + "Invocation Target Exception failed because of:" + cause.getMessage(),
                invocationTargetException);
        invocationTargetException.printStackTrace();

    }
}

From source file:com.puppycrawl.tools.checkstyle.MainTest.java

@Test
public void testCreateListenerIllegalStateException() throws Exception {
    Method method = Main.class.getDeclaredMethod("createListener", String.class, String.class);
    method.setAccessible(true);//ww  w  .  java2 s  .  co m
    try {
        method.invoke(null, "myformat", null);
        fail();
    } catch (InvocationTargetException e) {
        assertTrue(e.getCause() instanceof IllegalStateException);
        assertTrue(e.getCause().getMessage().startsWith("Invalid output format. Found"));
    }
}

From source file:org.eclipse.gemini.blueprint.test.AbstractOsgiTests.java

/**
 * Delegates the test execution to the OSGi copy.
 * /*from   ww  w . j a  va2  s  .  co  m*/
 * @throws Exception
 */
private void invokeOSGiTestExecution() throws Exception {
    Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
    try {
        serviceTrigger.invoke(service, null);
    } catch (InvocationTargetException ex) {
        Throwable th = ex.getCause();
        if (th instanceof Exception)
            throw ((Exception) th);
        else
            throw ((Error) th);
    }
}

From source file:com.puppycrawl.tools.checkstyle.MainTest.java

@Test
public void testCreateListenerWithLocationIllegalStateException() throws Exception {
    Method method = Main.class.getDeclaredMethod("createListener", String.class, String.class);
    method.setAccessible(true);//from   w  ww.jav a  2  s . c o  m
    String outDir = "myfolder123";
    try {
        method.invoke(null, "myformat", outDir);
        fail();
    } catch (InvocationTargetException e) {
        assertTrue(e.getCause() instanceof IllegalStateException);
        assertTrue(e.getCause().getMessage().startsWith("Invalid output format. Found"));
    } finally {
        // method creates output folder
        FileUtils.deleteQuietly(new File(outDir));
    }
}

From source file:com.puppycrawl.tools.checkstyle.MainTest.java

@Test
public void testLoadPropertiesIOException() throws Exception {
    Class<?>[] param = new Class<?>[1];
    param[0] = File.class;
    Method method = Main.class.getDeclaredMethod("loadProperties", param);
    method.setAccessible(true);/*w  w  w  .  jav  a2s  . c  o  m*/
    try {
        if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
            // https://support.microsoft.com/en-us/kb/177506 but this only for NTFS
            // WindowsServer 2012 use Resilient File System (ReFS), so any name is ok
            File file = new File(File.separator + ":invalid");
            if (file.exists()) {
                file.delete();
            }
            method.invoke(null, new File(file.getAbsolutePath()));
        } else {
            method.invoke(null, new File(File.separator + ":invalid"));
        }
        fail("Exception was expected");
    } catch (InvocationTargetException e) {
        assertTrue(e.getCause() instanceof CheckstyleException);
        // We do separate validation for message as in Windows
        // disk drive letter appear in message,
        // so we skip that drive letter for compatibility issues
        assertTrue(e.getCause().getMessage().startsWith("Unable to load properties from file '"));
        assertTrue(e.getCause().getMessage().endsWith(":invalid'."));
    }
}

From source file:org.apache.directory.server.jndi.ServerContextFactory.java

/**
 * Starts up the LDAPS protocol provider to service LDAPS requests
 *
 * @throws NamingException if there are problems starting the LDAPS provider
 *//*from w w w .  j av a  2s.  c o  m*/
private void startLDAPS(ServerStartupConfiguration cfg, Hashtable env) throws NamingException {
    // Skip if disabled
    if (!cfg.isEnableLdaps()) {
        return;
    }

    // We use the reflection API in case this is not running on JDK 1.5+.
    IoFilterChainBuilder chain;
    try {
        chain = (IoFilterChainBuilder) Class
                .forName("org.apache.directory.server.ssl.LdapsInitializer", true,
                        ServerContextFactory.class.getClassLoader())
                .getMethod("init", new Class[] { ServerStartupConfiguration.class })
                .invoke(null, new Object[] { cfg });
        ldapsStarted = true;
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof NamingException) {
            throw (NamingException) e.getCause();
        } else {
            throw (NamingException) new NamingException("Failed to load LDAPS initializer.")
                    .initCause(e.getCause());
        }
    } catch (Exception e) {
        throw (NamingException) new NamingException("Failed to load LDAPS initializer.").initCause(e);
    }

    startLDAP0(cfg, env, cfg.getLdapsPort(), chain);
}

From source file:org.gluewine.rest_server.RESTServlet.java

/**
 * Executes the {@link RESTMethod} specified using the given parameters and returns the
 * result./*from w w w . j a v a2  s .  c o m*/
 *
 * @param method The method to execute.
 * @param params The parameters.
 * @return The result of the method invocation.
 * @throws IOException If an error occurs.
 */
@ContextInitializer
public Object executeMethod(RESTMethod method, Object[] params) throws IOException {
    try {
        if (logger.isDebugEnabled())
            logger.debug("Executing method: " + method.getMethod());
        Object result = method.getMethod().invoke(method.getObject(), params);
        if (logger.isDebugEnabled())
            logger.debug("Method returned: " + result);
        return result;
    } catch (InvocationTargetException e) {
        Throwable c = e.getCause();
        ErrorLogger.log(getClass(), c);
        throw new IOException(c.getMessage());
    } catch (Throwable e) {
        ErrorLogger.log(getClass(), e);
        if (e instanceof IOException)
            throw (IOException) e;
        else
            throw new IOException(e.getMessage());
    }
}