List of usage examples for java.lang.reflect InvocationTargetException getTargetException
public Throwable getTargetException()
From source file:com.amazonaws.hal.client.HalResourceInvocationHandler.java
/** *//*from w w w . j av a 2 s.c om*/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (halResource == null || !halResource.isDefined()) { halResource = halClient.getHalResource(resourcePath); } try { Method resourceInfoMethod = ResourceInfo.class.getMethod(method.getName(), method.getParameterTypes()); return resourceInfoMethod.invoke(halResource, args); } catch (NoSuchMethodException ignore) { // If the method is not defined in ResourceInfo, we handle it below } catch (InvocationTargetException e) { throw e.getTargetException(); } Link link; if ((link = method.getAnnotation(Link.class)) != null) { switch (link.method()) { case GET: if (List.class.isAssignableFrom(method.getReturnType())) { //noinspection unchecked return new HalLinkList(halResource, link.relation(), (Class) getCollectionType(method.getGenericReturnType(), 0, ResourceInfo.class), halClient); } else if (Map.class.isAssignableFrom(method.getReturnType())) { //noinspection unchecked return new HalLinkMap(halResource, link.relation(), link.keyField(), (Class) getCollectionType(method.getGenericReturnType(), 1, ResourceInfo.class), halClient); } else { return halClient.getResource(halResource, method.getReturnType(), getRelationHref(link, args == null ? EMPTY_ARGS : args, method.getParameterAnnotations()), false); } case POST: if (args == null) { throw new IllegalArgumentException("POST operations require a representation argument."); } return halClient.postResource(method.getReturnType(), getRelationHref(link, args, method.getParameterAnnotations()), args[0]); case PUT: if (args == null) { throw new IllegalArgumentException("PUT operations require a representation argument."); } return halClient.putResource(method.getReturnType(), getRelationHref(link, args, method.getParameterAnnotations()), args[0]); case DELETE: return halClient.deleteResource(method.getReturnType(), getRelationHref(link, args == null ? EMPTY_ARGS : args, method.getParameterAnnotations())); default: throw new UnsupportedOperationException("Unexpected HTTP method: " + link.method()); } } else if (method.getName().startsWith("get")) { String propertyName = getPropertyName(method.getName()); Object property = halResource.getProperty(propertyName); Type returnType = method.getGenericReturnType(); // When a value is accessed, it's intended type can either be a // class or some other type (like a ParameterizedType). // // If the target type is a class and the value is of that type, // we return it. If the value is not of that type, we convert // it and store the converted value (trusting it was converted // properly) back to the backing store. // // If the target type is not a class, it may be ParameterizedType // like List<T> or Map<K, V>. We check if the value is already // a converting type and if so, we return it. If the value is // not, we convert it and if it's now a converting type, we store // the new value in the backing store. if (returnType instanceof Class) { if (!((Class) returnType).isInstance(property)) { property = convert(returnType, property); //noinspection unchecked halResource.addProperty(propertyName, property); } } else { if (!(property instanceof ConvertingMap) && !(property instanceof ConvertingList)) { property = convert(returnType, property); if (property instanceof ConvertingMap || property instanceof ConvertingList) { //noinspection unchecked halResource.addProperty(propertyName, property); } } } return property; } else if (method.getName().equals("toString") && args == null) { return resourcePath; } else if (method.getName().equals("equals") && args != null && args.length == 1) { HalResourceInvocationHandler other; try { other = (HalResourceInvocationHandler) Proxy.getInvocationHandler(args[0]); } catch (IllegalArgumentException e) { // argument is not a proxy return false; } catch (ClassCastException e) { // argument is the wrong type of proxy return false; } return resourcePath.equals(other.resourcePath); } else if (method.getName().equals("hashCode") && args == null) { return resourcePath.hashCode(); } throw new UnsupportedOperationException("Don't know how to handle '" + method.getName() + "'"); }
From source file:net.mindengine.oculus.frontend.web.controllers.api.ApiController.java
@Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); response.addHeader("Content-Type", "application/json"); if (userIsAuthorized(request)) { MatchedMethod matchedMethod = findMatchedMethod(request); Object[] arguments = createMethodArguments(matchedMethod, request, response); try {//from w ww. j a v a 2 s .co m Object result = matchedMethod.getMethod().invoke(this, arguments); if (matchedMethod.getMethod().getReturnType().equals(Void.TYPE)) { return null; } else model.put("response", result); } catch (InvocationTargetException e) { response.setStatus(400); model.put("response", new ApiError( e.getTargetException().getClass().getName() + ": " + e.getTargetException().getMessage())); e.getTargetException().printStackTrace(); } } else { response.setStatus(401); model.put("response", new ApiError("You are not authorized for this request.")); } return new ModelAndView("jsonView", model); }
From source file:com.google.code.pathlet.web.PathletAjaxProcessor.java
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { setCharset(request, response);//w w w. j a v a 2 s .c om try { InstanceSpace requestSpace = container.getSpace(REQUEST_SCOPE, request, true); //Add the request and response instance into this InstanceSpace on default path requestSpace.addInstance(RESPONSE_PATH, response); requestSpace.addInstance(REQUEST_PATH, request); String servletPath = getServletPath(request); Path requestPath = new Path(servletPath); //1. Get method name if (!suffix.equals(requestPath.getSuffix())) { throw new ResourceException("Error path suffix! The path must be end with '." + suffix + "'"); } String methodName = requestPath.getNameWithoutSuffix(); //2. Get action path String actionPathPart = requestPath.getParent().getFullPath(); Path actionPath; if (prefixPath != null) { actionPath = new Path(prefixPath, actionPathPart.substring(1, actionPathPart.length() - 1)); //remove the first and last char '/' } else { actionPath = new Path(actionPathPart.substring(0, actionPathPart.length() - 1)); //remove the last char '/' } //3. Get action target object Object actionObj = requestSpace.getInstance(actionPath); if (actionObj == null) { throw new ResourceException("Get NULL resource target from the path:" + requestPath.toString()); } //4. Get execution method Method method = actionObj.getClass().getMethod(methodName); if (method == null) { throw new ResourceException("Failed to get action method: " + methodName); } //5. Process request // Set action target object properties value for (RequestProcessor requestProcessor : requestProcessors) { if (requestProcessor.process(requestPath, actionObj, request)) { break; } } //6. Execute action method Object returnResult = method.invoke(actionObj); //7. Proceed return result object and HttpServletResponse object. if (returnResult != null) { for (ResponseProcessor processor : resultResponseProcessors) { if (processor.processResult(requestPath, returnResult, response)) { break; } } } } catch (InvocationTargetException ite) { //If exception wrapped by InvocationTargetException, find the target exception and throw it. Throwable targetEx = ite.getTargetException(); log.fatal(targetEx.getMessage(), targetEx); throw new ServletException(targetEx); } catch (Exception re) { log.fatal(re.getMessage(), re); throw new ServletException(re); } finally { container.destroySpace(REQUEST_SCOPE, request); } }
From source file:com.jigsforjava.web.controller.MultiActionController.java
/** * Invoke the selected exception handler. * // www. j a v a 2 s . com * @param handler handler method to invoke * @param request current HTTP request * @param response current HTTP response * @param ex the exception that got thrown * @return The ModelAndView instance appropriate to render to the end user. */ private ModelAndView invokeExceptionHandler(Method handler, HttpServletRequest request, HttpServletResponse response, Throwable ex) throws Exception { if (handler == null) { throw new NestedServletException("No handler for exception", ex); } try { ViewContext returnValue = (ViewContext) handler.invoke(this, new Object[] { request, response, ex }); return (returnValue != null ? returnValue.asModelAndView() : null); } catch (InvocationTargetException ex2) { Throwable targetEx = ex2.getTargetException(); if (targetEx instanceof Exception) { throw (Exception) targetEx; } if (targetEx instanceof Error) { throw (Error) targetEx; } // Should never happen! throw new NestedServletException("Unknown Throwable type encountered", targetEx); } }
From source file:BrowserLauncher.java
/** * Attempts to locate the default web browser on the local system. Caches results so it * only locates the browser once for each use of this class per JVM instance. * @return The browser for the system. Note that this may not be what you would consider * to be a standard web browser; instead, it's the application that gets called to * open the default web browser. In some cases, this will be a non-String object * that provides the means of calling the default browser. */// ww w . ja v a2s. c om private static Object locateBrowser() { if (browser != null) { return browser; } switch (jvm) { case MRJ_2_0: try { Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR }); Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode }); Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT }); Object appleEvent = appleEventConstructor.newInstance( new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID }); // Don't set browser = appleEvent because then the next time we call // locateBrowser(), we'll get the same AppleEvent, to which we'll already have // added the relevant parameter. Instead, regenerate the AppleEvent every time. // There's probably a way to do this better; if any has any ideas, please let // me know. return appleEvent; } catch (IllegalAccessException iae) { browser = null; errorMessage = iae.getMessage(); return browser; } catch (InstantiationException ie) { browser = null; errorMessage = ie.getMessage(); return browser; } catch (InvocationTargetException ite) { browser = null; errorMessage = ite.getMessage(); return browser; } case MRJ_2_1: File systemFolder; try { systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType }); } catch (IllegalArgumentException iare) { browser = null; errorMessage = iare.getMessage(); return browser; } catch (IllegalAccessException iae) { browser = null; errorMessage = iae.getMessage(); return browser; } catch (InvocationTargetException ite) { browser = null; errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); return browser; } String[] systemFolderFiles = systemFolder.list(); // Avoid a FilenameFilter because that can't be stopped mid-list for (int i = 0; i < systemFolderFiles.length; i++) { try { File file = new File(systemFolder, systemFolderFiles[i]); if (!file.isFile()) { continue; } // We're looking for a file with a creator code of 'MACS' and // a type of 'FNDR'. Only requiring the type results in non-Finder // applications being picked up on certain Mac OS 9 systems, // especially German ones, and sending a GURL event to those // applications results in a logout under Multiple Users. Object fileType = getFileType.invoke(null, new Object[] { file }); if (FINDER_TYPE.equals(fileType.toString())) { Object fileCreator = getFileCreator.invoke(null, new Object[] { file }); if (FINDER_CREATOR.equals(fileCreator.toString())) { browser = file.toString(); // Actually the Finder, but that's OK return browser; } } } catch (IllegalArgumentException iare) { browser = browser; errorMessage = iare.getMessage(); return null; } catch (IllegalAccessException iae) { browser = null; errorMessage = iae.getMessage(); return browser; } catch (InvocationTargetException ite) { browser = null; errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); return browser; } } browser = null; break; case MRJ_3_0: case MRJ_3_1: browser = ""; // Return something non-null break; case WINDOWS_NT: browser = "cmd.exe"; break; case WINDOWS_9x: browser = "command.com"; break; case OTHER: default: browser = "firefox"; break; } return browser; }
From source file:bboss.org.apache.velocity.runtime.parser.node.ASTMethod.java
/** * invokes the method. Returns null if a problem, the * actual return if the method returns something, or * an empty string "" if the method returns void * @param o/*from www.ja v a 2 s.c o m*/ * @param context * @return Result or null. * @throws MethodInvocationException */ public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException { /* * new strategy (strategery!) for introspection. Since we want * to be thread- as well as context-safe, we *must* do it now, * at execution time. There can be no in-node caching, * but if we are careful, we can do it in the context. */ Object[] params = new Object[paramCount]; /* * sadly, we do need recalc the values of the args, as this can * change from visit to visit */ final Class[] paramClasses = paramCount > 0 ? new Class[paramCount] : ArrayUtils.EMPTY_CLASS_ARRAY; for (int j = 0; j < paramCount; j++) { params[j] = jjtGetChild(j + 1).value(context); if (params[j] != null) { paramClasses[j] = params[j].getClass(); } } VelMethod method = ClassUtils.getMethod(methodName, params, paramClasses, o, context, this, strictRef); if (method == null) return null; try { /* * get the returned object. It may be null, and that is * valid for something declared with a void return type. * Since the caller is expecting something to be returned, * as long as things are peachy, we can return an empty * String so ASTReference() correctly figures out that * all is well. */ Object obj = method.invoke(o, params); if (obj == null) { if (method.getReturnType() == Void.TYPE) { return ""; } } return obj; } catch (InvocationTargetException ite) { return handleInvocationException(o, context, ite.getTargetException()); } /** Can also be thrown by method invocation **/ catch (IllegalArgumentException t) { return handleInvocationException(o, context, t); } /** * pass through application level runtime exceptions */ catch (RuntimeException e) { throw e; } catch (Exception e) { String msg = "ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.getClass(); log.error(msg, e); throw new VelocityException(msg, e); } }
From source file:com.impetus.kundera.proxy.cglib.CglibLazyInitializer.java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (constructed) { String methodName = method.getName(); int params = args.length; if (params == 0) { if (isUninitialized() && method.equals(getIdentifierMethod)) { return getIdentifier(); }// w w w. j a v a 2 s. c o m else if ("getKunderaLazyInitializer".equals(methodName)) { return this; } } Object target = getImplementation(); try { final Object returnValue; if (method.isAccessible()) { if (!method.getDeclaringClass().isInstance(target)) { throw new ClassCastException(target.getClass().getName()); } returnValue = method.invoke(target, args); } else { if (!method.isAccessible()) { method.setAccessible(true); } returnValue = method.invoke(target, args); } return returnValue == target ? proxy : returnValue; } catch (InvocationTargetException ite) { throw ite.getTargetException(); } } else { // while constructor is running throw new LazyInitializationException("unexpected case hit, method=" + method.getName()); } }
From source file:com.github.pfmiles.org.apache.velocity.runtime.parser.node.ASTMethod.java
/** * invokes the method. Returns null if a problem, the * actual return if the method returns something, or * an empty string "" if the method returns void * @param o/* www . ja va2 s. c o m*/ * @param context * @return Result or null. * @throws MethodInvocationException */ public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException { /* * new strategy (strategery!) for introspection. Since we want * to be thread- as well as context-safe, we *must* do it now, * at execution time. There can be no in-node caching, * but if we are careful, we can do it in the context. */ Object[] params = new Object[paramCount]; /* * sadly, we do need recalc the values of the args, as this can * change from visit to visit */ Class[] paramClasses = paramCount > 0 ? new Class[paramCount] : ArrayUtils.EMPTY_CLASS_ARRAY; for (int j = 0; j < paramCount; j++) { params[j] = jjtGetChild(j + 1).value(context); if (params[j] != null) { paramClasses[j] = params[j].getClass(); } } // recParsing if (ParseUtil.class.equals(o) && "recParsing".equals(methodName) && paramCount == 1) { Object[] temp = params; params = new Object[2]; params[0] = temp[0]; params[1] = this.getTemplateName(); Class[] clsTemp = paramClasses; paramClasses = new Class[2]; paramClasses[0] = clsTemp[0]; paramClasses[1] = String.class; } VelMethod method = ClassUtils.getMethod(methodName, params, paramClasses, o, context, this, strictRef); if (method == null) return null; try { /* * get the returned object. It may be null, and that is * valid for something declared with a void return type. * Since the caller is expecting something to be returned, * as long as things are peachy, we can return an empty * String so ASTReference() correctly figures out that * all is well. */ Object obj = method.invoke(o, params); if (obj == null) { if (method.getReturnType() == Void.TYPE) { return ""; } } return obj; } catch (InvocationTargetException ite) { return handleInvocationException(o, context, ite.getTargetException()); } /** Can also be thrown by method invocation **/ catch (IllegalArgumentException t) { return handleInvocationException(o, context, t); } /** * pass through application level runtime exceptions */ catch (RuntimeException e) { throw e; } catch (Exception e) { String msg = "ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.getClass(); log.error(msg, e); throw new VelocityException(msg, e); } }
From source file:com.netsteadfast.greenstep.aspect.HessianServiceProxyAspect.java
private Object proxyProcess(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable { MethodSignature signature = (MethodSignature) pjp.getSignature(); Annotation[] annotations = pjp.getTarget().getClass().getAnnotations(); String serviceId = AspectConstants.getServiceId(annotations); /**/*from w w w . j a v a2s.com*/ * ???? service-bean */ if (!GreenStepHessianUtils.isProxyServiceId(serviceId)) { //logger.info( "reject proxy service: " + serviceId ); return pjp.proceed(); } String userId = StringUtils.defaultString((String) SecurityUtils.getSubject().getPrincipal()); if (GreenStepHessianUtils.getConfigHessianHeaderCheckValueModeEnable()) { /** * ???? service-bean */ if (StringUtils.isBlank(userId)) { logger.warn("no userId"); pjp.proceed(); } /** * ???? service-bean */ if (GreenStepHessianUtils.isProxyBlockedAccountId(userId)) { logger.warn("reject proxy service: " + serviceId + " , blocked userId: " + userId); return pjp.proceed(); } } String serviceInterfacesName = ""; Class<?> serviceInterfaces[] = pjp.getTarget().getClass().getInterfaces(); for (Class<?> clazz : serviceInterfaces) { if (clazz.getName().indexOf(".service.") > -1) { serviceInterfacesName = clazz.getName(); } } if (StringUtils.isBlank(serviceInterfacesName)) { logger.error("error no service interface: " + serviceId); throw new Exception("error no service interface: " + serviceId); } String url = GreenStepHessianUtils.getServiceUrl(serviceId); String theSystemPath = ApplicationSiteUtils.getHost(Constants.getSystem()) + "/" + ApplicationSiteUtils.getContextPath(Constants.getSystem()); /** * ?????, ? HessianServiceProxyAspect ? (server-remote???) * http://127.0.0.1:8080/ * hessian.enable=Y ???, ?url hessian.serverUrl=http://127.0.0.1:8080/ * */ if (url.indexOf(theSystemPath) > -1) { logger.error("cannot open same-server. now system contextPath = " + theSystemPath + " , but proxy url = " + url); throw new Exception("cannot open same-server. now system contextPath = " + theSystemPath + " , but proxy url = " + url); } logger.info("proxy url = " + url); HessianProxyFactory factory = null; Object proxyServiceObject = null; if (GreenStepHessianUtils.getConfigHessianHeaderCheckValueModeEnable()) { // ?checkValue? factory = new GreenStepHessianProxyFactory(); ((GreenStepHessianProxyFactory) factory) .setHeaderCheckValue(GreenStepHessianUtils.getEncAuthValue(userId)); proxyServiceObject = ((GreenStepHessianProxyFactory) factory) .createForHeaderMode(Class.forName(serviceInterfacesName), url); } else { // ?checkValue? factory = new HessianProxyFactory(); proxyServiceObject = factory.create(Class.forName(serviceInterfacesName), url); } Method[] proxyObjectMethods = proxyServiceObject.getClass().getMethods(); Method proxyObjectMethod = null; if (null == proxyObjectMethods) { logger.error("error no find proxy method: " + serviceId); throw new Exception("error no find proxy method: " + serviceId); } for (Method m : proxyObjectMethods) { if (m.getName().equals(signature.getMethod().getName()) && Arrays.equals(m.getParameterTypes(), signature.getMethod().getParameterTypes())) { proxyObjectMethod = m; } } if (null == proxyObjectMethod) { logger.error("error no execute proxy method: " + serviceId); throw new Exception("error no execute proxy method: " + serviceId); } Object resultObj = null; try { resultObj = proxyObjectMethod.invoke(proxyServiceObject, pjp.getArgs()); this.setReCalculateSizePageOfForPageFindGridResult(resultObj, pjp.getArgs()); } catch (InvocationTargetException e) { if (e.getMessage() != null) { throw new ServiceException(e.getMessage().toString()); } if (e.getTargetException().getMessage() != null) { throw new ServiceException(e.getTargetException().getMessage().toString()); } throw e; } catch (Exception e) { logger.error(e.getMessage().toString()); throw e; } logger.info("proxy success: " + serviceId + " method: " + proxyObjectMethod.getName()); return resultObj; }
From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java
/** * Returns a new instance of the given class if its a public non abstract class which has a public zero argument constructor otherwise returns null *//*from www.jav a2 s . c o m*/ protected Object tryCreateInstance(Class<?> type) { Object answer = null; int modifiers = type.getModifiers(); if (!Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !type.isInterface()) { // if its a concrete class with no args make one Constructor<?> constructor = null; try { constructor = type.getConstructor(); } catch (NoSuchMethodException e) { // ignore } if (constructor != null) { if (Modifier.isPublic(constructor.getModifiers())) { try { answer = constructor.newInstance(); } catch (InstantiationException e) { throw new ProvisionException("Failed to instantiate " + constructor, e); } catch (IllegalAccessException e) { throw new ProvisionException("Failed to instantiate " + constructor, e); } catch (InvocationTargetException ie) { Throwable e = ie.getTargetException(); throw new ProvisionException("Failed to instantiate " + constructor, e); } } } } return answer; }