SpringParser.java 12.1 KB
Newer Older
duanledexianxianxian's avatar
duanledexianxianxian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
package com.apigcc.springmvc;

import com.apidoc.core.ApiDoc;
import com.apidoc.core.common.URI;
import com.apidoc.core.common.description.ObjectTypeDescription;
import com.apidoc.core.common.description.TypeDescription;
import com.apidoc.core.common.helper.AnnotationHelper;
import com.apidoc.core.common.helper.ExpressionHelper;
import com.apidoc.core.common.helper.StringHelper;
import com.apidoc.core.parser.ParserStrategy;
import com.apidoc.core.schema.Chapter;
import com.apidoc.core.schema.Header;
import com.apidoc.core.schema.Row;
import com.apidoc.core.schema.Section;
import com.apigcc.springmvc.resovler.SpringComponentTypeResolver;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Expression;

import java.util.List;
import java.util.Optional;

import static com.apigcc.springmvc.ParameterHelper.ANNOTATION_REQUEST_HEADER;
import static com.apigcc.springmvc.ParameterHelper.ANNOTATION_REQUEST_PARAM;


/**
 * spring 解析
 *
 * @author fengyuchenglun
 * @version 1.0.0
 */
public class SpringParser implements ParserStrategy {

    /**
     * The constant FRAMEWORK.
     */
    public static final String FRAMEWORK = "springmvc";


    /**
     * The constant EXT_URI.
     */
    public static final String EXT_URI = "uri";



    @Override
    public String name() {
        return FRAMEWORK;
    }

    @Override
    public void onLoad() {
        // 添加类型解析器
        ApiDoc.getInstance().getTypeResolvers().addResolver(new SpringComponentTypeResolver());
        // 类型名称解析器
        ApiDoc.getInstance().getTypeResolvers().addNameResolver(new SpringComponentTypeResolver());
    }

    /**
     * 处理被@RestController和@Controller标记的类
     *
     * @return classOrInterfaceDeclaration
     */
    @Override
    public boolean accept(ClassOrInterfaceDeclaration classOrInterfaceDeclaration) {
        return AnnotationHelper.isAnnotationPresent(classOrInterfaceDeclaration, SpringMVCContext.getInstance().getControllers());
    }

    /**
     * 类被@RestController标记,或方法被@ResponseBody标记
     *
     * @param methodDeclaration methodDeclaration
     * @return boolean
     */
    @Override
    public boolean accept(MethodDeclaration methodDeclaration) {
        //类被@RestController标记,或方法被@ResponseBody标记
        return RequestMappingHelper.isRest(methodDeclaration) && AnnotationHelper.isAnnotationPresent(methodDeclaration, RequestMappingHelper.ANNOTATION_REQUEST_MAPPINGS);
    }

    /**
     * 解析类定义
     *
     * @param n
     * @param chapter
     */
    @Override
    public void visit(ClassOrInterfaceDeclaration n, Chapter chapter) {
        chapter.getExt().put(EXT_URI, RequestMappingHelper.pickUriToParent(n));
    }

    /**
     * 解析方法定义
     *
     * @param n
     * @param chapter
     * @param section
     */
    @Override
    public void visit(MethodDeclaration n, Chapter chapter, Section section) {
        visitMethod(n, chapter, section);
        visitUri(n, chapter, section);
        visitPathVariable(n, chapter, section);
        visitHeaders(n, chapter, section);
        visitParameters(n, chapter, section);
        visitReturn(n, chapter, section);
    }

