Java Code Examples for java.lang.reflect.InvocationTargetException.getCause()

The following are Jave code examples for showing how to use getCause() of the java.lang.reflect.InvocationTargetException class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: GitHub   File: DynamicPropertiesIT.java   Source Code and License Vote up 7 votes
public void setDeclaredPropertyTest(Map<String, Object> config, String schemaLocation, String typeName, Class<?> fieldType, String fieldName, String fieldGetter, Object value) throws Throwable {
    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(schemaLocation, "com.example", config);

    Class<?> type = resultsClassLoader.loadClass("com.example." + typeName);
    Object instance = type.newInstance();

    try {
        type.getMethod("set", String.class, Object.class)
                .invoke(instance, fieldName, value);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }

    assertThat("set for field " + fieldName + " of type " + fieldType + " works.",
            fieldType.cast(type.getMethod(fieldGetter)
                    .invoke(instance)),
            equalTo(value));

}
 
Example 2
Project: openjdk-jdk10   File: TestFramesNoFrames.java   Source Code and License Vote up 7 votes
@Override
public void runTests() throws Exception {
    for (Method m : getClass().getDeclaredMethods()) {
        Annotation a = m.getAnnotation(Test.class);
        if (a != null) {
            for (FrameKind fk : FrameKind.values()) {
                for (OverviewKind ok : OverviewKind.values()) {
                    for (HtmlKind hk : HtmlKind.values()) {
                        try {
                            out.println("Running test " + m.getName() + " " + fk + " " + ok + " " + hk);
                            Path base = Paths.get(m.getName() + "_" + fk + "_" + ok + "_" + hk);
                            Files.createDirectories(base);
                            m.invoke(this, new Object[]{base, fk, ok, hk});
                        } catch (InvocationTargetException e) {
                            Throwable cause = e.getCause();
                            throw (cause instanceof Exception) ? ((Exception) cause) : e;
                        }
                        out.println();
                    }
                }
            }
        }
    }
    printSummary();
}
 
Example 3
Project: openjdk-jdk10   File: ProfileOptionTest.java   Source Code and License Vote up 7 votes
/** Run all test cases. */
void run() throws Exception {
    try {
        initTestClasses();

        for (Method m: getClass().getDeclaredMethods()) {
            Annotation a = m.getAnnotation(Test.class);
            if (a != null) {
                System.err.println(m.getName());
                try {
                    m.invoke(this, new Object[] { });
                } catch (InvocationTargetException e) {
                    Throwable cause = e.getCause();
                    throw (cause instanceof Exception) ? ((Exception) cause) : e;
                }
                System.err.println();
            }
        }

        if (errors > 0)
            throw new Exception(errors + " errors occurred");
    } finally {
        fm.close();
    }
}
 
Example 4
Project: lams   File: AttributeRestoringConnectionInvocationHandler.java   Source Code and License Vote up 7 votes
public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    if (method.getName().equals("setAutoCommit")) {
        setAutoCommit(((Boolean)args[0]).booleanValue());
    } else if (method.getName().equals("setTransactionIsolation")) {
        setTransactionIsolation(((Integer)args[0]).intValue());
    } else if (method.getName().equals("close")) {
        close();
    } else {
        try {
            return method.invoke(conn, args);
        }
        catch(InvocationTargetException ite) {
            throw (ite.getCause() != null ? ite.getCause() : ite);
        }
        
    }
    
    return null;
}
 
Example 5
Project: android-project-gallery   File: Bus.java   Source Code and License Vote up 6 votes
/**
 * Throw a {@link RuntimeException} with given message and cause lifted from an {@link
 * InvocationTargetException}. If the specified {@link InvocationTargetException} does not have a
 * cause, neither will the {@link RuntimeException}.
 */
private static void throwRuntimeException(String msg, InvocationTargetException e) {
  Throwable cause = e.getCause();
  if (cause != null) {
    throw new RuntimeException(msg + ": " + cause.getMessage(), cause);
  } else {
    throw new RuntimeException(msg + ": " + e.getMessage(), e);
  }
}
 
