List of usage examples for java.lang.reflect Method getParameterAnnotations
@Override
public Annotation[][] getParameterAnnotations()
From source file:org.mulesoft.restx.component.BaseComponent.java
protected void initialiseComponentDescriptor() throws RestxException { if (annotationsHaveBeenParsed || componentDescriptor != null) { return;//from w w w. ja va 2 s. c o m } final Class<? extends BaseComponent> myclass = this.getClass(); /* * Examine the class annotations to get information about the component. */ final ComponentInfo ci = this.getClass().getAnnotation(ComponentInfo.class); if (ci == null) { throw new RestxException("Component does not have a ComponentInfo annotation"); } componentDescriptor = new ComponentDescriptor(ci.name(), ci.desc(), ci.doc()); /* * Examine field annotations to identify resource creation time parameters. */ for (final Field f : myclass.getFields()) { final Parameter fa = f.getAnnotation(Parameter.class); if (fa != null) { final String paramName = fa.name(); final String paramDesc = fa.desc(); String defaultVal = null; boolean required = true; String[] choices = null; // Check if we have a default value and set that one as well final Default fad = f.getAnnotation(Default.class); if (fad != null) { defaultVal = fad.value(); required = false; } // Check if we have a list of choices final Choices cad = f.getAnnotation(Choices.class); if (cad != null) { choices = cad.value(); } final Class<?> ftype = f.getType(); componentDescriptor.addParameter(paramName, createParamDefType(ftype, paramDesc, required, defaultVal, choices)); } } /* * Examine the method annotations to identify service methods and their * parameters. */ paramOrder = new HashMap<String, ArrayList<String>>(); paramTypes = new HashMap<String, ArrayList<Class<?>>>(); for (final Method m : myclass.getMethods()) { if (m.isAnnotationPresent(Service.class)) { final String serviceName = m.getName(); final Service at = m.getAnnotation(Service.class); boolean pinreq = false; if (m.isAnnotationPresent(ParamsInReqBody.class)) { pinreq = true; } // Looking for output type annotations ArrayList<String> outputTypes = null; if (m.isAnnotationPresent(OutputType.class)) { final OutputType ot = m.getAnnotation(OutputType.class); outputTypes = new ArrayList<String>(); outputTypes.add(ot.value()); } if (m.isAnnotationPresent(OutputTypes.class)) { final OutputTypes ots = m.getAnnotation(OutputTypes.class); final String[] otsSpecs = ots.value(); if (otsSpecs.length > 0) { if (outputTypes == null) { outputTypes = new ArrayList<String>(); } for (final String ts : otsSpecs) { outputTypes.add(ts); } } } // Looking for output type annotations ArrayList<String> inputTypes = null; if (m.isAnnotationPresent(InputType.class)) { final InputType it = m.getAnnotation(InputType.class); inputTypes = new ArrayList<String>(); final String it_val = it.value(); if (!it_val.equals(InputType.NO_INPUT)) { inputTypes.add(it_val); } else { inputTypes.add(null); } } if (m.isAnnotationPresent(InputTypes.class)) { final InputTypes its = m.getAnnotation(InputTypes.class); final String[] itsSpecs = its.value(); if (itsSpecs.length > 0) { if (inputTypes == null) { inputTypes = new ArrayList<String>(); } for (final String ts : itsSpecs) { if (!ts.equals(InputType.NO_INPUT)) { inputTypes.add(ts); } else { inputTypes.add(null); } } } } final ServiceDescriptor sd = new ServiceDescriptor(at.desc(), pinreq, outputTypes, inputTypes); final Class<?>[] types = m.getParameterTypes(); final Annotation[][] allParamAnnotations = m.getParameterAnnotations(); int i = 0; final ArrayList<String> positionalParams = new ArrayList<String>(); for (final Annotation[] pa : allParamAnnotations) { String name = null; String desc = null; boolean required = true; String defaultVal = null; for (final Annotation a : pa) { if (a.annotationType() == Parameter.class) { name = ((Parameter) a).name(); desc = ((Parameter) a).desc(); if (!paramOrder.containsKey(serviceName)) { paramOrder.put(serviceName, new ArrayList<String>()); paramTypes.put(serviceName, new ArrayList<Class<?>>()); } if (((Parameter) a).positional()) { positionalParams.add(name); } paramOrder.get(serviceName).add(name); paramTypes.get(serviceName).add(types[i]); } else if (a.annotationType() == Default.class) { defaultVal = ((Default) a).value(); required = false; } } if (name != null) { sd.addParameter(name, createParamDefType(types[i], desc, required, defaultVal, null)); } ++i; } if (!positionalParams.isEmpty()) { sd.setPositionalParameters(positionalParams); } componentDescriptor.addService(m.getName(), sd); } } annotationsHaveBeenParsed = true; }
From source file:org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationUtil.java
private List<Feature> getFeatures(Method[] annotatedMethods) throws Throwable { List<Feature> featureList = new ArrayList<>(); for (Method method : annotatedMethods) { Annotation methodAnnotation = method.getAnnotation(featureClazz); if (methodAnnotation != null) { Annotation[] annotations = method.getDeclaredAnnotations(); for (int i = 0; i < annotations.length; i++) { if (annotations[i].annotationType().getName() .equals(org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature.class .getName())) { Feature feature = new Feature(); Method[] featureAnnoMethods = featureClazz.getMethods(); Annotation featureAnno = method.getAnnotation(featureClazz); for (int k = 0; k < featureAnnoMethods.length; k++) { switch (featureAnnoMethods[k].getName()) { case "name": feature.setName(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; case "code": feature.setCode(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; case "description": feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; case "type": feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; }/*from www .j av a 2 s.c om*/ } //Extracting method with which feature is exposed if (annotations[i].annotationType().getName().equals(GET.class.getName())) { feature.setMethod(HttpMethod.GET); } if (annotations[i].annotationType().getName().equals(POST.class.getName())) { feature.setMethod(HttpMethod.POST); } if (annotations[i].annotationType().getName().equals(OPTIONS.class.getName())) { feature.setMethod(HttpMethod.OPTIONS); } if (annotations[i].annotationType().getName().equals(DELETE.class.getName())) { feature.setMethod(HttpMethod.DELETE); } if (annotations[i].annotationType().getName().equals(PUT.class.getName())) { feature.setMethod(HttpMethod.PUT); } try { Class<FormParam> formParamClazz = (Class<FormParam>) classLoader .loadClass(FormParam.class.getName()); Method[] formMethods = formParamClazz.getMethods(); //Extract method parameter information and store same as feature meta info List<Feature.MetadataEntry> metaInfoList = new ArrayList<>(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int j = 0; j < paramAnnotations.length; j++) { for (Annotation anno : paramAnnotations[j]) { if (anno.annotationType().getName().equals(FormParam.class.getName())) { Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); metadataEntry.setId(j); metadataEntry.setValue(invokeMethod(formMethods[0], anno, STRING)); metaInfoList.add(metadataEntry); } } } feature.setMetadataEntries(metaInfoList); } catch (ClassNotFoundException e) { log.debug("No Form Param found for class " + featureClazz.getName()); } featureList.add(feature); } } } } return featureList; }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
/** * @param classes Generates all testcases for all the rest-full services found in the classes discovered *//*w ww . j a va2s .c o m*/ @SuppressWarnings({ "rawtypes", "unchecked" }) private void generateRestTestCases(List<Class> classes) { try { Map<String, Integer> classTypes = new HashMap<String, Integer>(); for (Class claz : classes) { classTypes.put(claz.getSimpleName(), 0); Annotation theClassPath = claz.getAnnotation(Path.class); if (theClassPath == null) theClassPath = claz.getAnnotation(RequestMapping.class); if (theClassPath != null) { List<TestCase> tcases = new ArrayList<TestCase>(); Method[] methods = claz.getMethods(); for (Method method : methods) { Annotation theMethodPath = method.getAnnotation(Path.class); if (theMethodPath == null) theMethodPath = method.getAnnotation(RequestMapping.class); if (theMethodPath != null) { TestCase tcase = new TestCase(); String completeServicePath = null; String httpMethod = ""; String consumes = "text/plain"; if (theClassPath instanceof Path && theMethodPath instanceof Path) { Path cpath = (Path) theClassPath; Path mpath = (Path) theMethodPath; completeServicePath = cpath.value() + mpath.value(); } else if (theClassPath instanceof RequestMapping && theMethodPath instanceof RequestMapping) { RequestMapping cpath = (RequestMapping) theClassPath; RequestMapping mpath = (RequestMapping) theMethodPath; completeServicePath = cpath.value()[0] + mpath.value()[0]; httpMethod = mpath.method()[0].name(); consumes = mpath.consumes()[0]; } else { throw new Exception( "Invalid Annotation found on the Service class - " + claz.getSimpleName()); } if (completeServicePath != null && completeServicePath.charAt(0) == '/') { completeServicePath = completeServicePath.substring(1); } String url = getUrl(completeServicePath); String completeServiceSubmitPath = url; Type[] argTypes = method.getGenericParameterTypes(); Annotation[][] argAnot = method.getParameterAnnotations(); boolean mayBemultipartContent = false; if (isDebugEnabled()) getLog().info( "Started looking at " + claz.getSimpleName() + " " + method.getName()); ViewField contentvf = null; Map<String, String> params = new HashMap<String, String>(); Map<String, String> hparams = new HashMap<String, String>(); for (int i = 0; i < argTypes.length; i++) { Annotation[] annotations = getRestArgAnnotation(argAnot[i]); if (annotations[0] != null) { String formpnm = null; if (annotations[0] instanceof FormParam) { formpnm = ((FormParam) annotations[0]).value(); if (annotations[1] != null) params.put(formpnm, ((DefaultValue) annotations[1]).value()); else params.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } if (annotations[0] instanceof RequestParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (((RequestParam) annotations[0]).defaultValue() != null) completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).defaultValue() + "}&"; else completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof QueryParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (annotations[1] != null) completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((DefaultValue) annotations[1]).value() + "}&"; else completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((QueryParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof HeaderParam) { formpnm = ((HeaderParam) annotations[0]).value(); if (annotations[1] != null) hparams.put(formpnm, ((DefaultValue) annotations[1]).value()); else hparams.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } } else { ViewField vf = getViewField(argTypes[i]); if (vf != null) { contentvf = vf; if (isDebugEnabled()) getLog().info("Done looking at " + claz.getSimpleName() + " " + method.getName()); break; } else { mayBemultipartContent = true; } } } classTypes.put(claz.getSimpleName(), classTypes.get(claz.getSimpleName()) + 1); Annotation hm = method.getAnnotation(POST.class); if (hm != null) { httpMethod = "POST"; } else { hm = method.getAnnotation(GET.class); if (hm != null) { httpMethod = "GET"; } else { hm = method.getAnnotation(PUT.class); if (hm != null) { httpMethod = "PUT"; } else { hm = method.getAnnotation(DELETE.class); if (hm != null) { httpMethod = "DELETE"; } } } } Annotation annot = method.getAnnotation(Consumes.class); if (annot != null) { consumes = ((Consumes) annot).value()[0]; } String produces = null; if ("JSON".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_JSON; } else if ("XML".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_XML; } else { produces = MediaType.TEXT_PLAIN; } annot = method.getAnnotation(Produces.class); if (annot != null) { produces = ((Produces) annot).value()[0]; } String content = ""; try { if (!params.isEmpty() || consumes.equals(MediaType.APPLICATION_FORM_URLENCODED)) { for (Map.Entry<String, String> entry : params.entrySet()) { content += entry.getKey() + "=" + entry.getValue() + "&"; } consumes = MediaType.APPLICATION_FORM_URLENCODED; } else if (contentvf != null && contentvf.getValue() != null && contentvf.getValue() instanceof String) { content = (String) contentvf.getValue(); } else if (("JSON".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_JSON)) && contentvf != null && contentvf.getValue() != null) { content = new ObjectMapper().writerWithDefaultPrettyPrinter() .writeValueAsString(contentvf.getValue()); consumes = MediaType.APPLICATION_JSON; } else if (("XML".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_XML)) && contentvf != null && contentvf.getValue() != null) { JAXBContext context = JAXBContext.newInstance(contentvf.getValue().getClass()); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter writer = new StringWriter(); m.marshal(contentvf.getValue(), writer); content = writer.toString(); consumes = MediaType.APPLICATION_XML; } else if ((httpMethod.equals("POST") || httpMethod.equals("PUT")) && mayBemultipartContent) { consumes = MediaType.MULTIPART_FORM_DATA; } else if (httpMethod.equals("GET") || httpMethod.equals("DELETE")) { consumes = ""; } } catch (Exception e) { getLog().error(e); } if (consumes != null && !consumes.trim().isEmpty()) { hparams.put(HttpHeaders.CONTENT_TYPE, consumes); } completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("\\?&", "?"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("&&", "&"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("/\\?", "?"); completeServiceSubmitPath = completeServiceSubmitPath.trim(); if (completeServiceSubmitPath.charAt(completeServiceSubmitPath.length() - 1) == '&') { completeServiceSubmitPath = completeServiceSubmitPath.substring(0, completeServiceSubmitPath.length() - 1); } tcase.setUrl(completeServiceSubmitPath); tcase.setMethod(httpMethod); tcase.setContent(content); tcase.setName(claz.getName() + "." + method.getName()); tcase.setDescription(tcase.getName()); tcase.setDetailedLog(false); tcase.setSkipTest(false); tcase.setSecure(isOverrideSecure()); tcase.setSoapBase(false); tcase.setExpectedResCode(200); tcase.setExpectedResContentType(produces); if (hparams.size() > 0) tcase.setHeaders(hparams); if (tcase.getNumberOfExecutions() == null) tcase.setNumberOfExecutions(1); if (tcase.getExpectedNodes().size() == 0) tcase.setExpectedNodes(null); if (tcase.getWorkflowContextParameterMap().size() == 0) tcase.setWorkflowContextParameterMap(null); if (tcase.getSoapParameterValues().size() == 0) tcase.setSoapParameterValues(null); if (tcase.getRepeatScenarios().size() == 0) tcase.setRepeatScenarios(null); if (tcase.getMultipartContent().size() == 0) tcase.setMultipartContent(null); tcases.add(tcase); } } if (!tcases.isEmpty()) { if ("json".equalsIgnoreCase(getTestCaseFormat())) { String postManJson = new ObjectMapper().writeValueAsString(tcases); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } else if ("csv".equalsIgnoreCase(getTestCaseFormat())) { StringBuilder build = new StringBuilder(); for (TestCase testCase : tcases) { build.append(testCase.toCSV()); build.append(SystemUtils.LINE_SEPARATOR); } String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.csv"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(build.toString()); bw.close(); } else { XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new GatfPrettyPrintWriter(out, TestCase.CDATA_NODES); } }); xstream.processAnnotations(new Class[] { TestCase.class }); xstream.alias("TestCases", List.class); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.xml"; xstream.toXML(tcases, new FileOutputStream(file)); } if (getPostmanCollectionVersion() > 0) { PostmanCollection postmanCollection = new PostmanCollection(); postmanCollection.setName(claz.getSimpleName()); postmanCollection.setDescription(postmanCollection.getName()); for (TestCase testCase : tcases) { postmanCollection.addTestCase(testCase, getPostmanCollectionVersion()); } String postManJson = new ObjectMapper().writeValueAsString(postmanCollection); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_postman.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } } } } } catch (Exception e) { getLog().error(e); } }
From source file:ca.uhn.fhir.rest.server.RestfulServer.java
private int findResourceMethods(Object theProvider, Class<?> clazz) throws ConfigurationException { int count = 0; for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) { BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(), theProvider);//from ww w .j a va 2s . c o m if (foundMethodBinding == null) { continue; } count++; if (foundMethodBinding instanceof ConformanceMethodBinding) { myServerConformanceMethod = foundMethodBinding; continue; } if (!Modifier.isPublic(m.getModifiers())) { throw new ConfigurationException( "Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public"); } else { if (Modifier.isStatic(m.getModifiers())) { throw new ConfigurationException( "Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static"); } else { ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName()); String resourceName = foundMethodBinding.getResourceName(); ResourceBinding resourceBinding; if (resourceName == null) { resourceBinding = myServerBinding; } else { RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName); if (myResourceNameToBinding.containsKey(definition.getName())) { resourceBinding = myResourceNameToBinding.get(definition.getName()); } else { resourceBinding = new ResourceBinding(); resourceBinding.setResourceName(resourceName); myResourceNameToBinding.put(resourceName, resourceBinding); } } List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations(); if (allowableParams != null) { for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) { for (Annotation annotation : nextParamAnnotations) { Package pack = annotation.annotationType().getPackage(); if (pack.equals(IdParam.class.getPackage())) { if (!allowableParams.contains(annotation.annotationType())) { throw new ConfigurationException("Method[" + m.toString() + "] is not allowed to have a parameter annotated with " + annotation); } } } } } resourceBinding.addMethod(foundMethodBinding); ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName()); } } } return count; }
From source file:net.ymate.platform.webmvc.RequestMeta.java
public RequestMeta(IWebMvc owner, Class<?> targetClass, Method method) throws Exception { this.targetClass = targetClass; this.method = method; ///*from ww w. j a v a 2 s . c o m*/ this.allowMethods = new HashSet<Type.HttpMethod>(); this.allowHeaders = new HashMap<String, String>(); this.allowParams = new HashMap<String, String>(); // Controller _controller = targetClass.getAnnotation(Controller.class); this.name = StringUtils.defaultIfBlank(_controller.name(), targetClass.getName()); this.singleton = _controller.singleton(); // this.responseCache = method.getAnnotation(ResponseCache.class); if (this.responseCache == null) { this.responseCache = targetClass.getAnnotation(ResponseCache.class); } // this.parameterEscape = method.getAnnotation(ParameterEscape.class); if (this.parameterEscape == null) { this.parameterEscape = targetClass.getAnnotation(ParameterEscape.class); if (this.parameterEscape == null && owner.getModuleCfg().isParameterEscapeMode()) { this.parameterEscape = this.getClass().getAnnotation(ParameterEscape.class); } } if (this.parameterEscape != null && this.parameterEscape.skiped()) { this.parameterEscape = null; } // this.responseView = method.getAnnotation(ResponseView.class); if (this.responseView == null) { this.responseView = targetClass.getAnnotation(ResponseView.class); } // this.responseHeaders = new HashSet<Header>(); ResponseHeader _respHeader = targetClass.getAnnotation(ResponseHeader.class); if (_respHeader != null) { Collections.addAll(this.responseHeaders, _respHeader.value()); } _respHeader = method.getAnnotation(ResponseHeader.class); if (_respHeader != null) { Collections.addAll(this.responseHeaders, _respHeader.value()); } // RequestMapping _reqMapping = targetClass.getAnnotation(RequestMapping.class); String _root = null; if (_reqMapping != null) { _root = _reqMapping.value(); __doSetAllowValues(_reqMapping); } _reqMapping = method.getAnnotation(RequestMapping.class); __doSetAllowValues(_reqMapping); // if (this.allowMethods.isEmpty()) { this.allowMethods.add(Type.HttpMethod.GET); } // this.mapping = __doBuildRequestMapping(_root, _reqMapping); // RequestProcessor _reqProcessor = method.getAnnotation(RequestProcessor.class); if (_reqProcessor != null) { this.processor = _reqProcessor.value(); } if (this.processor == null) { _reqProcessor = targetClass.getAnnotation(RequestProcessor.class); if (_reqProcessor != null) { this.processor = _reqProcessor.value(); } } // Map<String, ParameterMeta> _targetClassParameterMetas = __CLASS_PARAMETER_METAS.get(targetClass); if (_targetClassParameterMetas == null) { ClassUtils.BeanWrapper<?> _wrapper = ClassUtils.wrapper(targetClass); if (_wrapper != null) { _targetClassParameterMetas = new HashMap<String, ParameterMeta>(); // for (String _fieldName : _wrapper.getFieldNames()) { if (!_targetClassParameterMetas.containsKey(_fieldName)) { ParameterMeta _meta = new ParameterMeta(this, _wrapper.getField(_fieldName)); if (_meta.isParamField()) { _targetClassParameterMetas.put(_fieldName, _meta); } } } __CLASS_PARAMETER_METAS.put(targetClass, _targetClassParameterMetas); } } // this.__methodParameterMetas = new ArrayList<ParameterMeta>(); this.methodParamNames = Arrays.asList(ClassUtils.getMethodParamNames(method)); if (!this.methodParamNames.isEmpty()) { Class<?>[] _paramTypes = method.getParameterTypes(); Annotation[][] _paramAnnotations = method.getParameterAnnotations(); for (int _idx = 0; _idx < this.methodParamNames.size(); _idx++) { ParameterMeta _meta = new ParameterMeta(this, _paramTypes[_idx], this.methodParamNames.get(_idx), _paramAnnotations[_idx]); if (_meta.isParamField()) { this.__methodParameterMetas.add(_meta); } } } }
From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java
protected Method[] processMethods(Method[] declaredMethods) throws Exception { ArrayList<Method> list = new ArrayList<Method>(); //short the elements in the array Arrays.sort(declaredMethods, new MathodComparator()); // since we do not support overload HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>(); XmlSchemaComplexType methodSchemaType; XmlSchemaSequence sequence = null;//from w w w . j a v a 2 s . com for (Method jMethod : declaredMethods) { if (jMethod.isBridge()) { continue; } WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod); String methodName = jMethod.getName(); if (methodAnnon != null) { if (methodAnnon.isExclude()) { continue; } if (methodAnnon.getOperationName() != null) { methodName = methodAnnon.getOperationName(); } } // no need to think abt this method , since that is system // config method if (excludeMethods.contains(methodName)) { continue; } if (!Modifier.isPublic(jMethod.getModifiers())) { // no need to generate Schema for non public methods continue; } if (uniqueMethods.get(methodName) != null) { log.warn("We don't support method overloading. Ignoring [" + methodName + "]"); continue; } boolean addToService = false; AxisOperation axisOperation = service.getOperation(new QName(methodName)); if (axisOperation == null) { axisOperation = Utils.getAxisOperationForJmethod(jMethod); // if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals( // axisOperation.getMessageExchangePattern())) { // AxisMessage outMessage = axisOperation.getMessage( // WSDLConstants.MESSAGE_LABEL_OUT_VALUE); // if (outMessage != null) { // outMessage.setName(methodName + RESPONSE); // } // } addToService = true; } // by now axis operation should be assigned but we better recheck & add the paramether if (axisOperation != null) { axisOperation.addParameter("JAXRSAnnotaion", JAXRSUtils.getMethodModel(this.classModel, jMethod)); } // Maintain a list of methods we actually work with list.add(jMethod); processException(jMethod, axisOperation); uniqueMethods.put(methodName, jMethod); Class<?>[] parameters = jMethod.getParameterTypes(); String parameterNames[] = null; AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMessage != null) { inMessage.setName(methodName + Java2WSDLConstants.MESSAGE_SUFFIX); } if (parameters.length > 0) { parameterNames = methodTable.getParameterNames(methodName); // put the parameter names to use it for parsing service.addParameter(methodName, parameterNames); } // we need to add the method opration wrapper part even to // empty parameter operations sequence = new XmlSchemaSequence(); String requestElementSuffix = getRequestElementSuffix(); String requestLocalPart = methodName; if (requestElementSuffix != null) { requestLocalPart += requestElementSuffix; } methodSchemaType = createSchemaTypeForMethodPart(requestLocalPart); methodSchemaType.setParticle(sequence); inMessage.setElementQName(typeTable.getQNamefortheType(requestLocalPart)); Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG); if (param != null) { inMessage.setPartName((String) param.getValue()); } service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation); Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations(); Type[] genericParameterTypes = jMethod.getGenericParameterTypes(); for (int j = 0; j < parameters.length; j++) { Class<?> methodParameter = parameters[j]; String parameterName = getParameterName(parameterAnnotation, j, parameterNames); if (nonRpcMethods.contains(jMethod.getName())) { generateSchemaForType(sequence, null, jMethod.getName()); break; } else { Type genericParameterType = genericParameterTypes[j]; Type genericType = null; if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); genericType = parameterArgTypes[0]; generateSchemaForType(sequence, genericType, parameterName, true); } else { generateSchemaForType(sequence, methodParameter, parameterName); } } } // for its return type Class<?> returnType = jMethod.getReturnType(); if (!"void".equals(jMethod.getReturnType().getName())) { String partQname = methodName + RESPONSE; methodSchemaType = createSchemaTypeForMethodPart(partQname); sequence = new XmlSchemaSequence(); methodSchemaType.setParticle(sequence); WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod); String returnName = "return"; if (returnAnnon != null) { returnName = returnAnnon.getName(); if (returnName == null || "".equals(returnName)) { returnName = "return"; } } Type genericParameterType = jMethod.getGenericReturnType(); if (nonRpcMethods.contains(jMethod.getName())) { generateSchemaForType(sequence, null, returnName); } else if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); generateSchemaForType(sequence, parameterArgTypes[0], returnName, true); } else { generateSchemaForType(sequence, returnType, returnName); } AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); outMessage.setElementQName(typeTable.getQNamefortheType(partQname)); outMessage.setName(partQname); Parameter outparam = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG); if (outparam != null) { outMessage.setPartName((String) outparam.getValue()); } service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation); } if (addToService) { service.addOperation(axisOperation); } } return list.toArray(new Method[list.size()]); }
From source file:plugins.PlayReader.java
private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); String responseContainer = null; Type responseType = null;//from w ww . j a v a 2 s. c o m Map<String, Property> defaultResponseHeaders = new HashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) { operation.security(sec); } } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { operation.consumes(apiOperation.consumes()); } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { operation.produces(apiOperation.produces()); } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration Logger.debug("picking up response class from method " + method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (apiOperation != null && apiOperation.consumes() != null && apiOperation.consumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (apiOperation != null && apiOperation.produces() != null && apiOperation.produces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<ApiResponse>(); if (responseAnnotation != null) { for (ApiResponse apiResponse : responseAnnotation.value()) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter); } Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i])); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }
From source file:org.wso2.msf4j.swagger.ExtendedSwaggerReader.java
private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters, List<ApiResponse> classApiResponses) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); String responseContainer = null; Type responseType = null;//from w w w.j a v a 2 s .com Map<String, Property> defaultResponseHeaders = new HashMap<>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { securities.forEach(operation::security); } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() }); for (String consume : consumesAr) { operation.consumes(consume); } } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() }); for (String produce : producesAr) { operation.produces(produce); } } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (operation.getProduces() == null || operation.getProduces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<>(); if (responseAnnotation != null) { apiResponses.addAll(Arrays.asList(responseAnnotation.value())); } Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class); if (exceptionResponses != null) { apiResponses.addAll(Arrays.asList(exceptionResponses.value())); } } for (ApiResponse apiResponse : apiResponses) { addResponse(operation, apiResponse); } // merge class level @ApiResponse for (ApiResponse apiResponse : classApiResponses) { String key = apiResponse.code() == 0 ? "default" : String.valueOf(apiResponse.code()); if (operation.getResponses().containsKey(key)) { continue; } addResponse(operation, apiResponse); } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters globalParameters.forEach(operation::parameter); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i])); parameters.forEach(operation::parameter); } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }
From source file:io.swagger.jaxrs.Reader.java
private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); String responseContainer = null; Type responseType = null;/*from w w w . j a v a2 s. c om*/ Map<String, Property> defaultResponseHeaders = new HashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) { operation.security(sec); } } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { operation.consumes(apiOperation.consumes()); } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { operation.produces(apiOperation.produces()); } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (apiOperation != null && apiOperation.consumes() != null && apiOperation.consumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (apiOperation != null && apiOperation.produces() != null && apiOperation.produces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<ApiResponse>(); if (responseAnnotation != null) { apiResponses.addAll(Arrays.asList(responseAnnotation.value())); } Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class); if (exceptionResponses != null) { apiResponses.addAll(Arrays.asList(exceptionResponses.value())); } } for (ApiResponse apiResponse : apiResponses) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter); } Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i])); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }