com.cimr.boot.swagger.SwaggerAutoConfiguration.java Source code

Java tutorial

Introduction

Here is the source code for com.cimr.boot.swagger.SwaggerAutoConfiguration.java

Source

package com.cimr.boot.swagger;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.BasicAuth;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;

/**
 * @author 
 * Create date2017/8/7.
 * My blog http://blog.didispace.com
 */
@Configuration
@Import({ Swagger2Configuration.class })
public class SwaggerAutoConfiguration implements BeanFactoryAware {

    private BeanFactory beanFactory;

    @Bean
    @ConditionalOnMissingBean
    public SwaggerProperties swaggerProperties() {
        return new SwaggerProperties();
    }

    @Bean
    public UiConfiguration uiConfiguration(SwaggerProperties swaggerProperties) {
        return new UiConfiguration(swaggerProperties.getUiConfig().getDeepLinking(),
                swaggerProperties.getUiConfig().getDisplayOperationId(),
                swaggerProperties.getUiConfig().getDefaultModelsExpandDepth(),
                swaggerProperties.getUiConfig().getDefaultModelExpandDepth(),
                swaggerProperties.getUiConfig().getDefaultModelRendering(),
                swaggerProperties.getUiConfig().getDisplayRequestDuration(),
                swaggerProperties.getUiConfig().getDocExpansion(), swaggerProperties.getUiConfig().getFilter(),
                swaggerProperties.getUiConfig().getMaxDisplayedTags(),
                swaggerProperties.getUiConfig().getOperationsSorter(),
                swaggerProperties.getUiConfig().getShowExtensions(),
                swaggerProperties.getUiConfig().getTagsSorter(), swaggerProperties.getUiConfig().getValidatorUrl()); // requestTimeout => in milliseconds, defaults to null (uses jquery xh timeout)
    }

    //    @Bean
    //    public UiConfiguration uiConfiguration(SwaggerProperties swaggerProperties) {
    //        return new UiConfiguration(
    //                swaggerProperties.getUiConfig().getValidatorUrl(),// url
    //                swaggerProperties.getUiConfig().getDocExpansion(),       // docExpansion          => none | list
    //                swaggerProperties.getUiConfig().getApiSorter(),      // apiSorter             => alpha
    //                swaggerProperties.getUiConfig().getDefaultModelRendering(),     // defaultModelRendering => schema
    //                swaggerProperties.getUiConfig().getSubmitMethods().split(","),
    //                swaggerProperties.getUiConfig().getJsonEditor(),        // enableJsonEditor      => true | false
    //                swaggerProperties.getUiConfig().getShowRequestHeaders(),         // showRequestHeaders    => true | false
    //                swaggerProperties.getUiConfig().getRequestTimeout());      // requestTimeout => in milliseconds, defaults to null (uses jquery xh timeout)
    //    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean(UiConfiguration.class)
    @ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
    public List<Docket> createRestApi(SwaggerProperties swaggerProperties) {
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
        List<Docket> docketList = new LinkedList<>();

        // 
        if (swaggerProperties.getDocket().size() == 0) {
            ApiInfo apiInfo = new ApiInfoBuilder().title(swaggerProperties.getTitle())
                    .description(swaggerProperties.getDescription()).version(swaggerProperties.getVersion())
                    .license(swaggerProperties.getLicense()).licenseUrl(swaggerProperties.getLicenseUrl())
                    .contact(new Contact(swaggerProperties.getContact().getName(),
                            swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
                    .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()).build();

            // base-path?
            // ?path?/**
            if (swaggerProperties.getBasePath().isEmpty()) {
                swaggerProperties.getBasePath().add("/**");
            }
            List<Predicate<String>> basePath = new ArrayList();
            for (String path : swaggerProperties.getBasePath()) {
                basePath.add(PathSelectors.ant(path));
            }

            // exclude-path?
            List<Predicate<String>> excludePath = new ArrayList();
            for (String path : swaggerProperties.getExcludePath()) {
                excludePath.add(PathSelectors.ant(path));
            }

            Docket docketForBuilder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost())
                    .apiInfo(apiInfo)
                    .securitySchemes(buildSecuritySchemeFromSwaggerProperties(
                            swaggerProperties.getSecuritySchemesParameters()))
                    .globalOperationParameters(buildGlobalOperationParametersFromSwaggerProperties(
                            swaggerProperties.getGlobalOperationParameters()));

            // ??
            if (!swaggerProperties.getApplyDefaultResponseMessages()) {
                buildGlobalResponseMessage(swaggerProperties, docketForBuilder);
            }

            Docket docket = docketForBuilder.select()
                    .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                    .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                    .build();

            /** ignoredParameterTypes **/
            Class[] array = new Class[swaggerProperties.getIgnoredParameterTypes().size()];
            Class[] ignoredParameterTypes = swaggerProperties.getIgnoredParameterTypes().toArray(array);
            docket.ignoredParameterTypes(ignoredParameterTypes);

            configurableBeanFactory.registerSingleton("defaultDocket", docket);
            docketList.add(docket);
            return docketList;
        }

        // 
        for (String groupName : swaggerProperties.getDocket().keySet()) {
            SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName);

            ApiInfo apiInfo = new ApiInfoBuilder()
                    .title(docketInfo.getTitle().isEmpty() ? swaggerProperties.getTitle() : docketInfo.getTitle())
                    .description(docketInfo.getDescription().isEmpty() ? swaggerProperties.getDescription()
                            : docketInfo.getDescription())
                    .version(docketInfo.getVersion().isEmpty() ? swaggerProperties.getVersion()
                            : docketInfo.getVersion())
                    .license(docketInfo.getLicense().isEmpty() ? swaggerProperties.getLicense()
                            : docketInfo.getLicense())
                    .licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? swaggerProperties.getLicenseUrl()
                            : docketInfo.getLicenseUrl())
                    .contact(new Contact(
                            docketInfo.getContact().getName().isEmpty() ? swaggerProperties.getContact().getName()
                                    : docketInfo.getContact().getName(),
                            docketInfo.getContact().getUrl().isEmpty() ? swaggerProperties.getContact().getUrl()
                                    : docketInfo.getContact().getUrl(),
                            docketInfo.getContact().getEmail().isEmpty() ? swaggerProperties.getContact().getEmail()
                                    : docketInfo.getContact().getEmail()))
                    .termsOfServiceUrl(
                            docketInfo.getTermsOfServiceUrl().isEmpty() ? swaggerProperties.getTermsOfServiceUrl()
                                    : docketInfo.getTermsOfServiceUrl())
                    .build();

