├── .github ├── FUNDING.yml └── workflows │ └── master.yml ├── src ├── test │ ├── resources │ │ └── acceptance-project │ │ │ ├── settings.gradle │ │ │ ├── src │ │ │ └── main │ │ │ │ ├── resources │ │ │ │ ├── application.properties │ │ │ │ ├── application-slower.properties │ │ │ │ ├── application-multiple-endpoints.properties │ │ │ │ ├── application-multiple-grouped-apis.properties │ │ │ │ ├── application-different-url.properties │ │ │ │ ├── keystore.p12 │ │ │ │ └── application-ssl.properties │ │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── demo │ │ │ │ ├── endpoints │ │ │ │ ├── HelloWorldController.java │ │ │ │ ├── ConditionalController.java │ │ │ │ ├── ProfileController.java │ │ │ │ └── GroupedController.java │ │ │ │ ├── config │ │ │ │ └── GroupedConfiguration.java │ │ │ │ └── DemoApplication.java │ │ │ ├── truststore.p12 │ │ │ └── .gitignore │ └── kotlin │ │ └── org │ │ └── springdoc │ │ └── openapi │ │ └── gradle │ │ └── plugin │ │ └── OpenApiGradlePluginTest.kt └── main │ └── kotlin │ └── org │ └── springdoc │ └── openapi │ └── gradle │ └── plugin │ ├── Constants.kt │ ├── OpenApiExtension.kt │ ├── OpenApiGradlePlugin.kt │ └── OpenApiGeneratorTask.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── settings.gradle.kts ├── CHANGELOG.md ├── main.yml ├── .run └── TEST.run.xml ├── CODE_OF_CONDUCT.adoc ├── .gitignore ├── gradlew.bat ├── gradlew ├── CONTRIBUTING.adoc ├── README.md ├── LICENSE └── config └── detekt └── detekt.yml /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | open_collective: springdoc-openapi 2 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'demo' -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/application-slower.properties: -------------------------------------------------------------------------------- 1 | slower=true -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/application-multiple-endpoints.properties: -------------------------------------------------------------------------------- 1 | test.props=So very special -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/application-multiple-grouped-apis.properties: -------------------------------------------------------------------------------- 1 | test.props=So very special -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/application-different-url.properties: -------------------------------------------------------------------------------- 1 | springdoc.api-docs.path=/secret-api-docs -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | org.gradle.caching=true 3 | org.gradle.parallel=true 4 | org.gradle.vfs.watch=true 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springdoc/springdoc-openapi-gradle-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/truststore.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springdoc/springdoc-openapi-gradle-plugin/HEAD/src/test/resources/acceptance-project/truststore.p12 -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/keystore.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springdoc/springdoc-openapi-gradle-plugin/HEAD/src/test/resources/acceptance-project/src/main/resources/keystore.p12 -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "springdoc-openapi-gradle-plugin" 2 | 3 | pluginManagement { 4 | repositories { 5 | mavenCentral() 6 | gradlePluginPortal() 7 | } 8 | } 9 | 10 | plugins { 11 | id("org.gradle.toolchains.foojay-resolver-convention") version("0.8.0") 12 | } 13 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [UnReleased] - 9 | 10 | ## Added 11 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/resources/application-ssl.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | server.ssl.key-alias=ssl 3 | server.ssl.key-password=+bAyoiVYOy6Tg/v2IG4blme2Hu+ORTksvFh/w9s= 4 | server.ssl.key-store=classpath:keystore.p12 5 | server.ssl.key-store-password=+bAyoiVYOy6Tg/v2IG4blme2Hu+ORTksvFh/w9s= 6 | server.ssl.key-store-type=PKCS12 7 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/java/com/example/demo/endpoints/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.endpoints; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.ResponseBody; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController("/hello") 9 | @RequestMapping("/hello") 10 | public class HelloWorldController { 11 | 12 | @GetMapping("/world") 13 | @ResponseBody 14 | public String helloWorld() { 15 | return "Hello World!"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/java/com/example/demo/endpoints/ConditionalController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.endpoints; 2 | 3 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @ConditionalOnProperty(value = { "some.second.property" }, havingValue = "someValue") 8 | @RestController("/conditional") 9 | public class ConditionalController { 10 | 11 | @GetMapping("/conditional") 12 | public String conditional() { 13 | return "conditional"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/java/com/example/demo/endpoints/ProfileController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.endpoints; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Profile; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @Profile("multiple-endpoints") 9 | @RestController("/special") 10 | public class ProfileController { 11 | 12 | @Value("${test.props}") 13 | String profileRelatedValue; 14 | 15 | @GetMapping("/") 16 | public String special() { 17 | return profileRelatedValue; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/java/com/example/demo/endpoints/GroupedController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.endpoints; 2 | 3 | import org.springframework.context.annotation.Profile; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @Profile("multiple-grouped-apis") 8 | @RestController("/grouped") 9 | public class GroupedController { 10 | 11 | @GetMapping("/groupA") 12 | public String groupA() { 13 | return "groupA"; 14 | } 15 | 16 | @GetMapping("/groupB/first") 17 | public String groupB_first() { 18 | return "groupB_first"; 19 | } 20 | 21 | @GetMapping("/groupB/second") 22 | public String groupB_second() { 23 | return "groupB_second"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/java/com/example/demo/config/GroupedConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springdoc.core.GroupedOpenApi; 4 | 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.annotation.Profile; 8 | 9 | @Profile("multiple-grouped-apis") 10 | @Configuration 11 | public class GroupedConfiguration { 12 | 13 | @Bean 14 | public GroupedOpenApi groupA() { 15 | return GroupedOpenApi.builder() 16 | .group("groupA") 17 | .pathsToMatch("/groupA/**") 18 | .build(); 19 | } 20 | 21 | @Bean 22 | public GroupedOpenApi groupB() { 23 | return GroupedOpenApi.builder() 24 | .group("groupB") 25 | .pathsToMatch("/groupB/**") 26 | .build(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /main.yml: -------------------------------------------------------------------------------- 1 | name: Test CI 2 | on: [ push, fork ] 3 | 4 | jobs: 5 | TEST_ALL: 6 | runs-on: ubuntu-latest 7 | strategy: 8 | matrix: 9 | java: [ '11', '17' ] 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v3 13 | 14 | - uses: actions/cache@v3 15 | with: 16 | path: | 17 | ~/.gradle/caches 18 | ~/.gradle/wrapper 19 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 20 | restore-keys: | 21 | ${{ runner.os }}-gradle- 22 | 23 | - name: 🪜 Setup java ${{ matrix.java }} 24 | uses: actions/setup-java@v3 25 | with: 26 | java-version: ${{ matrix.java }} 27 | distribution: temurin 28 | 29 | - name: 🦞 chmod /gradlew 30 | run: chmod +x ./gradlew 31 | 32 | - name: 🔦 Test 33 | run: ./gradlew test --info 34 | -------------------------------------------------------------------------------- /.github/workflows/master.yml: -------------------------------------------------------------------------------- 1 | name: Test CI 2 | on: [ push, fork ] 3 | 4 | jobs: 5 | TEST_ALL: 6 | runs-on: ubuntu-latest 7 | strategy: 8 | matrix: 9 | java: [ '11', '17' ] 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v3 13 | 14 | - uses: actions/cache@v3 15 | with: 16 | path: | 17 | ~/.gradle/caches 18 | ~/.gradle/wrapper 19 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 20 | restore-keys: | 21 | ${{ runner.os }}-gradle- 22 | 23 | - name: 🪜 Setup java ${{ matrix.java }} 24 | uses: actions/setup-java@v3 25 | with: 26 | java-version: ${{ matrix.java }} 27 | distribution: temurin 28 | 29 | - name: 🦞 chmod /gradlew 30 | run: chmod +x ./gradlew 31 | 32 | - name: 🔦 Test 33 | run: ./gradlew test --info 34 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springdoc/openapi/gradle/plugin/Constants.kt: -------------------------------------------------------------------------------- 1 | package org.springdoc.openapi.gradle.plugin 2 | 3 | const val EXTENSION_NAME = "openApi" 4 | const val GROUP_NAME = "OpenApi" 5 | const val OPEN_API_TASK_NAME = "generateOpenApiDocs" 6 | const val OPEN_API_TASK_DESCRIPTION = "Generates the spring doc openapi file" 7 | const val SPRING_BOOT_RUN_TASK_NAME = "bootRun" 8 | const val SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME = "bootRunMainClassName" 9 | const val SPRING_BOOT_3_RUN_MAIN_CLASS_NAME_TASK_NAME = "bootRun" 10 | const val FORKED_SPRING_BOOT_RUN_TASK_NAME = "forkedSpringBootRun" 11 | 12 | const val DEFAULT_API_DOCS_URL = "http://localhost:8080/v3/api-docs" 13 | const val DEFAULT_OPEN_API_FILE_NAME = "openapi.json" 14 | const val DEFAULT_WAIT_TIME_IN_SECONDS = 30 15 | 16 | const val SPRING_BOOT_PLUGIN = "org.springframework.boot" 17 | const val EXEC_FORK_PLUGIN = "com.github.psxpaul.execfork" 18 | 19 | const val CLASS_PATH_PROPERTY_NAME = "java.class.path" 20 | -------------------------------------------------------------------------------- /src/test/resources/acceptance-project/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import java.time.Duration; 4 | 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.ApplicationArguments; 7 | import org.springframework.boot.ApplicationRunner; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | 11 | @SpringBootApplication 12 | public class DemoApplication implements ApplicationRunner { 13 | 14 | @Value("${slower:false}") 15 | boolean slower; 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(DemoApplication.class, args); 19 | } 20 | 21 | @Override 22 | public void run(ApplicationArguments arg0) throws Exception { 23 | System.out.println("Hello World from Application Runner"); 24 | if (slower) { 25 | Duration waitTime = Duration.ofSeconds(40); 26 | System.out.println("Waiting for " + waitTime + " before starting"); 27 | Thread.sleep(waitTime.toMillis()); 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /.run/TEST.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 12 | 13 | 22 | 34 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.adoc: -------------------------------------------------------------------------------- 1 | = Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. 6 | 7 | Examples of unacceptable behavior by participants include: 8 | 9 | * The use of sexualized language or imagery 10 | * Personal attacks 11 | * Trolling or insulting/derogatory comments 12 | * Public or private harassment 13 | * Publishing other's private information, such as physical or electronic addresses, without explicit permission 14 | * Other unethical or unprofessional conduct 15 | 16 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 17 | 18 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. 19 | Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. 20 | 21 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 22 | 23 | This Code of Conduct is adapted from the 24 | https://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at 25 | https://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/] and https://github.com/spring-projects/spring-boot/blob/master/CODE_OF_CONDUCT.adoc[spring-boot Contributor Code of Conduct] 26 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiExtension.kt: -------------------------------------------------------------------------------- 1 | package org.springdoc.openapi.gradle.plugin 2 | 3 | import org.gradle.api.Action 4 | import org.gradle.api.file.ConfigurableFileCollection 5 | import org.gradle.api.file.DirectoryProperty 6 | import org.gradle.api.file.ProjectLayout 7 | import org.gradle.api.model.ObjectFactory 8 | import org.gradle.api.provider.ListProperty 9 | import org.gradle.api.provider.MapProperty 10 | import org.gradle.api.provider.Property 11 | import javax.inject.Inject 12 | 13 | open class OpenApiExtension @Inject constructor( 14 | objects: ObjectFactory, 15 | layout: ProjectLayout 16 | ) { 17 | val apiDocsUrl: Property = objects.property(String::class.java) 18 | val outputFileName: Property = objects.property(String::class.java) 19 | val outputDir: DirectoryProperty = objects.directoryProperty() 20 | val waitTimeInSeconds: Property = objects.property(Int::class.java) 21 | val trustStore: Property = objects.property(String::class.java) 22 | val trustStorePassword: Property = objects.property(CharArray::class.java) 23 | 24 | val groupedApiMappings: MapProperty = 25 | objects.mapProperty(String::class.java, String::class.java) 26 | val requestHeaders: MapProperty = 27 | objects.mapProperty(String::class.java, String::class.java) 28 | val customBootRun: CustomBootRunAction = 29 | objects.newInstance(CustomBootRunAction::class.java) 30 | 31 | init { 32 | apiDocsUrl.convention(DEFAULT_API_DOCS_URL) 33 | outputFileName.convention(DEFAULT_OPEN_API_FILE_NAME) 34 | outputDir.convention(layout.buildDirectory) 35 | waitTimeInSeconds.convention(DEFAULT_WAIT_TIME_IN_SECONDS) 36 | groupedApiMappings.convention(emptyMap()) 37 | } 38 | 39 | fun customBootRun(action: Action) { 40 | action.execute(customBootRun) 41 | } 42 | } 43 | 44 | open class CustomBootRunAction @Inject constructor( 45 | objects: ObjectFactory, 46 | ) { 47 | val systemProperties: MapProperty = 48 | objects.mapProperty(String::class.java, Any::class.java) 49 | val workingDir: DirectoryProperty = objects.directoryProperty() 50 | val mainClass: Property = objects.property(String::class.java) 51 | val args: ListProperty = objects.listProperty(String::class.java) 52 | val classpath: ConfigurableFileCollection = objects.fileCollection() 53 | val jvmArgs: ListProperty = objects.listProperty(String::class.java) 54 | val environment: MapProperty = 55 | objects.mapProperty(String::class.java, Any::class.java) 56 | } 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ###################### 2 | # Project Specific 3 | ###################### 4 | /target/www/** 5 | /src/test/javascript/coverage/ 6 | 7 | ###################### 8 | # Node 9 | ###################### 10 | /node/ 11 | node_tmp/ 12 | node_modules/ 13 | npm-debug.log.* 14 | /.awcache/* 15 | /.cache-loader/* 16 | 17 | ###################### 18 | # SASS 19 | ###################### 20 | .sass-cache/ 21 | 22 | ###################### 23 | # Eclipse 24 | ###################### 25 | *.pydevproject 26 | .project 27 | .metadata 28 | tmp/ 29 | tmp/**/* 30 | *.tmp 31 | *.bak 32 | *.swp 33 | *~.nib 34 | local.properties 35 | .classpath 36 | .settings/ 37 | .loadpath 38 | .factorypath 39 | /src/main/resources/rebel.xml 40 | 41 | # External tool builders 42 | .externalToolBuilders/** 43 | 44 | # Locally stored "Eclipse launch configurations" 45 | *.launch 46 | 47 | # CDT-specific 48 | .cproject 49 | 50 | # PDT-specific 51 | .buildpath 52 | 53 | ###################### 54 | # Intellij 55 | ###################### 56 | .idea/ 57 | *.iml 58 | *.iws 59 | *.ipr 60 | *.ids 61 | *.orig 62 | classes/ 63 | out/ 64 | 65 | ###################### 66 | # Visual Studio Code 67 | ###################### 68 | .vscode/ 69 | 70 | ###################### 71 | # Maven 72 | ###################### 73 | /log/ 74 | /target/ 75 | 76 | ###################### 77 | # Gradle 78 | ###################### 79 | HELP.md 80 | .gradle 81 | build/ 82 | !gradle/wrapper/gradle-wrapper.jar 83 | !**/src/main/** 84 | !**/src/test/** 85 | 86 | ###################### 87 | # Package Files 88 | ###################### 89 | *.war 90 | *.ear 91 | *.db 92 | 93 | ###################### 94 | # Windows 95 | ###################### 96 | # Windows image file caches 97 | Thumbs.db 98 | 99 | # Folder config file 100 | Desktop.ini 101 | 102 | ###################### 103 | # Mac OSX 104 | ###################### 105 | .DS_Store 106 | .svn 107 | 108 | # Thumbnails 109 | ._* 110 | 111 | # Files that might appear on external disk 112 | .Spotlight-V100 113 | .Trashes 114 | 115 | ###################### 116 | # Directories 117 | ###################### 118 | /bin/ 119 | /deploy/ 120 | 121 | ###################### 122 | # Logs 123 | ###################### 124 | *.log* 125 | 126 | ###################### 127 | # Others 128 | ###################### 129 | *.class 130 | *.*~ 131 | *~ 132 | .merge_file* 133 | .java-version 134 | 135 | ###################### 136 | # Gradle Wrapper 137 | ###################### 138 | !gradle/wrapper/gradle-wrapper.jar 139 | 140 | ###################### 141 | # Maven Wrapper 142 | ###################### 143 | !.mvn/wrapper/maven-wrapper.jar 144 | 145 | ###################### 146 | # ESLint 147 | ###################### 148 | .eslintcache -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePlugin.kt: -------------------------------------------------------------------------------- 1 | package org.springdoc.openapi.gradle.plugin 2 | 3 | import com.github.psxpaul.task.JavaExecFork 4 | import org.gradle.api.Plugin 5 | import org.gradle.api.Project 6 | import org.gradle.api.Task 7 | import org.gradle.api.UnknownDomainObjectException 8 | import org.gradle.api.tasks.TaskProvider 9 | import org.gradle.internal.jvm.Jvm 10 | import org.springframework.boot.gradle.tasks.run.BootRun 11 | 12 | open class OpenApiGradlePlugin : Plugin { 13 | 14 | override fun apply(project: Project) { 15 | with(project) { 16 | // Run time dependency on the following plugins 17 | plugins.apply(SPRING_BOOT_PLUGIN) 18 | plugins.apply(EXEC_FORK_PLUGIN) 19 | 20 | extensions.create(EXTENSION_NAME, OpenApiExtension::class.java) 21 | tasks.register(FORKED_SPRING_BOOT_RUN_TASK_NAME, JavaExecFork::class.java) 22 | tasks.register(OPEN_API_TASK_NAME, OpenApiGeneratorTask::class.java) 23 | 24 | generate(this) 25 | } 26 | } 27 | 28 | private fun generate(project: Project) = project.run { 29 | springBoot3CompatibilityCheck() 30 | 31 | // The task, used to run the Spring Boot application (`bootRun`) 32 | val bootRunTask = tasks.named(SPRING_BOOT_RUN_TASK_NAME) 33 | // The task, used to resolve the application's main class (`bootRunMainClassName`) 34 | val bootRunMainClassNameTask = 35 | try { 36 | val task = tasks.named(SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME) 37 | logger.debug( 38 | "Detected Spring Boot task {}", 39 | SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME 40 | ) 41 | task 42 | } catch (e: UnknownDomainObjectException) { 43 | val task = tasks.named(SPRING_BOOT_3_RUN_MAIN_CLASS_NAME_TASK_NAME) 44 | logger.debug( 45 | "Detected Spring Boot task {}", 46 | SPRING_BOOT_3_RUN_MAIN_CLASS_NAME_TASK_NAME 47 | ) 48 | task 49 | } 50 | 51 | val extension = extensions.findByName(EXTENSION_NAME) as OpenApiExtension 52 | val customBootRun = extension.customBootRun 53 | // Create a forked version spring boot run task 54 | val forkedSpringBoot = tasks.named( 55 | FORKED_SPRING_BOOT_RUN_TASK_NAME, 56 | JavaExecFork::class.java 57 | ) { fork -> 58 | fork.dependsOn(tasks.named(bootRunMainClassNameTask.name)) 59 | fork.onlyIf { needToFork(bootRunTask, customBootRun, fork) } 60 | } 61 | 62 | val openApiTask = 63 | tasks.named(OPEN_API_TASK_NAME, OpenApiGeneratorTask::class.java) { 64 | // This is my task. Before I can run it, I have to run the dependent tasks 65 | it.dependsOn(forkedSpringBoot) 66 | 67 | // Ensure the task inputs match those of the original application 68 | it.inputs.files(bootRunTask.get().inputs.files) 69 | } 70 | 71 | // The forked task need to be terminated as soon as my task is finished 72 | forkedSpringBoot.get().stopAfter = openApiTask as TaskProvider 73 | } 74 | 75 | private fun Project.springBoot3CompatibilityCheck() { 76 | val tasksNames = tasks.names 77 | val boot2TaskName = "bootRunMainClassName" 78 | val boot3TaskName = "resolveMainClassName" 79 | if (!tasksNames.contains(boot2TaskName) && tasksNames.contains(boot3TaskName)) { 80 | tasks.register(boot2TaskName) { it.dependsOn(tasks.named(boot3TaskName)) } 81 | } 82 | } 83 | 84 | private fun needToFork( 85 | bootRunTask: TaskProvider, 86 | customBootRun: CustomBootRunAction, 87 | fork: JavaExecFork 88 | ): Boolean { 89 | val bootRun = bootRunTask.get() as BootRun 90 | 91 | val baseSystemProperties = 92 | customBootRun.systemProperties.orNull?.takeIf { it.isNotEmpty() } 93 | ?: bootRun.systemProperties 94 | with(fork) { 95 | // copy all system properties, excluding those starting with `java.class.path` 96 | systemProperties = baseSystemProperties.filter { 97 | !it.key.startsWith(CLASS_PATH_PROPERTY_NAME) 98 | } 99 | 100 | // use original bootRun parameter if the list-type customBootRun properties are empty 101 | workingDir = customBootRun.workingDir.asFile.orNull 102 | ?: fork.temporaryDir 103 | args = customBootRun.args.orNull?.takeIf { it.isNotEmpty() }?.toMutableList() 104 | ?: bootRun.args?.toMutableList() ?: mutableListOf() 105 | classpath = customBootRun.classpath.takeIf { !it.isEmpty } 106 | ?: bootRun.classpath 107 | main = customBootRun.mainClass.orNull 108 | ?: bootRun.mainClass.get() 109 | jvmArgs = customBootRun.jvmArgs.orNull?.takeIf { it.isNotEmpty() } 110 | ?: bootRun.jvmArgs 111 | environment = customBootRun.environment.orNull?.takeIf { it.isNotEmpty() } 112 | ?: bootRun.environment 113 | if (Jvm.current().toString().startsWith("1.8")) { 114 | killDescendants = false 115 | } 116 | } 117 | return true 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGeneratorTask.kt: -------------------------------------------------------------------------------- 1 | package org.springdoc.openapi.gradle.plugin 2 | 3 | import com.google.gson.GsonBuilder 4 | import com.google.gson.JsonObject 5 | import com.google.gson.JsonSyntaxException 6 | import org.awaitility.Durations 7 | import org.awaitility.core.ConditionTimeoutException 8 | import org.awaitility.kotlin.atMost 9 | import org.awaitility.kotlin.await 10 | import org.awaitility.kotlin.ignoreException 11 | import org.awaitility.kotlin.until 12 | import org.awaitility.kotlin.withPollInterval 13 | import org.gradle.api.DefaultTask 14 | import org.gradle.api.GradleException 15 | import org.gradle.api.file.DirectoryProperty 16 | import org.gradle.api.provider.MapProperty 17 | import org.gradle.api.provider.Property 18 | import org.gradle.api.tasks.Input 19 | import org.gradle.api.tasks.Internal 20 | import org.gradle.api.tasks.Optional 21 | import org.gradle.api.tasks.OutputDirectory 22 | import org.gradle.api.tasks.TaskAction 23 | import java.io.FileInputStream 24 | import java.net.ConnectException 25 | import java.net.HttpURLConnection 26 | import java.net.URL 27 | import java.security.KeyStore 28 | import java.security.SecureRandom 29 | import java.time.Duration 30 | import java.time.temporal.ChronoUnit.SECONDS 31 | import java.util.Locale 32 | import javax.net.ssl.HttpsURLConnection 33 | import javax.net.ssl.KeyManager 34 | import javax.net.ssl.SSLContext 35 | import javax.net.ssl.TrustManagerFactory 36 | 37 | private const val MAX_HTTP_STATUS_CODE = 299 38 | 39 | open class OpenApiGeneratorTask : DefaultTask() { 40 | @get:Input 41 | val apiDocsUrl: Property = project.objects.property(String::class.java) 42 | 43 | @get:Input 44 | val outputFileName: Property = project.objects.property(String::class.java) 45 | 46 | @get:Input 47 | val groupedApiMappings: MapProperty = 48 | project.objects.mapProperty(String::class.java, String::class.java) 49 | 50 | @get:Input 51 | val requestHeaders: MapProperty = 52 | project.objects.mapProperty(String::class.java, String::class.java) 53 | 54 | @get:OutputDirectory 55 | val outputDir: DirectoryProperty = project.objects.directoryProperty() 56 | 57 | @get:Internal 58 | val waitTimeInSeconds: Property = project.objects.property(Int::class.java) 59 | 60 | @get:Optional 61 | @get:Input 62 | val trustStore: Property = project.objects.property(String::class.java) 63 | 64 | @get:Optional 65 | @get:Input 66 | val trustStorePassword: Property = project.objects.property(CharArray::class.java) 67 | 68 | init { 69 | description = OPEN_API_TASK_DESCRIPTION 70 | group = GROUP_NAME 71 | // load my extensions 72 | val extension: OpenApiExtension = 73 | project.extensions.getByName(EXTENSION_NAME) as OpenApiExtension 74 | 75 | apiDocsUrl.convention(extension.apiDocsUrl) 76 | outputFileName.convention(extension.outputFileName) 77 | groupedApiMappings.convention(extension.groupedApiMappings) 78 | outputDir.convention(extension.outputDir) 79 | waitTimeInSeconds.convention(extension.waitTimeInSeconds) 80 | trustStore.convention(extension.trustStore) 81 | trustStorePassword.convention(extension.trustStorePassword) 82 | requestHeaders.convention(extension.requestHeaders) 83 | } 84 | 85 | @TaskAction 86 | fun execute() { 87 | if (groupedApiMappings.isPresent && groupedApiMappings.get().isNotEmpty()) { 88 | groupedApiMappings.get().forEach(this::generateApiDocs) 89 | } else { 90 | generateApiDocs(apiDocsUrl.get(), outputFileName.get()) 91 | } 92 | } 93 | 94 | private fun generateApiDocs(url: String, fileName: String) { 95 | try { 96 | val isYaml = url.lowercase(Locale.getDefault()).matches(Regex(".+[./]yaml(/.+)*")) 97 | val sslContext = getCustomSslContext() 98 | await ignoreException ConnectException::class withPollInterval Durations.ONE_SECOND atMost Duration.of( 99 | waitTimeInSeconds.get().toLong(), 100 | SECONDS 101 | ) until { 102 | HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.socketFactory) 103 | val connection: HttpURLConnection = 104 | URL(url).openConnection() as HttpURLConnection 105 | connection.requestMethod = "GET" 106 | requestHeaders.get().forEach { header -> 107 | connection.setRequestProperty(header.key, header.value) 108 | } 109 | 110 | connection.connect() 111 | val statusCode = connection.responseCode 112 | logger.trace("apiDocsUrl = {} status code = {}", url, statusCode) 113 | statusCode < MAX_HTTP_STATUS_CODE 114 | } 115 | logger.info("Generating OpenApi Docs..") 116 | HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.socketFactory) 117 | val connection: HttpURLConnection = 118 | URL(url).openConnection() as HttpURLConnection 119 | connection.requestMethod = "GET" 120 | requestHeaders.get().forEach { header -> 121 | connection.setRequestProperty(header.key, header.value) 122 | } 123 | connection.connect() 124 | 125 | val response = String(connection.inputStream.readBytes(), Charsets.UTF_8) 126 | 127 | val apiDocs = if (isYaml) response else prettifyJson(response) 128 | 129 | val outputFile = outputDir.file(fileName).get().asFile 130 | outputFile.writeText(apiDocs) 131 | } catch (e: ConditionTimeoutException) { 132 | this.logger.error( 133 | "Unable to connect to $url waited for ${waitTimeInSeconds.get()} seconds", 134 | e 135 | ) 136 | throw GradleException("Unable to connect to $url waited for ${waitTimeInSeconds.get()} seconds") 137 | } 138 | } 139 | 140 | private fun getCustomSslContext(): SSLContext { 141 | if (trustStore.isPresent) { 142 | logger.debug("Reading truststore: ${trustStore.get()}") 143 | FileInputStream(trustStore.get()).use { truststoreFile -> 144 | val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) 145 | val truststore = KeyStore.getInstance(KeyStore.getDefaultType()) 146 | truststore.load(truststoreFile, trustStorePassword.get()) 147 | trustManagerFactory.init(truststore) 148 | val sslContext: SSLContext = SSLContext.getInstance("TLSv1.2") 149 | val keyManagers = arrayOf() 150 | sslContext.init(keyManagers, trustManagerFactory.trustManagers, SecureRandom()) 151 | 152 | return sslContext 153 | } 154 | } 155 | return SSLContext.getDefault() 156 | } 157 | 158 | private fun prettifyJson(response: String): String { 159 | val gson = GsonBuilder().setPrettyPrinting().create() 160 | try { 161 | val googleJsonObject = gson.fromJson(response, JsonObject::class.java) 162 | return gson.toJson(googleJsonObject) 163 | } catch (e: RuntimeException) { 164 | throw JsonSyntaxException( 165 | "Failed to parse the API docs response string. " + 166 | "Please ensure that the response is in the correct format. response=$response", 167 | e 168 | ) 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /CONTRIBUTING.adoc: -------------------------------------------------------------------------------- 1 | = Contributing to springdoc-openapi 2 | 3 | springdoc-openapi is released under the Apache 2.0 license. 4 | If you would like to contribute something, or simply want to hack on the code this document should help you get started. 5 | 6 | == Code of Conduct 7 | 8 | This project adheres to the Contributor Covenant link:CODE_OF_CONDUCT.adoc[code of 9 | conduct]. 10 | By participating, you are expected to uphold this code. 11 | 12 | == Using GitHub Issues 13 | 14 | We use GitHub issues to track bugs and enhancements. 15 | If you have a general usage question please ask on https://stackoverflow.com[Stack Overflow]. 16 | The springdoc-openapi team and the broader community monitor the https://stackoverflow.com/tags/springdoc[`springdoc`] 17 | tag. 18 | 19 | These are some basic guidelines before opening an issue. 20 | First of all you need to make sure, you don't create duplicate issues, and there no question already answred on https://stackoverflow.com/tags/springdoc. 21 | 22 | If you are starting using springdoc-openapi, we advise you to use the last available release. 23 | 24 | Then refer to the relevant documentation: 25 | 26 | 1. For OpenAPI specification 3: 27 | - https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md 28 | 2. For swagger2-annotations: 29 | - https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations 30 | 3. For swagger-ui configuration: 31 | - https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md 32 | 4. For springdoc-openapi: 33 | - https://springdoc.github.io/springdoc-openapi-demos/ 34 | - https://springdoc.github.io/springdoc-openapi-demos/faq.html 35 | - https://springdoc.github.io/springdoc-openapi-demos/migrating-from-springfox.html 36 | 37 | 38 | If you are reporting a bug, please help to speed up problem diagnosis by providing as much information as possible: 39 | 40 | - You need to describe your context (the title of an issue is not enough) 41 | - What version of spring-boot you are using? 42 | - What modules and versions of springdoc-openapi are you using? 43 | - What are the actual and the expected result using OpenAPI Description (yml or json)? 44 | - Provide with a sample code (HelloController) or Test that reproduces the problem 45 | 46 | == Reporting Security Vulnerabilities 47 | 48 | If you think you have found a security vulnerability in Spring Boot please *DO NOT* 49 | disclose it publicly until we've had a chance to fix it. 50 | Please don't report security vulnerabilities using GitHub issues, instead head over to support@springdoc.org and learn how to disclose them responsibly. 51 | 52 | == Code Conventions and Housekeeping 53 | 54 | None of these is essential for a pull request, but they will all help. 55 | They can also be added after the original pull request but before a merge. 56 | 57 | * We use the https://github.com/spring-io/spring-javaformat/[Spring JavaFormat] project to apply code formatting conventions. 58 | If you use Eclipse and you follow the '`Importing into eclipse`' instructions below you should get project specific formatting automatically. 59 | You can also install the 60 | https://github.com/spring-io/spring-javaformat/#intellij-idea[Spring JavaFormat IntelliJ 61 | Plugin] 62 | * Make sure all new `.java` files to have a simple Javadoc class comment with at least an 63 | `@author` tag identifying you, and preferably at least a paragraph on what the class is for. 64 | * Add the ASF license header comment to all new `.java` files (copy from existing files in the project) 65 | * Add yourself as an `@author` to the `.java` files that you modify substantially (more than cosmetic changes). 66 | * Add some Javadocs. 67 | * A few unit tests would help a lot as well -- someone has to do it. 68 | * If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project). 69 | * When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], if you are fixing an existing issue please add `Fixes #XXXX` at the end of the commit message (where `XXXX` is the issue number). 70 | 71 | == Working with the Code 72 | 73 | If you don't have an IDE preference we would recommend that you use IntellIJ. 74 | 75 | === Importing into IntelliJ IDEA 76 | 77 | If you have performed a checkout of this repository already, use "`File`" -> "`Open`" and then select the root `build.gradle` file to import the code. 78 | 79 | Alternatively, you can let IntellIJ IDEA checkout the code for you. 80 | Use "`File`" -> 81 | "`New`" -> "`Project from Version Control`" and 82 | `https://github.com/spring-projects/spring-boot` for the URL. 83 | Once the checkout has completed, a pop-up will suggest to open the project. 84 | 85 | ==== Install the Spring Formatter plugin 86 | 87 | If you haven't done so, install the formatter plugin so that proper formatting rules are applied automatically when you reformat code in the IDE. 88 | 89 | * Download the latest https://search.maven.org/search?q=g:io.spring.javaformat%20AND%20a:spring-javaformat-intellij-plugin[IntelliJ IDEA plugin]. 90 | * Select "`IntelliJ IDEA`" -> "`Preferences`". 91 | * Select "`Plugins`". 92 | * Select the wheel and "`Install Plugin from Disk...`". 93 | * Select the jar file you've downloaded. 94 | 95 | ==== Import additional code style 96 | 97 | The formatter does not cover all rules (such as order of imports) and an additional file needs to be added. 98 | 99 | * Select "`IntelliJ IDEA`" -> "`Preferences`". 100 | * Select "`Editor`" -> "`Code Style`". 101 | * Select the wheel and "`Import Scheme`" -> "`IntelliJ IDEA code style XML`". 102 | * Select https://github.com/spring-projects/spring-boot/blob/master/idea/codeStyleConfig.xml[`idea/codeStyleConfig.xml`] from this repository. 103 | 104 | ==== Importing into Eclipse 105 | 106 | You can use Spring Boot project specific source formatting settings. 107 | 108 | ===== Install the Spring Formatter plugin 109 | 110 | * Select "`Help`" -> "`Install New Software`". 111 | * Add `https://repo.spring.io/javaformat-eclipse-update-site/` as a site. 112 | * Install "Spring Java Format". 113 | 114 | NOTE: The plugin is optional. 115 | Projects can be imported without the plugins, your code changes just won't be automatically formatted. 116 | 117 | === Building from Source 118 | 119 | springdoc-openapi source can be built from the command line using https://maven.apache.org/[Maven] on JDK 1.8 or above. 120 | 121 | The project can be built from the root directory using the standard maven command: 122 | 123 | [indent=0] 124 | ---- 125 | $ ./mvn install 126 | ---- 127 | 128 | == Cloning the git repository on Windows 129 | 130 | Some files in the git repository may exceed the Windows maximum file path (260 characters), depending on where you clone the repository. 131 | If you get `Filename too long` 132 | errors, set the `core.longPaths=true` git option: 133 | 134 | ``` 135 | git clone -c core.longPaths=true https://github.com/springdoc/springdoc-openapi 136 | ``` 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://ci-cd.springdoc.org:8443/buildStatus/icon?job=springdoc-openapi-gradle-IC)](https://ci-cd.springdoc.org:8443/view/springdoc-openapi/job/springdoc-openapi-gradle-IC/) 2 | 3 | # Introducing springdoc-openapi-gradle-plugin 4 | 5 | Gradle plugin for springdoc-openapi. 6 | 7 | This plugin allows you to generate an OpenAPI 3 specification for a Spring Boot 8 | application from a Gradle build. 9 | Compatibility Notes 10 | ------------------- 11 | 12 | The plugin is built on Gradle version 7.0. 13 | 14 | Dependencies 15 | ------------ 16 | This plugin has a runtime dependency on the following plugins: 17 | 18 | 1. Spring Boot Gradle plugin - `org.springframework.boot` 19 | 2. Gradle process plugin - `com.github.psxpaul.execfork` 20 | 21 | How To Use 22 | ---------- 23 | 24 | Gradle Groovy DSL 25 | 26 | ```groovy 27 | plugins { 28 | id "org.springframework.boot" version "2.7.0" 29 | id "org.springdoc.openapi-gradle-plugin" version "1.9.0" 30 | } 31 | ``` 32 | 33 | Gradle Kotlin DSL 34 | 35 | ```groovy 36 | plugins { 37 | id("org.springframework.boot") version "2.7.0" 38 | id("org.springdoc.openapi-gradle-plugin") version "1.9.0" 39 | } 40 | ``` 41 | 42 | Note: For latest versions of the plugins please check 43 | the [Gradle Plugins portal](https://plugins.gradle.org/). 44 | 45 | How the plugin works? 46 | ------------ 47 | 48 | When you add this plugin and its runtime dependency plugins to your build file, the plugin 49 | creates the following tasks: 50 | 51 | 1. forkedSpringBootRun 52 | 53 | 2. generateOpenApiDocs 54 | 55 | Running the task `generateOpenApiDocs` writes the OpenAPI spec into a `openapi.json` file 56 | in your project's build dir. 57 | 58 | ```bash 59 | gradle generateOpenApiDocs 60 | ``` 61 | 62 | When you run the gradle task **generateOpenApiDocs**, it starts your spring boot 63 | application in the background using **forkedSpringBootRun** task. 64 | Once your application is up and running **generateOpenApiDocs** makes a rest call to your 65 | applications doc url to download and store the open api docs file as json. 66 | 67 | 68 | Customization 69 | ------------- 70 | 71 | The following customizations can be done on task generateOpenApiDocs using extension 72 | openApi as follows 73 | 74 | ```kotlin 75 | openApi { 76 | apiDocsUrl.set("https://localhost:9000/api/docs") 77 | outputDir.set(file("$buildDir/docs")) 78 | outputFileName.set("swagger.json") 79 | waitTimeInSeconds.set(10) 80 | trustStore.set("keystore/truststore.p12") 81 | trustStorePassword.set("changeit".toCharArray()) 82 | groupedApiMappings.set( 83 | ["https://localhost:8080/v3/api-docs/groupA" to "swagger-groupA.json", 84 | "https://localhost:8080/v3/api-docs/groupB" to "swagger-groupB.json"] 85 | ) 86 | customBootRun { 87 | args.set(["--spring.profiles.active=special"]) 88 | } 89 | requestHeaders = [ 90 | "x-forwarded-host": "custom-host", 91 | "x-forwarded-port": "7000" 92 | ] 93 | } 94 | ``` 95 | 96 | | Parameter | Description | Required | Default | 97 | |----------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------------------------| 98 | | `apiDocsUrl` | The URL from where the OpenAPI doc can be downloaded. If the url ends with `.yaml`, output will YAML format. | No | http://localhost:8080/v3/api-docs | 99 | | `outputDir` | The output directory for the generated OpenAPI file | No | $buildDir - Your project's build dir | 100 | | `outputFileName` | Specifies the output file name. | No | openapi.json | 101 | | `waitTimeInSeconds` | Time to wait in seconds for your Spring Boot application to start, before we make calls to `apiDocsUrl` to download the OpenAPI doc | No | 30 seconds | 102 | | `trustStore` | Path to a trust store that contains custom trusted certificates. | No | `` | 103 | | `trustStorePassword` | Password to open Trust Store | No | `` | 104 | | `groupedApiMappings` | A map of URLs (from where the OpenAPI docs can be downloaded) to output file names | No | [] | 105 | | `customBootRun` | Any bootRun property that you would normal need to start your spring boot application. | No | (N/A) | 106 | | `requestHeaders` | customize Generated server url, relies on `server.forward-headers-strategy=framework` | No | (N/A) | 107 | 108 | ### `customBootRun` properties examples 109 | 110 | `customBootRun` allows you to send in the properties that might be necessary to allow for 111 | the forked spring boot application that gets started 112 | to be able to start (profiles, other custom properties, etc.) 113 | `customBootRun` allows you can specify bootRun style parameter, such 114 | as `args`, `jvmArgs`, `systemProperties` and `workingDir`. 115 | If you don't specify `customBootRun` parameter, this plugin uses the parameter specified 116 | to `bootRun` in Spring Boot Gradle Plugin. 117 | 118 | #### Passing static args 119 | 120 | This allows for you to be able to just send the static properties when executing Spring 121 | application in `generateOpenApiDocs`. 122 | 123 | ``` 124 | openApi { 125 | customBootRun { 126 | args = ["--spring.profiles.active=special"] 127 | } 128 | } 129 | ``` 130 | 131 | #### Passing straight from gradle 132 | 133 | This allows for you to be able to just send in whatever you need when you generate docs. 134 | 135 | `./gradlew generateOpenApiDocs -Dspring.profiles.active=special` 136 | 137 | and as long as the config looks as follows that value will be passed into the forked 138 | spring boot application. 139 | 140 | ``` 141 | openApi { 142 | customBootRun { 143 | systemProperties = System.properties 144 | } 145 | } 146 | ``` 147 | 148 | ### Trust Store Configuration 149 | 150 | If you have restricted your application to HTTPS only and prefer not to include your certificate 151 | in Java's cacerts file, you can configure your own set of trusted certificates through plugin 152 | properties, ensuring SSL connections are established. 153 | 154 | #### Generating a Trust Store 155 | 156 | To create your own Trust Store, utilize the Java keytool command: 157 | 158 | ```shell 159 | keytool -storepass changeit -noprompt -import -alias ca -file [CERT_PATH]/ca.crt -keystore [KEYSTORE_PATH]/truststore.p12 -deststoretype PKCS12 160 | ``` 161 | 162 | ### Grouped API Mappings Notes 163 | 164 | The `groupedApiMappings` customization allows you to specify multiple URLs/file names for 165 | use within this plugin. This configures the plugin to ignore the `apiDocsUrl` 166 | and `outputFileName` parameters and only use those found in `groupedApiMappings`. The 167 | plugin will then attempt to download each OpenAPI doc in turn as it would for a single 168 | OpenAPI doc. 169 | 170 | # Building the plugin 171 | 172 | 1. Clone the repo `git@github.com:springdoc/springdoc-openapi-gradle-plugin.git` 173 | 2. Build and publish the plugin into your local maven repository by running the following 174 | ``` 175 | ./gradlew clean pTML 176 | ``` 177 | 178 | # Testing the plugin 179 | 180 | 1. Create a new spring boot application or use an existing spring boot app and follow 181 | the `How To Use` section above to configure this plugin. 182 | 2. Update the version for the plugin to match the current version found 183 | in `build.gradle.kts` 184 | 185 | ``` 186 | id("org.springdoc.openapi-gradle-plugin") version "1.8.0" 187 | ``` 188 | 189 | 3. Add the following to the spring boot apps `settings.gradle` 190 | 191 | ``` 192 | pluginManagement { 193 | repositories { 194 | mavenLocal() 195 | gradlePluginPortal() 196 | } 197 | } 198 | ``` 199 | 200 | # **Thank you for the support** 201 | 202 | * Thanks a lot [JetBrains](https://www.jetbrains.com/?from=springdoc-openapi) for 203 | supporting springdoc-openapi project. 204 | 205 | ![JetBrains logo](https://springdoc.org/img/jetbrains.svg) 206 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePluginTest.kt: -------------------------------------------------------------------------------- 1 | package org.springdoc.openapi.gradle.plugin 2 | 3 | import com.beust.klaxon.JsonArray 4 | import com.beust.klaxon.JsonObject 5 | import com.beust.klaxon.Parser 6 | import com.fasterxml.jackson.databind.ObjectMapper 7 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory 8 | import com.fasterxml.jackson.module.kotlin.KotlinModule 9 | import org.gradle.internal.impldep.org.apache.commons.lang.RandomStringUtils 10 | import org.gradle.testkit.runner.BuildResult 11 | import org.gradle.testkit.runner.GradleRunner 12 | import org.gradle.testkit.runner.TaskOutcome 13 | import org.junit.jupiter.api.Assertions.assertEquals 14 | import org.junit.jupiter.api.Assertions.assertFalse 15 | import org.junit.jupiter.api.Assertions.assertNotNull 16 | import org.junit.jupiter.api.Assertions.assertTrue 17 | import org.junit.jupiter.api.BeforeEach 18 | import org.junit.jupiter.api.Test 19 | import org.slf4j.Logger 20 | import org.slf4j.LoggerFactory 21 | import java.io.File 22 | import java.io.FileReader 23 | import java.nio.file.Files 24 | 25 | class OpenApiGradlePluginTest { 26 | 27 | private val projectTestDir = Files.createTempDirectory("acceptance-project").toFile() 28 | private val buildFile = File(projectTestDir, "build.gradle") 29 | private val projectBuildDir = File(projectTestDir, "build") 30 | 31 | private val pathsField = "paths" 32 | private val openapiField = "openapi" 33 | 34 | private val baseBuildGradle = """plugins { 35 | id 'java' 36 | id 'org.springframework.boot' version '2.7.6' 37 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 38 | id 'org.springdoc.openapi-gradle-plugin' 39 | } 40 | 41 | group = 'com.example' 42 | version = '0.0.1-SNAPSHOT' 43 | sourceCompatibility = '8' 44 | 45 | repositories { 46 | mavenCentral() 47 | } 48 | 49 | dependencies { 50 | implementation 'org.springframework.boot:spring-boot-starter-web' 51 | implementation 'org.springdoc:springdoc-openapi-webmvc-core:1.6.13' 52 | } 53 | """.trimIndent() 54 | 55 | companion object { 56 | val logger: Logger = LoggerFactory.getLogger(OpenApiGradlePluginTest::class.java) 57 | } 58 | 59 | @BeforeEach 60 | fun createTemporaryAcceptanceProjectFromTemplate() { 61 | File(javaClass.classLoader.getResource("acceptance-project")!!.path).copyRecursively( 62 | projectTestDir 63 | ) 64 | } 65 | 66 | @Test 67 | fun `default build no options`() { 68 | buildFile.writeText(baseBuildGradle) 69 | 70 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 71 | assertOpenApiJsonFile(1) 72 | } 73 | 74 | @Test 75 | fun `different output dir`() { 76 | val specialOutputDir = File(projectTestDir, "specialDir") 77 | specialOutputDir.mkdirs() 78 | 79 | buildFile.writeText( 80 | """$baseBuildGradle 81 | openApi{ 82 | outputDir = file("${specialOutputDir.toURI().path}") 83 | } 84 | """.trimMargin() 85 | ) 86 | 87 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 88 | assertOpenApiJsonFile(1, buildDir = specialOutputDir) 89 | } 90 | 91 | @Test 92 | fun `different output file name`() { 93 | val specialOutputJsonFileName = RandomStringUtils.randomAlphanumeric(15) 94 | 95 | buildFile.writeText( 96 | """$baseBuildGradle 97 | openApi{ 98 | outputFileName = "$specialOutputJsonFileName" 99 | } 100 | """.trimMargin() 101 | ) 102 | 103 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 104 | assertOpenApiJsonFile(1, specialOutputJsonFileName) 105 | } 106 | 107 | @Test 108 | fun `accessing the task does not break later configuration`() { 109 | val specialOutputDir = File(projectTestDir, "specialDir") 110 | specialOutputDir.mkdirs() 111 | 112 | buildFile.writeText( 113 | """$baseBuildGradle 114 | tasks.withType(org.springdoc.openapi.gradle.plugin.OpenApiGeneratorTask.class) { 115 | dependsOn("clean") 116 | } 117 | 118 | openApi{ 119 | outputDir = file("${specialOutputDir.toURI().path}") 120 | } 121 | """.trimMargin() 122 | ) 123 | 124 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild("clean")).outcome) 125 | assertOpenApiJsonFile(1, buildDir = specialOutputDir) 126 | } 127 | 128 | @Test 129 | fun `using properties`() { 130 | buildFile.writeText( 131 | """$baseBuildGradle 132 | bootRun { 133 | args = ["--spring.profiles.active=multiple-endpoints", "--some.second.property=someValue"] 134 | } 135 | """.trimMargin() 136 | ) 137 | 138 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 139 | assertOpenApiJsonFile(3) 140 | } 141 | 142 | @Test 143 | fun `using forked properties via System properties`() { 144 | buildFile.writeText( 145 | """$baseBuildGradle 146 | bootRun { 147 | systemProperties = System.properties 148 | } 149 | """.trimMargin() 150 | ) 151 | 152 | assertEquals( 153 | TaskOutcome.SUCCESS, 154 | openApiDocsTask(runTheBuild("-Dspring.profiles.active=multiple-endpoints")).outcome 155 | ) 156 | assertOpenApiJsonFile(2) 157 | } 158 | 159 | @Test 160 | fun `using forked properties via System properties with customBootRun`() { 161 | buildFile.writeText( 162 | """$baseBuildGradle 163 | openApi { 164 | customBootRun { 165 | systemProperties = System.properties 166 | } 167 | } 168 | """.trimMargin() 169 | ) 170 | 171 | assertEquals( 172 | TaskOutcome.SUCCESS, 173 | openApiDocsTask(runTheBuild("-Dspring.profiles.active=multiple-endpoints")).outcome 174 | ) 175 | assertOpenApiJsonFile(2) 176 | } 177 | 178 | @Test 179 | fun `configurable wait time`() { 180 | buildFile.writeText( 181 | """$baseBuildGradle 182 | bootRun { 183 | args = ["--spring.profiles.active=slower"] 184 | } 185 | openApi{ 186 | waitTimeInSeconds = 60 187 | } 188 | """.trimMargin() 189 | ) 190 | 191 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 192 | assertOpenApiJsonFile(1) 193 | } 194 | 195 | @Test 196 | fun `using different api url`() { 197 | buildFile.writeText( 198 | """$baseBuildGradle 199 | bootRun { 200 | args = ["--spring.profiles.active=different-url"] 201 | } 202 | openApi{ 203 | apiDocsUrl = "http://localhost:8080/secret-api-docs" 204 | } 205 | """.trimMargin() 206 | ) 207 | 208 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 209 | assertOpenApiJsonFile(1) 210 | } 211 | 212 | @Test 213 | fun `using different api url via customBootRun`() { 214 | buildFile.writeText( 215 | """$baseBuildGradle 216 | openApi{ 217 | apiDocsUrl = "http://localhost:8080/secret-api-docs" 218 | customBootRun { 219 | args = ["--spring.profiles.active=different-url"] 220 | } 221 | } 222 | """.trimMargin() 223 | ) 224 | 225 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 226 | assertOpenApiJsonFile(1) 227 | } 228 | 229 | @Test 230 | fun `using HTTPS api url to download api-docs`() { 231 | val trustStore = File(projectTestDir, "truststore.p12") 232 | buildFile.writeText( 233 | """$baseBuildGradle 234 | 235 | openApi{ 236 | trustStore = "${trustStore.absolutePath}" 237 | trustStorePassword = "changeit".toCharArray() 238 | apiDocsUrl = "https://127.0.0.1:8081/v3/api-docs" 239 | customBootRun { 240 | args = ["--spring.profiles.active=ssl"] 241 | } 242 | } 243 | """.trimMargin() 244 | ) 245 | 246 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 247 | assertOpenApiJsonFile(1) 248 | } 249 | 250 | @Test 251 | fun `yaml generation`() { 252 | val outputYamlFileName = "openapi.yaml" 253 | 254 | buildFile.writeText( 255 | """$baseBuildGradle 256 | 257 | openApi{ 258 | apiDocsUrl = "http://localhost:8080/v3/api-docs.yaml" 259 | outputFileName = "$outputYamlFileName" 260 | } 261 | """.trimMargin() 262 | ) 263 | 264 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 265 | assertOpenApiYamlFile(1, outputYamlFileName) 266 | } 267 | 268 | @Test 269 | fun `using multiple grouped apis`() { 270 | val outputJsonFileNameGroupA = "openapi-groupA.json" 271 | val outputJsonFileNameGroupB = "openapi-groupB.json" 272 | 273 | buildFile.writeText( 274 | """$baseBuildGradle 275 | bootRun { 276 | args = ["--spring.profiles.active=multiple-grouped-apis"] 277 | } 278 | openApi{ 279 | groupedApiMappings = ["http://localhost:8080/v3/api-docs/groupA": "$outputJsonFileNameGroupA", 280 | "http://localhost:8080/v3/api-docs/groupB": "$outputJsonFileNameGroupB"] 281 | } 282 | """.trimMargin() 283 | ) 284 | 285 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 286 | assertOpenApiJsonFile(1, outputJsonFileNameGroupA) 287 | assertOpenApiJsonFile(2, outputJsonFileNameGroupB) 288 | } 289 | 290 | @Test 291 | fun `using multiple grouped apis with yaml`() { 292 | val outputYamlFileNameGroupA = "openapi-groupA.yaml" 293 | val outputYamlFileNameGroupB = "openapi-groupB.yaml" 294 | 295 | buildFile.writeText( 296 | """$baseBuildGradle 297 | bootRun { 298 | args = ["--spring.profiles.active=multiple-grouped-apis"] 299 | } 300 | openApi{ 301 | groupedApiMappings = ["http://localhost:8080/v3/api-docs.yaml/groupA": "$outputYamlFileNameGroupA", 302 | "http://localhost:8080/v3/api-docs.yaml/groupB": "$outputYamlFileNameGroupB"] 303 | } 304 | """.trimMargin() 305 | ) 306 | 307 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 308 | assertOpenApiYamlFile(1, outputYamlFileNameGroupA) 309 | assertOpenApiYamlFile(2, outputYamlFileNameGroupB) 310 | } 311 | 312 | @Test 313 | fun `using multiple grouped apis should ignore single api properties`() { 314 | val outputJsonFileNameSingleGroupA = "openapi-single-groupA.json" 315 | val outputJsonFileNameGroupA = "openapi-groupA.json" 316 | val outputJsonFileNameGroupB = "openapi-groupB.json" 317 | 318 | buildFile.writeText( 319 | """$baseBuildGradle 320 | bootRun { 321 | args = ["--spring.profiles.active=multiple-grouped-apis"] 322 | } 323 | openApi{ 324 | apiDocsUrl = "http://localhost:8080/v3/api-docs/groupA" 325 | outputFileName = "$outputJsonFileNameSingleGroupA" 326 | groupedApiMappings = ["http://localhost:8080/v3/api-docs/groupA": "$outputJsonFileNameGroupA", 327 | "http://localhost:8080/v3/api-docs/groupB": "$outputJsonFileNameGroupB"] 328 | } 329 | """.trimMargin() 330 | ) 331 | 332 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 333 | assertFalse(File(projectBuildDir, outputJsonFileNameSingleGroupA).exists()) 334 | assertOpenApiJsonFile(1, outputJsonFileNameGroupA) 335 | assertOpenApiJsonFile(2, outputJsonFileNameGroupB) 336 | } 337 | 338 | @Test 339 | fun `using invalid doc url`() { 340 | buildFile.writeText( 341 | """$baseBuildGradle 342 | openApi{ 343 | apiDocsUrl = "http://localhost:8080/hello/world" 344 | } 345 | """.trimMargin() 346 | ) 347 | 348 | try { 349 | openApiDocsTask(runTheBuild()) 350 | } catch (e: RuntimeException) { 351 | logger.error(e.message) 352 | assertNotNull(e.message?.lines()?.find { 353 | it.contains( 354 | "Failed to parse the API docs response string. " + 355 | "Please ensure that the response is in the correct format." 356 | ) 357 | }) 358 | } 359 | } 360 | 361 | @Test 362 | fun `adding headers for custom generated url`() { 363 | val outputJsonFileName: String = DEFAULT_OPEN_API_FILE_NAME 364 | val buildDir: File = projectBuildDir 365 | val customHost = "custom-host" 366 | val customPort = "7000" 367 | 368 | buildFile.writeText( 369 | """$baseBuildGradle 370 | bootRun { 371 | args = ["--server.forward-headers-strategy=framework"] 372 | } 373 | openApi{ 374 | outputFileName = "$outputJsonFileName" 375 | requestHeaders = [ 376 | "x-forwarded-host": "$customHost", 377 | "x-forwarded-port": "$customPort" 378 | ] 379 | } 380 | """.trimMargin()) 381 | 382 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 383 | assertOpenApiJsonFile(1, outputJsonFileName) 384 | val openApiJson = getOpenApiJsonAtLocation(File(buildDir, outputJsonFileName)) 385 | val servers: JsonArray>? = openApiJson.array("servers") 386 | assertTrue(servers!!.any { s -> s.get("url").equals("http://$customHost:$customPort") }) 387 | } 388 | 389 | @Test 390 | fun `running the same build keeps the OpenAPI task up to date`() { 391 | buildFile.writeText( 392 | """ 393 | $baseBuildGradle 394 | openApi {} 395 | """.trimMargin() 396 | ) 397 | 398 | // Run the first build to generate the OpenAPI file 399 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 400 | assertOpenApiJsonFile(1) 401 | 402 | // Rerunning the build does not regenerate the OpenAPI file 403 | assertEquals(TaskOutcome.UP_TO_DATE, openApiDocsTask(runTheBuild()).outcome) 404 | assertOpenApiJsonFile(1) 405 | } 406 | 407 | @Test 408 | fun `changing the source code regenerates the OpenAPI`() { 409 | buildFile.writeText( 410 | """ 411 | $baseBuildGradle 412 | openApi {} 413 | """.trimMargin() 414 | ) 415 | 416 | // Run the first build to generate the OpenAPI file 417 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 418 | assertOpenApiJsonFile(1) 419 | 420 | val addedFile = projectTestDir.resolve("src/main/java/com/example/demo/endpoints/AddedController.java") 421 | addedFile.createNewFile() 422 | addedFile.writeText(""" 423 | package com.example.demo.endpoints; 424 | 425 | import org.springframework.web.bind.annotation.GetMapping; 426 | import org.springframework.web.bind.annotation.RestController; 427 | 428 | @RestController 429 | public class AddedController { 430 | 431 | @GetMapping("/added") 432 | public String added() { 433 | return "Added file"; 434 | } 435 | } 436 | """.trimIndent()) 437 | 438 | // Run the same build with added source file 439 | assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) 440 | assertOpenApiJsonFile(2) 441 | } 442 | 443 | private fun runTheBuild(vararg additionalArguments: String = emptyArray()) = 444 | GradleRunner.create() 445 | .withProjectDir(projectTestDir) 446 | .withArguments(*additionalArguments, "generateOpenApiDocs") 447 | .withPluginClasspath() 448 | .build() 449 | 450 | private fun assertOpenApiJsonFile( 451 | expectedPathCount: Int, 452 | outputJsonFileName: String = DEFAULT_OPEN_API_FILE_NAME, 453 | buildDir: File = projectBuildDir 454 | ) { 455 | val openApiJson = getOpenApiJsonAtLocation(File(buildDir, outputJsonFileName)) 456 | assertEquals("3.0.1", openApiJson.string(openapiField)) 457 | assertEquals(expectedPathCount, openApiJson.obj(pathsField)!!.size) 458 | } 459 | 460 | private fun getOpenApiJsonAtLocation(path: File) = 461 | Parser.default().parse(FileReader(path)) as JsonObject 462 | 463 | private fun assertOpenApiYamlFile( 464 | expectedPathCount: Int, 465 | outputJsonFileName: String = DEFAULT_OPEN_API_FILE_NAME, 466 | buildDir: File = projectBuildDir 467 | ) { 468 | val mapper = ObjectMapper(YAMLFactory()) 469 | mapper.registerModule(KotlinModule.Builder().build()) 470 | val node = mapper.readTree(File(buildDir, outputJsonFileName)) 471 | assertEquals("3.0.1", node.get(openapiField).asText()) 472 | assertEquals(expectedPathCount, node.get(pathsField)!!.size()) 473 | } 474 | 475 | private fun openApiDocsTask(result: BuildResult) = 476 | result.tasks.find { it.path.contains("generateOpenApiDocs") }!! 477 | } 478 | -------------------------------------------------------------------------------- /config/detekt/detekt.yml: -------------------------------------------------------------------------------- 1 | build: 2 | maxIssues: 0 3 | excludeCorrectable: false 4 | weights: 5 | # complexity: 2 6 | # LongParameterList: 1 7 | # style: 1 8 | # comments: 1 9 | 10 | config: 11 | validation: true 12 | warningsAsErrors: false 13 | # when writing own rules with new properties, exclude the property path e.g.: 'my_rule_set,.*>.*>[my_property]' 14 | excludes: '' 15 | 16 | processors: 17 | active: true 18 | exclude: 19 | - 'DetektProgressListener' 20 | # - 'KtFileCountProcessor' 21 | # - 'PackageCountProcessor' 22 | # - 'ClassCountProcessor' 23 | # - 'FunctionCountProcessor' 24 | # - 'PropertyCountProcessor' 25 | # - 'ProjectComplexityProcessor' 26 | # - 'ProjectCognitiveComplexityProcessor' 27 | # - 'ProjectLLOCProcessor' 28 | # - 'ProjectCLOCProcessor' 29 | # - 'ProjectLOCProcessor' 30 | # - 'ProjectSLOCProcessor' 31 | # - 'LicenseHeaderLoaderExtension' 32 | 33 | console-reports: 34 | active: true 35 | exclude: 36 | - 'ProjectStatisticsReport' 37 | - 'ComplexityReport' 38 | - 'NotificationReport' 39 | # - 'FindingsReport' 40 | - 'FileBasedFindingsReport' 41 | 42 | output-reports: 43 | active: true 44 | exclude: 45 | # - 'TxtOutputReport' 46 | # - 'XmlOutputReport' 47 | # - 'HtmlOutputReport' 48 | 49 | comments: 50 | active: true 51 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 52 | AbsentOrWrongFileLicense: 53 | active: false 54 | licenseTemplateFile: 'license.template' 55 | licenseTemplateIsRegex: false 56 | CommentOverPrivateFunction: 57 | active: false 58 | CommentOverPrivateProperty: 59 | active: false 60 | EndOfSentenceFormat: 61 | active: false 62 | endOfSentenceFormat: '([.?!][ \t\n\r\f<])|([.?!:]$)' 63 | UndocumentedPublicClass: 64 | active: false 65 | searchInNestedClass: true 66 | searchInInnerClass: true 67 | searchInInnerObject: true 68 | searchInInnerInterface: true 69 | UndocumentedPublicFunction: 70 | active: false 71 | UndocumentedPublicProperty: 72 | active: false 73 | 74 | complexity: 75 | active: true 76 | ComplexCondition: 77 | active: true 78 | threshold: 4 79 | ComplexInterface: 80 | active: false 81 | threshold: 10 82 | includeStaticDeclarations: false 83 | includePrivateDeclarations: false 84 | ComplexMethod: 85 | active: true 86 | threshold: 15 87 | ignoreSingleWhenExpression: false 88 | ignoreSimpleWhenEntries: false 89 | ignoreNestingFunctions: false 90 | nestingFunctions: [ run, let, apply, with, also, use, forEach, isNotNull, ifNull ] 91 | LabeledExpression: 92 | active: false 93 | ignoredLabels: [ ] 94 | LargeClass: 95 | active: true 96 | threshold: 600 97 | LongMethod: 98 | active: true 99 | threshold: 60 100 | LongParameterList: 101 | active: true 102 | functionThreshold: 6 103 | constructorThreshold: 7 104 | ignoreDefaultParameters: false 105 | ignoreDataClasses: true 106 | ignoreAnnotated: [ ] 107 | MethodOverloading: 108 | active: false 109 | threshold: 6 110 | NamedArguments: 111 | active: false 112 | threshold: 3 113 | NestedBlockDepth: 114 | active: true 115 | threshold: 4 116 | ReplaceSafeCallChainWithRun: 117 | active: false 118 | StringLiteralDuplication: 119 | active: false 120 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 121 | threshold: 3 122 | ignoreAnnotation: true 123 | excludeStringsWithLessThan5Characters: true 124 | ignoreStringsRegex: '$^' 125 | TooManyFunctions: 126 | active: true 127 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 128 | thresholdInFiles: 11 129 | thresholdInClasses: 11 130 | thresholdInInterfaces: 11 131 | thresholdInObjects: 11 132 | thresholdInEnums: 11 133 | ignoreDeprecated: false 134 | ignorePrivate: false 135 | ignoreOverridden: false 136 | 137 | coroutines: 138 | active: true 139 | GlobalCoroutineUsage: 140 | active: false 141 | RedundantSuspendModifier: 142 | active: false 143 | SleepInsteadOfDelay: 144 | active: false 145 | SuspendFunWithFlowReturnType: 146 | active: false 147 | 148 | empty-blocks: 149 | active: true 150 | EmptyCatchBlock: 151 | active: true 152 | allowedExceptionNameRegex: '_|(ignore|expected).*' 153 | EmptyClassBlock: 154 | active: true 155 | EmptyDefaultConstructor: 156 | active: true 157 | EmptyDoWhileBlock: 158 | active: true 159 | EmptyElseBlock: 160 | active: true 161 | EmptyFinallyBlock: 162 | active: true 163 | EmptyForBlock: 164 | active: true 165 | EmptyFunctionBlock: 166 | active: true 167 | ignoreOverridden: false 168 | EmptyIfBlock: 169 | active: true 170 | EmptyInitBlock: 171 | active: true 172 | EmptyKtFile: 173 | active: true 174 | EmptySecondaryConstructor: 175 | active: true 176 | EmptyTryBlock: 177 | active: true 178 | EmptyWhenBlock: 179 | active: true 180 | EmptyWhileBlock: 181 | active: true 182 | 183 | exceptions: 184 | active: true 185 | ExceptionRaisedInUnexpectedLocation: 186 | active: true 187 | methodNames: [ toString, hashCode, equals, finalize ] 188 | InstanceOfCheckForException: 189 | active: false 190 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 191 | NotImplementedDeclaration: 192 | active: false 193 | ObjectExtendsThrowable: 194 | active: false 195 | PrintStackTrace: 196 | active: true 197 | RethrowCaughtException: 198 | active: true 199 | ReturnFromFinally: 200 | active: true 201 | ignoreLabeled: false 202 | SwallowedException: 203 | active: true 204 | ignoredExceptionTypes: 205 | - InterruptedException 206 | - NumberFormatException 207 | - ParseException 208 | - MalformedURLException 209 | - UnknownDomainObjectException 210 | allowedExceptionNameRegex: '_|(ignore|expected).*' 211 | ThrowingExceptionFromFinally: 212 | active: true 213 | ThrowingExceptionInMain: 214 | active: false 215 | ThrowingExceptionsWithoutMessageOrCause: 216 | active: true 217 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 218 | exceptions: 219 | - IllegalArgumentException 220 | - IllegalStateException 221 | - IOException 222 | ThrowingNewInstanceOfSameException: 223 | active: true 224 | TooGenericExceptionCaught: 225 | active: true 226 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 227 | exceptionNames: 228 | - ArrayIndexOutOfBoundsException 229 | - Error 230 | - Exception 231 | - IllegalMonitorStateException 232 | - NullPointerException 233 | - IndexOutOfBoundsException 234 | - Throwable 235 | allowedExceptionNameRegex: '_|(ignore|expected).*' 236 | TooGenericExceptionThrown: 237 | active: true 238 | exceptionNames: 239 | - Error 240 | - Exception 241 | - Throwable 242 | - RuntimeException 243 | 244 | formatting: 245 | active: true 246 | android: false 247 | autoCorrect: true 248 | AnnotationOnSeparateLine: 249 | active: false 250 | autoCorrect: true 251 | AnnotationSpacing: 252 | active: false 253 | autoCorrect: true 254 | ArgumentListWrapping: 255 | active: false 256 | autoCorrect: true 257 | ChainWrapping: 258 | active: true 259 | autoCorrect: true 260 | CommentSpacing: 261 | active: true 262 | autoCorrect: true 263 | EnumEntryNameCase: 264 | active: false 265 | autoCorrect: true 266 | Filename: 267 | active: true 268 | FinalNewline: 269 | active: true 270 | autoCorrect: true 271 | insertFinalNewLine: true 272 | ImportOrdering: 273 | active: false 274 | autoCorrect: true 275 | layout: 'idea' 276 | Indentation: 277 | active: false 278 | autoCorrect: true 279 | indentSize: 4 280 | continuationIndentSize: 4 281 | MaximumLineLength: 282 | active: true 283 | maxLineLength: 150 284 | ModifierOrdering: 285 | active: true 286 | autoCorrect: true 287 | MultiLineIfElse: 288 | active: true 289 | autoCorrect: true 290 | NoBlankLineBeforeRbrace: 291 | active: true 292 | autoCorrect: true 293 | NoConsecutiveBlankLines: 294 | active: true 295 | autoCorrect: true 296 | NoEmptyClassBody: 297 | active: true 298 | autoCorrect: true 299 | NoEmptyFirstLineInMethodBlock: 300 | active: false 301 | autoCorrect: true 302 | NoLineBreakAfterElse: 303 | active: true 304 | autoCorrect: true 305 | NoLineBreakBeforeAssignment: 306 | active: true 307 | autoCorrect: true 308 | NoMultipleSpaces: 309 | active: true 310 | autoCorrect: true 311 | NoSemicolons: 312 | active: true 313 | autoCorrect: true 314 | NoTrailingSpaces: 315 | active: true 316 | autoCorrect: true 317 | NoUnitReturn: 318 | active: true 319 | autoCorrect: true 320 | NoUnusedImports: 321 | active: true 322 | autoCorrect: true 323 | NoWildcardImports: 324 | active: false 325 | PackageName: 326 | active: true 327 | autoCorrect: true 328 | SpacingAroundAngleBrackets: 329 | active: false 330 | autoCorrect: true 331 | SpacingAroundColon: 332 | active: true 333 | autoCorrect: true 334 | SpacingAroundComma: 335 | active: true 336 | autoCorrect: true 337 | SpacingAroundCurly: 338 | active: true 339 | autoCorrect: true 340 | SpacingAroundDot: 341 | active: true 342 | autoCorrect: true 343 | SpacingAroundDoubleColon: 344 | active: false 345 | autoCorrect: true 346 | SpacingAroundKeyword: 347 | active: true 348 | autoCorrect: true 349 | SpacingAroundOperators: 350 | active: true 351 | autoCorrect: true 352 | SpacingAroundParens: 353 | active: true 354 | autoCorrect: true 355 | SpacingAroundRangeOperator: 356 | active: true 357 | autoCorrect: true 358 | SpacingAroundUnaryOperator: 359 | active: false 360 | autoCorrect: true 361 | SpacingBetweenDeclarationsWithAnnotations: 362 | active: false 363 | autoCorrect: true 364 | SpacingBetweenDeclarationsWithComments: 365 | active: false 366 | autoCorrect: true 367 | StringTemplate: 368 | active: true 369 | autoCorrect: true 370 | 371 | naming: 372 | active: true 373 | ClassNaming: 374 | active: true 375 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 376 | classPattern: '[A-Z][a-zA-Z0-9]*' 377 | ConstructorParameterNaming: 378 | active: true 379 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 380 | parameterPattern: '[a-z][A-Za-z0-9]*' 381 | privateParameterPattern: '[a-z][A-Za-z0-9]*' 382 | excludeClassPattern: '$^' 383 | ignoreOverridden: true 384 | EnumNaming: 385 | active: true 386 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 387 | enumEntryPattern: '[A-Z][_a-zA-Z0-9]*' 388 | ForbiddenClassName: 389 | active: false 390 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 391 | forbiddenName: [ ] 392 | FunctionMaxLength: 393 | active: false 394 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 395 | maximumFunctionNameLength: 30 396 | FunctionMinLength: 397 | active: false 398 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 399 | minimumFunctionNameLength: 3 400 | FunctionNaming: 401 | active: true 402 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 403 | functionPattern: '([a-z][a-zA-Z0-9]*)|(`.*`)' 404 | excludeClassPattern: '$^' 405 | ignoreOverridden: true 406 | ignoreAnnotated: [ 'Composable' ] 407 | FunctionParameterNaming: 408 | active: true 409 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 410 | parameterPattern: '[a-z][A-Za-z0-9]*' 411 | excludeClassPattern: '$^' 412 | ignoreOverridden: true 413 | InvalidPackageDeclaration: 414 | active: false 415 | excludes: [ '*.kts' ] 416 | rootPackage: '' 417 | MatchingDeclarationName: 418 | active: true 419 | mustBeFirst: true 420 | MemberNameEqualsClassName: 421 | active: true 422 | ignoreOverridden: true 423 | NoNameShadowing: 424 | active: false 425 | NonBooleanPropertyPrefixedWithIs: 426 | active: false 427 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 428 | ObjectPropertyNaming: 429 | active: true 430 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 431 | constantPattern: '[A-Za-z][_A-Za-z0-9]*' 432 | propertyPattern: '[A-Za-z][_A-Za-z0-9]*' 433 | privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*' 434 | PackageNaming: 435 | active: true 436 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 437 | packagePattern: '[a-z]+(\.[a-z][A-Za-z0-9]*)*' 438 | TopLevelPropertyNaming: 439 | active: true 440 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 441 | constantPattern: '[A-Z][_A-Z0-9]*' 442 | propertyPattern: '[A-Za-z][_A-Za-z0-9]*' 443 | privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*' 444 | VariableMaxLength: 445 | active: false 446 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 447 | maximumVariableNameLength: 64 448 | VariableMinLength: 449 | active: false 450 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 451 | minimumVariableNameLength: 1 452 | VariableNaming: 453 | active: true 454 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 455 | variablePattern: '[a-z][A-Za-z0-9]*' 456 | privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' 457 | excludeClassPattern: '$^' 458 | ignoreOverridden: true 459 | 460 | performance: 461 | active: true 462 | ArrayPrimitive: 463 | active: true 464 | ForEachOnRange: 465 | active: true 466 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 467 | SpreadOperator: 468 | active: true 469 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 470 | UnnecessaryTemporaryInstantiation: 471 | active: true 472 | 473 | potential-bugs: 474 | active: true 475 | CastToNullableType: 476 | active: false 477 | Deprecation: 478 | active: false 479 | DontDowncastCollectionTypes: 480 | active: false 481 | DuplicateCaseInWhenExpression: 482 | active: true 483 | EqualsAlwaysReturnsTrueOrFalse: 484 | active: true 485 | EqualsWithHashCodeExist: 486 | active: true 487 | ExitOutsideMain: 488 | active: false 489 | ExplicitGarbageCollectionCall: 490 | active: true 491 | HasPlatformType: 492 | active: false 493 | IgnoredReturnValue: 494 | active: false 495 | restrictToAnnotatedMethods: true 496 | returnValueAnnotations: [ '*.CheckReturnValue', '*.CheckResult' ] 497 | ImplicitDefaultLocale: 498 | active: true 499 | ImplicitUnitReturnType: 500 | active: false 501 | allowExplicitReturnType: true 502 | InvalidRange: 503 | active: true 504 | IteratorHasNextCallsNextMethod: 505 | active: true 506 | IteratorNotThrowingNoSuchElementException: 507 | active: true 508 | LateinitUsage: 509 | active: false 510 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 511 | excludeAnnotatedProperties: [ ] 512 | ignoreOnClassesPattern: '' 513 | MapGetWithNotNullAssertionOperator: 514 | active: false 515 | MissingWhenCase: 516 | active: true 517 | allowElseExpression: true 518 | NullableToStringCall: 519 | active: false 520 | RedundantElseInWhen: 521 | active: true 522 | UnconditionalJumpStatementInLoop: 523 | active: false 524 | UnnecessaryNotNullOperator: 525 | active: true 526 | UnnecessarySafeCall: 527 | active: true 528 | UnreachableCatchBlock: 529 | active: false 530 | UnreachableCode: 531 | active: true 532 | UnsafeCallOnNullableType: 533 | active: true 534 | UnsafeCast: 535 | active: true 536 | UnusedUnaryOperator: 537 | active: false 538 | UselessPostfixExpression: 539 | active: false 540 | WrongEqualsTypeParameter: 541 | active: true 542 | 543 | style: 544 | active: true 545 | ClassOrdering: 546 | active: false 547 | CollapsibleIfStatements: 548 | active: false 549 | DataClassContainsFunctions: 550 | active: false 551 | conversionFunctionPrefix: 'to' 552 | DataClassShouldBeImmutable: 553 | active: false 554 | DestructuringDeclarationWithTooManyEntries: 555 | active: false 556 | maxDestructuringEntries: 3 557 | EqualsNullCall: 558 | active: true 559 | EqualsOnSignatureLine: 560 | active: false 561 | ExplicitCollectionElementAccessMethod: 562 | active: false 563 | ExplicitItLambdaParameter: 564 | active: false 565 | ExpressionBodySyntax: 566 | active: false 567 | includeLineWrapping: false 568 | ForbiddenComment: 569 | active: true 570 | values: [ 'TODO:', 'FIXME:', 'STOPSHIP:' ] 571 | allowedPatterns: '' 572 | ForbiddenImport: 573 | active: false 574 | imports: [ ] 575 | forbiddenPatterns: '' 576 | ForbiddenMethodCall: 577 | active: false 578 | methods: [ 'kotlin.io.println', 'kotlin.io.print' ] 579 | ForbiddenPublicDataClass: 580 | active: true 581 | excludes: [ '**' ] 582 | ignorePackages: [ '*.internal', '*.internal.*' ] 583 | ForbiddenVoid: 584 | active: false 585 | ignoreOverridden: false 586 | ignoreUsageInGenerics: false 587 | FunctionOnlyReturningConstant: 588 | active: true 589 | ignoreOverridableFunction: true 590 | ignoreActualFunction: true 591 | excludedFunctions: 'describeContents' 592 | excludeAnnotatedFunction: [ 'dagger.Provides' ] 593 | LibraryCodeMustSpecifyReturnType: 594 | active: true 595 | excludes: [ '**' ] 596 | LibraryEntitiesShouldNotBePublic: 597 | active: true 598 | excludes: [ '**' ] 599 | LoopWithTooManyJumpStatements: 600 | active: true 601 | maxJumpCount: 1 602 | MagicNumber: 603 | active: true 604 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 605 | ignoreNumbers: [ '-1', '0', '1', '2' ] 606 | ignoreHashCodeFunction: true 607 | ignorePropertyDeclaration: false 608 | ignoreLocalVariableDeclaration: false 609 | ignoreConstantDeclaration: true 610 | ignoreCompanionObjectPropertyDeclaration: true 611 | ignoreAnnotation: false 612 | ignoreNamedArgument: true 613 | ignoreEnums: false 614 | ignoreRanges: false 615 | ignoreExtensionFunctions: true 616 | MandatoryBracesIfStatements: 617 | active: false 618 | MandatoryBracesLoops: 619 | active: false 620 | MaxLineLength: 621 | active: true 622 | maxLineLength: 150 623 | excludePackageStatements: true 624 | excludeImportStatements: true 625 | excludeCommentStatements: false 626 | MayBeConst: 627 | active: true 628 | ModifierOrder: 629 | active: true 630 | MultilineLambdaItParameter: 631 | active: false 632 | NestedClassesVisibility: 633 | active: true 634 | NewLineAtEndOfFile: 635 | active: true 636 | NoTabs: 637 | active: false 638 | OptionalAbstractKeyword: 639 | active: true 640 | OptionalUnit: 641 | active: false 642 | OptionalWhenBraces: 643 | active: false 644 | PreferToOverPairSyntax: 645 | active: false 646 | ProtectedMemberInFinalClass: 647 | active: true 648 | RedundantExplicitType: 649 | active: false 650 | RedundantHigherOrderMapUsage: 651 | active: false 652 | RedundantVisibilityModifierRule: 653 | active: false 654 | ReturnCount: 655 | active: true 656 | max: 2 657 | excludedFunctions: 'equals' 658 | excludeLabeled: false 659 | excludeReturnFromLambda: true 660 | excludeGuardClauses: false 661 | SafeCast: 662 | active: true 663 | SerialVersionUIDInSerializableClass: 664 | active: true 665 | SpacingBetweenPackageAndImports: 666 | active: false 667 | ThrowsCount: 668 | active: true 669 | max: 2 670 | TrailingWhitespace: 671 | active: false 672 | UnderscoresInNumericLiterals: 673 | active: false 674 | acceptableDecimalLength: 5 675 | UnnecessaryAbstractClass: 676 | active: true 677 | excludeAnnotatedClasses: [ 'dagger.Module' ] 678 | UnnecessaryAnnotationUseSiteTarget: 679 | active: false 680 | UnnecessaryApply: 681 | active: true 682 | UnnecessaryFilter: 683 | active: false 684 | UnnecessaryInheritance: 685 | active: true 686 | UnnecessaryLet: 687 | active: false 688 | UnnecessaryParentheses: 689 | active: false 690 | UntilInsteadOfRangeTo: 691 | active: false 692 | UnusedImports: 693 | active: false 694 | UnusedPrivateClass: 695 | active: true 696 | UnusedPrivateMember: 697 | active: true 698 | allowedNames: '(_|ignored|expected|serialVersionUID)' 699 | UseArrayLiteralsInAnnotations: 700 | active: false 701 | UseCheckNotNull: 702 | active: false 703 | UseCheckOrError: 704 | active: false 705 | UseDataClass: 706 | active: false 707 | excludeAnnotatedClasses: [ ] 708 | allowVars: false 709 | UseEmptyCounterpart: 710 | active: false 711 | UseIfEmptyOrIfBlank: 712 | active: false 713 | UseIfInsteadOfWhen: 714 | active: false 715 | UseIsNullOrEmpty: 716 | active: false 717 | UseOrEmpty: 718 | active: false 719 | UseRequire: 720 | active: false 721 | UseRequireNotNull: 722 | active: false 723 | UselessCallOnNotNull: 724 | active: true 725 | UtilityClassWithPublicConstructor: 726 | active: true 727 | VarCouldBeVal: 728 | active: true 729 | WildcardImport: 730 | active: false 731 | excludes: [ '**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**' ] 732 | excludeImports: [ 'java.util.*', 'kotlinx.android.synthetic.*' ] 733 | --------------------------------------------------------------------------------