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:org.aguntuk.xwidget.management.RequestProcessor.java

public Object processRequest(HttpServletRequest request, HttpServletResponse response,
        TemplatePlugin templatePlugin) throws GeneralException {
    try {/*from   ww  w.  jav  a  2s  .  co m*/
        Gson gson = null;
        Object serviceMethodReturn;
        String requestType = request.getServletPath();
        Service service = ServiceFacade.INSTANCE.getServiceForRequestType(requestType);
        Request blockRequest = service.getRequest(requestType);
        //String[] requestClass = blockRequest.getRequestClassName();
        RequestKey requestKeys[] = blockRequest.getRequestKey();
        Method m = blockRequest.getServiceMethod();
        InputFormat inputType = blockRequest.getInputType();
        if (inputType.equals(InputFormat.json)) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            gson = new Gson();
            Object[] beans = new Object[requestKeys.length];
            for (int i = 0; i < beans.length; i++) {
                Class<?> reqBeanClass = Class.forName(requestKeys[i].getKeyType());
                beans[i] = gson.fromJson(reader, reqBeanClass);
            }
            serviceMethodReturn = m.invoke(service.getServiceInstance(), beans);
        } else if (requestKeys != null && requestKeys.length > 0) {
            Object[] argValues = new Object[requestKeys.length];
            int j = 0;
            for (RequestKey requestKey : requestKeys) {
                if (!requestKey.isCustomObject) {
                    Object argumentValue = null;
                    String requestKeyType = requestKey.getKeyType();
                    if (ClassUtils.INSTANCE.isArrayType(requestKeyType)) {
                        argumentValue = request.getParameterValues(requestKey.getKeyName());
                        argValues[j] = ClassUtils.INSTANCE
                                .fromStringObjectToOtherArrayType((String[]) argumentValue, requestKeyType);
                    } else {
                        argumentValue = request.getParameter(requestKey.getKeyName());
                        argValues[j] = ClassUtils.INSTANCE.fromStringToOtherType((String) argumentValue,
                                requestKeyType);
                    }

                } else {
                    Object bean = populateBean(request, requestKey.getKeyType());
                    argValues[j] = bean;
                }
                ++j;
            }
            serviceMethodReturn = m.invoke(service.getServiceInstance(), argValues);
        } else {
            serviceMethodReturn = m.invoke(service.getServiceInstance());
        }
        String returnValue = null;
        //if a xWidgetType is specified from the browser then thats our output otherwise just follow the standard annotation
        /*         if(xWidgetType != null) {
                    gson = new Gson();
                    widgetTmpl = gson.fromJson(xWidgetType, XWidget.class);
                    ViewType type = ViewType.toViewType(widgetTmpl.getType());
                    switch(type) {
                    //for a list type view we expect the java service to return a tree structure. In other words a Map of a Map
                       case LIST:
          //TODO: Implement this part later. 
          break;
                    }
                 } else {*/
        switch (blockRequest.getOutputType()) {
        case html:
            String templateFile = blockRequest.getTemplate();
            returnValue = templatePlugin.process(serviceMethodReturn, templateFile);
            break;
        case json:
            gson = new Gson();
            returnValue = gson.toJson(serviceMethodReturn);
            break;
        case jsp:
            request.setAttribute("out", serviceMethodReturn);
            request.getRequestDispatcher(blockRequest.getJsp()).forward(request, response);
            returnValue = null;
            break;
        }
        //}
        //get the template
        return returnValue;
    } catch (InstantiationException ie) {
        throw new GeneralException(ie);
    } catch (IllegalAccessException iae) {
        throw new GeneralException(iae);
    } catch (ClassNotFoundException cnfe) {
        throw new GeneralException(cnfe);
    } catch (InvocationTargetException ite) {
        Throwable t = ite.getCause();
        throw new GeneralException(t);
    } catch (IOException ioe) {
        throw new GeneralException(ioe);
    } catch (TemplateException te) {
        throw new GeneralException(te);
    } catch (Exception exc) {
        throw new GeneralException(exc);
    }
}

From source file:com.github.lukaszbudnik.gugis.GugisReplicatorInterceptor.java

public Stream<Try<Object>> executeBindings(boolean allowFailure, Stream<Binding<Object>> bindings,
        String methodName, Object[] arguments) {
    Stream<Try<Object>> executedBindingsStream = bindings.parallel().map(binding -> {
        try {/*from   w w  w.ja  v  a  2s. c  o  m*/
            Object component = binding.getProvider().get();
            return new Success<Object>(MethodUtils.invokeMethod(component, methodName, arguments));
        } catch (InvocationTargetException e) {
            if (!allowFailure) {
                // pass the original exception thrown
                throw new GugisException(e.getCause());
            }
            return new Failure<Object>(e.getCause());
        } catch (NoSuchMethodException | IllegalAccessException e) {
            throw new GugisException(e);
        }
    });
    return executedBindingsStream;
}

From source file:com.conversantmedia.mapreduce.tool.AnnotatedTool.java