Example 6
Project: businessworks   File: ConstructorInjector.java   Source Code and License Vote up 6 votes
/** Provisions a new T. */
private T provision(Errors errors, InternalContext context,
    ConstructionContext<T> constructionContext) throws ErrorsException {
  try {
    T t;
    try {
      Object[] parameters = SingleParameterInjector.getAll(errors, context, parameterInjectors);
      t = constructionProxy.newInstance(parameters);
      constructionContext.setProxyDelegates(t);
    } finally {
      constructionContext.finishConstruction();
    }

    // Store reference. If an injector re-enters this factory, they'll get the same reference.
    constructionContext.setCurrentReference(t);

    membersInjector.injectMembers(t, errors, context, false);
    membersInjector.notifyListeners(t, errors);

    return t;
  } catch (InvocationTargetException userException) {
    Throwable cause = userException.getCause() != null
        ? userException.getCause()
        : userException;
    throw errors.withSource(constructionProxy.getInjectionPoint())
        .errorInjectingConstructor(cause).toException();
  } finally {
    constructionContext.removeCurrentReference();
  }
}
 
Example 7
Project: firebase-admin-java   File: FirebaseAuthTest.java   Source Code and License Vote up 6 votes
@Test
public void testInvokeAfterAppDelete() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testInvokeAfterAppDelete");
  FirebaseAuth auth = FirebaseAuth.getInstance(app);
  assertNotNull(auth);
  app.delete();

  for (Method method : auth.getClass().getDeclaredMethods()) {
    int modifiers = method.getModifiers();
    if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers)) {
      continue;
    }

    List<Object> parameters = new ArrayList<>(method.getParameterTypes().length);
    for (Class<?> parameterType : method.getParameterTypes()) {
      parameters.add(Defaults.defaultValue(parameterType));
    }
    try {
      method.invoke(auth, parameters.toArray());
      fail("No error thrown when invoking auth after deleting app; method: " + method.getName());
    } catch (InvocationTargetException expected) {
      String message = "FirebaseAuth instance is no longer alive. This happens when "
          + "the parent FirebaseApp instance has been deleted.";
      Throwable cause = expected.getCause();
      assertTrue(cause instanceof IllegalStateException);
      assertEquals(message, cause.getMessage());
    }
  }
}
 
Example 8
Project: VirtualHook   File: RefMethod.java   Source Code and License Vote up 6 votes
public T callWithException(Object receiver, Object... args) throws Throwable {
    try {
        return (T) this.method.invoke(receiver, args);
    } catch (InvocationTargetException e) {
        if (e.getCause() != null) {
            throw e.getCause();
        }
        throw e;
    }
}
 
