Search in sources :

Example 1 with Api2Doc

use of com.terran4j.commons.api2doc.annotations.Api2Doc in project commons by terran4j.

the class Api2DocCollector method toApiFolder.

/**
 * 解析 API 组,一组 API 对应一个 Controller 类, 其中每个 method 对应一个 api 。<br>
 * 只要有 @ApiDoc 注解,有会生成文档,没有这个注解就不会。
 *
 * @param bean
 * @param beanName
 * @return
 */
public ApiFolderObject toApiFolder(Object bean, String beanName) throws BusinessException {
    Class<?> clazz = Classes.getTargetClass(bean);
    Controller controller = AnnotationUtils.findAnnotation(clazz, Controller.class);
    if (controller == null) {
        // 不是 Controller 类,不用收集。
        return null;
    }
    if (log.isInfoEnabled()) {
        log.info("prepare to get API Info by bean:  {}", beanName);
    }
    List<MappingMethod> methods = MappingMethod.getMappingMethods(clazz);
    // Classes.getMethods(RequestMapping.class, clazz);
    if (methods == null || methods.size() == 0) {
        // }
        return null;
    }
    Api2Doc classApi2Doc = clazz.getAnnotation(Api2Doc.class);
    if (classApi2Doc != null && classApi2Doc.ignore()) {
        // 整个类的文档被忽略。
        if (log.isInfoEnabled()) {
            log.info("@Api2Doc ignore = true, no need to get, " + "beanName = {}", beanName);
        }
        return null;
    }
    List<MappingMethod> ali2DocMethods = new ArrayList<>();
    for (MappingMethod mappingMethod : methods) {
        Method method = mappingMethod.getMethod();
        Api2Doc api2Doc = method.getAnnotation(Api2Doc.class);
        if (classApi2Doc == null && api2Doc == null) {
            // 本方法的文档被忽略。
            continue;
        }
        if (api2Doc != null && api2Doc.ignore()) {
            // 本方法的文档被忽略。
            continue;
        }
        ali2DocMethods.add(mappingMethod);
    }
    if (classApi2Doc == null && ali2DocMethods.size() == 0) {
        // 整个类中的方法,都忽略从 API 生成文档,不用收集。
        if (log.isInfoEnabled()) {
            log.info("all method were ignored, no need to get, beanName = {}", beanName);
        }
        return null;
    }
    ApiFolderObject folder = new ApiFolderObject();
    folder.setSourceClass(clazz);
    String id = beanName;
    if (classApi2Doc != null && StringUtils.hasText(classApi2Doc.value())) {
        id = classApi2Doc.value();
    }
    if (classApi2Doc != null && StringUtils.hasText(classApi2Doc.id())) {
        id = classApi2Doc.id();
    }
    folder.setId(id);
    checkId(id);
    String pathPattern = "api2doc/" + id + "/*.md";
    try {
        Resource[] resources = Classes.scanResources(pathPattern);
        if (resources != null && resources.length > 0) {
            Map<String, String> mds = new HashMap<>();
            for (Resource resource : resources) {
                String md = resource.getFilename();
                mds.put(ApiFolderObject.name2Id(md), md);
            }
            folder.setMds(mds);
        }
    } catch (IOException e) {
        String msg = "scan classpath[" + pathPattern + "] failed: " + e.getMessage();
        throw new BeanDefinitionStoreException(msg);
    }
    if (classApi2Doc != null) {
        folder.setOrder(classApi2Doc.order());
    }
    // API 组的名称。
    String name = beanName;
    RequestMapping classMapping = clazz.getAnnotation(RequestMapping.class);
    if (classMapping != null && StringUtils.hasText(classMapping.name())) {
        name = classMapping.name();
    }
    if (classApi2Doc != null && StringUtils.hasText(classApi2Doc.name())) {
        name = classApi2Doc.name();
    }
    folder.setName(name);
    // API 组的注释。
    ApiComment apiComment = clazz.getAnnotation(ApiComment.class);
    folder.setComment(ApiCommentUtils.getComment(apiComment, null, null));
    // 在类上的 seeClass ,是默认的。
    Class<?> defaultSeeClass = ApiCommentUtils.getDefaultSeeClass(apiComment, null);
    // API 组的路径前缀。
    String[] basePaths = getPath(classMapping);
    // 根据方法生成 API 文档。
    List<ApiDocObject> docs = new ArrayList<>();
    for (MappingMethod method : ali2DocMethods) {
        ApiDocObject doc = getApiDoc(method, basePaths, beanName, classApi2Doc, defaultSeeClass);
        if (doc == null) {
            continue;
        }
        String docId = doc.getId();
        ApiDocObject existDoc = folder.getDoc(docId);
        if (existDoc != null) {
            String msg = "文档id值重复: " + docId + "\n" + "如果方法上没有用  @Api2Doc(id = \"xxx\") 来指定文档id,则重载方法会出现此问题。\n" + "请在重载的方法上用 @Api2Doc(id = \"xxx\") 来指定一个不同的文档id";
            throw new BeanDefinitionStoreException(msg);
        }
        docs.add(doc);
        if (log.isInfoEnabled()) {
            log.info("add doc: {}/{}", folder.getId(), docId);
        }
    }
    Collections.sort(docs);
    folder.addDocs(docs);
    return folder;
}
Also used : BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) Resource(org.springframework.core.io.Resource) Method(java.lang.reflect.Method) IOException(java.io.IOException) Controller(org.springframework.stereotype.Controller) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Api2Doc(com.terran4j.commons.api2doc.annotations.Api2Doc) ApiComment(com.terran4j.commons.api2doc.annotations.ApiComment)