@Override
public void init(AnnotatedToolContext context) throws ToolException, ParseException {
    List<Method> methods = new ArrayList<>();
    if (this.validateMethod != null) {
        methods.addAll(this.validateMethod);
    }/* w  ww  . jav a  2  s .c o m*/
    if (this.driverInitMethod != null) {
        methods.addAll(this.driverInitMethod);
    }

    try {
        // Now call the all @Validate and @DriverInit methods
        for (Method m : methods) {
            m.invoke(this.tool);
        }

        // Initialize our annotations handlers
        initializeAnnotationHandlers();

    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof ParseException) {
            // If any of these throws a ParseException, treat pass
            // that up so we can output the CLI help message instead of 
            // a full stack trace.
            throw new ToolException(e.getCause().getMessage());
        }
        throw new ToolException(findRootException(e.getCause()));
    } catch (IllegalAccessException | IllegalArgumentException e) {
        throw new ToolException(e);
    }
}

From source file:org.ops4j.pax.exam.rbc.client.RemoteBundleContextClient.java

/**
 * {@inheritDoc}/*from   w  w w.jav a  2s .c  o m*/
 * Returns a dynamic proxy in place of the actual service, forwarding the calls via the remote bundle context.
 */
@SuppressWarnings("unchecked")
public <T> T getService(final Class<T> serviceType, final long timeoutInMillis) {
    return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { serviceType },
            new InvocationHandler() {
                /**
                 * {@inheritDoc}
                 * Delegates the call to remote bundle context.
                 */
                public Object invoke(final Object proxy, final Method method, final Object[] params)
                        throws Throwable {
                    try {
                        return getRemoteBundleContext().remoteCall(method.getDeclaringClass(), method.getName(),
                                method.getParameterTypes(), timeoutInMillis, params);
                    } catch (InvocationTargetException e) {
                        throw e.getCause();
                    } catch (RemoteException e) {
                        throw new TestContainerException("Remote exception", e);
                    } catch (Exception e) {
                        throw new TestContainerException("Invocation exception", e);
                    }
                }
            });
}

From source file:org.sonatype.nexus.test.booter.EmbeddedNexusBooter.java

@Override
public void stopNexus() throws Exception {
    try {//from w  w  w .  j  ava 2s . c o m
        log.info("Stopping Nexus");

        if (launcher != null) {
            launcherClass.getMethod("destroy").invoke(launcher);
        }
        launcher = null;
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IllegalStateException) {
            log.debug("Ignoring", cause);
        } else {
            log.error("Stop failed", cause);
            throw Throwables.propagate(cause);
        }
    } finally {
        try {
            // The JVM caches URLs along with their current URL handler in a couple of static maps.
            // This causes unexpected issues when restarting legacy tests (even when using isolated
            // classloaders) because the cached handler persists across the restart and still refers
            // to the now shutdown framework. Felix has a few tricks to workaround this, but these
            // are defeated by the isolated legacy test classloader as the new framework cannot see
            // the old handler classes to reflectively update them.

            // (the other solution would be to not shutdown the framework when running legacy tests,
            // this would keep the old URL handlers alive at the cost of a few additional resources)

            Class<?> jarFileFactoryClass = Class.forName("sun.net.www.protocol.jar.JarFileFactory");
            Field fileCacheField = jarFileFactoryClass.getDeclaredField("fileCache");
            Field urlCacheField = jarFileFactoryClass.getDeclaredField("urlCache");
            fileCacheField.setAccessible(true);
            urlCacheField.setAccessible(true);
            ((Map<?, ?>) fileCacheField.get(null)).clear();
            ((Map<?, ?>) urlCacheField.get(null)).clear();
        } catch (Exception e) {
            log.warn("Unable to clear URL cache", e);
        }

        Thread.yield();
        System.gc();
    }
}

From source file:org.apache.nifi.processors.windows.event.log.ConsumeWindowsEventLogTest.java

@Test(expected = ProcessException.class)
public void testScheduleQueueStopThrowsException() throws Throwable {
    ReflectionUtils.invokeMethodsWithAnnotation(OnScheduled.class, evtSubscribe,
            testRunner.getProcessContext());

    WinNT.HANDLE handle = mockEventHandles(wEvtApi, kernel32, Arrays.asList("test")).get(0);
    getRenderingCallback().onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, handle);

    try {/* ww  w. j av a 2s  . com*/
        ReflectionUtils.invokeMethodsWithAnnotation(OnStopped.class, evtSubscribe,
                testRunner.getProcessContext());
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtilsTest.java

@Test
public void mustCreateAndRunNestedSwitchStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.INT_TYPE, Type.INT_TYPE });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**//  ww w  .  j  av  a2  s  .c o m
     * switch(arg1) {
     *    case 0:
     *        throw new RuntimeException("0");
     *    case 1:
     *         throw new RuntimeException("1");
     *    case 2:
     *         switch(arg2) {
     *             case 0:
     *                 throw new RuntimeException("0");
     *             case 1:
     *                 throw new RuntimeException("1");
     *             case 2:
     *                 return "OK!";
     *             default:
     *                 throw new RuntimeException("innerdefault")
     *         }
     *     default:
     *         throw new RuntimeException("default");
     * }
     */
    methodNode.instructions = tableSwitch(loadVar(intVar1), throwException("default"), 0, throwException("0"),
            throwException("1"),
            tableSwitch(loadVar(intVar2), throwException("innerdefault"), 0, throwException("inner0"),
                    throwException("inner1"),
                    InstructionUtils.returnValue(Type.getType(String.class), loadStringConst("OK!"))));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("OK!", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 2));

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 0, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("0", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 10);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("innerdefault", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 10, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("default", ex.getCause().getMessage());
        }
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testConstructionForbidden()
        throws IllegalAccessException, InstantiationException, NoSuchMethodException {
    Constructor<KeyFileUtilities> constructor = KeyFileUtilities.class.getDeclaredConstructor();
    constructor.setAccessible(true);//from  w  w w  .j  a  va2  s .  c  o m

    try {
        constructor.newInstance();
        fail("Expected exception java.lang.reflect.InvocationTargetException, but got no exception.");
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        assertNotNull("Expected cause for InvocationTargetException, but got no cause.", cause);
        assertSame("Expected exception java.lang.RuntimeException, but got " + cause.getClass(),
                RuntimeException.class, cause.getClass());
        assertEquals("The message was incorrect.", "This class cannot be instantiated.", cause.getMessage());
    }
}

