diff --git a/README.md b/README.md index a57ba53..3bb60cf 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,11 @@ Gradle plugin for springdoc-openapi. This plugin allows you to generate an OpenAPI 3 specification for a Spring Boot application from a Gradle build. + Compatibility Notes ------------------- -The plugin is built on Gradle version 7.0. +The plugin is built on Gradle version 8.12.1 and Java 17. Dependencies ------------ @@ -25,17 +26,17 @@ Gradle Groovy DSL ```groovy plugins { - id "org.springframework.boot" version "2.7.0" - id "org.springdoc.openapi-gradle-plugin" version "1.9.0" + id "org.springframework.boot" version "3.4.2" + id "org.springdoc.openapi-gradle-plugin" version "2.0.0" } ``` Gradle Kotlin DSL -```groovy +```kotlin plugins { - id("org.springframework.boot") version "2.7.0" - id("org.springdoc.openapi-gradle-plugin") version "1.9.0" + id("org.springframework.boot") version "3.4.2" + id("org.springdoc.openapi-gradle-plugin") version "2.0.0" } ``` @@ -80,30 +81,34 @@ openApi { trustStore.set("keystore/truststore.p12") trustStorePassword.set("changeit".toCharArray()) groupedApiMappings.set( - ["https://localhost:8080/v3/api-docs/groupA" to "swagger-groupA.json", - "https://localhost:8080/v3/api-docs/groupB" to "swagger-groupB.json"] + mapOf( + "https://localhost:8080/v3/api-docs/groupA" to "swagger-groupA.json", + "https://localhost:8080/v3/api-docs/groupB" to "swagger-groupB.json" + ) ) customBootRun { - args.set(["--spring.profiles.active=special"]) + args.set(listOf("--spring.profiles.active=special")) } - requestHeaders = [ - "x-forwarded-host": "custom-host", - "x-forwarded-port": "7000" - ] + requestHeaders = mapOf( + "x-forwarded-host" to "custom-host", + "x-forwarded-port" to "7000" + ) } ``` -| Parameter | Description | Required | Default | -|----------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------------------------| -| `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 | -| `outputDir` | The output directory for the generated OpenAPI file | No | $buildDir - Your project's build dir | -| `outputFileName` | Specifies the output file name. | No | openapi.json | -| `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 | -| `trustStore` | Path to a trust store that contains custom trusted certificates. | No | `` | -| `trustStorePassword` | Password to open Trust Store | No | `` | -| `groupedApiMappings` | A map of URLs (from where the OpenAPI docs can be downloaded) to output file names | No | [] | -| `customBootRun` | Any bootRun property that you would normal need to start your spring boot application. | No | (N/A) | -| `requestHeaders` | customize Generated server url, relies on `server.forward-headers-strategy=framework` | No | (N/A) | +| Parameter | Description | Required | Default | +|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------------------------| +| `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 | +| `outputDir` | The output directory for the generated OpenAPI file | No | $buildDir - Your project's build dir | +| `outputFileName` | Specifies the output file name. | No | openapi.json | +| `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 | +| `trustStore` | Path to a trust store that contains custom trusted certificates. | No | `` | +| `trustStorePassword` | Password to open Trust Store | No | `` | +| `groupedApiMappings` | A map of URLs (from where the OpenAPI docs can be downloaded) to output file names | No | [] | +| `customBootRun` | Any bootRun property that you would normal need to start your spring boot application. | No | (N/A) | +| `requestHeaders` | customize Generated server url, relies on `server.forward-headers-strategy=framework` | No | (N/A) | +| `bootRunTaskName` | The name of the bootRun task to be used to start the Spring Boot application. | No | bootRun | +| `classNameResolveTaskName` | The name of the task to resolve the main class of the Spring Boot application. | No | resolveMainClassName | ### `customBootRun` properties examples @@ -115,15 +120,25 @@ as `args`, `jvmArgs`, `systemProperties` and `workingDir`. If you don't specify `customBootRun` parameter, this plugin uses the parameter specified to `bootRun` in Spring Boot Gradle Plugin. +#### Running with Spring Boot Testcontainers Support + +AS a convenience, you can use the `useTestBootRun` method to configure this plugin to use the `bootTestRun` task available with the Spring Boot Testcontainers support added in Spring Boot since 3.1.x. + +```kotlin +openApi { + useTestBootRun() +} +``` + #### Passing static args This allows for you to be able to just send the static properties when executing Spring application in `generateOpenApiDocs`. -``` +```kotlin openApi { customBootRun { - args = ["--spring.profiles.active=special"] + args.set(listOf("--spring.profiles.active=special")) } } ``` @@ -183,7 +198,7 @@ OpenAPI doc. in `build.gradle.kts` ``` - id("org.springdoc.openapi-gradle-plugin") version "1.8.0" + id("org.springdoc.openapi-gradle-plugin") version "2.0.0" ``` 3. Add the following to the spring boot apps `settings.gradle` diff --git a/build.gradle.kts b/build.gradle.kts index 40911ad..906efe4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,15 +1,18 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + plugins { `java-gradle-plugin` - id("com.gradle.plugin-publish") version "1.2.0" - id("org.sonarqube") version "3.1.1" - kotlin("jvm") version "1.8.20" + alias(libs.plugins.plugin.publish) + alias(libs.plugins.sonarqube) + kotlin("jvm") version libs.versions.kotlin + `kotlin-dsl` `maven-publish` - id("com.github.ben-manes.versions") version "0.38.0" - id("io.gitlab.arturbosch.detekt") version "1.23.1" + alias(libs.plugins.versions) + alias(libs.plugins.detekt) } group = "org.springdoc" -version = "1.9.0" +version = "2.0.0" sonarqube { properties { @@ -27,6 +30,7 @@ repositories { name = "Gradle Plugins Maven Repository" url = uri("https://plugins.gradle.org/m2/") } + mavenLocal() } publishing { @@ -40,9 +44,9 @@ publishing { url = if (version.toString() .endsWith("SNAPSHOT") ) { - snapshotsRepoUrl + snapshotsRepoUrl } else { - releasesRepoUrl + releasesRepoUrl } credentials { username = System.getenv("OSSRH_USER") @@ -54,19 +58,19 @@ publishing { dependencies { implementation(kotlin("reflect")) - implementation("com.google.code.gson:gson:2.8.9") - implementation("org.awaitility:awaitility-kotlin:4.0.3") - implementation("com.github.psxpaul:gradle-execfork-plugin:0.2.0") - implementation("org.springframework.boot:spring-boot-gradle-plugin:2.7.14") + implementation(gradleKotlinDsl()) + implementation(libs.klaxon) + implementation(libs.awaitility.kotlin) + implementation(libs.pluginlib.gradle.execfork) + implementation(libs.pluginlib.spring.boot) testImplementation(gradleTestKit()) - testImplementation(platform("org.junit:junit-bom:5.7.1")) + testImplementation(platform(libs.junit.bom)) testImplementation("org.junit.jupiter:junit-jupiter") - testImplementation("com.beust:klaxon:5.5") - testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.15.2") - testImplementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.13.2") + testImplementation(libs.jackson.kotlin) + testImplementation(libs.jackson.yaml) - detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.1") + detektPlugins(libs.detekt.formatting) } gradlePlugin { @@ -83,17 +87,16 @@ gradlePlugin { } } -val jvmVersion: JavaLanguageVersion = JavaLanguageVersion.of(8) java { - toolchain.languageVersion.set(jvmVersion) + toolchain.languageVersion.set(libs.versions.java.map(JavaLanguageVersion::of)) // Recommended by https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_packaging withSourcesJar() } tasks.withType { - kotlinOptions { - jvmTarget = "1.$jvmVersion" + compilerOptions{ + jvmTarget.set(libs.versions.java.map (JvmTarget::fromTarget)) } } @@ -108,5 +111,5 @@ detekt { parallel = true } tasks.withType().configureEach { - jvmTarget = "1.$jvmVersion" + jvmTarget = libs.versions.java.get() } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..cb4172f --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,23 @@ +[versions] +java = "17" +kotlin = "2.0.21" +spring-boot = "3.4.2" +detekt = "1.23.6" +junit = "5.11.4" +jackson = "2.18.2" + +[libraries] +awaitility-kotlin = { group = "org.awaitility", name = "awaitility-kotlin", version = "4.2.2" } +detekt-formatting = { group = "io.gitlab.arturbosch.detekt", name = "detekt-formatting", version.ref = "detekt" } +junit-bom = { group = "org.junit", name = "junit-bom", version.ref = "junit" } +klaxon = { group = "com.beust", name = "klaxon", version = "5.5" } +pluginlib-spring-boot = { group = "org.springframework.boot", name = "spring-boot-gradle-plugin", version.ref = "spring-boot" } +pluginlib-gradle-execfork = { group = "com.github.psxpaul", name = "gradle-execfork-plugin", version = "0.2.2" } +jackson-yaml = { group = "com.fasterxml.jackson.dataformat", name = "jackson-dataformat-yaml", version.ref = "jackson" } +jackson-kotlin = { group = "com.fasterxml.jackson.module", name = "jackson-module-kotlin", version.ref = "jackson" } + +[plugins] +detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } +plugin-publish = { id = "com.gradle.plugin-publish", version = "1.3.1" } +sonarqube = { id = "org.sonarqube", version = "6.0.1.5171" } +versions = { id = "com.github.ben-manes.versions", version = "0.52.0" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..a4b76b9 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9f4197d..e18bc25 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 4f906e0..f3b75f3 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,69 +15,103 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index ac1b06f..9b42019 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/Constants.kt b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/Constants.kt index 95dae65..7e3c167 100644 --- a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/Constants.kt +++ b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/Constants.kt @@ -5,8 +5,9 @@ const val GROUP_NAME = "OpenApi" const val OPEN_API_TASK_NAME = "generateOpenApiDocs" const val OPEN_API_TASK_DESCRIPTION = "Generates the spring doc openapi file" const val SPRING_BOOT_RUN_TASK_NAME = "bootRun" -const val SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME = "bootRunMainClassName" -const val SPRING_BOOT_3_RUN_MAIN_CLASS_NAME_TASK_NAME = "bootRun" +const val SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME = "resolveMainClassName" +const val SPRING_BOOT_TEST_RUN_TASK_NAME = "bootTestRun" +const val SPRING_BOOT_RUN_TEST_MAIN_CLASS_NAME_TASK_NAME = "resolveTestMainClassName" const val FORKED_SPRING_BOOT_RUN_TASK_NAME = "forkedSpringBootRun" const val DEFAULT_API_DOCS_URL = "http://localhost:8080/v3/api-docs" diff --git a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiExtension.kt b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiExtension.kt index d275604..a656b62 100644 --- a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiExtension.kt +++ b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiExtension.kt @@ -25,6 +25,8 @@ open class OpenApiExtension @Inject constructor( objects.mapProperty(String::class.java, String::class.java) val requestHeaders: MapProperty = objects.mapProperty(String::class.java, String::class.java) + val bootRunTaskName: Property = objects.property(String::class.java) + val classNameResolveTaskName: Property = objects.property(String::class.java) val customBootRun: CustomBootRunAction = objects.newInstance(CustomBootRunAction::class.java) @@ -34,6 +36,13 @@ open class OpenApiExtension @Inject constructor( outputDir.convention(layout.buildDirectory) waitTimeInSeconds.convention(DEFAULT_WAIT_TIME_IN_SECONDS) groupedApiMappings.convention(emptyMap()) + bootRunTaskName.convention(SPRING_BOOT_RUN_TASK_NAME) + classNameResolveTaskName.convention(SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME) + } + + fun useTestBootRun() { + bootRunTaskName.set(SPRING_BOOT_TEST_RUN_TASK_NAME) + classNameResolveTaskName.set(SPRING_BOOT_RUN_TEST_MAIN_CLASS_NAME_TASK_NAME) } fun customBootRun(action: Action) { diff --git a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGeneratorTask.kt b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGeneratorTask.kt index c46bc8b..79e31d4 100644 --- a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGeneratorTask.kt +++ b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGeneratorTask.kt @@ -1,25 +1,16 @@ package org.springdoc.openapi.gradle.plugin -import com.google.gson.GsonBuilder -import com.google.gson.JsonObject -import com.google.gson.JsonSyntaxException +import com.beust.klaxon.Klaxon import org.awaitility.Durations import org.awaitility.core.ConditionTimeoutException -import org.awaitility.kotlin.atMost -import org.awaitility.kotlin.await -import org.awaitility.kotlin.ignoreException -import org.awaitility.kotlin.until -import org.awaitility.kotlin.withPollInterval +import org.awaitility.kotlin.* import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Property -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.* import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.TaskAction import java.io.FileInputStream import java.net.ConnectException import java.net.HttpURLConnection @@ -28,7 +19,7 @@ import java.security.KeyStore import java.security.SecureRandom import java.time.Duration import java.time.temporal.ChronoUnit.SECONDS -import java.util.Locale +import java.util.* import javax.net.ssl.HttpsURLConnection import javax.net.ssl.KeyManager import javax.net.ssl.SSLContext @@ -156,12 +147,14 @@ open class OpenApiGeneratorTask : DefaultTask() { } private fun prettifyJson(response: String): String { - val gson = GsonBuilder().setPrettyPrinting().create() try { - val googleJsonObject = gson.fromJson(response, JsonObject::class.java) - return gson.toJson(googleJsonObject) - } catch (e: RuntimeException) { - throw JsonSyntaxException( + return if (response.startsWith("[")) { + Klaxon().parseJsonArray(response.reader()).toJsonString(true) + } else { + Klaxon().parseJsonObject(response.reader()).toJsonString(true) + } + } catch (e: Exception) { + throw RuntimeException( "Failed to parse the API docs response string. " + "Please ensure that the response is in the correct format. response=$response", e diff --git a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePlugin.kt b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePlugin.kt index 64ca896..3802b79 100644 --- a/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePlugin.kt +++ b/src/main/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePlugin.kt @@ -4,9 +4,8 @@ import com.github.psxpaul.task.JavaExecFork import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task -import org.gradle.api.UnknownDomainObjectException import org.gradle.api.tasks.TaskProvider -import org.gradle.internal.jvm.Jvm +import org.gradle.kotlin.dsl.named import org.springframework.boot.gradle.tasks.run.BootRun open class OpenApiGradlePlugin : Plugin { @@ -26,61 +25,37 @@ open class OpenApiGradlePlugin : Plugin { } private fun generate(project: Project) = project.run { - springBoot3CompatibilityCheck() + val extension = extensions.findByName(EXTENSION_NAME) as OpenApiExtension - // The task, used to run the Spring Boot application (`bootRun`) - val bootRunTask = tasks.named(SPRING_BOOT_RUN_TASK_NAME) // The task, used to resolve the application's main class (`bootRunMainClassName`) - val bootRunMainClassNameTask = - try { - val task = tasks.named(SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME) - logger.debug( - "Detected Spring Boot task {}", - SPRING_BOOT_RUN_MAIN_CLASS_NAME_TASK_NAME - ) - task - } catch (e: UnknownDomainObjectException) { - val task = tasks.named(SPRING_BOOT_3_RUN_MAIN_CLASS_NAME_TASK_NAME) - logger.debug( - "Detected Spring Boot task {}", - SPRING_BOOT_3_RUN_MAIN_CLASS_NAME_TASK_NAME - ) - task - } + val bootRunMainClassNameTask = extension.classNameResolveTaskName.map { + tasks.named(it) + }.get() - val extension = extensions.findByName(EXTENSION_NAME) as OpenApiExtension + // The task, used to run the Spring Boot application (`bootRun`) + val bootRunTask = tasks.named(extension.bootRunTaskName.get()) val customBootRun = extension.customBootRun // Create a forked version spring boot run task - val forkedSpringBoot = tasks.named( - FORKED_SPRING_BOOT_RUN_TASK_NAME, - JavaExecFork::class.java - ) { fork -> - fork.dependsOn(tasks.named(bootRunMainClassNameTask.name)) - fork.onlyIf { needToFork(bootRunTask, customBootRun, fork) } + val forkedSpringBoot: TaskProvider = tasks.named( + FORKED_SPRING_BOOT_RUN_TASK_NAME + ) { + this.dependsOn(tasks.named(bootRunMainClassNameTask.name)) + this.onlyIf { needToFork(bootRunTask, customBootRun, this) } } val openApiTask = - tasks.named(OPEN_API_TASK_NAME, OpenApiGeneratorTask::class.java) { + tasks.named(OPEN_API_TASK_NAME, OpenApiGeneratorTask::class.java) { // This is my task. Before I can run it, I have to run the dependent tasks - it.dependsOn(forkedSpringBoot) + this.dependsOn(forkedSpringBoot) // Ensure the task inputs match those of the original application - it.inputs.files(bootRunTask.get().inputs.files) + this.inputs.files(bootRunTask.get().inputs.files) } // The forked task need to be terminated as soon as my task is finished forkedSpringBoot.get().stopAfter = openApiTask as TaskProvider } - private fun Project.springBoot3CompatibilityCheck() { - val tasksNames = tasks.names - val boot2TaskName = "bootRunMainClassName" - val boot3TaskName = "resolveMainClassName" - if (!tasksNames.contains(boot2TaskName) && tasksNames.contains(boot3TaskName)) { - tasks.register(boot2TaskName) { it.dependsOn(tasks.named(boot3TaskName)) } - } - } - private fun needToFork( bootRunTask: TaskProvider, customBootRun: CustomBootRunAction, @@ -101,7 +76,7 @@ open class OpenApiGradlePlugin : Plugin { workingDir = customBootRun.workingDir.asFile.orNull ?: fork.temporaryDir args = customBootRun.args.orNull?.takeIf { it.isNotEmpty() }?.toMutableList() - ?: bootRun.args?.toMutableList() ?: mutableListOf() + ?: bootRun.args.toMutableList() classpath = customBootRun.classpath.takeIf { !it.isEmpty } ?: bootRun.classpath main = customBootRun.mainClass.orNull @@ -110,9 +85,6 @@ open class OpenApiGradlePlugin : Plugin { ?: bootRun.jvmArgs environment = customBootRun.environment.orNull?.takeIf { it.isNotEmpty() } ?: bootRun.environment - if (Jvm.current().toString().startsWith("1.8")) { - killDescendants = false - } } return true } diff --git a/src/test/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePluginTest.kt b/src/test/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePluginTest.kt index bc3e120..71196c9 100644 --- a/src/test/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePluginTest.kt +++ b/src/test/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePluginTest.kt @@ -31,29 +31,34 @@ class OpenApiGradlePluginTest { private val pathsField = "paths" private val openapiField = "openapi" - private val baseBuildGradle = """plugins { + private val baseBuildGradle = + //language=gradle + """ + plugins { id 'java' - id 'org.springframework.boot' version '2.7.6' - id 'io.spring.dependency-management' version '1.0.15.RELEASE' + id 'org.springframework.boot' version '3.4.2' + id 'io.spring.dependency-management' version '1.1.7' id 'org.springdoc.openapi-gradle-plugin' } group = 'com.example' version = '0.0.1-SNAPSHOT' - sourceCompatibility = '8' + sourceCompatibility = '17' repositories { mavenCentral() } dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springdoc:springdoc-openapi-webmvc-core:1.6.13' + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.5") + testImplementation("org.springframework.boot:spring-boot-testcontainers") } """.trimIndent() companion object { val logger: Logger = LoggerFactory.getLogger(OpenApiGradlePluginTest::class.java) + const val DEFAULT_OPENAPI_VERSION = "3.1.0" } @BeforeEach @@ -440,6 +445,23 @@ class OpenApiGradlePluginTest { assertOpenApiJsonFile(2) } + @Test + fun `can run from a different bootRun task`() { + buildFile.writeText( + """ + $baseBuildGradle + openApi { + bootRunTaskName = "$SPRING_BOOT_TEST_RUN_TASK_NAME" + classNameResolveTaskName = "$SPRING_BOOT_RUN_TEST_MAIN_CLASS_NAME_TASK_NAME" + } + """.trimMargin() + ) + + // Run the same build with added source file + assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome) + assertOpenApiJsonFile(2) + } + private fun runTheBuild(vararg additionalArguments: String = emptyArray()) = GradleRunner.create() .withProjectDir(projectTestDir) @@ -453,7 +475,7 @@ class OpenApiGradlePluginTest { buildDir: File = projectBuildDir ) { val openApiJson = getOpenApiJsonAtLocation(File(buildDir, outputJsonFileName)) - assertEquals("3.0.1", openApiJson.string(openapiField)) + assertEquals(DEFAULT_OPENAPI_VERSION, openApiJson.string(openapiField)) assertEquals(expectedPathCount, openApiJson.obj(pathsField)!!.size) } @@ -468,7 +490,7 @@ class OpenApiGradlePluginTest { val mapper = ObjectMapper(YAMLFactory()) mapper.registerModule(KotlinModule.Builder().build()) val node = mapper.readTree(File(buildDir, outputJsonFileName)) - assertEquals("3.0.1", node.get(openapiField).asText()) + assertEquals(DEFAULT_OPENAPI_VERSION, node.get(openapiField).asText()) assertEquals(expectedPathCount, node.get(pathsField)!!.size()) } diff --git a/src/test/resources/acceptance-project/src/main/java/com/example/demo/config/GroupedConfiguration.java b/src/test/resources/acceptance-project/src/main/java/com/example/demo/config/GroupedConfiguration.java index f648861..00c5b31 100644 --- a/src/test/resources/acceptance-project/src/main/java/com/example/demo/config/GroupedConfiguration.java +++ b/src/test/resources/acceptance-project/src/main/java/com/example/demo/config/GroupedConfiguration.java @@ -1,7 +1,7 @@ -package com.example.demo; +package com.example.demo.config; -import org.springdoc.core.GroupedOpenApi; +import org.springdoc.core.models.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; diff --git a/src/test/resources/acceptance-project/src/test/java/com/example/demo/ExtraConfiguration.java b/src/test/resources/acceptance-project/src/test/java/com/example/demo/ExtraConfiguration.java new file mode 100644 index 0000000..b7fe9c3 --- /dev/null +++ b/src/test/resources/acceptance-project/src/test/java/com/example/demo/ExtraConfiguration.java @@ -0,0 +1,17 @@ +package com.example.demo; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@TestConfiguration() +public class ExtraConfiguration { + + @RestController + public static class ExtraController { + @GetMapping("/added") + public String added() { + return "added"; + } + } +} \ No newline at end of file diff --git a/src/test/resources/acceptance-project/src/test/java/com/example/demo/TestDemoApplication.java b/src/test/resources/acceptance-project/src/test/java/com/example/demo/TestDemoApplication.java new file mode 100644 index 0000000..416405c --- /dev/null +++ b/src/test/resources/acceptance-project/src/test/java/com/example/demo/TestDemoApplication.java @@ -0,0 +1,14 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; + +public class TestDemoApplication { + + + public static void main(String[] args) { + SpringApplication.from(DemoApplication::main) + .with(ExtraConfiguration.class) + .run(args); + } + +} \ No newline at end of file