com.thoughtworks.qdox.model.JavaMethod Java Examples
The following examples show how to use
com.thoughtworks.qdox.model.JavaMethod.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocUtil.java From smart-doc with Apache License 2.0 | 6 votes |
/** * obtain params comments * * @param javaMethod JavaMethod * @param tagName java comments tag * @param className class name * @return Map */ public static Map<String, String> getParamsComments(final JavaMethod javaMethod, final String tagName, final String className) { List<DocletTag> paramTags = javaMethod.getTagsByName(tagName); Map<String, String> paramTagMap = new HashMap<>(); for (DocletTag docletTag : paramTags) { String value = docletTag.getValue(); if (StringUtil.isEmpty(value) && StringUtil.isNotEmpty(className)) { throw new RuntimeException("ERROR: #" + javaMethod.getName() + "() - bad @" + tagName + " javadoc from " + javaMethod.getDeclaringClass().getCanonicalName() + ", must be add comment if you use it."); } String pName; String pValue; int idx = value.indexOf("\n"); //existed \n if (idx > -1) { pName = value.substring(0, idx); pValue = value.substring(idx + 1); } else { pName = (value.contains(" ")) ? value.substring(0, value.indexOf(" ")) : value; pValue = value.contains(" ") ? value.substring(value.indexOf(' ') + 1) : DocGlobalConstants.NO_COMMENTS_FOUND; } paramTagMap.put(pName, pValue); } return paramTagMap; }
Example #2
Source File: TestParser.java From yatspec with Apache License 2.0 | 6 votes |
private static Sequence<TestMethod> collectTestMethods(Class aClass, Sequence<Method> methods) throws IOException { final Option<JavaClass> javaClass = getJavaClass(aClass); if (javaClass.isEmpty()) { return empty(); } Map<String, List<JavaMethod>> sourceMethodsByName = getMethods(javaClass.get()).toMap(sourceMethodName()); Map<String, List<Method>> reflectionMethodsByName = methods.toMap(reflectionMethodName()); List<TestMethod> testMethods = new ArrayList<TestMethod>(); TestMethodExtractor extractor = new TestMethodExtractor(); for (String name : sourceMethodsByName.keySet()) { List<JavaMethod> javaMethods = sourceMethodsByName.get(name); List<Method> reflectionMethods = reflectionMethodsByName.get(name); testMethods.add(extractor.toTestMethod(aClass, javaMethods.get(0), reflectionMethods.get(0))); // TODO: If people overload test methods we will have to use the full name rather than the short name } Sequence<TestMethod> myTestMethods = sequence(testMethods); Sequence<TestMethod> parentTestMethods = collectTestMethods(aClass.getSuperclass(), methods); return myTestMethods.join(parentTestMethods); }
Example #3
Source File: SeleniumTestsReporter.java From seleniumtestsframework with Apache License 2.0 | 6 votes |
protected String getJavadocComments(final ITestNGMethod method) { try { final Method m = method.getConstructorOrMethod().getMethod(); final String javaClass = m.getDeclaringClass().getName(); final String javaMethod = m.getName(); final JavaClass jc = getJavaDocBuilder(m.getDeclaringClass()).getClassByName(javaClass); final Class<?>[] types = method.getConstructorOrMethod().getMethod().getParameterTypes(); final Type[] qdoxTypes = new Type[types.length]; for (int i = 0; i < types.length; i++) { final String type = getType(types[i]); final int dim = getDim(types[i]); qdoxTypes[i] = new Type(type, dim); } final JavaMethod jm = jc.getMethodBySignature(javaMethod, qdoxTypes); return jm.getComment(); } catch (final Throwable e) { logger.error("Exception loading the javadoc comments for : " + method.getMethodName() + e); return null; } }
Example #4
Source File: MockClassInfo.java From auto-generate-test-maven-plugin with Apache License 2.0 | 6 votes |
/** * mock父类的方法,mock父类和当前测试类非本测试方法的方法 * @param javaClass 测试类信息 * @param javaGenInfoModel 存储类的信息 * @param javaClassModelMap 类信息存储,key - 类的全限定名称,value - 类信息 */ private static void mockThisOtherMethod(JavaClass javaClass, JavaGenInfoModel javaGenInfoModel, Map<String, JavaClassModel> javaClassModelMap) { JavaClass superJavaClass = javaClass.getSuperJavaClass(); JavaClassModel superJavaClassModel = new JavaClassModel(); superJavaClassModel.setName(javaGenInfoModel.getModelNameLowerCamel()); superJavaClassModel.setType(InitConstant.getAbbreviation(superJavaClass.getFullyQualifiedName())); superJavaClassModel.setFullyType(superJavaClass.getFullyQualifiedName()); List<JavaMethodModel> javaMethodModelList1 = new ArrayList<>(); //遍历父类的方法 for (JavaMethod method : superJavaClass.getMethods()) { JavaMethodModel javaMethodModel = getJavaMethodModel(method,javaGenInfoModel.getModelNameLowerCamel(),javaClass.getFullyQualifiedName(), superJavaClass); String key = "this." + javaMethodModel.getName(); Map<String, String> mockFullyTypeNameMap = javaGenInfoModel.getMockFullyTypeNameMap(); if (!mockFullyTypeNameMap.containsKey(key)) { mockFullyTypeNameMap.put(key, superJavaClassModel.getFullyType()); } javaMethodModelList1.add(javaMethodModel); } superJavaClassModel.setJavaMethodModelList(javaMethodModelList1); if (!javaClassModelMap.containsKey(superJavaClassModel.getFullyType())) { javaClassModelMap.put(superJavaClassModel.getFullyType(), superJavaClassModel); } }
Example #5
Source File: BuildMockClassMethod.java From auto-generate-test-maven-plugin with Apache License 2.0 | 6 votes |
/** * 构建mock的类方法信息 * @param javaGenInfoModel 存储的类信息 * @param javaMethod 方法信息 * @param javaMethodDTO 模板的方法信息 */ public static void buildMock(JavaGenInfoModel javaGenInfoModel, JavaMethod javaMethod, JavaMethodDTO javaMethodDTO) { //Mock方法模拟 List<JavaMockMethodInfoDTO> javaMockMethodInfoDTOList = new ArrayList<>(); //获取方法的源码 String methodCode = javaMethod.getSourceCode(); Map<String, String> mockFullyTypeNameMap = javaGenInfoModel.getMockFullyTypeNameMap(); //判断方法中是否有需要mock的方法,需要有 属性名+方法名称 for (String name : mockFullyTypeNameMap.keySet()) { //name - 属性名称 String pattern = name + "\\([\\S ]+\\);"; //正则匹配 Pattern p = Pattern.compile(pattern); // 获取 matcher 对象 Matcher m = p.matcher(methodCode); while (m.find()) { saveMockMethodInfoDTO(javaGenInfoModel, javaMockMethodInfoDTOList, methodCode, name, m); } } javaMethodDTO.setJavaMockMethodInfoDTOList(javaMockMethodInfoDTOList); }
Example #6
Source File: BuildClassMethod.java From auto-generate-test-maven-plugin with Apache License 2.0 | 5 votes |
/** * 排除静态方法和私有方法 * * @param javaMethod 类方法信息 * @return true-进行排除,false-不是静态方法和私有方法 */ private static boolean excludeMethod(JavaMethod javaMethod) { //是否是静态方法 boolean mStatic = javaMethod.isStatic(); if (mStatic) { return true; } boolean isPublic = javaMethod.isPublic(); return !isPublic; }
Example #7
Source File: SwaggerGenerator.java From onos with Apache License 2.0 | 5 votes |
private void addResponses(JavaMethod javaMethod, ObjectNode methodNode, DocletTag tag, boolean responseJson) { ObjectNode responses = mapper.createObjectNode(); methodNode.set("responses", responses); Optional<JavaAnnotation> responsesAnnotation = getResponsesAnnotation(javaMethod); if (responsesAnnotation.isPresent()) { Object annotationsObj = responsesAnnotation.get().getNamedParameter("value"); if (annotationsObj != null && annotationsObj instanceof List) { List<JavaAnnotation> responseAnnotation = (List<JavaAnnotation>) annotationsObj; responseAnnotation.forEach( javaAnnotation -> { ObjectNode response = mapper.createObjectNode(); response.put("description", String.valueOf(javaAnnotation.getNamedParameter("message")) .replaceAll("^\"|\"$", "")); responses.set(String.valueOf(javaAnnotation.getNamedParameter("code")), response); } ); } } else { ObjectNode success = mapper.createObjectNode(); success.put("description", "successful operation"); responses.set("200", success); ObjectNode defaultObj = mapper.createObjectNode(); defaultObj.put("description", "Unexpected error"); responses.set("default", defaultObj); if (tag != null && responseJson) { ObjectNode schema = mapper.createObjectNode(); tag.getParameters().stream().forEach( param -> schema.put("$ref", "#/definitions/" + param)); success.set("schema", schema); } } }
Example #8
Source File: TestParser.java From yatspec with Apache License 2.0 | 5 votes |
public static Callable1<? super JavaMethod, Sequence<Annotation>> annotations() { return new Callable1<JavaMethod, Sequence<Annotation>>() { @Override public Sequence<Annotation> call(JavaMethod javaMethod) throws Exception { return sequence(javaMethod.getAnnotations()); } }; }
Example #9
Source File: TestParser.java From yatspec with Apache License 2.0 | 5 votes |
private static Callable1<JavaMethod, String> sourceMethodName() { return new Callable1<JavaMethod, String>() { @Override public String call(JavaMethod javaMethod) throws Exception { return javaMethod.getName(); } }; }
Example #10
Source File: BuildClassMethod.java From auto-generate-test-maven-plugin with Apache License 2.0 | 5 votes |
/** * 方法抛出的异常 * * @param javaMethod * @return */ private static List<JavaExceptionsDTO> getJavaExceptionsDTOList(JavaMethod javaMethod) { List<JavaClass> exceptions = javaMethod.getExceptions(); List<JavaExceptionsDTO> javaExceptionsDTOS = new ArrayList<>(); for (JavaClass exception : exceptions) { JavaExceptionsDTO javaExceptionsDTO = new JavaExceptionsDTO(); javaExceptionsDTO.setType(exception.getFullyQualifiedName()); javaExceptionsDTOS.add(javaExceptionsDTO); } return javaExceptionsDTOS; }
Example #11
Source File: JsonBuildHelper.java From smart-doc with Apache License 2.0 | 5 votes |
/** * build return json * * @param method The JavaMethod object * @param builder ProjectDocConfigBuilder builder * @return String */ public static String buildReturnJson(JavaMethod method, ProjectDocConfigBuilder builder) { if (method.getReturns().isVoid()) { return "This api return nothing."; } ApiReturn apiReturn = DocClassUtil.processReturnType(method.getReturnType().getGenericCanonicalName()); String returnType = apiReturn.getGenericCanonicalName(); String typeName = apiReturn.getSimpleName(); return JsonFormatUtil.formatJson(buildJson(typeName, returnType, Boolean.TRUE, 0, new HashMap<>(), builder)); }
Example #12
Source File: MockClassInfo.java From auto-generate-test-maven-plugin with Apache License 2.0 | 5 votes |
/** * 设置mock方法的信息 * * @param javaField 类属性 * @param javaMethod 方法 * @param superClass 父类 */ private static JavaMockMethodInfoDTO setMockMethodInfo(JavaField javaField, JavaMethod javaMethod, JavaClass superClass) { JavaMethodModel javaMethodModel = getJavaMethodModel(javaMethod, javaField.getName(),javaField.getType().getFullyQualifiedName(), superClass); JavaMockMethodInfoDTO javaMockMethodInfoDTO = new JavaMockMethodInfoDTO(); javaMockMethodInfoDTO.setParentClassFullyType(javaMethodModel.getParentClassFullyType()); javaMockMethodInfoDTO.setFieldName(javaMethodModel.getFieldName()); javaMockMethodInfoDTO.setClassType(javaMethodModel.getClassType()); javaMockMethodInfoDTO.setName(javaMethodModel.getName()); List<JavaParameteModel> javaParameteModelList = javaMethodModel.getJavaParameteModelList(); List<JavaParameterDTO> javaParameterDTOList = new ArrayList<>(); if (javaParameteModelList != null) { for (JavaParameteModel javaParameteModel : javaParameteModelList) { JavaParameterDTO javaParameterDTO = new JavaParameterDTO(); javaParameterDTO.setName(javaParameteModel.getName()); javaParameterDTO.setUpName(javaParameteModel.getUpName()); javaParameterDTO.setType(javaParameteModel.getType()); javaParameterDTO.setFullyType(javaParameteModel.getFullyType()); javaParameterDTO.setCustomType(javaParameteModel.getCustomType()); javaParameterDTO.setValue(javaParameteModel.getValue()); javaParameterDTOList.add(javaParameterDTO); } } javaMockMethodInfoDTO.setJavaParameterDTOList(javaParameterDTOList); javaMockMethodInfoDTO.setReturnFullyType(javaMethodModel.getReturnFullyType()); javaMockMethodInfoDTO.setReturnType(javaMethodModel.getReturnType()); return javaMockMethodInfoDTO; }
Example #13
Source File: MockClassInfo.java From auto-generate-test-maven-plugin with Apache License 2.0 | 5 votes |
/** * 存储父类的信息 * @param javaGenInfoModel 存储的类信息 * @param javaField 类属性信息 * @param javaMockClassInfoDTO 模板中的类信息 * @param superClass 父类 * @param javaClassModel 类信息 */ private static void handleSuperClass(JavaGenInfoModel javaGenInfoModel, JavaField javaField, JavaMockClassInfoDTO javaMockClassInfoDTO, JavaClass superClass, JavaClassModel javaClassModel) { //父类的方法 Map<String, JavaClassModel> javaClassModelMap= javaGenInfoModel.getJavaClassModelMap(); List<JavaMethod> superJavaMethod = superClass.getMethods(); JavaClassModel superJavaClassModel = new JavaClassModel(); superJavaClassModel.setName(superClass.getName()); superJavaClassModel.setType(InitConstant.getAbbreviation(superClass.getFullyQualifiedName())); superJavaClassModel.setFullyType(superClass.getFullyQualifiedName()); List<JavaMethodModel> javaMethodModelList1 = new ArrayList<>(); for (JavaMethod javaMethod : superJavaMethod) { JavaMethodModel javaMethodModel = getJavaMethodModel(javaMethod, javaField.getName(),javaField.getType().getFullyQualifiedName(), superClass); String key = javaClassModel.getName() + "." + javaMethodModel.getName(); Map<String, String> mockFullyTypeNameMap = javaGenInfoModel.getMockFullyTypeNameMap(); if (!mockFullyTypeNameMap.containsKey(key)) { mockFullyTypeNameMap.put(key, superJavaClassModel.getFullyType()); } javaMethodModelList1.add(javaMethodModel); } superJavaClassModel.setJavaMethodModelList(javaMethodModelList1); if (!javaClassModelMap.containsKey(superJavaClassModel.getFullyType())) { javaClassModelMap.put(superJavaClassModel.getFullyType(), superJavaClassModel); } //TODO 暂时只处理一个接口 ,如果是接口,暂时设置最后一个接口的全限定名称 - 后面需要将接口和类进行区分 javaMockClassInfoDTO.setParentClassFullyType(superClass.getFullyQualifiedName()); }
Example #14
Source File: MockClassInfo.java From auto-generate-test-maven-plugin with Apache License 2.0 | 4 votes |
/** * 获取方法的信息,参数,方法返回值,参数类型 * @param javaMethod 方法 * @param fieldName 调用该方法的变量名 * @param classType 该方法的类的类型 * @param superClass 父类 * @return 方法信息 */ private static JavaMethodModel getJavaMethodModel(JavaMethod javaMethod, String fieldName,String classType, JavaClass superClass) { JavaMethodModel javaMethodModel = new JavaMethodModel(); javaMethodModel.setFieldName(fieldName); javaMethodModel.setClassType(classType); javaMethodModel.setName(javaMethod.getName()); javaMethodModel.setName(javaMethod.getName()); //方法参数 List<JavaParameter> javaParameterList = javaMethod.getParameters(); List<JavaParameteModel> javaParameteModelList = new ArrayList<>(); for (JavaParameter javaParameter : javaParameterList) { JavaParameteModel javaParameteModel = new JavaParameteModel(); String typeS = javaParameter.getType().getFullyQualifiedName(); String pType = InitConstant.getAbbreviation(typeS); javaParameteModel.setName(javaParameter.getName()); javaParameteModel.setUpName(javaParameter.getName().substring(0, 1).toUpperCase() + javaParameter.getName().substring(1)); javaParameteModel.setType(pType); javaParameteModel.setFullyType(typeS); javaParameteModel.setKeyName(""); //TODO 设置值 javaParameteModel.setCustomType(true); javaParameteModel.setValue(""); javaParameteModelList.add(javaParameteModel); } javaMethodModel.setJavaParameteModelList(javaParameteModelList); String rTypeStr = javaMethod.getReturnType().getFullyQualifiedName(); javaMethodModel.setReturnFullyType(rTypeStr); String rType = InitConstant.getAbbreviation(rTypeStr); javaMethodModel.setReturnType(rType); if (superClass != null) { //设置父类类型 javaMethodModel.setParentClassFullyType(superClass.getFullyQualifiedName()); } return javaMethodModel; }
Example #15
Source File: BuildClassMethod.java From auto-generate-test-maven-plugin with Apache License 2.0 | 4 votes |
/** * 构建测试类核心方法 * @param javaClass 被测试类的信息 * @param javaGenInfoModel 贯穿本次类构造,记录类信息 * @return 方法DTO集合 */ public static List<JavaMethodDTO> build(JavaClass javaClass, JavaGenInfoModel javaGenInfoModel) { List<JavaMethodDTO> javaMethodDTOList = new ArrayList<>(); Map<String, Integer> methodMap = javaGenInfoModel.getMethodMap(); //获取方法集合 List<JavaMethod> javaMethodList = javaClass.getMethods(); //遍历类中的方法 for (JavaMethod javaMethod : javaMethodList) { JavaMethodDTO javaMethodDTO = new JavaMethodDTO(); //获取方法名称 String methodName = javaMethod.getName(); javaMethodDTO.setMethodName(methodName); //处理重名方法 methodDdealingWithRenaming(methodMap, methodName, javaMethodDTO); //获取方法返回类型 JavaClass returnValue = javaMethod.getReturns(); String returnValueStr = returnValue.getFullyQualifiedName(); javaMethodDTO.setReturnFullyType(returnValueStr); returnValueStr = InitConstant.getAbbreviation(returnValueStr); javaMethodDTO.setReturnType(returnValueStr); //排除静态方法和私有方法 if (excludeMethod(javaMethod)) { continue; } //方法参数的设置,包装类设置属性 默认值 BuildClassMethodParamete.build(javaMethod, javaGenInfoModel,javaMethodDTO); //方法抛出的异常 List<JavaExceptionsDTO> javaExceptionsDTOS = getJavaExceptionsDTOList(javaMethod); javaMethodDTO.setJavaExceptionsDTOList(javaExceptionsDTOS); //Mock方法的设置 BuildMockClassMethod.buildMock(javaGenInfoModel, javaMethod, javaMethodDTO); javaMethodDTOList.add(javaMethodDTO); } return javaMethodDTOList; }
Example #16
Source File: GenJava.java From auto-generate-test-maven-plugin with Apache License 2.0 | 4 votes |
/** * 开始生成测试类入口 * @param javaName 当前需要生成测试类的类全限定名称 */ public static void genTest(String javaName) { try { //类名 String className = javaName.substring(javaName.lastIndexOf("/") + 1, javaName.lastIndexOf(".")); //设置配置文件 Configuration cfg = getConfiguration(); String testJavaName = ConfigConstant.CONFIG_ENTITY.getBasedir() + BaseConstant.JAVA_TEST_SRC + ConfigConstant.CONFIG_ENTITY.getTestPackageName().replace(".", "/") + "/" + className + "Test.java"; log.info("生成的文件路径:" + testJavaName + ", className:" + className); //已经生成的测试类的方法名称 Set<String> testMethodNameSet = new HashSet<>(); boolean fileIsExists = false; File file = new File(testJavaName); //已经存在文件 if (file.exists()) { log.info(file + "已经存在,进行类方法追加生成"); //获取当前测试的类信息 String testClassName = ConfigConstant.CONFIG_ENTITY.getTestPackageName() + "." + className + "Test"; JavaClass testJavaClass = BaseConstant.javaProjectBuilder.getClassByName(testClassName); //遍历方法 List<JavaMethod> javaMethodList = testJavaClass.getMethods(); for (JavaMethod javaMethod : javaMethodList) { testMethodNameSet.add(javaMethod.getName()); log.info("获取测试类的方法名称:" + javaMethod.getName()); } log.info("获取的已经生成的类方法名称为:" + javaMethodList + ",测试类:" + testClassName); fileIsExists = true; } else { if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { log.error(file.getParentFile() + "生成失败"); return; } } JavaClassDTO javaClassDTO = new JavaClassDTO(); javaClassDTO.setDate(BaseConstant.DATE); javaClassDTO.setAuthor(ConfigConstant.CONFIG_ENTITY.getAuthor()); javaClassDTO.setModelNameUpperCamel(className); javaClassDTO.setModelNameLowerCamel(StringUtil.strConvertLowerCamel(className)); javaClassDTO.setModelNameUpperCamelTestClass(className + "Test"); javaClassDTO.setModelNameLowerCamelTestClass(StringUtil.strConvertLowerCamel(className + "Test")); //获取类中方法 if(!BuildClass.build(ConfigConstant.CONFIG_ENTITY.getTestPackageName() + "." + className,javaClassDTO)){ return; } Map<String, Object> data = new HashMap<>(2); data.put("javaClassDTO", javaClassDTO); //获取mock的类 if (!fileIsExists) { cfg.getTemplate(ConfigConstant.CONFIG_ENTITY.getConfigFileName()).process(data, new FileWriter(file)); log.info(file + "生成成功"); } else { File newFile = fileIsExists(className, cfg, testMethodNameSet, file, javaClassDTO, data); if (newFile == null) { log.error("追加方法失败"); return; } log.info(file + ", 追加方法成功,生成的临时文件:" + newFile); } } catch (Exception e) { log.error("生成失败,出现异常", e); } }
Example #17
Source File: IDocBuildTemplate.java From smart-doc with Apache License 2.0 | 4 votes |
default List<ApiParam> buildReturnApiParams(JavaMethod method, ProjectDocConfigBuilder projectBuilder) { if (method.getReturns().isVoid()) { return null; } ApiReturn apiReturn = DocClassUtil.processReturnType(method.getReturnType().getGenericCanonicalName()); String returnType = apiReturn.getGenericCanonicalName(); String typeName = apiReturn.getSimpleName(); if (this.ignoreReturnObject(typeName)) { return null; } if (JavaClassValidateUtil.isPrimitive(typeName)) { String processedName = projectBuilder.getApiConfig().getShowJavaType() ? JavaClassUtil.getClassSimpleName(typeName) : DocClassUtil.processTypeNameForParams(typeName); return ParamsBuildHelper.primitiveReturnRespComment(processedName); } if (JavaClassValidateUtil.isCollection(typeName)) { if (returnType.contains("<")) { String gicName = returnType.substring(returnType.indexOf("<") + 1, returnType.lastIndexOf(">")); if (JavaClassValidateUtil.isPrimitive(gicName)) { return ParamsBuildHelper.primitiveReturnRespComment("array of " + DocClassUtil.processTypeNameForParams(gicName)); } return ParamsBuildHelper.buildParams(gicName, "", 0, null, projectBuilder.getCustomRespFieldMap(), Boolean.TRUE, new HashMap<>(), projectBuilder, null); } else { return null; } } if (JavaClassValidateUtil.isMap(typeName)) { String[] keyValue = DocClassUtil.getMapKeyValueType(returnType); if (keyValue.length == 0) { return null; } if (JavaClassValidateUtil.isPrimitive(keyValue[1])) { return ParamsBuildHelper.primitiveReturnRespComment("key value"); } return ParamsBuildHelper.buildParams(keyValue[1], "", 0, null, projectBuilder.getCustomRespFieldMap(), Boolean.TRUE, new HashMap<>(), projectBuilder, null); } if (StringUtil.isNotEmpty(returnType)) { return ParamsBuildHelper.buildParams(returnType, "", 0, null, projectBuilder.getCustomRespFieldMap(), Boolean.TRUE, new HashMap<>(), projectBuilder, null); } return null; }
Example #18
Source File: SpringMVCRequestHeaderHandler.java From smart-doc with Apache License 2.0 | 4 votes |
/** * handle Spring MVC Request Header * * @param method JavaMethod * @return list of ApiReqHeader */ public List<ApiReqHeader> handle(JavaMethod method) { List<ApiReqHeader> apiReqHeaders = new ArrayList<>(); for (JavaParameter javaParameter : method.getParameters()) { List<JavaAnnotation> javaAnnotations = javaParameter.getAnnotations(); String className = method.getDeclaringClass().getCanonicalName(); Map<String, String> paramMap = DocUtil.getParamsComments(method, DocTags.PARAM, className); String paramName = javaParameter.getName(); ApiReqHeader apiReqHeader; for (JavaAnnotation annotation : javaAnnotations) { String annotationName = annotation.getType().getValue(); if (SpringMvcAnnotations.REQUEST_HERDER.equals(annotationName)) { apiReqHeader = new ApiReqHeader(); Map<String, Object> requestHeaderMap = annotation.getNamedParameterMap(); if (requestHeaderMap.get(DocAnnotationConstants.VALUE_PROP) != null) { apiReqHeader.setName(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.VALUE_PROP))); } else { apiReqHeader.setName(paramName); } StringBuilder desc = new StringBuilder(); String comments = paramMap.get(paramName); desc.append(comments); if (requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP) != null) { apiReqHeader.setValue(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP))); desc.append("(defaultValue: ") .append(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP))) .append(")"); } apiReqHeader.setDesc(desc.toString()); if (requestHeaderMap.get(DocAnnotationConstants.REQUIRED_PROP) != null) { apiReqHeader.setRequired(!Boolean.FALSE.toString().equals(requestHeaderMap.get(DocAnnotationConstants.REQUIRED_PROP))); } else { apiReqHeader.setRequired(true); } String typeName = javaParameter.getType().getValue().toLowerCase(); apiReqHeader.setType(DocClassUtil.processTypeNameForParams(typeName)); apiReqHeaders.add(apiReqHeader); break; } } } return apiReqHeaders; }
Example #19
Source File: TestParser.java From yatspec with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private static Sequence<JavaMethod> getMethods(JavaClass javaClass) { return sequence(javaClass.getMethods()).filter(where(annotations(), contains(Test.class))); }
Example #20
Source File: SpringMVCRequestMappingHandler.java From smart-doc with Apache License 2.0 | 4 votes |
/** * handle spring request mapping * * @param serverUrl server url * @param controllerBaseUrl spring mvc controller base url * @param method JavaMethod * @return RequestMapping */ public RequestMapping handle(String serverUrl, String controllerBaseUrl, JavaMethod method) { List<JavaAnnotation> annotations = method.getAnnotations(); String url; String methodType = null; String shortUrl = null; String mediaType = null; boolean deprecated = false; for (JavaAnnotation annotation : annotations) { String annotationName = annotation.getType().getName(); Object produces = annotation.getNamedParameter("produces"); if (produces != null) { mediaType = produces.toString(); } if ("Deprecated".equals(annotationName)) { deprecated = true; } if (SpringMvcAnnotations.REQUEST_MAPPING.equals(annotationName) || DocGlobalConstants.REQUEST_MAPPING_FULLY.equals(annotationName)) { shortUrl = DocUtil.handleMappingValue(annotation); Object nameParam = annotation.getNamedParameter("method"); if (null != nameParam) { methodType = nameParam.toString(); methodType = DocUtil.handleHttpMethod(methodType); } else { methodType = Methods.GET.getValue(); } } else if (SpringMvcAnnotations.GET_MAPPING.equals(annotationName) || DocGlobalConstants.GET_MAPPING_FULLY.equals(annotationName)) { shortUrl = DocUtil.handleMappingValue(annotation); methodType = Methods.GET.getValue(); } else if (SpringMvcAnnotations.POST_MAPPING.equals(annotationName) || DocGlobalConstants.POST_MAPPING_FULLY.equals(annotationName)) { shortUrl = DocUtil.handleMappingValue(annotation); methodType = Methods.POST.getValue(); } else if (SpringMvcAnnotations.PUT_MAPPING.equals(annotationName) || DocGlobalConstants.PUT_MAPPING_FULLY.equals(annotationName)) { shortUrl = DocUtil.handleMappingValue(annotation); methodType = Methods.PUT.getValue(); } else if (SpringMvcAnnotations.PATCH_MAPPING.equals(annotationName) || DocGlobalConstants.PATCH_MAPPING_FULLY.equals(annotationName)) { shortUrl = DocUtil.handleMappingValue(annotation); methodType = Methods.PATCH.getValue(); } else if (SpringMvcAnnotations.DELETE_MAPPING.equals(annotationName) || DocGlobalConstants.DELETE_MAPPING_FULLY.equals(annotationName)) { shortUrl = DocUtil.handleMappingValue(annotation); methodType = Methods.DELETE.getValue(); } } if (shortUrl != null) { if (null != method.getTagByName(IGNORE)) { return null; } shortUrl = StringUtil.removeQuotes(shortUrl); String[] urls = shortUrl.split(","); if (urls.length > 1) { url = DocUrlUtil.getMvcUrls(serverUrl, controllerBaseUrl, Arrays.asList(urls)); shortUrl = DocUrlUtil.getMvcUrls("", controllerBaseUrl, Arrays.asList(urls)); } else { url = UrlUtil.simplifyUrl(serverUrl + "/" + controllerBaseUrl + "/" + shortUrl); shortUrl = UrlUtil.simplifyUrl("/" + controllerBaseUrl + "/" + shortUrl); } return RequestMapping.builder().setMediaType(mediaType).setMethodType(methodType) .setUrl(url).setShortUrl(shortUrl).setDeprecated(deprecated); } return null; }
Example #21
Source File: SwaggerGenerator.java From onos with Apache License 2.0 | 4 votes |
private void processRestMethod(JavaMethod javaMethod, String method, Map<String, ObjectNode> pathMap, String resourcePath, ArrayNode tagArray, ObjectNode definitions, File srcDirectory) { String fullPath = resourcePath, consumes = "", produces = "", comment = javaMethod.getComment(); DocletTag tag = javaMethod.getTagByName("onos.rsModel"); for (JavaAnnotation annotation : javaMethod.getAnnotations()) { String name = annotation.getType().getName(); if (name.equals(PATH)) { fullPath = resourcePath + "/" + getPath(annotation); fullPath = fullPath.replaceFirst("^//", "/"); } if (name.equals(CONSUMES)) { consumes = getIOType(annotation); } if (name.equals(PRODUCES)) { produces = getIOType(annotation); } } ObjectNode methodNode = mapper.createObjectNode(); methodNode.set("tags", tagArray); addSummaryDescriptions(methodNode, comment); addJsonSchemaDefinition(srcDirectory, definitions, tag); processParameters(javaMethod, methodNode, method, tag); processConsumesProduces(methodNode, "consumes", consumes); processConsumesProduces(methodNode, "produces", produces); if (tag == null || !(tag.getParameters().size() > 1)) { addResponses(javaMethod, methodNode, tag, false); } else { addResponses(javaMethod, methodNode, tag, true); } ObjectNode operations = pathMap.get(fullPath); if (operations == null) { operations = mapper.createObjectNode(); operations.set(method, methodNode); pathMap.put(fullPath, operations); } else { operations.set(method, methodNode); } }
Example #22
Source File: SwaggerGenerator.java From onos with Apache License 2.0 | 4 votes |
private Optional<JavaAnnotation> getResponsesAnnotation(JavaMethod javaMethod) { return javaMethod.getAnnotations().stream().filter( a -> a.getType().getName().equals(RESPONSES) ).findAny(); }
Example #23
Source File: SwaggerGenerator.java From onos with Apache License 2.0 | 4 votes |
private void processParameters(JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) { ArrayNode parameters = mapper.createArrayNode(); methodNode.set("parameters", parameters); boolean required = true; for (JavaParameter javaParameter : javaMethod.getParameters()) { ObjectNode individualParameterNode = mapper.createObjectNode(); Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter( annotation -> annotation.getType().getName().equals(PATH_PARAM) || annotation.getType().getName().equals(QUERY_PARAM)).findAny(); JavaAnnotation pathType = optional.orElse(null); String annotationName = javaParameter.getName(); if (pathType != null) { //the parameter is a path or query parameter individualParameterNode.put("name", pathType.getNamedParameter("value") .toString().replace("\"", "")); if (pathType.getType().getName().equals(PATH_PARAM)) { individualParameterNode.put("in", "path"); } else if (pathType.getType().getName().equals(QUERY_PARAM)) { individualParameterNode.put("in", "query"); } individualParameterNode.put("type", getType(javaParameter.getType())); } else { // the parameter is a body parameter individualParameterNode.put("name", annotationName); individualParameterNode.put("in", "body"); // Adds the reference to the Json model for the input // that goes in the post or put operation if (tag != null && (method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))) { ObjectNode schema = mapper.createObjectNode(); tag.getParameters().stream().forEach(param -> { schema.put("$ref", "#/definitions/" + param); }); individualParameterNode.set("schema", schema); } } for (DocletTag p : javaMethod.getTagsByName("param")) { if (p.getValue().contains(annotationName)) { String description = ""; if (p.getValue().split(" ", 2).length >= 2) { description = p.getValue().split(" ", 2)[1].trim(); if (description.contains("optional")) { required = false; } } else { throw new RuntimeException(String.format("No description for parameter \"%s\" in " + "method \"%s\" in %s (line %d)", p.getValue(), javaMethod.getName(), javaMethod.getDeclaringClass().getName(), javaMethod.getLineNumber())); } individualParameterNode.put("description", description); } } individualParameterNode.put("required", required); parameters.add(individualParameterNode); } }
Example #24
Source File: OnosSwaggerMojo.java From onos with Apache License 2.0 | 4 votes |
private void processRestMethod(JavaMethod javaMethod, String method, Map<String, ObjectNode> pathMap, String resourcePath, ArrayNode tagArray, ObjectNode definitions) { String fullPath = resourcePath, consumes = "", produces = "", comment = javaMethod.getComment(); DocletTag tag = javaMethod.getTagByName("onos.rsModel"); for (JavaAnnotation annotation : javaMethod.getAnnotations()) { String name = annotation.getType().getName(); if (name.equals(PATH)) { fullPath = resourcePath + "/" + getPath(annotation); fullPath = fullPath.replaceFirst("^//", "/"); } if (name.equals(CONSUMES)) { consumes = getIOType(annotation); } if (name.equals(PRODUCES)) { produces = getIOType(annotation); } } ObjectNode methodNode = mapper.createObjectNode(); methodNode.set("tags", tagArray); addSummaryDescriptions(methodNode, comment); addJsonSchemaDefinition(definitions, tag); processParameters(javaMethod, methodNode, method, tag); processConsumesProduces(methodNode, "consumes", consumes); processConsumesProduces(methodNode, "produces", produces); if (tag == null || ((method.toLowerCase().equals("post") || method.toLowerCase().equals("put")) && !(tag.getParameters().size() > 1))) { addResponses(methodNode, tag, false); } else { addResponses(methodNode, tag, true); } ObjectNode operations = pathMap.get(fullPath); if (operations == null) { operations = mapper.createObjectNode(); operations.set(method, methodNode); pathMap.put(fullPath, operations); } else { operations.set(method, methodNode); } }
Example #25
Source File: OnosSwaggerMojo.java From onos with Apache License 2.0 | 4 votes |
private void processParameters(JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) { ArrayNode parameters = mapper.createArrayNode(); methodNode.set("parameters", parameters); boolean required = true; for (JavaParameter javaParameter : javaMethod.getParameters()) { ObjectNode individualParameterNode = mapper.createObjectNode(); Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter( annotation -> annotation.getType().getName().equals(PATH_PARAM) || annotation.getType().getName().equals(QUERY_PARAM)).findAny(); JavaAnnotation pathType = optional.orElse(null); String annotationName = javaParameter.getName(); if (pathType != null) { //the parameter is a path or query parameter individualParameterNode.put("name", pathType.getNamedParameter("value") .toString().replace("\"", "")); if (pathType.getType().getName().equals(PATH_PARAM)) { individualParameterNode.put("in", "path"); } else if (pathType.getType().getName().equals(QUERY_PARAM)) { individualParameterNode.put("in", "query"); } individualParameterNode.put("type", getType(javaParameter.getType())); } else { // the parameter is a body parameter individualParameterNode.put("name", annotationName); individualParameterNode.put("in", "body"); // Adds the reference to the Json model for the input // that goes in the post or put operation if (tag != null && (method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))) { ObjectNode schema = mapper.createObjectNode(); tag.getParameters().forEach(param -> { schema.put("$ref", "#/definitions/" + param); }); individualParameterNode.set("schema", schema); } } for (DocletTag p : javaMethod.getTagsByName("param")) { if (p.getValue().contains(annotationName)) { String description = ""; if (p.getValue().split(" ", 2).length >= 2) { description = p.getValue().split(" ", 2)[1].trim(); if (description.contains("optional")) { required = false; } } else { getLog().warn(String.format( "No description for parameter \"%s\" in " + "method \"%s\" in %s (line %d)", p.getValue(), javaMethod.getName(), javaMethod.getDeclaringClass().getName(), javaMethod.getLineNumber())); } individualParameterNode.put("description", description); } } individualParameterNode.put("required", required); parameters.add(individualParameterNode); } }
Example #26
Source File: DocUtil.java From smart-doc with Apache License 2.0 | 2 votes |
/** * obtain java doc tags comments,like apiNote * * @param javaMethod JavaMethod * @param tagName java comments tag * @param className class name * @return Map */ public static String getNormalTagComments(final JavaMethod javaMethod, final String tagName, final String className) { Map<String, String> map = getParamsComments(javaMethod, tagName, className); return getFirstKeyAndValue(map); }