Example 2 with Api2Doc

use of com.terran4j.commons.api2doc.annotations.Api2Doc in project commons by terran4j.

the class ApiResultObject method parseResultType.

/**
 * 找到一个方法返回类型中字段,收集它的 Api2Doc 信息。
 *
 * @param method
 * @param totalResults
 * @return
 */
public static final ApiResultObject parseResultType(Method method, KeyedList<String, ApiResultObject> totalResults) {
    if (method == null) {
        return null;
    }
    if (totalResults == null) {
        totalResults = new KeyedList<>();
    }
    final Class<?> clazz = method.getReturnType();
    final ApiDataType dataType = ApiDataType.toDataType(clazz);
    if (dataType == null) {
        return null;
    }
    String typeName = getTypeName(clazz, dataType);
    // 基本类型,直接处理。
    if (dataType.isSimpleType()) {
        return createSimple(clazz, clazz, dataType, typeName);
    }
    // 子类型。
    Class<?> elementType = null;
    // 数组类型,找到它的元素的具体类型,然后处理具体类型。
    if (dataType.isArrayType()) {
        elementType = Api2DocUtils.getArrayElementClass(method);
        if (elementType == null) {
            log.warn("Can't find element class by method: {}", method);
            return null;
        }
        ApiDataType elementDataType = ApiDataType.toDataType(elementType);
        typeName = getTypeName(elementType, elementDataType) + "[]";
        // 数组类型,但元素是基本类型的,也直接处理。
        if (elementDataType != null && elementDataType.isSimpleType()) {
            return createSimple(elementType, clazz, elementDataType, typeName);
        }
    }
    // 复杂类型的情况。
    ApiResultObject result = new ApiResultObject();
    result.setDataType(dataType);
    result.setSourceType(clazz);
    result.setTypeName(typeName);
    result.setId("");
    if (dataType.isObjectType()) {
        elementType = method.getReturnType();
    }
    // TODO:  暂时不解析 Map 内部的类型。
    if (elementType == null || Map.class.equals(elementType)) {
        return result;
    }
    result.setSourceType(elementType);
    // 没有子类型,直接返回。
    PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(elementType);
    if (props == null || props.length == 0) {
        return result;
    }
    // 根据类型生成字段集的 id 和 name 。
    String groupId = getGroupId(elementType);
    result.setGroupId(groupId);
    String groupName = elementType.getSimpleName();
    result.setGroupName(groupName);
    // 加入到结果字段集中。
    if (totalResults.containsKey(groupId)) {
        return result;
    } else {
        totalResults.add(groupId, result);
    }
    // 有子类型,补充子类型信息。
    for (PropertyDescriptor prop : props) {
        if (Api2DocUtils.isFilter(prop, elementType)) {
            continue;
        }
        String fieldName = prop.getName();
        Method subMethod = prop.getReadMethod();
        // 处理子类型。
        ApiResultObject childPropResult;
        try {
            childPropResult = parseResultType(subMethod, totalResults);
        } catch (Exception e) {
            String msg = String.format("解析类[ %s ]的属性[ %s ]出错: %s", elementType.getName(), fieldName, e.getMessage());
            throw new RuntimeException(msg);
        }
        // 补充子类型信息。
        if (childPropResult != null) {
            // 补充到当前节点中。
            result.addChild(childPropResult);
            String id = prop.getName();
            childPropResult.setId(id);
            childPropResult.setName(id);
            Class<?> childPropClass = subMethod.getReturnType();
            ApiDataType childPropDataType = ApiDataType.toDataType(childPropClass);
            childPropResult.setDataType(childPropDataType);
            Api2Doc childApi2Doc;
            ApiComment childApiComment;
            String childName;
            Field field = Classes.getField(id, elementType);
            if (field != null) {
                childApiComment = field.getAnnotation(ApiComment.class);
                childApi2Doc = field.getAnnotation(Api2Doc.class);
                childName = field.getName();
            } else {
                childApiComment = subMethod.getAnnotation(ApiComment.class);
                childApi2Doc = subMethod.getAnnotation(Api2Doc.class);
                childName = subMethod.getName();
            }
            ApiComment elementApiComment = elementType.getAnnotation(ApiComment.class);
            Class<?> defaultSeeClass = ApiCommentUtils.getDefaultSeeClass(elementApiComment, null);
            String comment = ApiCommentUtils.getComment(childApiComment, defaultSeeClass, childName);
            if (comment == null) {
                comment = "";
            }
            childPropResult.insertComment(comment);
            String sample = ApiCommentUtils.getSample(childApiComment, defaultSeeClass, childName);
            if (sample == null) {
                sample = "";
            }
            childPropResult.setSample(sample);
            if (childApi2Doc != null) {
                childPropResult.setOrder(childApi2Doc.order());
            }
            // 记录所引用的类型。
            Class<?> childSubType = null;
            if (childPropDataType != null) {
                if (childPropDataType.isArrayType()) {
                    childSubType = Api2DocUtils.getArrayElementClass(subMethod);
                } else if (childPropDataType.isObjectType()) {
                    childSubType = subMethod.getReturnType();
                }
            }
            if (childSubType != null) {
                String refGroupId = getGroupId(childSubType);
                childPropResult.setRefGroupId(refGroupId);
            }
        }
    }
    Collections.sort(result.getChildren());
    return result;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) Method(java.lang.reflect.Method) Field(java.lang.reflect.Field) Api2Doc(com.terran4j.commons.api2doc.annotations.Api2Doc) ApiComment(com.terran4j.commons.api2doc.annotations.ApiComment) Map(java.util.Map)