    /**
     * 解析请求方法
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitMethod(MethodDeclaration n, Chapter chapter, Section section) {
        section.setMethod(RequestMappingHelper.pickMethod(n));
    }

    /**
     * 解析请求URI,与父类URI拼接
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitUri(MethodDeclaration n, Chapter chapter, Section section) {
        URI uri = (URI) chapter.getExt().get(EXT_URI);
        section.setUri(new URI(uri.toString()).add(RequestMappingHelper.pickUri(n.getAnnotations())).toString());
    }

    /**
     * 解析方法参数
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitParameters(MethodDeclaration n, Chapter chapter, Section section) {
        if (ParameterHelper.hasRequestBody(n.getParameters())) {
            visitRequestBody(n, chapter, section);
        } else {
            visitParameter(n, chapter, section);
        }
    }

    /**
     * 解析PathVariable
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitPathVariable(MethodDeclaration n, Chapter chapter, Section section) {
        for (Parameter parameter : n.getParameters()) {
            if (ParameterHelper.isPathVariable(parameter)) {
                section.getPathVariable().put(parameter.getNameAsString(), "");
                Row row = new Row();
                row.setKey(parameter.getNameAsString());
                row.setType(parameter.getType().toString());
                section.getParamTag(row.getKey()).ifPresent(tag -> row.setRemark(tag.getContent()));
                section.addRequestRow(row);
            }
        }
    }

    /**
     * 解析RequestHeader
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitHeaders(MethodDeclaration n, Chapter chapter, Section section) {

        List<String> headers = RequestMappingHelper.pickHeaders(n.getAnnotations());
        for (String text : headers) {
            section.addInHeader(Header.valueOf(text));
        }

        List<String> consumers = RequestMappingHelper.pickConsumers(n.getAnnotations());
        if (!consumers.isEmpty()) {
            section.addInHeader(new Header("Content-Type", String.join(",", consumers)));
        }

        List<String> produces = RequestMappingHelper.pickProduces(n.getAnnotations());
        if (!produces.isEmpty()) {
            section.addOutHeader(new Header("Content-Type", String.join(",", produces)));
        }

        for (Parameter parameter : n.getParameters()) {
            if (ParameterHelper.isRequestHeader(parameter)) {
                String key = parameter.getNameAsString();
                String defaultValue = "{value}";
                AnnotationExpr annotationExpr = parameter.getAnnotationByName(ANNOTATION_REQUEST_HEADER).get();
                Optional<Expression> valueOptional = AnnotationHelper.getAnyAttribute(annotationExpr, "value", "name");
                if (valueOptional.isPresent()) {
                    key = String.valueOf(ExpressionHelper.getValue(valueOptional.get()));
                }
                Optional<Expression> defaultValueOptional = AnnotationHelper.getAttribute(annotationExpr, "defaultValue");
                if (defaultValueOptional.isPresent()) {
                    defaultValue = String.valueOf(ExpressionHelper.getValue(defaultValueOptional.get()));
                }
                TypeDescription description = ApiDoc.getInstance().getTypeResolvers().resolve(parameter.getType());
                if (description.isAvailable()) {
                    Object value = description.getValue();
                    if (StringHelper.isBlank(defaultValue) && StringHelper.nonBlank(value)) {
                        defaultValue = String.valueOf(value);
                    }
                    section.addInHeader(new Header(key, defaultValue));
                }
            }
        }
    }

    /**
     * 解析RequestBody
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitRequestBody(MethodDeclaration n, Chapter chapter, Section section) {
        section.setQueryParameter(false);
        section.addInHeader(Header.APPLICATION_JSON);
        for (Parameter parameter : n.getParameters()) {
            if (ParameterHelper.isRequestBody(parameter)) {
                TypeDescription description = ApiDoc.getInstance().getTypeResolvers().resolve(parameter.getType());
                if (description.isAvailable()) {
                    if (description.isArray()) {
                        section.setParameter(description.asArray().getValue());
                    } else if (description.isObject()) {
                        section.setParameter(description.asObject().getValue());
                    }
                    section.addRequestRows(description.rows());
                }
                break;
            }
        }

    }

    /**
     * 解析RequestParameter
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitParameter(MethodDeclaration n, Chapter chapter, Section section) {
        ObjectTypeDescription objectTypeDescription = new ObjectTypeDescription();
        for (Parameter parameter : n.getParameters()) {
            if (ParameterHelper.isRequestParam(parameter)) {
                String key = parameter.getNameAsString();

                Object defaultValue = null;
                Boolean required = null;

                Optional<AnnotationExpr> optional = parameter.getAnnotationByName(ANNOTATION_REQUEST_PARAM);
                if (optional.isPresent()) {
                    Optional<Expression> valueOptional = AnnotationHelper.getAnyAttribute(optional.get(), "value", "name");
                    if (valueOptional.isPresent()) {
                        key = String.valueOf(ExpressionHelper.getValue(valueOptional.get()));
                    }
                    Optional<Expression> defaultValueOptional = AnnotationHelper.getAttribute(optional.get(), "defaultValue");
                    if (defaultValueOptional.isPresent()) {
                        defaultValue = ExpressionHelper.getValue(defaultValueOptional.get());
                    }
                    Optional<Expression> requiredOptional = AnnotationHelper.getAttribute(optional.get(), "required");
                    if (requiredOptional.isPresent() && requiredOptional.get().isBooleanLiteralExpr()) {
                        required = requiredOptional.get().asBooleanLiteralExpr().getValue();
                    }
                }

                TypeDescription description = ApiDoc.getInstance().getTypeResolvers().resolve(parameter.getType());
                if (description.isAvailable()) {
                    section.getParamTag(key).ifPresent(tag -> description.addRemark(tag.getContent()));
                    if (required != null) {
                        description.setRequired(required);
                    }
                    if (description.isObject()) {
                        objectTypeDescription.merge(description.asObject());
                    } else {
                        description.setKey(key);
                        if (defaultValue != null && (description.isPrimitive() || description.isString())) {
                            description.setDefaultValue(defaultValue);
                        }
                        objectTypeDescription.add(description);
                    }
                }
            }
        }
        section.setParameter(objectTypeDescription.getValue());
        section.addRequestRows(objectTypeDescription.rows());
    }

    /**
     * 解析方法返回参数
     *
     * @param n       the n
     * @param chapter the chapter
     * @param section the section
     */
    private void visitReturn(MethodDeclaration n, Chapter chapter, Section section) {
        TypeDescription description = ApiDoc.getInstance().getTypeResolvers().resolve(n.getType());
        if (description.isAvailable()) {
            if (description.isPrimitive()) {
                section.setRawResponse(description.getValue());
            } else if (description.isString()) {
                section.setRawResponse(description.getValue());
            } else if (description.isArray()) {
                section.setResponse(description.asArray().getValue());
            } else if (description.isObject()) {
                section.setResponse(description.asObject().getValue());
            }
            section.addResponseRows(description.rows());
        }
    }

}