From source file:test.org.wildfly.swarm.microprofile.openapi.TckTestRunner.java

/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 *///from   w  w  w  .  j  a  v  a 2 s.c o m
@Override
protected void runChild(final ProxiedTckTest child, final RunNotifier notifier) {
    OpenApiDocument.INSTANCE.set(TckTestRunner.OPEN_API_DOCS.get(child.getTest().getClass()));

    Description description = describeChild(child);
    if (isIgnored(child)) {
        notifier.fireTestIgnored(description);
    } else {
        Statement statement = new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    Object[] args = (Object[]) child.getTest().getClass().getMethod("getTestArguments")
                            .invoke(child.getTest());
                    child.getTestMethod().invoke(child.getDelegate(), args);
                } catch (InvocationTargetException e) {
                    Throwable cause = e.getCause();
                    org.testng.annotations.Test testAnno = child.getTestMethod()
                            .getAnnotation(org.testng.annotations.Test.class);
                    Class[] expectedExceptions = testAnno.expectedExceptions();
                    if (expectedExceptions != null && expectedExceptions.length > 0) {
                        Class expectedException = expectedExceptions[0];
                        Assert.assertEquals(expectedException, cause.getClass());
                    } else {
                        throw cause;
                    }
                }
            }
        };
        runLeaf(statement, description, notifier);
    }

}

From source file:org.quackbot.hooks.core.CoreQuackbotListener.java

protected String executeOnCommandLong(CommandEvent commandEvent) throws Exception {
    try {/*from   w  w  w  .  j a va  2s.c o m*/
        Command command = commandEvent.getCommandClass();
        Class clazz = command.getClass();
        for (Method curMethod : clazz.getMethods())
            if (curMethod.getName().equalsIgnoreCase("onCommand")
                    && curMethod.getParameterTypes().length != 1) {
                //Get parameters leaving off the first one
                Class[] parameters = (Class[]) ArrayUtils.remove(curMethod.getParameterTypes(), 0);

                Object[] args = new Object[0];
                String[] userArgs = commandEvent.getArgs();
                log.debug("UserArgs: " + StringUtils.join(userArgs, ", "));
                //Try and fill argument list, handling arrays
                for (int i = 0; i < userArgs.length; i++) {
                    log.trace("Current parameter: " + i);
                    if (i < parameters.length && parameters[i].isArray()) {
                        log.trace("Parameter " + i + " is an array");
                        //Look ahead to see how big of an array we need
                        int arrayLength = parameters.length - (i - 1);
                        for (int s = i; s < parameters.length; s++)
                            if (!parameters[s].isArray())
                                arrayLength--;

                        //Add our array of specified length
                        log.trace("Parameter " + i + " is an array. Assigning it the next " + arrayLength
                                + " args");
                        Object[] curArray = ArrayUtils.subarray(userArgs, i, i + arrayLength);
                        args = ArrayUtils.add(args, curArray);
                        log.trace("Parameter " + i + " set to " + StringUtils.join(curArray, ", "));

                        //Move the index forward to account for the args folded into the array
                        i += arrayLength - 1;
                    } else {
                        log.trace("User arg " + i + " isn't an array, assigning " + userArgs[i]);
                        args = ArrayUtils.add(args, userArgs[i]);
                    }
                }

                //Pad the args with null values
                args = Arrays.copyOf(args, parameters.length);

                //Prefix with command event
                args = ArrayUtils.addAll(new Object[] { commandEvent }, args);
                log.trace("Args minus CommandEvent: " + StringUtils.join(ArrayUtils.remove(args, 0), ", "));

                //Execute method
                return (String) curMethod.invoke(command, args);
            }
    } catch (InvocationTargetException e) {
        //Unrwap if nessesary
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof Exception)
            throw (Exception) e.getCause();
        throw e;
    }
    return null;
}