Example 3 with Api2Doc

use of com.terran4j.commons.api2doc.annotations.Api2Doc in project commons by terran4j.

the class Api2DocCollector method getApiDoc.

ApiDocObject getApiDoc(MappingMethod mappingMethod, String[] basePaths, String beanName, Api2Doc classApi2Doc, Class<?> defaultSeeClass) throws BusinessException {
    Method method = mappingMethod.getMethod();
    // 只要有 @ApiDoc 注解(无论是本方法上,还是类上),有会生成文档,没有这个注解就不会。
    Api2Doc api2Doc = method.getAnnotation(Api2Doc.class);
    if (api2Doc == null && classApi2Doc == null) {
        return null;
    }
    ApiDocObject doc = new ApiDocObject();
    doc.setSourceMethod(method);
    // 获取文档的 id,以 @Api2Doc、方法名 为顺序获取。
    String id = method.getName();
    if (api2Doc != null && StringUtils.hasText(api2Doc.value())) {
        id = api2Doc.value();
    }
    if (api2Doc != null && StringUtils.hasText(api2Doc.id())) {
        id = api2Doc.id();
    }
    doc.setId(id);
    checkId(id);
    // 获取文档的排序。
    if (api2Doc != null) {
        doc.setOrder(api2Doc.order());
    }
    // 获取文档名称,按 @Api2Doc 、@Mapping、方法名的顺序获取。
    String name = method.getName();
    String mappingName = mappingMethod.getName();
    if (StringUtils.hasText(mappingName)) {
        name = mappingName;
    }
    if (api2Doc != null && StringUtils.hasText(api2Doc.name())) {
        name = api2Doc.name();
    }
    doc.setName(name);
    // 获取 API 的注释信息。
    ApiComment apiComment = method.getAnnotation(ApiComment.class);
    defaultSeeClass = ApiCommentUtils.getDefaultSeeClass(apiComment, defaultSeeClass);
    doc.setComment(ApiCommentUtils.getComment(apiComment, defaultSeeClass, name));
    doc.setSample(ApiCommentUtils.getSample(apiComment, defaultSeeClass, name));
    // 获取 API 的访问路径。
    String[] paths = mappingMethod.getPath();
    paths = combine(basePaths, paths);
    doc.setPaths(paths);
    // 获取 HTTP 方法。
    doc.setMethods(mappingMethod.getRequestMethod());
    // 收集参数信息。
    List<ApiParamObject> apiParams = toApiParams(method, defaultSeeClass);
    if (apiParams != null && apiParams.size() > 0) {
        for (ApiParamObject apiParam : apiParams) {
            doc.addParam(apiParam);
        }
    }
    // 收集返回值信息。
    KeyedList<String, ApiResultObject> totalResults = new KeyedList<>();
    ApiResultObject.parseResultType(method, totalResults);
    doc.setResults(totalResults.getAll());
    // 确定返回类型的描述。
    String returnTypeDesc = null;
    List<ApiResultObject> results = doc.getResults();
    if (results != null && results.size() > 0) {
        ApiResultObject result = results.get(0);
        ApiDataType dataType = result.getDataType();
        if (dataType != null) {
            if (dataType == ApiDataType.ARRAY) {
                returnTypeDesc = result.getSourceType().getSimpleName() + "[]";
            } else {
                returnTypeDesc = result.getSourceType().getSimpleName();
            }
        }
    }
    if (returnTypeDesc == null) {
        Class<?> returnType = doc.getSourceMethod().getReturnType();
        if (returnType != null && returnType != void.class) {
            returnTypeDesc = returnType.getSimpleName();
        }
    }
    doc.setReturnTypeDesc(returnTypeDesc);
    // 收集错误码信息。
    ApiErrors errorCodes = method.getAnnotation(ApiErrors.class);
    if (errorCodes != null && errorCodes.value() != null && errorCodes.value().length > 0) {
        for (ApiError errorCode : errorCodes.value()) {
            ApiErrorObject error = getError(errorCode);
            if (error == null) {
                continue;
            }
            doc.addError(error);
        }
    } else {
        ApiError errorCode = method.getAnnotation(ApiError.class);
        ApiErrorObject error = getError(errorCode);
        if (error != null) {
            doc.addError(error);
        }
    }
    return doc;
}
Also used : KeyedList(com.terran4j.commons.util.value.KeyedList) ApiErrors(com.terran4j.commons.api2doc.annotations.ApiErrors) Method(java.lang.reflect.Method) Api2Doc(com.terran4j.commons.api2doc.annotations.Api2Doc) ApiComment(com.terran4j.commons.api2doc.annotations.ApiComment) ApiError(com.terran4j.commons.api2doc.annotations.ApiError)