Example 9
Project: openjdk-jdk10   File: GetSysPkgTest.java   Source Code and License Vote up 6 votes
private static Object invoke(Method m, Object obj, Object... args) throws Throwable {
    try {
        return m.invoke(obj, args);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}
 
Example 10
Project: gamecollection   File: MoveTranslatorTest.java   Source Code and License Vote up 6 votes
@Test(expected = IllegalArgumentException.class)
public void colToChar_wrongArguments_throwsException() throws Throwable {
    Method method = MoveTranslator.class.getDeclaredMethod("colToChar", int.class);
    method.setAccessible(true);

    try {
        method.invoke(null, 8);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}
 
Example 11
Project: Equella   File: ClientProxy.java   Source Code and License Vote up 6 votes
private Object invoke(Object proxy, Method method, Object[] args, boolean retry) throws Throwable // NOSONAR
{
	String methodName = method.getName();
	Method pMethod = iface.getClass().getMethod(methodName, method.getParameterTypes());
	try
	{
		return pMethod.invoke(iface, args);
	}
	catch( InvocationTargetException e )
	{
		throw e.getCause();
	}
}
 
Example 12
Project: VirtualHook   File: SettingsProviderHook.java   Source Code and License Vote up 6 votes
@Override
public Bundle call(Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
	String methodName = (String) args[args.length - 3];
	String arg = (String) args[args.length - 2];
	int methodType = getMethodType(methodName);
	if (METHOD_GET == methodType) {
		String presetValue = PRE_SET_VALUES.get(arg);
		if (presetValue != null) {
			Bundle res = new Bundle();
			res.putString("value", presetValue);
			return res;
		}
	}
	if (METHOD_PUT == methodType) {
		if (isSecureMethod(methodName)) {
			return null;
		}
	}
	try {
		return super.call(method, args);
	} catch (InvocationTargetException e) {
		if (e.getCause() instanceof SecurityException) {
			return null;
		}
		throw e;
	}
}
 
Example 13
Project: jdk8u-jdk   File: TCKOffsetTime.java   Source Code and License Vote up 6 votes
@Test(expectedExceptions=NullPointerException.class)
public void constructor_nullOffset() throws Throwable  {
    Constructor<OffsetTime> con = OffsetTime.class.getDeclaredConstructor(LocalTime.class, ZoneOffset.class);
    con.setAccessible(true);
    try {
        con.newInstance(LocalTime.of(11, 30, 0, 0), null);
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
}
 
Example 14
Project: openjdk-jdk10   File: WithClassLoaderName.java   Source Code and License Vote up 5 votes
public static void testURLClassLoader(String loaderName) throws Exception {
    System.err.println("---- test URLClassLoader name: " + loaderName);

    URL[] urls = new URL[] { CLASSES_DIR.toUri().toURL() };
    ClassLoader parent = ClassLoader.getSystemClassLoader();
    URLClassLoader loader = new URLClassLoader(loaderName, urls, parent);

    Class<?> c = Class.forName(THROW_EXCEPTION_CLASS, true, loader);
    Method method = c.getMethod("throwError");
    try {
        // invoke p.ThrowException::throwError
        method.invoke(null);
    } catch (InvocationTargetException x) {
        Throwable e = x.getCause();
        e.printStackTrace();

        StackTraceElement[] stes = e.getStackTrace();
        StackWalker.StackFrame[] frames = new StackWalker.StackFrame[] {
            Utils.makeStackFrame(c, "throwError", "ThrowException.java"),
            Utils.makeStackFrame(WithClassLoaderName.class, "testURLClassLoader",
                                 SRC_FILENAME),
            Utils.makeStackFrame(WithClassLoaderName.class, "main", SRC_FILENAME),
        };

        // p.ThrowException.throwError
        Utils.checkFrame(loaderName, frames[0], stes[0]);
        // skip reflection frames
        int i = 1;
        while (i < stes.length) {
            String cn = stes[i].getClassName();
            if (!cn.startsWith("java.lang.reflect.") &&
                !cn.startsWith("jdk.internal.reflect."))
                break;
            i++;
        }
        // WithClassLoaderName.testURLClassLoader
        Utils.checkFrame("app", frames[1], stes[i]);

        // WithClassLoaderName.main
        Utils.checkFrame("app", frames[2], stes[i+1]);

    }
}
 
Example 15
Project: TPlayer   File: PowerManagerStub.java   Source Code and License Vote up 5 votes
private Object onHandleError(InvocationTargetException e) throws Throwable {
	if (e.getCause() instanceof SecurityException) {
		return 0;
	}
	throw e.getCause();
}
 
Example 16
Project: lams   File: MultiHostConnectionProxy.java   Source Code and License Vote up 5 votes
/**
 * Proxies method invocation on the java.sql.Connection interface, trapping multi-host specific methods and generic methods.
 * Subclasses have to override this to complete the method invocation process, deal with exceptions and decide when to switch connection.
 * To avoid unnecessary additional exception handling overriders should consult #canDealWith(Method) before chaining here.
 */
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();

    if (METHOD_GET_MULTI_HOST_SAFE_PROXY.equals(methodName)) {
        return this.thisAsConnection;
    }

    if (METHOD_EQUALS.equals(methodName)) {
        // Let args[0] "unwrap" to its InvocationHandler if it is a proxy.
        return args[0].equals(this);
    }

    if (METHOD_HASH_CODE.equals(methodName)) {
        return this.hashCode();
    }

    if (METHOD_CLOSE.equals(methodName)) {
        doClose();
        this.isClosed = true;
        this.closedReason = "Connection explicitly closed.";
        this.closedExplicitly = true;
        return null;
    }

    if (METHOD_ABORT_INTERNAL.equals(methodName)) {
        doAbortInternal();
        this.currentConnection.abortInternal();
        this.isClosed = true;
        this.closedReason = "Connection explicitly closed.";
        return null;
    }

    if (METHOD_ABORT.equals(methodName) && args.length == 1) {
        doAbort((Executor) args[0]);
        this.isClosed = true;
        this.closedReason = "Connection explicitly closed.";
        return null;
    }

    if (METHOD_IS_CLOSED.equals(methodName)) {
        return this.isClosed;
    }

    try {
        return invokeMore(proxy, method, args);
    } catch (InvocationTargetException e) {
        throw e.getCause() != null ? e.getCause() : e;
    }
}
 
Example 17
Project: parabuild-ci   File: Math.java   Source Code and License Vote up 5 votes
/**
* Performs a calculation on an array of numbers. The mathematical methods
* in this class will accept an array of numbers, so
* <code>add(new int[]{1, 2, 3})</code>
* is equivalent to
* <code>add(add(1, 2), 3)</code>
* which is equivalent to 1 + 2 + 3.
* @param op the operation to perform
* @type the data type of the operands. All operands will be cast to the same
* data type
* @param operands these strings must parse to numbers.
*/
private Number calculateArray( String op, String type, String[] operands ) {
   try {
      Class c = this.getClass();

      // find candidate methods for the requested operation
      Vector candidates = new Vector();
      Method[] methods = c.getDeclaredMethods();
      for ( int i = 0; i < methods.length; i++ ) {
         String name = methods[ i ].getName();
         if ( name.equals( op ) ) {
            if ( methods[ i ].getParameterTypes().length == 1 ) {
               if ( methods[ i ].getParameterTypes() [ 0 ].isArray() )
                  candidates.addElement( methods[ i ] );
            }
         }
      }
      if ( candidates.size() == 0 )
         throw new RuntimeException( "Unknown operation: " + op );

      // get the desired data type for the operation, default is
      // Double.TYPE if no other match is found
      Object wantTypeClass = getDataTypeArray( type, operands.length );

      // find the actual method to invoke and invoke it immediately once
      // it is found
      Class typeClass = null;
      Enumeration en = candidates.elements();
      while ( en.hasMoreElements() ) {
         Method m = ( Method ) en.nextElement();
         if ( m.getParameterTypes() [ 0 ].equals( wantTypeClass.getClass() ) ) {
            typeClass = getDataType( type );
            Object[] params = getParamsArray( typeClass, operands );
            try {
               //System.out.println( "Math.calculateArray, invoking: " + m.toString() );
               Object result = m.invoke( c, params );
               return ( Number ) result;
            }
            catch ( InvocationTargetException ite ) {
               Throwable t = ite.getCause();
               if ( t != null && t instanceof ArithmeticException ) {
                  //System.out.println( "caught ArithmeticException in Math" );
                  throw ( ArithmeticException ) t;
               }
               else {
                  //System.out.println( "throwing " + ite.getMessage() );
                  throw ite;
               }
            }
         }
      }
   }
   catch ( Exception e ) {
      //e.printStackTrace();
      if ( e instanceof ArithmeticException ) {
         //System.out.println("rethrowing " + e.getMessage());
         throw ( ArithmeticException ) e;
      }
   }
   return null;
}
 
Example 18
Project: container   File: PowerManagerPatch.java   Source Code and License Vote up 5 votes
private Object onHandleError(InvocationTargetException e) throws Throwable {
	if (e.getCause() instanceof SecurityException) {
		return 0;
	}
	throw e.getCause();
}
 
Example 19
Project: lazycat   File: AstFunction.java   Source Code and License Vote up 5 votes
@Override
public Object getValue(EvaluationContext ctx) throws ELException {

	FunctionMapper fnMapper = ctx.getFunctionMapper();

	// quickly validate again for this request
	if (fnMapper == null) {
		throw new ELException(MessageFactory.get("error.fnMapper.null"));
	}
	Method m = fnMapper.resolveFunction(this.prefix, this.localName);
	if (m == null) {
		throw new ELException(MessageFactory.get("error.fnMapper.method", this.getOutputName()));
	}

	Class<?>[] paramTypes = m.getParameterTypes();
	Object[] params = null;
	Object result = null;
	int inputParameterCount = this.jjtGetNumChildren();
	int methodParameterCount = paramTypes.length;
	if (inputParameterCount == 0 && methodParameterCount == 1 && m.isVarArgs()) {
		params = new Object[] { null };
	} else if (inputParameterCount > 0) {
		params = new Object[methodParameterCount];
		try {
			for (int i = 0; i < methodParameterCount; i++) {
				if (m.isVarArgs() && i == methodParameterCount - 1) {
					if (inputParameterCount < methodParameterCount) {
						params[i] = new Object[] { null };
					} else if (inputParameterCount == methodParameterCount && paramTypes[i].isArray()) {
						params[i] = this.jjtGetChild(i).getValue(ctx);
					} else {
						Object[] varargs = new Object[inputParameterCount - methodParameterCount + 1];
						Class<?> target = paramTypes[i].getComponentType();
						for (int j = i; j < inputParameterCount; j++) {
							varargs[j - i] = this.jjtGetChild(j).getValue(ctx);
							varargs[j - i] = coerceToType(varargs[j - i], target);
						}
						params[i] = varargs;
					}
				} else {
					params[i] = this.jjtGetChild(i).getValue(ctx);
				}
				params[i] = coerceToType(params[i], paramTypes[i]);
			}
		} catch (ELException ele) {
			throw new ELException(MessageFactory.get("error.function", this.getOutputName()), ele);
		}
	}
	try {
		result = m.invoke(null, params);
	} catch (IllegalAccessException iae) {
		throw new ELException(MessageFactory.get("error.function", this.getOutputName()), iae);
	} catch (InvocationTargetException ite) {
		Throwable cause = ite.getCause();
		if (cause instanceof ThreadDeath) {
			throw (ThreadDeath) cause;
		}
		if (cause instanceof VirtualMachineError) {
			throw (VirtualMachineError) cause;
		}
		throw new ELException(MessageFactory.get("error.function", this.getOutputName()), cause);
	}
	return result;
}
 
Example 20
Project: Elasticsearch   File: ConstructorInjector.java   Source Code and License Vote up 5 votes
/**
 * Construct an instance. Returns {@code Object} instead of {@code T} because
 * it may return a proxy.
 */
Object construct(Errors errors, InternalContext context, Class<?> expectedType)
        throws ErrorsException {
    ConstructionContext<T> constructionContext = context.getConstructionContext(this);

    // We have a circular reference between constructors. Return a proxy.
    if (constructionContext.isConstructing()) {
        // TODO (crazybob): if we can't proxy this object, can we proxy the other object?
        return constructionContext.createProxy(errors, expectedType);
    }

    // If we're re-entering this factory while injecting fields or methods,
    // return the same instance. This prevents infinite loops.
    T t = constructionContext.getCurrentReference();
    if (t != null) {
        return t;
    }

    try {
        // First time through...
        constructionContext.startConstruction();
        try {
            Object[] parameters = SingleParameterInjector.getAll(errors, context, parameterInjectors);
            t = constructionProxy.newInstance(parameters);
            constructionContext.setProxyDelegates(t);
        } finally {
            constructionContext.finishConstruction();
        }

        // Store reference. If an injector re-enters this factory, they'll get the same reference.
        constructionContext.setCurrentReference(t);

        membersInjector.injectMembers(t, errors, context);
        membersInjector.notifyListeners(t, errors);

        return t;
    } catch (InvocationTargetException userException) {
        Throwable cause = userException.getCause() != null
                ? userException.getCause()
                : userException;
        throw errors.withSource(constructionProxy.getInjectionPoint())
                .errorInjectingConstructor(cause).toException();
    } finally {
        constructionContext.removeCurrentReference();
    }
}