List of usage examples for java.lang.reflect InvocationTargetException getCause
public Throwable getCause()
From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java
/** * Try to instantiate a protocol buffer of the given message class * from the given input stream.//from w w w . j ava 2 s .co m * * @param protoClass the class of the generated protocol buffer * @param dataIn the input stream to read from * @return the instantiated Message instance * @throws IOException if an IO problem occurs */ static Message tryInstantiateProtobuf(Class<?> protoClass, DataInput dataIn) throws IOException { try { if (dataIn instanceof InputStream) { // We can use the built-in parseDelimitedFrom and not have to re-copy // the data Method parseMethod = getStaticProtobufMethod(protoClass, "parseDelimitedFrom", InputStream.class); return (Message) parseMethod.invoke(null, (InputStream) dataIn); } else { // Have to read it into a buffer first, since protobuf doesn't deal // with the DataInput interface directly. // Read the size delimiter that writeDelimitedTo writes int size = ProtoUtil.readRawVarint32(dataIn); if (size < 0) { throw new IOException("Invalid size: " + size); } byte[] data = new byte[size]; dataIn.readFully(data); Method parseMethod = getStaticProtobufMethod(protoClass, "parseFrom", byte[].class); return (Message) parseMethod.invoke(null, data); } } catch (InvocationTargetException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw new IOException(e.getCause()); } } catch (IllegalAccessException iae) { throw new AssertionError("Could not access parse method in " + protoClass); } }
From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java
/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) * @author Alex/* ww w.j a va 2s . c o m*/ */ @SuppressWarnings("unchecked") public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate, final Optional<QueryComponent<T>> extra_query, final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform, final Map<String, BiFunction<Object, Object[], Object>> interceptors, final Optional<BiFunction<Object, Object[], Object>> default_interceptor) { InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes()); // First off, apply the extra term to any relevant args: final Object[] args_with_extra_query_pretransform = query_transform.map(q -> { return (null != args) ? Arrays.stream(args) .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass()) ? q.apply((QueryComponent<T>) o) : o) .collect(Collectors.toList()).toArray() : args; }).orElse(args); final Object[] args_with_extra_query = extra_query.map(q -> { return (null != args_with_extra_query_pretransform) ? Arrays.stream(args_with_extra_query_pretransform) .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass()) ? CrudUtils.allOf((QueryComponent<T>) o, q) : o) .collect(Collectors.toList()).toArray() : args_with_extra_query_pretransform; }).orElse(args_with_extra_query_pretransform); // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId final Object o = Lambdas.get(() -> { final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz) ? (SingleQueryComponent<T>) CrudUtils.allOf() : CrudUtils.allOf(clazz); try { if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec return delegate.countObjectsBySpec(extra_query.get()); } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query if (1 == args.length) { return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0]))); } else { return delegate.getObjectBySpec( CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])), (List<String>) args[1], (Boolean) args[2]); } } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) { CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get()); return l.thenApply(ll -> ll > 0); } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query return delegate.deleteObjectBySpec( CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0]))); } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query return delegate.updateObjectBySpec( CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])), Optional.empty(), (UpdateComponent<T>) args[1]); } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present Object o_internal = m.invoke(delegate, args_with_extra_query); Optional<QueryComponent<JsonNode>> json_extra_query = extra_query .map(qc -> qc.toJson()); return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query, Optional.empty(), interceptors, default_interceptor); } else { // wrap any CrudService types Object o_internal = m.invoke(delegate, args_with_extra_query); return (null != o_internal) && ICrudService.class.isAssignableFrom(o_internal.getClass()) ? intercept(clazz, (ICrudService<T>) o_internal, extra_query, Optional.empty(), interceptors, default_interceptor) : o_internal; } } catch (IllegalAccessException ee) { throw new RuntimeException(ee); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause().getMessage(), e); } }); return interceptors .getOrDefault(m.getName(), default_interceptor.orElse(CrudServiceUtils::identityInterceptor)) .apply(o, args_with_extra_query); } }; return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass()) ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(), new Class[] { ICrudService.IReadOnlyCrudService.class }, handler) : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(), new Class[] { ICrudService.class }, handler); }
From source file:org.jtester.utility.ReflectionUtils.java
/** * Creates an instance of the given type * //from w w w . java 2s . co m * @param <T> * The type of the instance * @param type * The type of the instance * @param bypassAccessibility * If true, no exception is thrown if the parameterless * constructor is not public * @param argumentTypes * The constructor arg types, not null * @param arguments * The constructor args, not null * @return An instance of this type * @throws JTesterException * If an instance could not be created */ @SuppressWarnings("rawtypes") public static <T> T createInstanceOfType(Class<T> type, boolean bypassAccessibility, Class[] argumentTypes, Object[] arguments) { if (type.isMemberClass() && !isStatic(type.getModifiers())) { throw new JTesterException( "Creation of an instance of a non-static innerclass is not possible using reflection. The type " + type.getSimpleName() + " is only known in the context of an instance of the enclosing class " + type.getEnclosingClass().getSimpleName() + ". Declare the innerclass as static to make construction possible."); } try { Constructor<T> constructor = type.getDeclaredConstructor(argumentTypes); if (bypassAccessibility) { constructor.setAccessible(true); } return constructor.newInstance(arguments); } catch (InvocationTargetException e) { throw new JTesterException("Error while trying to create object of class " + type.getName(), e.getCause()); } catch (Exception e) { throw new JTesterException("Error while trying to create object of class " + type.getName(), e); } }
From source file:com.google.dexmaker.ProxyBuilder.java
public static Object callSuper(Object proxy, Method method, Object... args) throws Throwable { try {//from w w w.j a v a2 s . c om return proxy.getClass().getMethod(superMethodName(method), method.getParameterTypes()).invoke(proxy, args); } catch (InvocationTargetException e) { throw e.getCause(); } }
From source file:com.google.dexmaker.ProxyBuilder.java
private static RuntimeException launderCause(InvocationTargetException e) { Throwable cause = e.getCause(); // Errors should be thrown as they are. if (cause instanceof Error) { throw (Error) cause; }/*from w ww . ja va 2 s.co m*/ // RuntimeException can be thrown as-is. if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } // Declared exceptions will have to be wrapped. throw new UndeclaredThrowableException(cause); }
From source file:org.apache.hawq.pxf.api.utilities.Utilities.java
private static Object instantiate(Constructor<?> con, Object... args) throws Exception { try {/*from w w w . j a va2 s .co m*/ return con.newInstance(args); } catch (InvocationTargetException e) { /* * We are creating resolvers, accessors, fragmenters, etc. using the * reflection framework. If for example, a resolver, during its * instantiation - in the c'tor, will throw an exception, the * Resolver's exception will reach the Reflection layer and there it * will be wrapped inside an InvocationTargetException. Here we are * above the Reflection layer and we need to unwrap the Resolver's * initial exception and throw it instead of the wrapper * InvocationTargetException so that our initial Exception text will * be displayed in psql instead of the message: * "Internal Server Error" */ throw (e.getCause() != null) ? new Exception(e.getCause()) : e; } }
From source file:org.unitils.util.ReflectionUtils.java
/** * Creates an instance of the given type * //from w w w .jav a2 s. c o m * @param <T> * The type of the instance * @param type * The type of the instance * @param bypassAccessibility * If true, no exception is thrown if the parameterless * constructor is not public * @param argumentTypes * The constructor arg types, not null * @param arguments * The constructor args, not null * @return An instance of this type * @throws UnitilsException * If an instance could not be created */ public static <T> T createInstanceOfType(Class<T> type, boolean bypassAccessibility, Class[] argumentTypes, Object[] arguments) { if (type.isMemberClass() && !isStatic(type.getModifiers())) { throw new UnitilsException( "Creation of an instance of a non-static innerclass is not possible using reflection. The type " + type.getSimpleName() + " is only known in the context of an instance of the enclosing class " + type.getEnclosingClass().getSimpleName() + ". Declare the innerclass as static to make construction possible."); } try { Constructor<T> constructor = type.getDeclaredConstructor(argumentTypes); if (bypassAccessibility) { constructor.setAccessible(true); } return constructor.newInstance(arguments); } catch (InvocationTargetException e) { throw new UnitilsException("Error while trying to create object of class " + type.getName(), e.getCause()); } catch (Exception e) { throw new UnitilsException("Error while trying to create object of class " + type.getName(), e); } }
From source file:com.mycompany.selenium.factory.Page.java
public void takeAction(String action, Object... param) throws Throwable { action = action.replaceAll(" ", "_"); try {// w w w . j a v a 2 s. c om MethodUtils.invokeMethod(this, action, param); } catch (NoSuchMethodException e) { StringBuilder sb = new StringBuilder(); sb.append("There is no \"").append(action).append("\" action ").append("in ").append(this.getTitle()) .append(" page object").append("\n"); sb.append("Possible actions are:").append("\n"); Class tClass = this.getClass(); Method[] methods = tClass.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { sb.append("\t\"").append(this.getTitle()).append("\"->\"").append(methods[i].getName()) .append("\" with ").append(methods[i].getGenericParameterTypes().length) .append(" input parameters").append("\n"); } throw new NoSuchMethodException(sb.toString()); } catch (InvocationTargetException ex) { throw ex.getCause(); } }
From source file:com.palantir.leader.proxy.ToggleableExceptionProxy.java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (throwException.get()) { throw Throwables.rewrap(exception); }/*from w w w . j a v a 2 s . c om*/ try { return method.invoke(delegate, args); } catch (InvocationTargetException e) { throw e.getCause(); } }
From source file:com.github.parisoft.resty.response.ResponseInvocationHandler.java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final Class<?> declaringClass = method.getDeclaringClass(); try {/*from w w w . j av a2s . c o m*/ if (declaringClass.isAssignableFrom(HttpResponse.class)) { return method.invoke(httpResponse, args); } if (declaringClass.isAssignableFrom(EntityReader.class)) { return method.invoke(entityReader, args); } if (declaringClass.isAssignableFrom(HttpResponseExtension.class)) { responseExtension.setResponse((Response) proxy); return method.invoke(responseExtension, args); } } catch (InvocationTargetException e) { throw e.getCause(); } return null; }