Example 4 with Api2Doc

use of com.terran4j.commons.api2doc.annotations.Api2Doc in project commons by terran4j.

the class ApiDocUtils method getId.

public static final String getId(Class<?> clazz) {
    if (clazz == null) {
        throw new NullPointerException();
    }
    Api2Doc api2doc = clazz.getAnnotation(Api2Doc.class);
    if (api2doc != null) {
        String id = api2doc.id();
        if (StringUtils.hasText(id)) {
            return id;
        }
        String value = api2doc.value();
        if (StringUtils.hasText(value)) {
            return value;
        }
    }
    return clazz.getName();
}
Also used : Api2Doc(com.terran4j.commons.api2doc.annotations.Api2Doc)

Aggregations

Api2Doc (com.terran4j.commons.api2doc.annotations.Api2Doc)4 ApiComment (com.terran4j.commons.api2doc.annotations.ApiComment)3 Method (java.lang.reflect.Method)3 ApiError (com.terran4j.commons.api2doc.annotations.ApiError)1 ApiErrors (com.terran4j.commons.api2doc.annotations.ApiErrors)1 KeyedList (com.terran4j.commons.util.value.KeyedList)1 PropertyDescriptor (java.beans.PropertyDescriptor)1 IOException (java.io.IOException)1 Field (java.lang.reflect.Field)1 Map (java.util.Map)1 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)1 Resource (org.springframework.core.io.Resource)1 Controller (org.springframework.stereotype.Controller)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1