            // base-path?
            // ?path?/**
            if (docketInfo.getBasePath().isEmpty()) {
                docketInfo.getBasePath().add("/**");
            }
            List<Predicate<String>> basePath = new ArrayList();
            for (String path : docketInfo.getBasePath()) {
                basePath.add(PathSelectors.ant(path));
            }

            // exclude-path?
            List<Predicate<String>> excludePath = new ArrayList();
            for (String path : docketInfo.getExcludePath()) {
                excludePath.add(PathSelectors.ant(path));
            }

            Docket docketForBuilder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost())
                    .apiInfo(apiInfo).globalOperationParameters(
                            assemblyGlobalOperationParameters(swaggerProperties.getGlobalOperationParameters(),
                                    docketInfo.getGlobalOperationParameters()));

            // ??
            if (!swaggerProperties.getApplyDefaultResponseMessages()) {
                buildGlobalResponseMessage(swaggerProperties, docketForBuilder);
            }

            Docket docket = docketForBuilder.groupName(groupName).select()
                    .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
                    .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                    .build();

            /** ignoredParameterTypes **/
            Class[] array = new Class[docketInfo.getIgnoredParameterTypes().size()];
            Class[] ignoredParameterTypes = docketInfo.getIgnoredParameterTypes().toArray(array);
            docket.ignoredParameterTypes(ignoredParameterTypes);

            configurableBeanFactory.registerSingleton(groupName, docket);
            docketList.add(docket);
        }
        return docketList;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    private List<Parameter> buildGlobalOperationParametersFromSwaggerProperties(
            List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters) {
        List<Parameter> parameters = Lists.newArrayList();

        if (Objects.isNull(globalOperationParameters)) {
            return parameters;
        }
        for (SwaggerProperties.GlobalOperationParameter globalOperationParameter : globalOperationParameters) {
            parameters.add(new ParameterBuilder().name(globalOperationParameter.getName())
                    .description(globalOperationParameter.getDescription())
                    .modelRef(new ModelRef(globalOperationParameter.getModelRef()))
                    .parameterType(globalOperationParameter.getParameterType())
                    .required(Boolean.parseBoolean(globalOperationParameter.getRequired())).build());
        }
        return parameters;
    }

    private List<SecurityScheme> buildSecuritySchemeFromSwaggerProperties(
            List<SwaggerProperties.SecuritySchemesParameter> securitySchemesParameters) {
        List<SecurityScheme> parameters = Lists.newArrayList();

        if (Objects.isNull(securitySchemesParameters)) {
            return parameters;
        }
        for (SwaggerProperties.SecuritySchemesParameter securitySchemesParameter : securitySchemesParameters) {
            if ("apiKey".equals(securitySchemesParameter.getType())) {
                parameters.add(new ApiKey(securitySchemesParameter.getName(), securitySchemesParameter.getKeyName(),
                        securitySchemesParameter.getIn()));
            }
            if ("basicAuth".equals(securitySchemesParameter.getType())) {
                parameters.add(new BasicAuth(securitySchemesParameter.getName()));
            }
            //             if("oauth2".equals(securitySchemesParameter.getType())) {
            //                parameters.add(new OAuth(securitySchemesParameter.getName()));
            //             }

        }
        return parameters;

    }

    /**
     * ?name?
     *
     * @param globalOperationParameters
     * @param docketOperationParameters
     * @return
     */
    private List<Parameter> assemblyGlobalOperationParameters(
            List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters,
            List<SwaggerProperties.GlobalOperationParameter> docketOperationParameters) {

        if (Objects.isNull(docketOperationParameters) || docketOperationParameters.isEmpty()) {
            return buildGlobalOperationParametersFromSwaggerProperties(globalOperationParameters);
        }

        Set<String> docketNames = docketOperationParameters.stream()
                .map(SwaggerProperties.GlobalOperationParameter::getName).collect(Collectors.toSet());

        List<SwaggerProperties.GlobalOperationParameter> resultOperationParameters = Lists.newArrayList();

        if (Objects.nonNull(globalOperationParameters)) {
            for (SwaggerProperties.GlobalOperationParameter parameter : globalOperationParameters) {
                if (!docketNames.contains(parameter.getName())) {
                    resultOperationParameters.add(parameter);
                }
            }
        }

        resultOperationParameters.addAll(docketOperationParameters);
        return buildGlobalOperationParametersFromSwaggerProperties(resultOperationParameters);
    }

    /**
     * ??
     *
     * @param swaggerProperties ? POST,GET,PUT,PATCH,DELETE,HEAD,OPTIONS,TRACE
     * @param docketForBuilder
     */
    private void buildGlobalResponseMessage(SwaggerProperties swaggerProperties, Docket docketForBuilder) {

        SwaggerProperties.GlobalResponseMessage globalResponseMessages = swaggerProperties
                .getGlobalResponseMessage();

        // POST,GET,PUT,PATCH,DELETE,HEAD,OPTIONS,TRACE ??
        List<ResponseMessage> postResponseMessages = getResponseMessageList(globalResponseMessages.getPost());
        List<ResponseMessage> getResponseMessages = getResponseMessageList(globalResponseMessages.getGet());
        List<ResponseMessage> putResponseMessages = getResponseMessageList(globalResponseMessages.getPut());
        List<ResponseMessage> patchResponseMessages = getResponseMessageList(globalResponseMessages.getPatch());
        List<ResponseMessage> deleteResponseMessages = getResponseMessageList(globalResponseMessages.getDelete());
        List<ResponseMessage> headResponseMessages = getResponseMessageList(globalResponseMessages.getHead());
        List<ResponseMessage> optionsResponseMessages = getResponseMessageList(globalResponseMessages.getOptions());
        List<ResponseMessage> trackResponseMessages = getResponseMessageList(globalResponseMessages.getTrace());

        docketForBuilder.useDefaultResponseMessages(swaggerProperties.getApplyDefaultResponseMessages())
                .globalResponseMessage(RequestMethod.POST, postResponseMessages)
                .globalResponseMessage(RequestMethod.GET, getResponseMessages)
                .globalResponseMessage(RequestMethod.PUT, putResponseMessages)
                .globalResponseMessage(RequestMethod.PATCH, patchResponseMessages)
                .globalResponseMessage(RequestMethod.DELETE, deleteResponseMessages)
                .globalResponseMessage(RequestMethod.HEAD, headResponseMessages)
                .globalResponseMessage(RequestMethod.OPTIONS, optionsResponseMessages)
                .globalResponseMessage(RequestMethod.TRACE, trackResponseMessages);
    }

    /**
     * ??
     *
     * @param globalResponseMessageBodyList
     * @return
     */
    private List<ResponseMessage> getResponseMessageList(
            List<SwaggerProperties.GlobalResponseMessageBody> globalResponseMessageBodyList) {
        List<ResponseMessage> responseMessages = new ArrayList<>();
        for (SwaggerProperties.GlobalResponseMessageBody globalResponseMessageBody : globalResponseMessageBodyList) {
            ResponseMessageBuilder responseMessageBuilder = new ResponseMessageBuilder();
            responseMessageBuilder.code(globalResponseMessageBody.getCode())
                    .message(globalResponseMessageBody.getMessage());

            if (!StringUtils.isEmpty(globalResponseMessageBody.getModelRef())) {
                responseMessageBuilder.responseModel(new ModelRef(globalResponseMessageBody.getModelRef()));
            }
            responseMessages.add(responseMessageBuilder.build());
        }

        return responseMessages;
    }
}