heyile commented on a change in pull request #1157: [SCB-1225][WIP][WEAK] swagger generator core not depend on dynamic class URL: https://github.com/apache/servicecomb-java-chassis/pull/1157#discussion_r270619218
########## File path: swagger/swagger-generator/generator-core/src/main/java/org/apache/servicecomb/swagger/generator/core/AbstractOperationGenerator.java ########## @@ -0,0 +1,594 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.servicecomb.swagger.generator.core; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.lang3.StringUtils; +import org.apache.servicecomb.config.inject.PlaceholderResolver; +import org.apache.servicecomb.swagger.SwaggerUtils; +import org.apache.servicecomb.swagger.generator.MethodAnnotationProcessor; +import org.apache.servicecomb.swagger.generator.OperationGenerator; +import org.apache.servicecomb.swagger.generator.ParameterGenerator; +import org.apache.servicecomb.swagger.generator.ParameterProcessor; +import org.apache.servicecomb.swagger.generator.ResponseTypeProcessor; +import org.apache.servicecomb.swagger.generator.SwaggerConst; +import org.apache.servicecomb.swagger.generator.core.model.HttpParameterType; + +import com.fasterxml.jackson.databind.BeanDescription; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; +import com.fasterxml.jackson.databind.type.TypeFactory; + +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiParam; +import io.swagger.converter.ModelConverters; +import io.swagger.models.HttpMethod; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Response; +import io.swagger.models.Swagger; +import io.swagger.models.parameters.AbstractSerializableParameter; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.CookieParameter; +import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.HeaderParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.parameters.PathParameter; +import io.swagger.models.parameters.QueryParameter; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; +import io.swagger.util.Json; +import io.swagger.util.ReflectionUtils; + +public abstract class AbstractOperationGenerator implements OperationGenerator { + protected AbstractSwaggerGenerator swaggerGenerator; + + protected Swagger swagger; + + protected Method method; + + protected String httpMethod; + + protected List<ParameterGenerator> parameterGenerators = new ArrayList<>(); + + protected String path; + + protected Operation swaggerOperation; + + // 根据方法上独立的ResponseHeader(s)标注生成的数据 + // 如果Response中不存在对应的header,则会将这些header补充进去 + protected Map<String, Property> methodResponseHeaders = new LinkedHashMap<>(); + + public AbstractOperationGenerator(AbstractSwaggerGenerator swaggerGenerator, Method method) { + this.swaggerGenerator = swaggerGenerator; + this.swagger = swaggerGenerator.getSwagger(); + this.method = method; + this.httpMethod = swaggerGenerator.getHttpMethod(); + + swaggerOperation = new Operation(); + } + + @Override + public void addMethodResponseHeader(String name, Property header) { + methodResponseHeaders.put(name, header); + } + + @Override + public void setHttpMethod(String httpMethod) { + if (StringUtils.isEmpty(httpMethod)) { + return; + } + + this.httpMethod = httpMethod.toLowerCase(Locale.US); + } + + @Override + public Operation getOperation() { + return swaggerOperation; + } + + public String getOperationId() { + return swaggerOperation.getOperationId(); + } + + @Override + public void setPath(String path) { + path = new PlaceholderResolver().replaceFirst(path); + if (!path.startsWith("/")) { + path = "/" + path; + } + this.path = path; + } + + public void generate() { + scanMethodAnnotation(); + scanMethodParameters(); + scanResponse(); + + correctOperation(); + } + + protected void scanMethodAnnotation() { + for (Annotation annotation : method.getAnnotations()) { + MethodAnnotationProcessor<Annotation> processor = swaggerGenerator + .findMethodAnnotationProcessor(annotation.annotationType()); + if (processor == null) { + continue; + } + processor.process(swaggerGenerator, this, annotation); + } + + if (StringUtils.isEmpty(swaggerOperation.getOperationId())) { + swaggerOperation.setOperationId(method.getName()); + } + + setDefaultTag(); + } + + private void setDefaultTag() { + // if tag has been defined, do nothing + if (null != swaggerOperation.getTags()) { + for (String tag : swaggerOperation.getTags()) { + if (StringUtils.isNotEmpty(tag)) { + return; + } + } + } + + // if there is no tag, set default tag + if (!swaggerGenerator.getDefaultTags().isEmpty()) { + swaggerOperation.setTags(new ArrayList<>(swaggerGenerator.getDefaultTags())); + } + } + + protected void scanMethodParameters() { + initParameterGenerators(); + + Set<String> names = new HashSet<>(); + for (ParameterGenerator parameterGenerator : parameterGenerators) { + scanMethodParameter(parameterGenerator); + + if (!names.add(parameterGenerator.parameterName)) { + throw new IllegalStateException( + String.format("not support duplicated parameter, name=%s.", parameterGenerator.parameterName)); + } + swaggerOperation.addParameter(parameterGenerator.generatedParameter); + } + } + + private void initParameterGenerators() { + // 1.group method annotations by parameter name + // key is parameter name + Map<String, List<Annotation>> methodAnnotationMap = initMethodAnnotationByParameterName(); + + // 2.create ParameterGenerators by method parameters, merge annotations with method annotations + initMethodParameterGenerators(methodAnnotationMap); + + // 3.create ParameterGenerators remains method annotations + initRemainMethodAnnotationsParameterGenerators(methodAnnotationMap); + + // 4.check + // httpParameterType should not be null + long bodyCount = parameterGenerators.stream().filter(p -> p.httpParameterType.equals(HttpParameterType.body)) + .count(); + if (bodyCount > 1) { + throw new IllegalStateException(String.format("defined %d body parameter.", bodyCount)); + } + } + + protected void initMethodParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap) { + for (java.lang.reflect.Parameter methodParameter : method.getParameters()) { + ParameterGenerator parameterGenerator = new ParameterGenerator(this, methodAnnotationMap, methodParameter); + // jaxrs: @BeanParam + // springmvc: is query, and is bean type + if (isAggregatedParameter(parameterGenerator, methodParameter)) { + extractAggregatedParameterGenerators(methodAnnotationMap, methodParameter); + continue; + } + + validateParameter(parameterGenerator.genericType); + if (swaggerGenerator.isContextParameter(parameterGenerator.genericType)) { + continue; + } + + parameterGenerators.add(parameterGenerator); + } + } + + protected boolean isAggregatedParameter(ParameterGenerator parameterGenerator, + java.lang.reflect.Parameter methodParameter) { + return false; + } + + protected void extractAggregatedParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap, + java.lang.reflect.Parameter methodParameter) { + JavaType javaType = TypeFactory.defaultInstance().constructType(methodParameter.getParameterizedType()); + BeanDescription beanDescription = Json.mapper().getSerializationConfig().introspect(javaType); + for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) { + if (propertyDefinition.getField() == null && !propertyDefinition.getField().isPublic()) { + continue; + } + + if (propertyDefinition.getSetter() == null && !propertyDefinition.getField().isPublic()) { + continue; + } + + List<Annotation> annotations = new ArrayList<>(); + if (propertyDefinition.getField() != null) { + Collections.addAll(annotations, propertyDefinition.getField().getAnnotated().getAnnotations()); + } + if (propertyDefinition.getGetter() != null) { + Collections.addAll(annotations, propertyDefinition.getGetter().getAnnotated().getAnnotations()); + } + if (propertyDefinition.getSetter() != null) { + Collections.addAll(annotations, propertyDefinition.getSetter().getAnnotated().getAnnotations()); + } + propertyDefinition.getField().getAllAnnotations(); + ParameterGenerator propertyParameterGenerator = new ParameterGenerator(this, + methodAnnotationMap, + propertyDefinition.getName(), + annotations.toArray(new Annotation[annotations.size()]), + propertyDefinition.getField().getAnnotated().getGenericType()); + parameterGenerators.add(propertyParameterGenerator); + } + } + + protected void initRemainMethodAnnotationsParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap) { + for (Entry<String, List<Annotation>> entry : methodAnnotationMap.entrySet()) { + ParameterGenerator parameterGenerator = new ParameterGenerator(this, entry.getKey(), entry.getValue()); + parameterGenerators.add(parameterGenerator); + } + } + + @Override + public List<Annotation> collectParameterAnnotations(Annotation[] parameterAnnotations, + Map<String, List<Annotation>> methodAnnotationMap, String parameterName) { + List<Annotation> methodAnnotations = methodAnnotationMap.remove(parameterName); + if (methodAnnotations == null) { + methodAnnotations = Collections.emptyList(); + } + + List<Annotation> annotations = new ArrayList<>(); + Collections.addAll(annotations, parameterAnnotations); + annotations.addAll(methodAnnotations); + + return annotations; + } + + private Map<String, List<Annotation>> initMethodAnnotationByParameterName() { + Map<String, List<Annotation>> methodAnnotations = new LinkedHashMap<>(); + for (Annotation annotation : method.getAnnotations()) { + if (annotation instanceof ApiImplicitParams) { + for (ApiImplicitParam apiImplicitParam : ((ApiImplicitParams) annotation).value()) { + addMethodAnnotationByParameterName(methodAnnotations, apiImplicitParam.name(), apiImplicitParam); + } + continue; + } + + if (annotation instanceof ApiParam) { + addMethodAnnotationByParameterName(methodAnnotations, ((ApiParam) annotation).name(), annotation); + } + } + return methodAnnotations; + } + + private void addMethodAnnotationByParameterName(Map<String, List<Annotation>> methodAnnotations, String name, + Annotation annotation) { + if (StringUtils.isEmpty(name)) { + throw new IllegalStateException( + String.format("%s.name should not be empty. method=", annotation.annotationType().getSimpleName(), method)); + } + + methodAnnotations.computeIfAbsent(name, n -> new ArrayList<>()) + .add(annotation); + } + + @Override + public Type collectGenericType(List<Annotation> annotations, Type defaultType) { + Type genericType = null; + for (Annotation annotation : annotations) { + ParameterProcessor<Parameter, Annotation> processor = swaggerGenerator + .findParameterProcessors(annotation.annotationType()); + if (processor == null) { + continue; + } + + Type type = processor.getGenericType(annotation); + if (type != null) { + genericType = type; Review comment: why not break when type != null, want the later one covers the former? ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
