diff --git a/src/main/java/com/power/doc/builder/openapi/AbstractOpenApiBuilder.java b/src/main/java/com/power/doc/builder/openapi/AbstractOpenApiBuilder.java index facded00..d5637d1c 100644 --- a/src/main/java/com/power/doc/builder/openapi/AbstractOpenApiBuilder.java +++ b/src/main/java/com/power/doc/builder/openapi/AbstractOpenApiBuilder.java @@ -59,6 +59,18 @@ @SuppressWarnings("all") public abstract class AbstractOpenApiBuilder { + private String componentKey; + + public String getComponentKey() { + return componentKey; + } + + public void setComponentKey(String componentKey) { + this.componentKey = componentKey; + } + + abstract String getModuleName(); + /** * Create OpenAPI definition * @@ -100,22 +112,22 @@ public abstract class AbstractOpenApiBuilder { public Map buildPaths(ApiConfig apiConfig, List apiDocList, Set tags) { Map pathMap = new HashMap<>(500); apiDocList.forEach( - a -> { - tags.add(OpenApiTag.of(a.getDesc(), a.getDesc())); - List apiMethodDocs = a.getList(); - apiMethodDocs.forEach( - method -> { - String url = method.getPath().replace("//", "/"); - Map request = buildPathUrls(apiConfig, method, a); - if (!pathMap.containsKey(url)) { - pathMap.put(url, request); - } else { - Map oldRequest = (Map) pathMap.get(url); - oldRequest.putAll(request); - } - } - ); - } + a -> { + tags.add(OpenApiTag.of(a.getDesc(), a.getDesc())); + List apiMethodDocs = a.getList(); + apiMethodDocs.forEach( + method -> { + String url = method.getPath().replace("//", "/"); + Map request = buildPathUrls(apiConfig, method, a); + if (!pathMap.containsKey(url)) { + pathMap.put(url, request); + } else { + Map oldRequest = (Map) pathMap.get(url); + oldRequest.putAll(request); + } + } + ); + } ); return pathMap; } @@ -140,13 +152,13 @@ public Map buildPathUrls(ApiConfig apiConfig, ApiMethodDoc apiMe * @param apiMethodDoc ApiMethodDoc * @param isRep is response */ - public static Map buildContent(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc, boolean isRep, String componentKey) { + public Map buildContent(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc, boolean isRep) { Map content = new HashMap<>(8); String contentType = apiMethodDoc.getContentType(); if (isRep) { contentType = "*/*"; } - content.put(contentType, buildContentBody(apiConfig, apiMethodDoc, isRep, componentKey)); + content.put(contentType, buildContentBody(apiConfig, apiMethodDoc, isRep)); return content; } @@ -158,19 +170,20 @@ public static Map buildContent(ApiConfig apiConfig, ApiMethodDoc * @param apiMethodDoc ApiMethodDoc * @param isRep is response */ - public static Map buildContentBody(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc, boolean isRep, String componentKey) { + public Map buildContentBody(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc, boolean isRep) { Map content = new HashMap<>(8); - if(OPENAPI_2_COMPONENT_KRY.equals(componentKey) && !isRep){ - content.put("name", apiMethodDoc.getName()); - } if (Objects.nonNull(apiMethodDoc.getReturnSchema()) && isRep) { content.put("schema", apiMethodDoc.getReturnSchema()); } else if (!isRep && Objects.nonNull(apiMethodDoc.getRequestSchema())) { content.put("schema", apiMethodDoc.getRequestSchema()); } else { - content.put("schema", buildBodySchema(apiMethodDoc, isRep, componentKey)); + content.put("schema", buildBodySchema(apiMethodDoc, isRep)); + } + + if (OPENAPI_2_COMPONENT_KRY.equals(componentKey) && !isRep) { + content.put("name", apiMethodDoc.getName()); } - if (OPENAPI_3_COMPONENT_KRY.equals (componentKey) && + if (OPENAPI_3_COMPONENT_KRY.equals(componentKey) && (!isRep && apiConfig.isRequestExample() || (isRep && apiConfig.isResponseExample()))) { content.put("examples", buildBodyExample(apiMethodDoc, isRep)); } @@ -184,17 +197,17 @@ public static Map buildContentBody(ApiConfig apiConfig, ApiMetho * @param apiMethodDoc ApiMethodDoc * @param isRep is response */ - public static Map buildBodySchema(ApiMethodDoc apiMethodDoc, boolean isRep, String componentsKey) { + public Map buildBodySchema(ApiMethodDoc apiMethodDoc, boolean isRep) { Map schema = new HashMap<>(10); Map innerScheme = new HashMap<>(10); String requestRef; if (apiMethodDoc.getContentType().equals(DocGlobalConstants.URL_CONTENT_TYPE)) { - requestRef = componentsKey + OpenApiSchemaUtil.getClassNameFromParams(apiMethodDoc.getQueryParams()); + requestRef = componentKey + OpenApiSchemaUtil.getClassNameFromParams(apiMethodDoc.getQueryParams(), COMPONENT_REQUEST_SUFFIX); } else { - requestRef = componentsKey + OpenApiSchemaUtil.getClassNameFromParams(apiMethodDoc.getRequestParams()); + requestRef = componentKey + OpenApiSchemaUtil.getClassNameFromParams(apiMethodDoc.getRequestParams(), COMPONENT_REQUEST_SUFFIX); } //remove special characters in url - String responseRef = componentsKey + OpenApiSchemaUtil.getClassNameFromParams(apiMethodDoc.getResponseParams()); + String responseRef = componentKey + OpenApiSchemaUtil.getClassNameFromParams(apiMethodDoc.getResponseParams(), COMPONENT_RESPONSE_SUFFIX); //List param if (apiMethodDoc.getIsRequestArray() == 1) { @@ -239,8 +252,8 @@ public static Map buildExampleData(ApiMethodDoc apiMethodDoc, bo content.put("summary", "test data"); if (!isRep) { content.put("value", StringUtil.isEmpty( - apiMethodDoc.getRequestExample().getJsonBody()) ? apiMethodDoc.getRequestExample().getExampleBody() : - apiMethodDoc.getRequestExample().getJsonBody()); + apiMethodDoc.getRequestExample().getJsonBody()) ? apiMethodDoc.getRequestExample().getExampleBody() : + apiMethodDoc.getRequestExample().getJsonBody()); } else { content.put("value", apiMethodDoc.getResponseUsage()); } @@ -322,14 +335,14 @@ public Map buildResponses(ApiConfig apiConfig, ApiMethodDoc apiM * * @param apiDocs List of ApiDoc */ - abstract public Map buildComponentsSchema(List apiDocs); + abstract public Map buildComponentsSchema(List apiDocs); /** * component schema properties * * @param apiParam list of ApiParam */ - public static Map buildProperties(List apiParam, Map component,String commpentKey) { + public Map buildProperties(List apiParam, Map component, boolean isResp) { Map properties = new HashMap<>(); Map propertiesData = new LinkedHashMap<>(); List requiredList = new ArrayList<>(); @@ -346,7 +359,7 @@ public static Map buildProperties(List apiParam, Map buildProperties(List apiParam, Map buildPropertiesData(ApiParam apiParam, Map component, String componentKey) { + private Map buildPropertiesData(ApiParam apiParam, Map component, boolean isResp) { Map propertiesData = new HashMap<>(); String openApiType = DocUtil.javaTypeToOpenApiTypeConvert(apiParam.getType()); //array object file map propertiesData.put("description", apiParam.getDesc()); - propertiesData.put("example",StringUtil.removeDoubleQuotes(apiParam.getValue())); + propertiesData.put("example", StringUtil.removeDoubleQuotes(apiParam.getValue())); if (!"object".equals(openApiType)) { propertiesData.put("type", openApiType); @@ -386,25 +399,24 @@ private static Map buildPropertiesData(ApiParam apiParam, Map arrayRef = new HashMap<>(4); - String childSchemaName = OpenApiSchemaUtil.getClassNameFromParams(apiParam.getChildren()); + String suffix = isResp ? COMPONENT_RESPONSE_SUFFIX : COMPONENT_REQUEST_SUFFIX; + String childSchemaName = OpenApiSchemaUtil.getClassNameFromParams(apiParam.getChildren(), suffix); if (childSchemaName.contains(OpenApiSchemaUtil.NO_BODY_PARAM)) { propertiesData.put("type", "object"); propertiesData.put("description", apiParam.getDesc() + "(object)"); } else { - component.put(childSchemaName, buildProperties(apiParam.getChildren(), component,componentKey)); + component.put(childSchemaName, buildProperties(apiParam.getChildren(), component, isResp)); arrayRef.put("$ref", componentKey + childSchemaName); propertiesData.put("items", arrayRef); } } } //基础数据类型 - else{ + else { Map arrayRef = new HashMap<>(4); arrayRef.put("type", "string"); propertiesData.put("items", arrayRef); } - - } if ("file".equals(apiParam.getType())) { propertiesData.put("type", "string"); @@ -414,13 +426,14 @@ private static Map buildPropertiesData(ApiParam apiParam, Map apiDocList = INSTANCE.getOpenApiDocs(config,projectBuilder); + List apiDocList = INSTANCE.getOpenApiDocs(config, projectBuilder); INSTANCE.openApiCreate(config, apiDocList); } @@ -88,6 +88,7 @@ public static void buildOpenApi(ApiConfig config, JavaProjectBuilder projectBuil */ @Override public void openApiCreate(ApiConfig config, List apiDocList) { + this.setComponentKey(getModuleName()); Map json = new HashMap<>(8); json.put("openapi", "3.0.3"); json.put("info", buildInfo(config)); @@ -145,7 +146,7 @@ public Map buildPathUrlsRequest(ApiConfig apiConfig, ApiMethodDo } else { request.put("tags", new String[]{apiDoc.getDesc()}); } - request.put("requestBody", buildRequestBody(apiConfig, apiMethodDoc, DocGlobalConstants.OPENAPI_3_COMPONENT_KRY)); + request.put("requestBody", buildRequestBody(apiConfig, apiMethodDoc)); request.put("parameters", buildParameters(apiMethodDoc)); request.put("responses", buildResponses(apiConfig, apiMethodDoc)); request.put("deprecated", apiMethodDoc.isDeprecated()); @@ -159,14 +160,14 @@ public Map buildPathUrlsRequest(ApiConfig apiConfig, ApiMethodDo * * @param apiMethodDoc ApiMethodDoc */ - private static Map buildRequestBody(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc, String componentKey) { + private Map buildRequestBody(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc) { Map requestBody = new HashMap<>(8); boolean isPost = (apiMethodDoc.getType().equals(Methods.POST.getValue()) - || apiMethodDoc.getType().equals(Methods.PUT.getValue()) || - apiMethodDoc.getType().equals(Methods.PATCH.getValue())); + || apiMethodDoc.getType().equals(Methods.PUT.getValue()) || + apiMethodDoc.getType().equals(Methods.PATCH.getValue())); //add content of post method if (isPost) { - requestBody.put("content", buildContent(apiConfig, apiMethodDoc, false, componentKey)); + requestBody.put("content", buildContent(apiConfig, apiMethodDoc, false)); return requestBody; } return null; @@ -183,7 +184,7 @@ private static Map buildRequestBody(ApiConfig apiConfig, ApiMeth public Map buildResponsesBody(ApiConfig apiConfig, ApiMethodDoc apiMethodDoc) { Map responseBody = new HashMap<>(10); responseBody.put("description", "OK"); - responseBody.put("content", buildContent(apiConfig, apiMethodDoc, true, DocGlobalConstants.OPENAPI_3_COMPONENT_KRY)); + responseBody.put("content", buildContent(apiConfig, apiMethodDoc, true)); return responseBody; } @@ -261,31 +262,31 @@ Map getStringParams(ApiParam apiParam, boolean hasItems) { @Override public Map buildComponentsSchema(List apiDocs) { - Map schemas = new HashMap<>(4); - Map component = new HashMap<>(); - component.put("string", STRING_COMPONENT); - apiDocs.forEach( - a -> { - List apiMethodDocs = a.getList(); - apiMethodDocs.forEach( - method -> { - //request components - String requestSchema = OpenApiSchemaUtil.getClassNameFromParams(method.getRequestParams()); - List requestParams = method.getRequestParams(); - Map prop = buildProperties(requestParams, component,OPENAPI_3_COMPONENT_KRY); - component.put(requestSchema, prop); - //response components - List responseParams = method.getResponseParams(); - String schemaName = OpenApiSchemaUtil.getClassNameFromParams(method.getResponseParams()); - component.put(schemaName, buildProperties(responseParams, component,OPENAPI_3_COMPONENT_KRY)); - } - ); - } - ); - component.remove(OpenApiSchemaUtil.NO_BODY_PARAM); - schemas.put("schemas", component); - return schemas; - } + Map schemas = new HashMap<>(4); + Map component = new HashMap<>(); + component.put("string", STRING_COMPONENT); + apiDocs.forEach( + a -> { + List apiMethodDocs = a.getList(); + apiMethodDocs.forEach( + method -> { + //request components + String requestSchema = OpenApiSchemaUtil.getClassNameFromParams(method.getRequestParams(), COMPONENT_REQUEST_SUFFIX); + List requestParams = method.getRequestParams(); + Map prop = buildProperties(requestParams, component, false); + component.put(requestSchema, prop); + //response components + List responseParams = method.getResponseParams(); + String schemaName = OpenApiSchemaUtil.getClassNameFromParams(method.getResponseParams(), COMPONENT_RESPONSE_SUFFIX); + component.put(schemaName, buildProperties(responseParams, component, true)); + } + ); + } + ); + component.remove(OpenApiSchemaUtil.NO_BODY_PARAM); + schemas.put("schemas", component); + return schemas; + } } diff --git a/src/main/java/com/power/doc/builder/openapi/SwaggerBuilder.java b/src/main/java/com/power/doc/builder/openapi/SwaggerBuilder.java index 976b3a6b..180aa96e 100644 --- a/src/main/java/com/power/doc/builder/openapi/SwaggerBuilder.java +++ b/src/main/java/com/power/doc/builder/openapi/SwaggerBuilder.java @@ -84,12 +84,18 @@ public static void buildOpenApi(ApiConfig config, JavaProjectBuilder projectBuil INSTANCE.openApiCreate(config, apiDocList); } + @Override + String getModuleName() { + return OPENAPI_2_COMPONENT_KRY; + } + /** * Build OpenApi * * @param config Configuration of smart-doc */ public void openApiCreate(ApiConfig config, List apiDocList) { + this.setComponentKey(getModuleName()); Map json = new HashMap<>(8); json.put("swagger", "2.0"); json.put("info", buildInfo(config)); @@ -158,7 +164,7 @@ public Map buildPathUrlsRequest(ApiConfig apiConfig, ApiMethodDo if (CollectionUtil.isNotEmpty(apiMethodDoc.getRequestParams())) { Map parameter = new HashMap<>(); parameter.put("in", "body"); - parameter.putAll(buildContentBody(apiConfig, apiMethodDoc, false, OPENAPI_2_COMPONENT_KRY)); + parameter.putAll(buildContentBody(apiConfig, apiMethodDoc, false)); parameters.add(parameter); } request.put("parameters", parameters); @@ -179,7 +185,7 @@ public Map buildResponsesBody(ApiConfig apiConfig, ApiMethodDoc Map responseBody = new HashMap<>(10); responseBody.put("description", "OK"); if (CollectionUtil.isNotEmpty(apiMethodDoc.getResponseParams())) { - responseBody.putAll(buildContentBody(apiConfig, apiMethodDoc, true, OPENAPI_2_COMPONENT_KRY)); + responseBody.putAll(buildContentBody(apiConfig, apiMethodDoc, true)); } return responseBody; } @@ -265,14 +271,14 @@ public Map buildComponentsSchema(List apiDocs) { apiMethodDocs.forEach( method -> { //request components - String requestSchema = OpenApiSchemaUtil.getClassNameFromParams(method.getRequestParams()); + String requestSchema = OpenApiSchemaUtil.getClassNameFromParams(method.getRequestParams(), COMPONENT_REQUEST_SUFFIX); List requestParams = method.getRequestParams(); - Map prop = buildProperties(requestParams, component, OPENAPI_2_COMPONENT_KRY); + Map prop = buildProperties(requestParams, component, false); component.put(requestSchema, prop); //response components List responseParams = method.getResponseParams(); - String schemaName = OpenApiSchemaUtil.getClassNameFromParams(method.getResponseParams()); - component.put(schemaName, buildProperties(responseParams, component, OPENAPI_2_COMPONENT_KRY)); + String schemaName = OpenApiSchemaUtil.getClassNameFromParams(method.getResponseParams(), COMPONENT_RESPONSE_SUFFIX); + component.put(schemaName, buildProperties(responseParams, component, true)); } ); } diff --git a/src/main/java/com/power/doc/constants/DocGlobalConstants.java b/src/main/java/com/power/doc/constants/DocGlobalConstants.java index 8bd509ba..f98ceb4d 100644 --- a/src/main/java/com/power/doc/constants/DocGlobalConstants.java +++ b/src/main/java/com/power/doc/constants/DocGlobalConstants.java @@ -249,4 +249,8 @@ public interface DocGlobalConstants { String OPENAPI_2_COMPONENT_KRY = "#/definitions/"; String OPENAPI_3_COMPONENT_KRY = "#/components/schemas/"; + + String COMPONENT_REQUEST_SUFFIX = "_request"; + + String COMPONENT_RESPONSE_SUFFIX = "_response"; } diff --git a/src/main/java/com/power/doc/template/IRestDocTemplate.java b/src/main/java/com/power/doc/template/IRestDocTemplate.java index 61eb4593..dbd1ae8c 100644 --- a/src/main/java/com/power/doc/template/IRestDocTemplate.java +++ b/src/main/java/com/power/doc/template/IRestDocTemplate.java @@ -79,7 +79,7 @@ public interface IRestDocTemplate extends IBaseDocBuildTemplate { AtomicInteger atomicInteger = new AtomicInteger(1); default List processApiData(ProjectDocConfigBuilder projectBuilder, FrameworkAnnotations frameworkAnnotations, - List configApiReqParams, IRequestMappingHandler baseMappingHandler, IHeaderHandler headerHandler) { + List configApiReqParams, IRequestMappingHandler baseMappingHandler, IHeaderHandler headerHandler) { ApiConfig apiConfig = projectBuilder.getApiConfig(); List apiDocList = new ArrayList<>(); int order = 0; @@ -105,7 +105,7 @@ default List processApiData(ProjectDocConfigBuilder projectBuilder, Fram order = Integer.parseInt(strOrder); } List apiMethodDocs = buildEntryPointMethod(cls, apiConfig, projectBuilder, - frameworkAnnotations, configApiReqParams, baseMappingHandler, headerHandler); + frameworkAnnotations, configApiReqParams, baseMappingHandler, headerHandler); this.handleApiDoc(cls, apiDocList, apiMethodDocs, order, apiConfig.isMd5EncryptedHtmlName()); } apiDocList = handleTagsApiDoc(apiDocList); @@ -114,8 +114,8 @@ default List processApiData(ProjectDocConfigBuilder projectBuilder, Fram } else if (setCustomOrder) { // while set custom oder return apiDocList.stream() - .sorted(Comparator.comparing(ApiDoc::getOrder)) - .peek(p -> p.setOrder(atomicInteger.getAndAdd(1))).collect(Collectors.toList()); + .sorted(Comparator.comparing(ApiDoc::getOrder)) + .peek(p -> p.setOrder(atomicInteger.getAndAdd(1))).collect(Collectors.toList()); } return apiDocList; } @@ -127,11 +127,11 @@ default String createDocRenderHeaders(List headers, boolean isAdoc) } for (ApiReqParam header : headers) { builder.append("|") - .append(header.getName()).append("|") - .append(header.getType()).append("|") - .append(header.isRequired()).append("|") - .append(header.getDesc()).append("|") - .append(header.getSince()).append("|\n"); + .append(header.getName()).append("|") + .append(header.getType()).append("|") + .append(header.isRequired()).append("|") + .append(header.getDesc()).append("|") + .append(header.getSince()).append("|\n"); } return builder.toString(); } @@ -180,12 +180,12 @@ default void mappingParamToApiParam(String str, List paramList, Map getClassAnnotations(JavaClass cls, FrameworkAnnotat } default List buildEntryPointMethod(final JavaClass cls, ApiConfig apiConfig, - ProjectDocConfigBuilder projectBuilder, FrameworkAnnotations frameworkAnnotations, - List configApiReqParams, IRequestMappingHandler baseMappingHandler, IHeaderHandler headerHandler) { + ProjectDocConfigBuilder projectBuilder, FrameworkAnnotations frameworkAnnotations, + List configApiReqParams, IRequestMappingHandler baseMappingHandler, IHeaderHandler headerHandler) { String clazName = cls.getCanonicalName(); boolean paramsDataToTree = projectBuilder.getApiConfig().isParamsDataToTree(); String group = JavaClassUtil.getClassTagsValue(cls, DocTags.GROUP, Boolean.TRUE); @@ -310,7 +310,7 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig } if (CollectionUtil.isNotEmpty(mappingAnnotation.getPathProps())) { baseUrl = StringUtil.removeQuotes(DocUtil.getPathUrl(annotation, mappingAnnotation.getPathProps() - .toArray(new String[0]))); + .toArray(new String[0]))); } } @@ -343,8 +343,8 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig JavaMethod method = docJavaMethod.getJavaMethod(); //handle request mapping RequestMapping requestMapping = baseMappingHandler.handle(projectBuilder, baseUrl, - method, frameworkAnnotations, - (javaClass, mapping) -> this.requestMappingPostProcess(javaClass, method, mapping)); + method, frameworkAnnotations, + (javaClass, mapping) -> this.requestMappingPostProcess(javaClass, method, mapping)); if (Objects.isNull(requestMapping)) { continue; } @@ -382,7 +382,7 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig apiMethodDoc.setDeprecated(requestMapping.isDeprecated()); final List apiReqParamList = configApiReqParams.stream() - .filter(param -> DocUtil.filterPath(requestMapping, param)).collect(Collectors.toList()); + .filter(param -> DocUtil.filterPath(requestMapping, param)).collect(Collectors.toList()); // build request params ApiMethodReqParam apiMethodReqParam = requestParams(docJavaMethod, projectBuilder, apiReqParamList, frameworkAnnotations); @@ -398,7 +398,7 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig final Map> reqParamMap = configApiReqParams.stream().collect(Collectors.groupingBy(ApiReqParam::getParamIn)); final List headerParamList = reqParamMap.getOrDefault(ApiReqParamInTypeEnum.HEADER.getValue(), Collections.emptyList()); allApiReqHeaders = Stream.of(headerParamList, apiReqHeaders).filter(Objects::nonNull) - .flatMap(Collection::stream).distinct().filter(param -> DocUtil.filterPath(requestMapping, param)).collect(Collectors.toList()); + .flatMap(Collection::stream).distinct().filter(param -> DocUtil.filterPath(requestMapping, param)).collect(Collectors.toList()); //reduce create in template apiMethodDoc.setHeaders(this.createDocRenderHeaders(allApiReqHeaders, apiConfig.isAdoc())); @@ -417,7 +417,7 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig // build request json ApiRequestExample requestExample = buildReqJson(docJavaMethod, apiMethodDoc, requestMapping.getMethodType(), - projectBuilder, frameworkAnnotations); + projectBuilder, frameworkAnnotations); String requestJson = requestExample.getExampleBody(); // set request example detail apiMethodDoc.setRequestExample(requestExample); @@ -439,7 +439,7 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig apiMethodDoc.setRequestSchema(docJavaMethod.getRequestSchema()); apiMethodDoc.setResponseParams(responseParams); - TornaUtil.setTornaArrayTags(apiMethodDoc); + TornaUtil.setTornaArrayTags(docJavaMethod.getJavaMethod(), apiMethodDoc); methodDocList.add(apiMethodDoc); } @@ -447,15 +447,15 @@ default List buildEntryPointMethod(final JavaClass cls, ApiConfig } default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc apiMethodDoc, String methodType, - ProjectDocConfigBuilder configBuilder, FrameworkAnnotations frameworkAnnotations) { + ProjectDocConfigBuilder configBuilder, FrameworkAnnotations frameworkAnnotations) { JavaMethod method = javaMethod.getJavaMethod(); Map pathParamsMap = new LinkedHashMap<>(); Map queryParamsMap = new LinkedHashMap<>(); apiMethodDoc.getPathParams().stream().filter(Objects::nonNull).filter(p -> StringUtil.isNotEmpty(p.getValue()) || p.isConfigParam()) - .forEach(param -> pathParamsMap.put(param.getSourceField(), param.getValue())); + .forEach(param -> pathParamsMap.put(param.getSourceField(), param.getValue())); apiMethodDoc.getQueryParams().stream().filter(Objects::nonNull).filter(p -> StringUtil.isNotEmpty(p.getValue()) || p.isConfigParam()) - .forEach(param -> queryParamsMap.put(param.getSourceField(), param.getValue())); + .forEach(param -> queryParamsMap.put(param.getSourceField(), param.getValue())); List methodAnnotations = method.getAnnotations(); Map mappingAnnotationMap = frameworkAnnotations.getMappingAnnotations(); for (JavaAnnotation annotation : methodAnnotations) { @@ -487,10 +487,10 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap url = apiMethodDoc.getServerUrl() + "/" + url; url = UrlUtil.simplifyUrl(url); CurlRequest curlRequest = CurlRequest.builder() - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); String format = CurlUtil.toCurl(curlRequest); return ApiRequestExample.builder().setUrl(apiMethodDoc.getUrl()).setExampleBody(format); } @@ -556,7 +556,7 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap requestExample.setJsonBody(mockValue).setJson(true); } else { String json = JsonBuildHelper.buildJson(typeName, gicTypeName, Boolean.FALSE, 0, new HashMap<>(), groupClasses, - configBuilder); + configBuilder); requestExample.setJsonBody(JsonUtil.toPrettyFormat(json)).setJson(true); } queryParamsMap.remove(paramName); @@ -621,9 +621,9 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap gicName = gicName.substring(0, gicName.indexOf("[")); } if (!JavaClassValidateUtil.isPrimitive(gicName) - && !configBuilder.getJavaProjectBuilder().getClassByName(gicName).isEnum()) { + && !configBuilder.getJavaProjectBuilder().getClassByName(gicName).isEnum()) { throw new RuntimeException("can't support binding Collection on method " - + method.getName() + "Check it in " + method.getDeclaringClass().getCanonicalName()); + + method.getName() + "Check it in " + method.getDeclaringClass().getCanonicalName()); } String value; JavaClass javaClass1 = configBuilder.getClassByName(gicName); @@ -659,7 +659,7 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap // set content-type to fromData boolean hasFormDataUploadFile = formDataList.stream().anyMatch(form -> Objects.equals(form.getType(), DocGlobalConstants.PARAM_TYPE_FILE)); Map> formDataGroupMap = formDataList.stream() - .collect(Collectors.groupingBy(e -> Objects.equals(e.getType(), DocGlobalConstants.PARAM_TYPE_FILE))); + .collect(Collectors.groupingBy(e -> Objects.equals(e.getType(), DocGlobalConstants.PARAM_TYPE_FILE))); List fileFormDataList = formDataGroupMap.getOrDefault(Boolean.TRUE, new ArrayList<>()); if (hasFormDataUploadFile) { formDataList = formDataGroupMap.getOrDefault(Boolean.FALSE, new ArrayList<>()); @@ -680,7 +680,7 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap //for post put path = DocUtil.formatAndRemove(path, pathParamsMap); body = UrlUtil.urlJoin(DocGlobalConstants.EMPTY, queryParamsMap) - .replace("?", DocGlobalConstants.EMPTY); + .replace("?", DocGlobalConstants.EMPTY); body = StringUtil.removeQuotes(body); url = apiMethodDoc.getServerUrl() + "/" + path; url = UrlUtil.simplifyUrl(url); @@ -690,30 +690,30 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap url = url + "?" + body; } CurlRequest curlRequest = CurlRequest.builder() - .setBody(requestExample.getJsonBody()) - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(requestExample.getJsonBody()) + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); exampleBody = CurlUtil.toCurl(curlRequest); } else { CurlRequest curlRequest; if (StringUtil.isNotEmpty(body)) { curlRequest = CurlRequest.builder() - .setBody(body) - .setContentType(apiMethodDoc.getContentType()) - .setFileFormDataList(fileFormDataList) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(body) + .setContentType(apiMethodDoc.getContentType()) + .setFileFormDataList(fileFormDataList) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); } else { curlRequest = CurlRequest.builder() - .setBody(requestExample.getJsonBody()) - .setContentType(apiMethodDoc.getContentType()) - .setFileFormDataList(fileFormDataList) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(requestExample.getJsonBody()) + .setContentType(apiMethodDoc.getContentType()) + .setFileFormDataList(fileFormDataList) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); } exampleBody = CurlUtil.toCurl(curlRequest); } @@ -722,23 +722,23 @@ default ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap // for get delete url = formatRequestUrl(pathParamsMap, queryParamsMap, apiMethodDoc.getServerUrl(), path); CurlRequest curlRequest = CurlRequest.builder() - .setBody(requestExample.getJsonBody()) - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(requestExample.getJsonBody()) + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); exampleBody = CurlUtil.toCurl(curlRequest); requestExample.setExampleBody(exampleBody) - .setJsonBody(requestExample.isJson() ? requestExample.getJsonBody() : DocGlobalConstants.EMPTY) - .setUrl(url); + .setJsonBody(requestExample.isJson() ? requestExample.getJsonBody() : DocGlobalConstants.EMPTY) + .setUrl(url); } return requestExample; } default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, ProjectDocConfigBuilder builder, - List configApiReqParams, FrameworkAnnotations frameworkAnnotations) { + List configApiReqParams, FrameworkAnnotations frameworkAnnotations) { JavaMethod javaMethod = docJavaMethod.getJavaMethod(); boolean isStrict = builder.getApiConfig().isStrict(); String className = javaMethod.getDeclaringClass().getCanonicalName(); @@ -768,22 +768,22 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje } } final Map> collect = configApiReqParams.stream().collect(Collectors.groupingBy(ApiReqParam::getParamIn, - Collectors.toMap(ApiReqParam::getName, m -> m, (k1, k2) -> k1))); + Collectors.toMap(ApiReqParam::getName, m -> m, (k1, k2) -> k1))); final Map pathReqParamMap = collect.getOrDefault(ApiReqParamInTypeEnum.PATH.getValue(), Collections.emptyMap()); final Map queryReqParamMap = collect.getOrDefault(ApiReqParamInTypeEnum.QUERY.getValue(), Collections.emptyMap()); List parameterList = getJavaParameterList(builder, docJavaMethod, frameworkAnnotations); if (parameterList.isEmpty()) { AtomicInteger querySize = new AtomicInteger(paramList.size() + 1); paramList.addAll(queryReqParamMap.values().stream() - .map(p -> ApiReqParam.convertToApiParam(p).setQueryParam(true).setId(querySize.getAndIncrement())) - .collect(Collectors.toList())); + .map(p -> ApiReqParam.convertToApiParam(p).setQueryParam(true).setId(querySize.getAndIncrement())) + .collect(Collectors.toList())); AtomicInteger pathSize = new AtomicInteger(1); return ApiMethodReqParam.builder() - .setPathParams(new ArrayList<>(pathReqParamMap.values().stream() - .map(p -> ApiReqParam.convertToApiParam(p).setPathParam(true).setId(pathSize.getAndIncrement())) - .collect(Collectors.toList()))) - .setQueryParams(paramList) - .setRequestParams(new ArrayList<>(0)); + .setPathParams(new ArrayList<>(pathReqParamMap.values().stream() + .map(p -> ApiReqParam.convertToApiParam(p).setPathParam(true).setId(pathSize.getAndIncrement())) + .collect(Collectors.toList()))) + .setQueryParams(paramList) + .setRequestParams(new ArrayList<>(0)); } boolean requestFieldToUnderline = builder.getApiConfig().isRequestFieldToUnderline(); int requestBodyCounter = 0; @@ -800,7 +800,7 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje String fullTypeName = apiParameter.getFullyQualifiedName(); if (!paramTagMap.containsKey(paramName) && JavaClassValidateUtil.isPrimitive(fullTypeName) && isStrict) { throw new RuntimeException("ERROR: Unable to find javadoc @param for actual param \"" - + paramName + "\" in method " + javaMethod.getName() + " from " + className); + + paramName + "\" in method " + javaMethod.getName() + " from " + className); } StringBuilder comment = new StringBuilder(this.paramCommentResolve(paramTagMap.get(paramName))); if (requestFieldToUnderline) { @@ -820,7 +820,7 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje continue out; } if (frameworkAnnotations.getRequestParamAnnotation().getAnnotationName().equals(annotationName) || - frameworkAnnotations.getPathVariableAnnotation().getAnnotationName().equals(annotationName)) { + frameworkAnnotations.getPathVariableAnnotation().getAnnotationName().equals(annotationName)) { String defaultValueProp = DocAnnotationConstants.DEFAULT_VALUE_PROP; String requiredProp = DocAnnotationConstants.REQUIRED_PROP; if (frameworkAnnotations.getRequestParamAnnotation().getAnnotationName().equals(annotationName)) { @@ -850,7 +850,7 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje if (frameworkAnnotations.getRequestBodyAnnotation().getAnnotationName().equals(annotationName)) { if (requestBodyCounter > 0) { throw new RuntimeException("You have use @RequestBody Passing multiple variables for method " - + javaMethod.getName() + " in " + className + ",@RequestBody annotation could only bind one variables."); + + javaMethod.getName() + " in " + className + ",@RequestBody annotation could only bind one variables."); } mockValue = JsonBuildHelper.buildJson(fullTypeName, typeName, Boolean.FALSE, 0, new HashMap<>(), groupClasses, builder); requestBodyCounter++; @@ -862,9 +862,9 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje //file upload if (JavaClassValidateUtil.isFile(typeName)) { ApiParam param = ApiParam.of().setField(paramName).setType(DocGlobalConstants.PARAM_TYPE_FILE) - .setId(paramList.size() + 1).setQueryParam(true) - .setRequired(required).setVersion(DocGlobalConstants.DEFAULT_VERSION) - .setDesc(comment.toString()); + .setId(paramList.size() + 1).setQueryParam(true) + .setRequired(required).setVersion(DocGlobalConstants.DEFAULT_VERSION) + .setDesc(comment.toString()); if (typeName.contains("[]") || typeName.endsWith(">")) { comment.append("(array of file)"); param.setType(DocGlobalConstants.PARAM_TYPE_FILE); @@ -891,13 +891,13 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje if (gicJavaClass.isEnum()) { Object value = JavaClassUtil.getEnumValue(gicJavaClass, Boolean.TRUE); ApiParam param = ApiParam.of().setField(paramName).setDesc(comment + ",[array of enum]") - .setRequired(required) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setId(paramList.size() + 1) - .setEnumValues(JavaClassUtil.getEnumValues(gicJavaClass)) - .setEnumInfo(JavaClassUtil.getEnumInfo(gicJavaClass, builder)) - .setType("array").setValue(String.valueOf(value)); + .setRequired(required) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setId(paramList.size() + 1) + .setEnumValues(JavaClassUtil.getEnumValues(gicJavaClass)) + .setEnumInfo(JavaClassUtil.getEnumInfo(gicJavaClass, builder)) + .setType("array").setValue(String.valueOf(value)); paramList.add(param); if (requestBodyCounter > 0) { Map map = OpenApiSchemaUtil.arrayTypeSchema(gicName); @@ -906,15 +906,15 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje } else if (JavaClassValidateUtil.isPrimitive(gicName)) { String shortSimple = DocClassUtil.processTypeNameForParams(gicName); ApiParam param = ApiParam.of() - .setField(paramName) - .setDesc(comment + ",[array of " + shortSimple + "]") - .setRequired(required) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setId(paramList.size() + 1) - .setType("array") - .setVersion(DocGlobalConstants.DEFAULT_VERSION) - .setValue(mockValue); + .setField(paramName) + .setDesc(comment + ",[array of " + shortSimple + "]") + .setRequired(required) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setId(paramList.size() + 1) + .setType("array") + .setVersion(DocGlobalConstants.DEFAULT_VERSION) + .setValue(mockValue); paramList.add(param); if (requestBodyCounter > 0) { Map map = OpenApiSchemaUtil.arrayTypeSchema(gicName); @@ -923,33 +923,33 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje } else if (JavaClassValidateUtil.isFile(gicName)) { //file upload ApiParam param = ApiParam.of().setField(paramName) - .setType(DocGlobalConstants.PARAM_TYPE_FILE) - .setId(paramList.size() + 1) - .setQueryParam(true) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION) - .setHasItems(true) - .setDesc(comment + "(array of file)"); + .setType(DocGlobalConstants.PARAM_TYPE_FILE) + .setId(paramList.size() + 1) + .setQueryParam(true) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION) + .setHasItems(true) + .setDesc(comment + "(array of file)"); paramList.add(param); } else { if (requestBodyCounter > 0) { //for json paramList.addAll(ParamsBuildHelper.buildParams(gicNameArr[0], DocGlobalConstants.EMPTY, 0, - String.valueOf(required), Boolean.FALSE, new HashMap<>(), builder, - groupClasses, 0, Boolean.TRUE, null)); + String.valueOf(required), Boolean.FALSE, new HashMap<>(), builder, + groupClasses, 0, Boolean.TRUE, null)); } } } else if (JavaClassValidateUtil.isPrimitive(fullTypeName)) { ApiParam param = ApiParam.of() - .setField(paramName) - .setType(DocClassUtil.processTypeNameForParams(simpleName)) - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setValue(mockValue) - .setDesc(comment.toString()) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION); + .setField(paramName) + .setType(DocClassUtil.processTypeNameForParams(simpleName)) + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setValue(mockValue) + .setDesc(comment.toString()) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION); paramList.add(param); if (requestBodyCounter > 0) { Map map = OpenApiSchemaUtil.primaryTypeSchema(simpleName); @@ -957,18 +957,18 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje } } else if (JavaClassValidateUtil.isMap(fullTypeName)) { log.warning("When using smart-doc, it is not recommended to use Map to receive parameters, Check it in " - + javaMethod.getDeclaringClass().getCanonicalName() + "#" + javaMethod.getName()); + + javaMethod.getDeclaringClass().getCanonicalName() + "#" + javaMethod.getName()); //is map without Gic if (JavaClassValidateUtil.isMap(typeName)) { ApiParam apiParam = ApiParam.of() - .setField(paramName) - .setType("map") - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setDesc(comment.toString()) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION); + .setField(paramName) + .setType("map") + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setDesc(comment.toString()) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION); paramList.add(apiParam); if (requestBodyCounter > 0) { Map map = OpenApiSchemaUtil.mapTypeSchema("object"); @@ -979,14 +979,14 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje String[] gicNameArr = DocClassUtil.getSimpleGicName(typeName); if (JavaClassValidateUtil.isPrimitive(gicNameArr[1])) { ApiParam apiParam = ApiParam.of() - .setField(paramName) - .setType("map") - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setDesc(comment.toString()) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION); + .setField(paramName) + .setType("map") + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setDesc(comment.toString()) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION); paramList.add(apiParam); if (requestBodyCounter > 0) { Map map = OpenApiSchemaUtil.mapTypeSchema(gicNameArr[1]); @@ -994,8 +994,8 @@ default ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje } } else { paramList.addAll(ParamsBuildHelper.buildParams(gicNameArr[1], DocGlobalConstants.EMPTY, 0, - String.valueOf(required), Boolean.FALSE, new HashMap<>(), - builder, groupClasses, 0, Boolean.FALSE, null)); + String.valueOf(required), Boolean.FALSE, new HashMap<>(), + builder, groupClasses, 0, Boolean.FALSE, null)); } } @@ -1004,19 +1004,19 @@ else if (javaClass.isEnum()) { String o = JavaClassUtil.getEnumParams(javaClass); Object value = JavaClassUtil.getEnumValue(javaClass, isPathVariable || queryParam); ApiParam param = ApiParam.of().setField(paramName) - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setValue(String.valueOf(value)) - .setType("enum").setDesc(StringUtil.removeQuotes(o)) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION) - .setEnumInfo(JavaClassUtil.getEnumInfo(javaClass, builder)) - .setEnumValues(JavaClassUtil.getEnumValues(javaClass)); + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setValue(String.valueOf(value)) + .setType("enum").setDesc(StringUtil.removeQuotes(o)) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION) + .setEnumInfo(JavaClassUtil.getEnumInfo(javaClass, builder)) + .setEnumValues(JavaClassUtil.getEnumValues(javaClass)); paramList.add(param); } else { paramList.addAll(ParamsBuildHelper.buildParams(typeName, DocGlobalConstants.EMPTY, 0, - String.valueOf(required), Boolean.FALSE, new HashMap<>(), builder, groupClasses, 0, Boolean.FALSE, null)); + String.valueOf(required), Boolean.FALSE, new HashMap<>(), builder, groupClasses, 0, Boolean.FALSE, null)); } } return ApiParamTreeUtil.buildMethodReqParam(paramList, queryReqParamMap, pathReqParamMap, requestBodyCounter); @@ -1057,7 +1057,7 @@ default List getParenClassMethods(ApiConfig apiConfig, ProjectDoc } default DocJavaMethod convertToDocJavaMethod(ApiConfig apiConfig, ProjectDocConfigBuilder projectBuilder, - JavaMethod method, Map actualTypesMap) { + JavaMethod method, Map actualTypesMap) { JavaClass cls = method.getDeclaringClass(); String clzName = cls.getCanonicalName(); if (StringUtil.isEmpty(method.getComment()) && apiConfig.isStrict()) { diff --git a/src/main/java/com/power/doc/template/JaxrsDocBuildTemplate.java b/src/main/java/com/power/doc/template/JaxrsDocBuildTemplate.java index 3e11cf40..fe1e476f 100644 --- a/src/main/java/com/power/doc/template/JaxrsDocBuildTemplate.java +++ b/src/main/java/com/power/doc/template/JaxrsDocBuildTemplate.java @@ -145,8 +145,8 @@ public List getApiData(ProjectDocConfigBuilder projectBuilder) { } else if (setCustomOrder) { // while set custom oder return apiDocList.stream() - .sorted(Comparator.comparing(ApiDoc::getOrder)) - .peek(p -> p.setOrder(atomicInteger.getAndAdd(1))).collect(Collectors.toList()); + .sorted(Comparator.comparing(ApiDoc::getOrder)) + .peek(p -> p.setOrder(atomicInteger.getAndAdd(1))).collect(Collectors.toList()); } return apiDocList; } @@ -160,8 +160,8 @@ public List getApiData(ProjectDocConfigBuilder projectBuilder) { * @return List */ private List buildControllerMethod(final JavaClass cls, ApiConfig apiConfig, - ProjectDocConfigBuilder projectBuilder, - FrameworkAnnotations frameworkAnnotations) { + ProjectDocConfigBuilder projectBuilder, + FrameworkAnnotations frameworkAnnotations) { String clzName = cls.getCanonicalName(); boolean paramsDataToTree = projectBuilder.getApiConfig().isParamsDataToTree(); String group = JavaClassUtil.getClassTagsValue(cls, DocTags.GROUP, Boolean.TRUE); @@ -171,7 +171,7 @@ private List buildControllerMethod(final JavaClass cls, ApiConfig for (JavaAnnotation annotation : classAnnotations) { String annotationName = annotation.getType().getFullyQualifiedName(); if (JakartaJaxrsAnnotations.JAX_PATH_FULLY.equals(annotationName) - || JAXRSAnnotations.JAX_PATH_FULLY.equals(annotationName)) { + || JAXRSAnnotations.JAX_PATH_FULLY.equals(annotationName)) { baseUrl = StringUtil.removeQuotes(DocUtil.getRequestHeaderValue(annotation)); } mediaType = DocUtil.handleContentType(mediaType, annotation, annotationName); @@ -198,7 +198,7 @@ private List buildControllerMethod(final JavaClass cls, ApiConfig // new api doc //handle request mapping JaxrsPathMapping jaxPathMapping = new JaxrsPathHandler() - .handle(projectBuilder, baseUrl, method, mediaType); + .handle(projectBuilder, baseUrl, method, mediaType); if (Objects.isNull(jaxPathMapping)) { continue; } @@ -239,15 +239,15 @@ private List buildControllerMethod(final JavaClass cls, ApiConfig allApiReqParams = ApiReqParams; if (this.headers != null) { allApiReqParams = Stream.of(this.headers, ApiReqParams) - .flatMap(Collection::stream).distinct().collect(Collectors.toList()); + .flatMap(Collection::stream).distinct().collect(Collectors.toList()); } allApiReqParams.removeIf(ApiReqParam -> { if (StringUtil.isEmpty(ApiReqParam.getPathPatterns()) - && StringUtil.isEmpty(ApiReqParam.getExcludePathPatterns())) { + && StringUtil.isEmpty(ApiReqParam.getExcludePathPatterns())) { return false; } else { boolean flag = DocPathUtil.matches(jaxPathMapping.getShortUrl(), ApiReqParam.getPathPatterns() - , ApiReqParam.getExcludePathPatterns()); + , ApiReqParam.getExcludePathPatterns()); return !flag; } }); @@ -257,7 +257,7 @@ private List buildControllerMethod(final JavaClass cls, ApiConfig // build request json ApiRequestExample requestExample = buildReqJson(docJavaMethod, apiMethodDoc, jaxPathMapping.getMethodType(), - projectBuilder); + projectBuilder); String requestJson = requestExample.getExampleBody(); // set request example detail apiMethodDoc.setRequestExample(requestExample); @@ -278,7 +278,7 @@ private List buildControllerMethod(final JavaClass cls, ApiConfig apiMethodDoc.setRequestSchema(docJavaMethod.getRequestSchema()); apiMethodDoc.setResponseParams(responseParams); methodDocList.add(apiMethodDoc); - TornaUtil.setTornaArrayTags(apiMethodDoc); + TornaUtil.setTornaArrayTags(docJavaMethod.getJavaMethod(), apiMethodDoc); } return methodDocList; } @@ -288,23 +288,23 @@ private List buildControllerMethod(final JavaClass cls, ApiConfig public FrameworkAnnotations registeredAnnotations() { FrameworkAnnotations annotations = FrameworkAnnotations.builder(); HeaderAnnotation headerAnnotation = HeaderAnnotation.builder() - .setAnnotationName(JAXRSAnnotations.JAX_HEADER_PARAM_FULLY) - .setValueProp(DocAnnotationConstants.VALUE_PROP) - .setDefaultValueProp(DocAnnotationConstants.DEFAULT_VALUE_PROP) - .setRequiredProp(DocAnnotationConstants.REQUIRED_PROP); + .setAnnotationName(JAXRSAnnotations.JAX_HEADER_PARAM_FULLY) + .setValueProp(DocAnnotationConstants.VALUE_PROP) + .setDefaultValueProp(DocAnnotationConstants.DEFAULT_VALUE_PROP) + .setRequiredProp(DocAnnotationConstants.REQUIRED_PROP); // add header annotation annotations.setHeaderAnnotation(headerAnnotation); // add entry annotation Map entryAnnotations = new HashMap<>(); EntryAnnotation jakartaPathAnnotation = EntryAnnotation.builder() - .setAnnotationName(JakartaJaxrsAnnotations.JAX_PATH_FULLY) - .setAnnotationFullyName(JakartaJaxrsAnnotations.JAX_PATH_FULLY); + .setAnnotationName(JakartaJaxrsAnnotations.JAX_PATH_FULLY) + .setAnnotationFullyName(JakartaJaxrsAnnotations.JAX_PATH_FULLY); entryAnnotations.put(jakartaPathAnnotation.getAnnotationName(), jakartaPathAnnotation); EntryAnnotation jaxPathAnnotation = EntryAnnotation.builder() - .setAnnotationName(JAXRSAnnotations.JAX_PATH_FULLY) - .setAnnotationFullyName(JAXRSAnnotations.JAX_PATH_FULLY); + .setAnnotationName(JAXRSAnnotations.JAX_PATH_FULLY) + .setAnnotationFullyName(JAXRSAnnotations.JAX_PATH_FULLY); entryAnnotations.put(jaxPathAnnotation.getAnnotationName(), jaxPathAnnotation); annotations.setEntryAnnotations(entryAnnotations); return annotations; @@ -319,7 +319,7 @@ public boolean isEntryPoint(JavaClass cls, FrameworkAnnotations frameworkAnnotat for (JavaAnnotation annotation : classAnnotations) { String annotationName = annotation.getType().getFullyQualifiedName(); if (JakartaJaxrsAnnotations.JAX_PATH_FULLY.equals(annotationName) - || JAXRSAnnotations.JAX_PATH_FULLY.equals(annotationName)) { + || JAXRSAnnotations.JAX_PATH_FULLY.equals(annotationName)) { return true; } } @@ -351,9 +351,9 @@ private ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje List parameterList = getJavaParameterList(builder, docJavaMethod, null); if (parameterList.isEmpty()) { return ApiMethodReqParam.builder() - .setPathParams(new ArrayList<>(0)) - .setQueryParams(paramList) - .setRequestParams(new ArrayList<>(0)); + .setPathParams(new ArrayList<>(0)) + .setQueryParams(paramList) + .setRequestParams(new ArrayList<>(0)); } boolean isStrict = builder.getApiConfig().isStrict(); JavaMethod javaMethod = docJavaMethod.getJavaMethod(); @@ -377,7 +377,7 @@ private ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje String simpleTypeName = apiParameter.getTypeValue(); if (!paramTagMap.containsKey(paramName) && JavaClassValidateUtil.isPrimitive(fullTypeName) && isStrict) { throw new RuntimeException("ERROR: Unable to find javadoc @QueryParam for actual param \"" - + paramName + "\" in method " + javaMethod.getName() + " from " + className); + + paramName + "\" in method " + javaMethod.getName() + " from " + className); } if (requestFieldToUnderline) { @@ -396,19 +396,19 @@ private ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje for (JavaAnnotation annotation : annotations) { String annotationName = annotation.getType().getFullyQualifiedName(); if (JakartaJaxrsAnnotations.JAX_HEADER_PARAM_FULLY.equals(annotationName) - || JAXRSAnnotations.JAX_HEADER_PARAM_FULLY.equals(annotationName)) { + || JAXRSAnnotations.JAX_HEADER_PARAM_FULLY.equals(annotationName)) { continue out; } //default value if (JakartaJaxrsAnnotations.JAX_DEFAULT_VALUE_FULLY.equals(annotationName) - || JAXRSAnnotations.JAX_DEFAULT_VALUE_FULLY.equals(annotationName)) { + || JAXRSAnnotations.JAX_DEFAULT_VALUE_FULLY.equals(annotationName)) { mockValue = StringUtil.removeQuotes(DocUtil.getRequestHeaderValue(annotation)); mockValue = DocUtil.handleConstants(constantsMap, mockValue); } // path param if (JakartaJaxrsAnnotations.JAX_PATH_PARAM_FULLY.equals(annotationName) - || JakartaJaxrsAnnotations.JAXB_REST_PATH_FULLY.equals(annotationName) - || JAXRSAnnotations.JAX_PATH_PARAM_FULLY.equals(annotationName)) { + || JakartaJaxrsAnnotations.JAXB_REST_PATH_FULLY.equals(annotationName) + || JAXRSAnnotations.JAX_PATH_PARAM_FULLY.equals(annotationName)) { isPathVariable = true; strRequired = "true"; } @@ -433,91 +433,91 @@ private ApiMethodReqParam requestParams(final DocJavaMethod docJavaMethod, Proje if (gicJavaClass.isEnum()) { Object value = JavaClassUtil.getEnumValue(gicJavaClass, Boolean.TRUE); ApiParam param = ApiParam.of().setField(paramName).setDesc(comment + ",[array of enum]") - .setRequired(required) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setId(paramList.size() + 1) - .setType("array").setValue(String.valueOf(value)); + .setRequired(required) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setId(paramList.size() + 1) + .setType("array").setValue(String.valueOf(value)); paramList.add(param); } else if (JavaClassValidateUtil.isPrimitive(gicName)) { String shortSimple = DocClassUtil.processTypeNameForParams(gicName); ApiParam param = ApiParam.of() - .setField(paramName) - .setDesc(comment + ",[array of " + shortSimple + "]") - .setRequired(required) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setId(paramList.size() + 1) - .setType("array") - .setValue(DocUtil.getValByTypeAndFieldName(gicName, paramName)); + .setField(paramName) + .setDesc(comment + ",[array of " + shortSimple + "]") + .setRequired(required) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setId(paramList.size() + 1) + .setType("array") + .setValue(DocUtil.getValByTypeAndFieldName(gicName, paramName)); paramList.add(param); } else { int id = paramList.size() + 1; ApiParam param = ApiParam.of() - .setField(paramName) - .setDesc(comment + ",[array of object]") - .setRequired(required) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setId(id) - .setType("array"); + .setField(paramName) + .setDesc(comment + ",[array of object]") + .setRequired(required) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setId(id) + .setType("array"); paramList.add(param); List apiParamList = ParamsBuildHelper.buildParams(typeName, "└─", 1, - "true", Boolean.FALSE, new HashMap<>(), builder, groupClasses, id, Boolean.FALSE, null); + "true", Boolean.FALSE, new HashMap<>(), builder, groupClasses, id, Boolean.FALSE, null); paramList.addAll(apiParamList); } } else if (JavaClassValidateUtil.isPrimitive(fullTypeName)) { ApiParam param = ApiParam.of() - .setField(paramName) - .setType(DocClassUtil.processTypeNameForParams(simpleName)) - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setValue(mockValue) - .setDesc(comment.toString()) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION); - paramList.add(param); - } else if (JavaClassValidateUtil.isMap(fullTypeName)) { - log.warning("When using smart-doc, it is not recommended to use Map to receive parameters, Check it in " - + javaMethod.getDeclaringClass().getCanonicalName() + "#" + javaMethod.getName()); - if (JavaClassValidateUtil.isMap(typeName)) { - ApiParam apiParam = ApiParam.of() .setField(paramName) - .setType("map") + .setType(DocClassUtil.processTypeNameForParams(simpleName)) .setId(paramList.size() + 1) .setPathParam(isPathVariable) .setQueryParam(queryParam) + .setValue(mockValue) .setDesc(comment.toString()) .setRequired(required) .setVersion(DocGlobalConstants.DEFAULT_VERSION); + paramList.add(param); + } else if (JavaClassValidateUtil.isMap(fullTypeName)) { + log.warning("When using smart-doc, it is not recommended to use Map to receive parameters, Check it in " + + javaMethod.getDeclaringClass().getCanonicalName() + "#" + javaMethod.getName()); + if (JavaClassValidateUtil.isMap(typeName)) { + ApiParam apiParam = ApiParam.of() + .setField(paramName) + .setType("map") + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setDesc(comment.toString()) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION); paramList.add(apiParam); continue; } String[] gicNameArr = DocClassUtil.getSimpleGicName(typeName); if (JavaClassValidateUtil.isPrimitive(gicNameArr[1])) { ApiParam apiParam = ApiParam.of() - .setField(paramName) - .setType("map") - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setDesc(comment.toString()) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION); + .setField(paramName) + .setType("map") + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setDesc(comment.toString()) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION); paramList.add(apiParam); } else { paramList.addAll(ParamsBuildHelper.buildParams(gicNameArr[1], DocGlobalConstants.EMPTY, 0, - "true", Boolean.FALSE, new HashMap<>(), - builder, groupClasses, 0, Boolean.FALSE, null)); + "true", Boolean.FALSE, new HashMap<>(), + builder, groupClasses, 0, Boolean.FALSE, null)); } } else if (JavaClassValidateUtil.isFile(typeName)) { //file upload ApiParam param = ApiParam.of().setField(paramName).setType("file") - .setId(paramList.size() + 1).setQueryParam(true) - .setRequired(required).setVersion(DocGlobalConstants.DEFAULT_VERSION) - .setDesc(comment.toString()); + .setId(paramList.size() + 1).setQueryParam(true) + .setRequired(required).setVersion(DocGlobalConstants.DEFAULT_VERSION) + .setDesc(comment.toString()); if (typeName.contains("[]") || typeName.endsWith(">")) { comment.append("(array of file)"); param.setDesc(comment.toString()); @@ -530,18 +530,18 @@ else if (javaClass.isEnum()) { String o = JavaClassUtil.getEnumParams(javaClass); Object value = JavaClassUtil.getEnumValue(javaClass, true); ApiParam param = ApiParam.of().setField(paramName) - .setId(paramList.size() + 1) - .setPathParam(isPathVariable) - .setQueryParam(queryParam) - .setValue(String.valueOf(value)) - .setType("enum").setDesc(StringUtil.removeQuotes(o)) - .setRequired(required) - .setVersion(DocGlobalConstants.DEFAULT_VERSION) - .setEnumValues(JavaClassUtil.getEnumValues(javaClass)); + .setId(paramList.size() + 1) + .setPathParam(isPathVariable) + .setQueryParam(queryParam) + .setValue(String.valueOf(value)) + .setType("enum").setDesc(StringUtil.removeQuotes(o)) + .setRequired(required) + .setVersion(DocGlobalConstants.DEFAULT_VERSION) + .setEnumValues(JavaClassUtil.getEnumValues(javaClass)); paramList.add(param); } else { paramList.addAll(ParamsBuildHelper.buildParams(typeName, DocGlobalConstants.EMPTY, 0, - "true", Boolean.FALSE, new HashMap<>(), builder, groupClasses, 0, Boolean.FALSE, null)); + "true", Boolean.FALSE, new HashMap<>(), builder, groupClasses, 0, Boolean.FALSE, null)); } } List pathParams = new ArrayList<>(); @@ -561,23 +561,23 @@ else if (javaClass.isEnum()) { } } return ApiMethodReqParam.builder() - .setRequestParams(bodyParams) - .setPathParams(pathParams) - .setQueryParams(queryParams); + .setRequestParams(bodyParams) + .setPathParams(pathParams) + .setQueryParams(queryParams); } private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc apiMethodDoc, String methodType, - ProjectDocConfigBuilder configBuilder) { + ProjectDocConfigBuilder configBuilder) { JavaMethod method = javaMethod.getJavaMethod(); Map pathParamsMap = new LinkedHashMap<>(); List parameterList = getJavaParameterList(configBuilder, javaMethod, null); List reqHeaderList = apiMethodDoc.getRequestHeaders(); if (parameterList.isEmpty()) { CurlRequest curlRequest = CurlRequest.builder() - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(apiMethodDoc.getUrl()); + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(apiMethodDoc.getUrl()); String format = CurlUtil.toCurl(curlRequest); return ApiRequestExample.builder().setUrl(apiMethodDoc.getUrl()).setExampleBody(format); } @@ -606,8 +606,8 @@ private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap for (JavaAnnotation annotation : annotations) { String annotationName = annotation.getType().getFullyQualifiedName(); if (JakartaJaxrsAnnotations.JAX_PATH_PARAM_FULLY.equals(annotationName) - || JakartaJaxrsAnnotations.JAXB_REST_PATH_FULLY.equals(annotationName) - || JAXRSAnnotations.JAX_PATH_PARAM_FULLY.equals(annotationName)) { + || JakartaJaxrsAnnotations.JAXB_REST_PATH_FULLY.equals(annotationName) + || JAXRSAnnotations.JAX_PATH_PARAM_FULLY.equals(annotationName)) { if (javaClass.isEnum()) { Object value = JavaClassUtil.getEnumValue(javaClass, Boolean.TRUE); mockValue = StringUtil.removeQuotes(String.valueOf(value)); @@ -640,9 +640,9 @@ private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap gicName = gicName.substring(0, gicName.indexOf("[")); } if (!JavaClassValidateUtil.isPrimitive(gicName) - && !configBuilder.getJavaProjectBuilder().getClassByName(gicName).isEnum()) { + && !configBuilder.getJavaProjectBuilder().getClassByName(gicName).isEnum()) { throw new RuntimeException("Jaxrs rest can't support binding Collection on method " - + method.getName() + "Check it in " + method.getDeclaringClass().getCanonicalName()); + + method.getName() + "Check it in " + method.getDeclaringClass().getCanonicalName()); } FormData formData = new FormData(); formData.setKey(paramName); @@ -665,7 +665,7 @@ private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap formDataList.add(formData); } else { formDataList.addAll( - FormDataBuildHelper.getFormData(gicTypeName, new HashMap<>(), 0, configBuilder, DocGlobalConstants.EMPTY)); + FormDataBuildHelper.getFormData(gicTypeName, new HashMap<>(), 0, configBuilder, DocGlobalConstants.EMPTY)); } } } else { @@ -689,7 +689,7 @@ private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap //for post put path = DocUtil.formatAndRemove(path, pathParamsMap); body = UrlUtil.urlJoin(DocGlobalConstants.EMPTY, DocUtil.formDataToMap(formDataList)) - .replace("?", DocGlobalConstants.EMPTY); + .replace("?", DocGlobalConstants.EMPTY); body = StringUtil.removeQuotes(body); url = apiMethodDoc.getServerUrl() + "/" + path; url = UrlUtil.simplifyUrl(url); @@ -699,28 +699,28 @@ private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap url = url + "?" + body; } CurlRequest curlRequest = CurlRequest.builder() - .setBody(requestExample.getJsonBody()) - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(requestExample.getJsonBody()) + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); exampleBody = CurlUtil.toCurl(curlRequest); } else { CurlRequest curlRequest; if (StringUtil.isNotEmpty(body)) { curlRequest = CurlRequest.builder() - .setBody(body) - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(body) + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); } else { curlRequest = CurlRequest.builder() - .setBody(requestExample.getJsonBody()) - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(requestExample.getJsonBody()) + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); } exampleBody = CurlUtil.toCurl(curlRequest); } @@ -729,15 +729,15 @@ private ApiRequestExample buildReqJson(DocJavaMethod javaMethod, ApiMethodDoc ap // for get delete url = formatRequestUrl(pathParamsMap, pathParamsMap, apiMethodDoc.getServerUrl(), path); CurlRequest curlRequest = CurlRequest.builder() - .setBody(requestExample.getJsonBody()) - .setContentType(apiMethodDoc.getContentType()) - .setType(methodType) - .setReqHeaders(reqHeaderList) - .setUrl(url); + .setBody(requestExample.getJsonBody()) + .setContentType(apiMethodDoc.getContentType()) + .setType(methodType) + .setReqHeaders(reqHeaderList) + .setUrl(url); exampleBody = CurlUtil.toCurl(curlRequest); requestExample.setExampleBody(exampleBody) - .setJsonBody(DocGlobalConstants.EMPTY) - .setUrl(url); + .setJsonBody(DocGlobalConstants.EMPTY) + .setUrl(url); } return requestExample; } diff --git a/src/main/java/com/power/doc/utils/OpenApiSchemaUtil.java b/src/main/java/com/power/doc/utils/OpenApiSchemaUtil.java index 4cf318dc..31730df5 100644 --- a/src/main/java/com/power/doc/utils/OpenApiSchemaUtil.java +++ b/src/main/java/com/power/doc/utils/OpenApiSchemaUtil.java @@ -39,8 +39,8 @@ */ public class OpenApiSchemaUtil { - public final static String NO_BODY_PARAM = "NO_BODY_PARAM"; - final static Pattern p = Pattern.compile("[A-Z]\\w+.*?|[A-Z]"); + public static final String NO_BODY_PARAM = "NO_BODY_PARAM"; + static final Pattern PATTRRN = Pattern.compile("[A-Z]\\w+.*?|[A-Z]"); public static Map primaryTypeSchema(String primaryType) { Map map = new HashMap<>(); @@ -81,22 +81,22 @@ public static Map returnSchema(String returnGicName) { return map; } - public static String getClassNameFromParams(List apiParams) { + public static String getClassNameFromParams(List apiParams, String suffix) { // if array[Primitive] or Primitive if (CollectionUtil.isNotEmpty(apiParams) && apiParams.size() == 1 - && CollectionUtil.isEmpty(apiParams.get(0).getChildren())) { + && CollectionUtil.isEmpty(apiParams.get(0).getChildren())) { return "string"; } for (ApiParam a : apiParams) { if (StringUtil.isNotEmpty(a.getClassName())) { - return OpenApiSchemaUtil.delClassName(a.getClassName()); + return OpenApiSchemaUtil.delClassName(a.getClassName()) + suffix; } } return NO_BODY_PARAM; } public static String delClassName(String className) { - return String.join("", getPatternResult(p, className)); + return String.join("", getPatternResult(PATTRRN, className)); } public static List getPatternResult(Pattern p, String content) { diff --git a/src/main/java/com/power/doc/utils/TornaUtil.java b/src/main/java/com/power/doc/utils/TornaUtil.java index 257d3f00..d56e4f90 100644 --- a/src/main/java/com/power/doc/utils/TornaUtil.java +++ b/src/main/java/com/power/doc/utils/TornaUtil.java @@ -33,6 +33,8 @@ import com.power.doc.model.torna.TornaRequestInfo; import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.model.JavaMethod; +import com.thoughtworks.qdox.model.JavaParameter; import org.apache.commons.lang3.StringUtils; import static com.power.doc.constants.DocGlobalConstants.ARRAY; @@ -65,8 +67,8 @@ public static void pushToTorna(TornaApi tornaApi, ApiConfig apiConfig, JavaProje public static boolean setDebugEnv(ApiConfig apiConfig, TornaApi tornaApi) { boolean hasDebugEnv = StringUtils.isNotBlank(apiConfig.getDebugEnvName()) - && - StringUtils.isNotBlank(apiConfig.getDebugEnvUrl()); + && + StringUtils.isNotBlank(apiConfig.getDebugEnvUrl()); //Set up the test environment List debugEnvs = new ArrayList<>(); if (hasDebugEnv) { @@ -82,22 +84,22 @@ public static boolean setDebugEnv(ApiConfig apiConfig, TornaApi tornaApi) { public static void printDebugInfo(ApiConfig apiConfig, String responseMsg, Map requestJson, String category) { if (apiConfig.isTornaDebug()) { String sb = "Configuration information : \n" + - "OpenUrl: " + - apiConfig.getOpenUrl() + - "\n" + - "appToken: " + - apiConfig.getAppToken() + - "\n"; + "OpenUrl: " + + apiConfig.getOpenUrl() + + "\n" + + "appToken: " + + apiConfig.getAppToken() + + "\n"; System.out.println(sb); try { JsonElement element = JsonParser.parseString(responseMsg); TornaRequestInfo info = new TornaRequestInfo() - .of() - .setCategory(category) - .setCode(element.getAsJsonObject().get(TornaConstants.CODE).getAsString()) - .setMessage(element.getAsJsonObject().get(TornaConstants.MESSAGE).getAsString()) - .setRequestInfo(requestJson) - .setResponseInfo(responseMsg); + .of() + .setCategory(category) + .setCode(element.getAsJsonObject().get(TornaConstants.CODE).getAsString()) + .setMessage(element.getAsJsonObject().get(TornaConstants.MESSAGE).getAsString()) + .setRequestInfo(requestJson) + .setResponseInfo(responseMsg); System.out.println(info.buildInfo()); } catch (Exception e) { //Ex : Nginx Error,Tomcat Error @@ -143,7 +145,7 @@ public static List buildApis(List apiMethodDocs, boolean has } if (CollectionUtil.isNotEmpty(apiMethodDoc.getQueryParams()) - && DocGlobalConstants.FILE_CONTENT_TYPE.equals(apiMethodDoc.getContentType())) { + && DocGlobalConstants.FILE_CONTENT_TYPE.equals(apiMethodDoc.getContentType())) { // file upload methodApi.setRequestParams(buildParams(apiMethodDoc.getQueryParams())); } else if (CollectionUtil.isNotEmpty(apiMethodDoc.getQueryParams())) { @@ -281,8 +283,8 @@ public static List buildTornaDic(List apiDocDicts) { for (ApiDocDict doc : apiDocDicts) { tornaDic = new TornaDic(); tornaDic.setName(doc.getTitle()) - .setDescription(DocUtil.replaceNewLineToHtmlBr(doc.getDescription())) - .setItems(buildTornaDicItems(doc.getDataDictList())); + .setDescription(DocUtil.replaceNewLineToHtmlBr(doc.getDescription())) + .setItems(buildTornaDicItems(doc.getDataDictList())); dics.add(tornaDic); } } @@ -310,31 +312,29 @@ private static List buildTornaDicItems(List dataDicts) { * * @param apiMethodDoc 请求参数 */ - public static void setTornaArrayTags(ApiMethodDoc apiMethodDoc) { - List reqList = apiMethodDoc.getRequestParams(); - List repList = apiMethodDoc.getResponseParams(); + public static void setTornaArrayTags(JavaMethod method, ApiMethodDoc apiMethodDoc) { + String returnTypeName = method.getReturnType().getCanonicalName(); apiMethodDoc.setIsRequestArray(0); apiMethodDoc.setIsResponseArray(0); + boolean respArray = JavaClassValidateUtil.isCollection(returnTypeName) || JavaClassValidateUtil.isArray(returnTypeName); //response - if (CollectionUtil.isNotEmpty(repList)) { - ApiParam apiParam = repList.get(0); - boolean isArray = repList.size() == 1 && ARRAY.equals(apiParam.getType()); - if (isArray) { - apiMethodDoc.setIsResponseArray(1); - Map schemaMap = apiMethodDoc.getReturnSchema(); - apiMethodDoc.setResponseArrayType(getArrayType(schemaMap)); - } + if (respArray) { + apiMethodDoc.setIsResponseArray(1); + apiMethodDoc.setResponseArrayType(getType(method.getReturnType().getGenericCanonicalName())); } //request - if (CollectionUtil.isNotEmpty(reqList)) { - ApiParam apiParam = reqList.get(0); - boolean isArray = reqList.size() == 1 && ARRAY.equals(apiParam.getType()); - if (isArray) { - apiMethodDoc.setIsRequestArray(1); - Map schemaMap = apiMethodDoc.getRequestSchema(); - apiMethodDoc.setRequestArrayType(getArrayType(schemaMap)); + if (CollectionUtil.isNotEmpty(method.getParameters()) && CollectionUtil.isNotEmpty(apiMethodDoc.getRequestParams())) { + for (JavaParameter param : method.getParameters()) { + String typeName = param.getType().getCanonicalName(); + boolean reqArray = JavaClassValidateUtil.isCollection(typeName) || JavaClassValidateUtil.isArray(typeName); + if (reqArray) { + apiMethodDoc.setIsRequestArray(1); + apiMethodDoc.setRequestArrayType(getType(param.getType().getGenericCanonicalName())); + break; + } } } + } private static String getArrayType(Map schemaMap) { @@ -342,7 +342,7 @@ private static String getArrayType(Map schemaMap) { if (Objects.nonNull(schemaMap) && Objects.equals(ARRAY, schemaMap.get("type"))) { Map innerSchemeMap = (Map) schemaMap.get("items"); if (Objects.nonNull(innerSchemeMap)) { - String type = (String) innerSchemeMap.get("type"); + String type = (String) innerSchemeMap.get("type"); if (StringUtil.isNotEmpty(type)) { String className = getType(type); arrayType = JavaClassValidateUtil.isPrimitive(className) ? className : OBJECT; diff --git a/src/test/java/com/power/doc/ApiDocTest.java b/src/test/java/com/power/doc/ApiDocTest.java index 49083ace..06671547 100644 --- a/src/test/java/com/power/doc/ApiDocTest.java +++ b/src/test/java/com/power/doc/ApiDocTest.java @@ -2,6 +2,7 @@ import com.power.common.util.DateTimeUtil; import com.power.doc.builder.HtmlApiDocBuilder; +import com.power.doc.builder.TornaBuilder; import com.power.doc.builder.openapi.OpenApiBuilder; import com.power.doc.builder.openapi.SwaggerBuilder; import com.power.doc.builder.rpc.RpcMarkdownBuilder; @@ -48,127 +49,16 @@ public void testBuilderControllersApi() { //不指定SourcePaths默认加载代码为项目src/main/java下的 config.setSourceCodePaths( SourceCodePath.builder().setDesc("本项目代码") - .setPath("C:\\Users\\xingzi\\Desktop\\smart-doc-example-cn") - - //SourcePath.path().setPath("F:\\Personal\\project\\smart\\src\\main\\java") - //SourcePath.path().setDesc("加载项目外代码").setPath("E:\\ApplicationPower\\ApplicationPower\\Common-util\\src\\main\\java") - ); - config.setPackageFilters("com.power.doc.dubbo.*"); -// config.setPackageFilters("com.power.doc.dubbo.*"); - -// config.setDataDictionaries( -// ApiDataDictionary.builder().setTitle("订单字典").setEnumClass(OrderEnum.class).setCodeField("code").setDescField("desc") -// ); - //设置请求头,如果没有请求头,可以不用设置 - /* config.setRequestHeaders( - ApiReqHeader.header().setName("access_token").setType("string").setDesc("Basic auth credentials"), - ApiReqHeader.header().setName("user_uuid").setType("string").setDesc("User Uuid key") - );*/ - //对于外部jar的类,api-doc目前无法自动获取注释, - //如果有这种场景,则自己添加字段和注释,api-doc后期遇到同名字段则直接给相应字段加注释 -// config.setCustomResponseFields( -//// CustomRespField.field().setName("success").setDesc("成功返回true,失败返回false"), -//// CustomRespField.field().setName("message").setDesc("接口响应信息"), -//// CustomRespField.field().setName("data").setDesc("接口响应数据"), -// CustomField.builder().setName("msg").setDesc("消息测试").setIgnore(true).setValue("000200"), -// CustomField.builder().setName("code2").setDesc("code测试").setIgnore(false).setValue("010000") -// //.setDesc("响应代码") -// ); -// config.setCustomRequestFields( -// CustomField.builder() -// .setName("age").setDesc("年龄").setIgnore(false).setValue("13").setRequire(false).setOwnerClassName("com.power.doc.entity.SimpleUser"), -// CustomField.builder() -// .setName("sex").setDesc("性别").setIgnore(false).setValue("男").setRequire(true).setOwnerClassName("com.power.doc.entity.SimpleUser") -// -// -// ); -// //非必须只有当setAllInOne设置为true时文档变更记录才生效,https://gitee.com/sunyurepository/ApplicationPower/issues/IPS4O -// config.setRevisionLogs( -// RevisionLog.builder().setRevisionTime("2018/12/15").setAuthor("chen").setRemarks("测试").setStatus("创建").setVersion("V1.0"), -// RevisionLog.builder().setRevisionTime("2018/12/16").setAuthor("chen2").setRemarks("测试2").setStatus("修改").setVersion("V2.0") -// ); -// config.setResponseBodyAdvice(BodyAdvice.builder() -// .setDataField("data") -// .setDataField("dadada") -// .setClassName("com.power.common.model.CommonResult")); - -// config.setRequestBodyAdvice(BodyAdvice.builder() -// .setDataField("data") -// .setDataField("dadada") -// .setClassName("com.power.common.model.CommonResult")); -// config.setRpcApiDependencies(RpcApiDependency.builder().setGroupId("com.test").setArtifactId("test1").setVersion("1.0"), -// RpcApiDependency.builder().setGroupId("com.smart").setArtifactId("test").setVersion("1.1.1") -// ); - long start = System.currentTimeMillis(); - - //TornaBuilder.buildApiDoc(config); -// SwaggerBuilder.buildOpenApi(config); - RpcMarkdownBuilder.buildApiDoc(config); - //HtmlApiDocBuilder.buildApiDoc(config); - //RpcTornaBuilder.buildApiDoc(config); - //TornaBuilder.buildApiDoc(config); - //RpcTornaBuilder.buildApiDoc(config); -// TornaBuilder.buildApiDoc(config); - // RpcHtmlBuilder.buildApiDoc(config); - long end = System.currentTimeMillis(); - DateTimeUtil.printRunTime(end, start); - } - - @Test - public void test_1() { - ApiConfig config = new ApiConfig(); - config.setServerUrl("http://127.0.0.1:8899"); - config.setOpenUrl("http://localhost:7700/api"); - config.setAppToken("be4211613a734b45888c075741680e49"); - - config.setDebugEnvName("测试环境"); - config.setStyle("randomLight"); - config.setCreateDebugPage(true); - config.setDebugEnvUrl("http://127.0.0.1"); - - config.setCreateDebugPage(false); - config.setAllInOne(true); - config.setOutPath("D:\\md3_vector"); - config.setMd5EncryptedHtmlName(true); - //不指定SourcePaths默认加载代码为项目src/main/java下的 - config.setSourceCodePaths( - SourceCodePath.builder().setDesc("本项目代码") - .setPath("F:\\IDEA\\IdeaProject\\seckill\\src\\main\\java\\com\\fht\\seckill\\controller") + .setPath("C:\\Users\\xingzi\\Desktop\\demo") ); -// config.setPackageFilters("com.power.doc.dubbo.*"); - //config.setPackageFilters("com.fht.seckill.controller.*"); + config.setPackageFilters("com.example.demo.controller.UserController"); - config.setDataDictionaries( - ApiDataDictionary.builder().setTitle("订单字典").setEnumClass(OrderEnum.class).setCodeField("code").setDescField("desc") - ); - //设置请求头,如果没有请求头,可以不用设置 - /* config.setRequestHeaders( - ApiReqHeader.header().setName("access_token").setType("string").setDesc("Basic auth credentials"), - ApiReqHeader.header().setName("user_uuid").setType("string").setDesc("User Uuid key") - );*/ - //对于外部jar的类,api-doc目前无法自动获取注释, - //如果有这种场景,则自己添加字段和注释,api-doc后期遇到同名字段则直接给相应字段加注释 - config.setCustomResponseFields( -// CustomRespField.field().setName("success").setDesc("成功返回true,失败返回false"), -// CustomRespField.field().setName("message").setDesc("接口响应信息"), -// CustomRespField.field().setName("data").setDesc("接口响应数据"), - CustomField.builder().setName("msg").setDesc("消息测试").setIgnore(true).setValue("000200"), - CustomField.builder().setName("code2").setDesc("code测试").setIgnore(false).setValue("010000") - //.setDesc("响应代码") - ); - //非必须只有当setAllInOne设置为true时文档变更记录才生效,https://gitee.com/sunyurepository/ApplicationPower/issues/IPS4O - config.setRevisionLogs( - RevisionLog.builder().setRevisionTime("2018/12/15").setAuthor("chen").setRemarks("测试").setStatus("创建").setVersion("V1.0"), - RevisionLog.builder().setRevisionTime("2018/12/16").setAuthor("chen2").setRemarks("测试2").setStatus("修改").setVersion("V2.0") - ); - config.setRpcApiDependencies(RpcApiDependency.builder().setGroupId("com.test").setArtifactId("test1").setVersion("1.0"), - RpcApiDependency.builder().setGroupId("com.smart").setArtifactId("test").setVersion("1.1.1") - ); long start = System.currentTimeMillis(); - + TornaBuilder.buildApiDoc(config); HtmlApiDocBuilder.buildApiDoc(config); long end = System.currentTimeMillis(); DateTimeUtil.printRunTime(end, start); } + }