List of usage examples for java.lang.reflect InvocationTargetException getCause
public Throwable getCause()
From source file:org.jspresso.framework.util.accessor.AbstractPropertyAccessor.java
/** * Sets a property value, taking care of Map vs bean implementation and nested * properties./*from w ww .ja v a 2s . com*/ * * @param target * the target object. * @param value * the value to set. * @throws IllegalAccessException * whenever an exception occurs. * @throws InvocationTargetException * whenever an exception occurs. * @throws NoSuchMethodException * whenever an exception occurs. */ @Override public void setValue(Object target, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { try { Object finalTarget = getLastNestedTarget(target, getProperty()); if (finalTarget != null) { if (finalTarget instanceof Map<?, ?>) { if (PropertyHelper.getPropertyNames(finalTarget.getClass()).contains(getLastNestedProperty())) { // We are explicitly on a bean property. Do not use // PROPERTY_UTILS_BEAN.getProperty since it will detect that the // target is a Map and access its properties as such. PROPERTY_UTILS_BEAN.setSimpleProperty(finalTarget, getLastNestedProperty(), value); } else { PROPERTY_UTILS_BEAN.setProperty(finalTarget, getLastNestedProperty(), value); } } else { PROPERTY_UTILS_BEAN.setProperty(finalTarget, getLastNestedProperty(), value); } } } catch (InvocationTargetException ex) { // un-nest invocation target exceptions so that the original // one can be correctly handled by the exception handlers. if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw ex; } }
From source file:io.milton.http.annotated.AbstractAnnotationHandler.java
protected Object invoke(ControllerMethod cm, AnnoResource sourceRes, Object... values) throws NotAuthorizedException, BadRequestException, NotFoundException, Exception { try {//from w ww. j a v a2s .com Object[] args; if (values == null || values.length == 0) { args = annoResourceFactory.buildInvokeArgs(sourceRes, cm.method); } else { args = annoResourceFactory.buildInvokeArgs(sourceRes, cm.method, values); } return cm.method.invoke(cm.controller, args); } catch (java.lang.reflect.InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof NotAuthorizedException) { NotAuthorizedException nae = (NotAuthorizedException) cause; if (nae.getResource() == null) { throw new NotAuthorizedException(sourceRes, nae); // need exception with resource so we can generate challenge } throw nae; } else if (cause instanceof BadRequestException) { throw (BadRequestException) cause; } else if (cause instanceof NotFoundException) { throw (NotFoundException) cause; } else if (cause instanceof ConflictException) { throw (ConflictException) cause; } throw e; } catch (NotAuthorizedException e) { throw e; } catch (BadRequestException e) { throw e; } catch (NotFoundException e) { throw e; } catch (Exception e) { throw new Exception("Method: " + cm, e); } }
From source file:de.matzefratze123.heavyspleef.commands.base.CommandManagerService.java
protected void executeCommand(CommandContext context) { Method method = context.getCommand().getCommandMethod(); Object instance = context.getCommand().getCommandClassInstance(); boolean accessible = method.isAccessible(); method.setAccessible(true);/* w ww. j a va 2 s . c o m*/ //Analyse the method //Default method format is: methodName(CommandContext) try { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { //No parameters in this method, so just invoke it method.invoke(instance); } else { Object[] parameterValues = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class<?> parameterType = parameterTypes[i]; if (parameterType == CommandContext.class) { parameterValues[i] = context; } else if (plugin.getClass() == parameterType) { parameterValues[i] = plugin; } else if (parameterType.isPrimitive()) { parameterValues[i] = getDefaultPrimitiveValue(parameterType); } else { for (Object arg : args) { if (parameterType.isInstance(arg)) { parameterValues[i] = arg; break; } } } } method.invoke(instance, parameterValues); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof CommandException) { ((CommandException) cause).sendToPlayer(context.getSender()); } else { logger.log(Level.SEVERE, "Unhandled exception executing command \"" + context.getCommand().getName() + "\"", cause); } } catch (IllegalAccessException | IllegalArgumentException e) { logger.log(Level.SEVERE, "Could not invoke command method for '" + context.getCommand().getFullyQualifiedName() + "'", e); } catch (Exception e) { logger.log(Level.SEVERE, "Unhandled exception executing command '" + context.getCommand().getFullyQualifiedName() + "'", e); } finally { method.setAccessible(accessible); } }
From source file:io.fluo.api.config.FluoConfigurationTest.java
@Test public void testIAE() { FluoConfiguration config = new FluoConfiguration(); String[] positiveIntMethods = { "setLoaderQueueSize", "setLoaderThreads", "setOracleInstances", "setOracleMaxMemory", "setOracleNumCores", "setWorkerInstances", "setWorkerMaxMemory", "setWorkerNumCores", "setWorkerThreads", "setZookeeperTimeout" }; for (String methodName : positiveIntMethods) { try {/*from w w w . j ava2 s.c om*/ config.getClass().getMethod(methodName, int.class).invoke(config, -5); Assert.fail(); } catch (InvocationTargetException e) { if (!(e.getCause() instanceof IllegalArgumentException)) { Assert.fail(); } } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } String[] nonEmptyMethods = { "setAccumuloInstance", "setAccumuloTable", "setAccumuloUser", "setAccumuloZookeepers", "setAdminClass", "setClientClass", "setMetricsYamlBase64", "setMiniClass", "setMiniDataDir", "setInstanceZookeepers" }; for (String methodName : nonEmptyMethods) { try { config.getClass().getMethod(methodName, String.class).invoke(config, ""); Assert.fail(); } catch (InvocationTargetException e) { if (!(e.getCause() instanceof IllegalArgumentException)) { Assert.fail(); } } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } }
From source file:org.codekaizen.vtj.AbstractValueTypeTest.java
private void validateConstruction() throws IllegalStateException, SecurityException, IllegalArgumentException { if (enumType) { // assume it is a Java 5 enum try {/*from w w w . j av a2 s . c o m*/ final Method m = testClass.getMethod("values", (Class<?>[]) null); final Enum<?>[] vals = (Enum<?>[]) m.invoke((Object) null); defaultEnum = (EnumValueType<?>) vals[0]; } catch (final Exception e) { throw new IllegalStateException(e); } } else { try { constructor = getTestClass().getConstructor(constructorArgClasses); } catch (final NoSuchMethodException nsme) { throw new IllegalArgumentException("constructor parameter classes are not valid", nsme); } try { constructor.newInstance(constructorArgs); } catch (InvocationTargetException ite) { throw new IllegalArgumentException("constructor arguments are not valid", ite.getCause()); } catch (final Exception e) { throw new IllegalStateException("unable to construct test object", e); } } }
From source file:com.doitnext.http.router.DefaultInvoker.java
@Override public InvokeResult invokeMethod(HttpMethod method, PathMatch pm, HttpServletRequest req, HttpServletResponse resp) throws ServletException { String terminus = pm.getMatchedPath().getTerminus(); // Extract variables from the path Map<String, PathElement> variableMatches = new HashMap<String, PathElement>(); for (int x = 0; x < pm.getMatchedPath().size(); x++) { PathElement p = pm.getMatchedPath().get(x); if (!p.getType().equalsIgnoreCase("LITERAL")) { variableMatches.put(p.getName(), p); }//from w w w .j a va2s . c o m } Route route = pm.getRoute(); Method implMethod = route.getImplMethod(); Annotation[][] parameterAnnotations = implMethod.getParameterAnnotations(); Class<?>[] parameterTypes = implMethod.getParameterTypes(); Object[] arguments = new Object[parameterTypes.length]; try { // First map annotated parameters, and HttpServletRequest // and HttpServletResponse parameters to arguments. mapParametersToArguments(parameterAnnotations, parameterTypes, variableMatches, req, resp, terminus, pm, arguments); if (logger.isDebugEnabled()) { logger.debug(String.format("Invoking %s", route)); } Object invocationResult = implMethod.invoke(route.getImplInstance(), arguments); if (logger.isTraceEnabled()) { logger.trace(String.format("Returned %s from %s", objectMapper.writeValueAsString(invocationResult), route)); } if (route.getSuccessHandler().handleResponse(pm, req, resp, invocationResult)) return InvokeResult.METHOD_SUCCESS; else return InvokeResult.METHOD_SUCCESS_UNHANDLED; } catch (InvocationTargetException ite) { if (logger.isDebugEnabled()) { logger.debug(String.format("Invocation threw a %s %s", ite.getCause().getClass().getSimpleName(), ite.getCause().getMessage())); } if (route.getErrorHandler().handleResponse(pm, req, resp, ite.getCause())) return InvokeResult.METHOD_ERROR; else return InvokeResult.METHOD_ERROR_UNHANDLED; } catch (Exception e) { throw new ServletException(String.format("Error invoking %s", route), e); } }
From source file:org.apache.axis2.rpc.receivers.RPCMessageReceiver.java
/** * reflect and get the Java method - for each i'th param in the java method - get the first * child's i'th child -if the elem has an xsi:type attr then find the deserializer for it - if * not found, lookup deser for th i'th param (java type) - error if not found - deserialize & * save in an object array - end for// w w w .ja v a2 s. c o m * <p/> * - invoke method and get the return value * <p/> * - look up serializer for return value based on the value and type * <p/> * - create response msg and add return value as grand child of <soap:body> * * @param inMessage incoming MessageContext * @param outMessage outgoing MessageContext * @throws AxisFault */ public void invokeBusinessLogic(MessageContext inMessage, MessageContext outMessage) throws AxisFault { Method method = null; try { // get the implementation class for the Web Service Object obj = getTheImplementationObject(inMessage); Class implClass = obj.getClass(); AxisOperation op = inMessage.getOperationContext().getAxisOperation(); method = (Method) (op.getParameterValue("myMethod")); // If the declaring class has changed, then the cached method is invalid, so we need to // reload it. This is to fix AXIS2-3947. if (method != null && method.getDeclaringClass() != implClass) { method = null; } AxisService service = inMessage.getAxisService(); OMElement methodElement = inMessage.getEnvelope().getBody().getFirstElement(); AxisMessage inAxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE); String messageNameSpace = null; if (method == null) { String methodName = op.getName().getLocalPart(); Method[] methods = implClass.getMethods(); for (Method method1 : methods) { if (method1.isBridge()) { continue; } if (method1.getName().equals(methodName)) { method = method1; op.addParameter("myMethod", method); break; } } if (method == null) { throw new AxisFault("No such method '" + methodName + "' in class " + implClass.getName()); } } Object resObject = null; if (inAxisMessage != null) { resObject = RPCUtil.invokeServiceClass(inAxisMessage, method, obj, messageNameSpace, methodElement, inMessage); } SOAPFactory fac = getSOAPFactory(inMessage); // Handling the response AxisMessage outaxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); if (outaxisMessage != null && outaxisMessage.getElementQName() != null) { messageNameSpace = outaxisMessage.getElementQName().getNamespaceURI(); } else { messageNameSpace = service.getTargetNamespace(); } OMNamespace ns = fac.createOMNamespace(messageNameSpace, service.getSchemaTargetNamespacePrefix()); SOAPEnvelope envelope = fac.getDefaultEnvelope(); OMElement bodyContent = null; if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(op.getMessageExchangePattern())) { OMElement bodyChild = fac.createOMElement(outMessage.getAxisMessage().getName(), ns); envelope.getBody().addChild(bodyChild); outMessage.setEnvelope(envelope); return; } Parameter generateBare = service.getParameter(Java2WSDLConstants.DOC_LIT_BARE_PARAMETER); if (generateBare != null && "true".equals(generateBare.getValue())) { RPCUtil.processResonseAsDocLitBare(resObject, service, envelope, fac, ns, bodyContent, outMessage); } else { RPCUtil.processResponseAsDocLitWrapped(resObject, service, method, envelope, fac, ns, bodyContent, outMessage); } outMessage.setEnvelope(envelope); } catch (InvocationTargetException e) { String msg = null; Throwable cause = e.getCause(); if (cause != null) { msg = cause.getMessage(); } if (msg == null) { msg = "Exception occurred while trying to invoke service method " + (method != null ? method.getName() : "null"); } if (cause instanceof AxisFault) { log.debug(msg, cause); throw (AxisFault) cause; } Class[] exceptionTypes = method.getExceptionTypes(); for (Class exceptionType : exceptionTypes) { if (exceptionType.getName().equals(cause.getClass().getName())) { // this is an bussiness logic exception so handle it properly String partQName = inMessage.getAxisService().getName() + getSimpleClassName(exceptionType); TypeTable typeTable = inMessage.getAxisService().getTypeTable(); QName elementQName = typeTable.getQNamefortheType(partQName); SOAPFactory fac = getSOAPFactory(inMessage); OMElement exceptionElement = fac.createOMElement(elementQName); if (exceptionType.getName().equals(Exception.class.getName())) { // this is an exception class. so create a element by hand and add the message OMElement innterExceptionElement = fac.createOMElement(elementQName); OMElement messageElement = fac.createOMElement("Message", inMessage.getAxisService().getTargetNamespace(), null); messageElement.setText(cause.getMessage()); innterExceptionElement.addChild(messageElement); exceptionElement.addChild(innterExceptionElement); } else { // if it is a normal bussiness exception we need to generate the schema assuming it is a pojo QName innerElementQName = new QName(elementQName.getNamespaceURI(), getSimpleClassName(exceptionType)); XMLStreamReader xr = BeanUtil.getPullParser(cause, innerElementQName, typeTable, true, false); StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(), new StreamWrapper(xr)); OMElement documentElement = stAXOMBuilder.getDocumentElement(); exceptionElement.addChild(documentElement); } AxisFault axisFault = new AxisFault(cause.getMessage()); axisFault.setDetail(exceptionElement); throw axisFault; } } log.error(msg, e); throw new AxisFault(msg, e); } catch (RuntimeException e) { log.error(e.getMessage(), e); throw AxisFault.makeFault(e); } catch (Exception e) { String msg = "Exception occurred while trying to invoke service method " + (method != null ? method.getName() : "null"); log.error(msg, e); throw AxisFault.makeFault(e); } }
From source file:sf.net.experimaestro.manager.scripting.GenericFunction.java
public Object call(LanguageContext lcx, ScriptContext cx, Object thisObj, Object[] args) { Declaration argmax = null;//from w w w .j a v a 2s .c o m int max = Integer.MIN_VALUE; Function argmaxConverters[] = new Function[args.length]; Function converters[] = new Function[args.length]; int argMaxOffset = 0; for (Declaration method : declarations()) { MutableInt offset = new MutableInt(0); int score = score(lcx, cx, method, args, converters, offset); if (score > max) { max = score; argmax = method; Function tmp[] = argmaxConverters; argMaxOffset = offset.intValue(); argmaxConverters = converters; converters = tmp; } } if (argmax == null) { String context = ""; if (thisObj instanceof JSBaseObject) context = " in an object of class " + ClassDescription.getClassName(thisObj.getClass()); throw ScriptRuntime.typeError(String.format("Could not find a matching method for %s(%s)%s", getName(), Output.toString(", ", args, o -> o.getClass().toString()), context)); } // Call the constructor try { Object[] transformedArgs = transform(lcx, cx, argmax, args, argmaxConverters, argMaxOffset); final Object result = argmax.invoke(transformedArgs); return result; } catch (InvocationTargetException e) { if (e.getCause() instanceof XPMRhinoException) { throw (XPMRhinoException) e.getCause(); } throw new WrappedException(new XPMRhinoException(e.getCause())); } catch (Throwable e) { throw new WrappedException(new XPMRhinoException(e)); } }
From source file:org.codekaizen.vtj.hibernate3.AbstractValueTypeUserTypeTest.java
private void validateConstruction() throws IllegalStateException, SecurityException, IllegalArgumentException { if (this.enumType) { // assume it is a Java 5 enum try {/* ww w . j a v a 2 s . co m*/ Method m = this.valueClazz.getMethod("values", (Class<?>[]) null); Enum<?>[] vals = (Enum<?>[]) m.invoke((Object) null); this.defaultEnum = (EnumValueType<?>) vals[0]; } catch (Exception e) { throw new IllegalStateException(e); } } else { try { this.constructor = this.valueClazz.getConstructor(this.constructorArgClasses); } catch (NoSuchMethodException nsme) { throw new IllegalArgumentException("constructor parameter classes are not valid", nsme); } try { this.constructor.newInstance(this.constructorArgs); } catch (InvocationTargetException ite) { throw new IllegalArgumentException("constructor arguments are not valid", ite.getCause()); } catch (Exception e) { throw new IllegalStateException("unable to construct test object", e); } } }
From source file:com.amazonaws.mturk.service.axis.AWSService.java
/** * /*from w w w. j a va 2 s. c o m*/ * @param m - Message structure which contains the details for making wsdl operation call * @return Reply structure containing results and errors from the wsdl operation call * @throws ServiceException */ public Reply executeRequestMessage(Message m) throws ServiceException { String axisMethodName = m.getMethodName(); Object requests = m.getRequests(); String credential = m.getCredential(); String resultAccessorName = m.getResultAccessorName(); try { Class bodyClass; Class responseClass; Class requestClass; Object body; // Construct the request body bodyClass = Class.forName(getPackagePrefix() + axisMethodName); body = bodyClass.newInstance(); responseClass = Class.forName(getPackagePrefix() + axisMethodName + RESPONSE_SUFFIX); requestClass = Class.forName(getPackagePrefix() + axisMethodName + REQUEST_SUFFIX); Class requestArrayClass = Array.newInstance(requestClass, 0).getClass(); Object requestArray = requestArrayClass.cast(requests); Method setRequest = bodyClass.getMethod(SET_REQUEST_METHOD_NAME, new Class[] { requestArrayClass }); setRequest.invoke(body, requestArray); Calendar now = null; String signature = null; synchronized (AWSService.class) { Method setAWSAccessKeyId = bodyClass.getMethod(SET_AWS_ACCESS_KEY_ID_METHOD_NAME, STRING_CLASS_ARRAY); setAWSAccessKeyId.invoke(body, getAWSAccessKeyId()); Method setValidate = bodyClass.getMethod(SET_VALIDATE_METHOD_NAME, STRING_CLASS_ARRAY); setValidate.invoke(body, (Object) null); if (credential != null && credential.length() > 0) { Method setCredential = bodyClass.getMethod(SET_CREDENTIAL_METHOD_NAME, STRING_CLASS_ARRAY); setCredential.invoke(body, credential); } Method setTimestamp = bodyClass.getMethod(SET_TIMESTAMP_METHOD_NAME, CALENDAR_CLASS_ARRAY); now = Calendar.getInstance(); setTimestamp.invoke(body, now); // Create the signature Method setSignature = bodyClass.getMethod(SET_SIGNATURE_METHOD_NAME, STRING_CLASS_ARRAY); signature = getSigner().sign(getServiceName(), axisMethodName, now); setSignature.invoke(body, signature); } Object response = responseClass.newInstance(); String axisClassMethodName = axisMethodName.substring(0, 1).toLowerCase() + axisMethodName.substring(1); Method axisMethod = getPort().getClass().getMethod(axisClassMethodName, new Class[] { bodyClass }); try { // Execute the request and get a response response = axisMethod.invoke(getPort(), body); } catch (InvocationTargetException e) { if (e.getCause() instanceof AxisFault) { //errors due to throttling are inside AxisFault. Get those if present AxisFault fault = (AxisFault) e.getCause(); String httpResponse = fault.getFaultCode().getLocalPart(); List<String> errorCodes = new ArrayList<String>(); errorCodes.add(httpResponse); // When Axis encounters networking errors, it sets the fault code to // {http://xml.apache.org/axis/}HTTP // In this case it sets the error code from the http response in // the "HttpErrorCode" element of the fault details // If this is the case, add it to the error codes so the SDK // can be configured to retry for specific response codes if (AXIS_HTTP_FAULT.equals(fault.getFaultCode())) { Element faultElement = fault.lookupFaultDetail(AXIS_HTTP_ERROR_CODE); if (faultElement != null && faultElement.getFirstChild() != null) { errorCodes.add(faultElement.getFirstChild().getNodeValue()); } } throw new InternalServiceException(e.getCause(), errorCodes); } throw new ServiceException(e.getCause()); } // Extract the Operation Request Method getOperationRequest = responseClass.getMethod(GET_OPERATION_REQUEST_METHOD_NAME); Object operationRequest = getOperationRequest.invoke(response); // Extract the Errors Method getErrors = operationRequest.getClass().getMethod(GET_ERRORS_METHOD_NAME); Object errors = getErrors.invoke(operationRequest); Object[] results = null; if (errors != null) { return new Reply(results, errors, getRequestId(operationRequest)); } Method getResult = responseClass.getMethod(GET_PREFIX + resultAccessorName); results = (Object[]) getResult.invoke(response); if (results == null || results.length == 0) { throw new ServiceException("Empty result, unknown error."); } for (int i = 0; i < results.length; i++) { Object result = results[i]; Method getRequest = result.getClass().getMethod(GET_REQUEST_METHOD_NAME); Object request = getRequest.invoke(result); getErrors = request.getClass().getMethod(GET_ERRORS_METHOD_NAME); errors = getErrors.invoke(request); if (errors != null) { break; //get only the first error } } return new Reply(results, errors, getRequestId(operationRequest)); } catch (ClassNotFoundException e) { throw new ServiceException(e); } catch (IllegalAccessException e) { throw new ServiceException(e); } catch (InstantiationException e) { throw new ServiceException(e); } catch (NoSuchMethodException e) { throw new ServiceException(e); } catch (InvocationTargetException e) { throw new ServiceException(e.getCause()); } }