commit bb84603051f37e605e2374cc48b0455c85ecfe32 Author: usbharu <64310155+usbharu@users.noreply.github.com> Date: Sat Oct 7 13:41:23 2023 +0900 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..4bfe3f9 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,70 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.openapitools.generator.gradle.plugin.tasks.GenerateTask + +plugins { + id("org.springframework.boot") version "3.1.4" + id("io.spring.dependency-management") version "1.1.3" + kotlin("jvm") version "1.8.22" + kotlin("plugin.spring") version "1.8.22" + id("org.openapi.generator") version "7.0.1" +} + +group = "dev.usbharu" +version = "0.0.1-SNAPSHOT" + +java { + sourceCompatibility = JavaVersion.VERSION_17 +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("org.jetbrains.kotlin:kotlin-reflect") + testImplementation("org.springframework.boot:spring-boot-starter-test") + + implementation("jakarta.validation:jakarta.validation-api") + implementation("jakarta.annotation:jakarta.annotation-api:2.1.0") + compileOnly("io.swagger.core.v3:swagger-annotations:2.2.6") + implementation("io.swagger.core.v3:swagger-models:2.2.6") +} + +tasks.withType { + kotlinOptions { + freeCompilerArgs += "-Xjsr305=strict" + jvmTarget = "17" + } +} + +tasks.withType { + useJUnitPlatform() +} + +tasks.create("openApiGenerateMastodonCompatibleApi", GenerateTask::class) { + generatorName.set("kotlin-spring") + inputSpec.set("$rootDir/src/main/resources/openapi/mastodon.yaml") + outputDir.set("$buildDir/generated/sources/mastodon") + apiPackage.set("dev.usbharu.hideout.controller.mastodon.generated") + modelPackage.set("dev.usbharu.hideout.domain.mastodon.model.generated") + configOptions.put("interfaceOnly", "true") + configOptions.put("useSpringBoot3", "true") + additionalProperties.put("useTags", "true") + importMappings.put("org.springframework.core.io.Resource", "org.springframework.web.multipart.MultipartFile") + typeMappings.put("org.springframework.core.io.Resource", "org.springframework.web.multipart.MultipartFile") + templateDir.set("$rootDir/templates") + globalProperties.put("debugModels","true") + globalProperties.put("debugOpenAPI","true") + globalProperties.put("debugOperations","true") +} + + +sourceSets.main { + kotlin.srcDirs( + "$buildDir/generated/ksp/main", + "$buildDir/generated/sources/openapi/src/main/kotlin", + "$buildDir/generated/sources/mastodon/src/main/kotlin" + ) +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f4197d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..fcb6fca --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# 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. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# 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/subprojects/plugins/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 +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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +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 ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + 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" && ! "$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=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=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +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" || "$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 + 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 + # 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 +fi + + +# 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, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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 new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +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. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +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. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +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! +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 + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..8c8b57a --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "openapi-spring-boot" diff --git a/src/main/kotlin/dev/usbharu/openapispringboot/DefaultApiImpl.kt b/src/main/kotlin/dev/usbharu/openapispringboot/DefaultApiImpl.kt new file mode 100644 index 0000000..22c83dc --- /dev/null +++ b/src/main/kotlin/dev/usbharu/openapispringboot/DefaultApiImpl.kt @@ -0,0 +1,14 @@ +package dev.usbharu.openapispringboot + +import dev.usbharu.hideout.controller.mastodon.generated.DefaultApi +import dev.usbharu.hideout.domain.mastodon.model.generated.StatusesRequest +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller + +@Controller +class DefaultApiImpl : DefaultApi { + override fun hogePost(statusesRequest: StatusesRequest): ResponseEntity { + println(statusesRequest) + return ResponseEntity.ok(Unit) + } +} diff --git a/src/main/kotlin/dev/usbharu/openapispringboot/JsonOrForm.kt b/src/main/kotlin/dev/usbharu/openapispringboot/JsonOrForm.kt new file mode 100644 index 0000000..47d4ffa --- /dev/null +++ b/src/main/kotlin/dev/usbharu/openapispringboot/JsonOrForm.kt @@ -0,0 +1,6 @@ +package dev.usbharu.openapispringboot + +@MustBeDocumented +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.VALUE_PARAMETER) +annotation class JsonOrForm() diff --git a/src/main/kotlin/dev/usbharu/openapispringboot/JsonOrFormModelMethodProcessor.kt b/src/main/kotlin/dev/usbharu/openapispringboot/JsonOrFormModelMethodProcessor.kt new file mode 100644 index 0000000..202b81b --- /dev/null +++ b/src/main/kotlin/dev/usbharu/openapispringboot/JsonOrFormModelMethodProcessor.kt @@ -0,0 +1,43 @@ +package dev.usbharu.openapispringboot + +import org.springframework.core.MethodParameter +import org.springframework.web.bind.support.WebDataBinderFactory +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.method.annotation.ModelAttributeMethodProcessor +import org.springframework.web.method.support.HandlerMethodArgumentResolver +import org.springframework.web.method.support.ModelAndViewContainer +import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor + +class JsonOrFormModelMethodProcessor( + private val modelAttributeMethodProcessor: ModelAttributeMethodProcessor, + private val requestResponseBodyMethodProcessor: RequestResponseBodyMethodProcessor +) : HandlerMethodArgumentResolver { + override fun supportsParameter(parameter: MethodParameter): Boolean { + return parameter.hasParameterAnnotation(JsonOrForm::class.java) + } + + private val isJsonRegex = Regex("application/((\\w*)\\+)?json") + + override fun resolveArgument( + parameter: MethodParameter, + mavContainer: ModelAndViewContainer?, + webRequest: NativeWebRequest, + binderFactory: WebDataBinderFactory? + ): Any? { + + if (webRequest.getHeader("Content-Type").orEmpty().contains(isJsonRegex)) { + return requestResponseBodyMethodProcessor.resolveArgument( + parameter, + mavContainer, + webRequest, + binderFactory + ) + } + + return try { + modelAttributeMethodProcessor.resolveArgument(parameter, mavContainer, webRequest, binderFactory) + } catch (e: Exception) { + requestResponseBodyMethodProcessor.resolveArgument(parameter, mavContainer, webRequest, binderFactory) + } + } +} diff --git a/src/main/kotlin/dev/usbharu/openapispringboot/MyMvcConfigurer.kt b/src/main/kotlin/dev/usbharu/openapispringboot/MyMvcConfigurer.kt new file mode 100644 index 0000000..a16b20e --- /dev/null +++ b/src/main/kotlin/dev/usbharu/openapispringboot/MyMvcConfigurer.kt @@ -0,0 +1,29 @@ +package dev.usbharu.openapispringboot + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.http.converter.HttpMessageConverter +import org.springframework.web.method.annotation.ModelAttributeMethodProcessor +import org.springframework.web.method.support.HandlerMethodArgumentResolver +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer +import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor +import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor + +@Configuration +class MyMvcConfigurer(private val jsonOrFormModelMethodProcessor: JsonOrFormModelMethodProcessor) : WebMvcConfigurer { + override fun addArgumentResolvers(resolvers: MutableList) { + resolvers.add(jsonOrFormModelMethodProcessor) + } + + +} + +@Configuration +class Config{ + @Bean + fun jsonOrFormModelMethodProcessor(httpMessageConverter:List>):JsonOrFormModelMethodProcessor{ + return JsonOrFormModelMethodProcessor(ServletModelAttributeMethodProcessor(true), + RequestResponseBodyMethodProcessor(httpMessageConverter) + ) + } +} diff --git a/src/main/kotlin/dev/usbharu/openapispringboot/OpenapiSpringBootApplication.kt b/src/main/kotlin/dev/usbharu/openapispringboot/OpenapiSpringBootApplication.kt new file mode 100644 index 0000000..42501c3 --- /dev/null +++ b/src/main/kotlin/dev/usbharu/openapispringboot/OpenapiSpringBootApplication.kt @@ -0,0 +1,11 @@ +package dev.usbharu.openapispringboot + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class OpenapiSpringBootApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/src/main/resources/openapi/mastodon.yaml b/src/main/resources/openapi/mastodon.yaml new file mode 100644 index 0000000..b4b6a85 --- /dev/null +++ b/src/main/resources/openapi/mastodon.yaml @@ -0,0 +1,37 @@ +openapi: 3.0.3 +info: + title: Title + description: Title + version: 1.0.0 +servers: + - url: 'https' +paths: + /hoge: + post: + requestBody: + description: 投稿する内容 + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/StatusesRequest" + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/StatusesRequest" + responses: + 200: + description: ok + description: "" + +components: + schemas: + StatusesRequest: + type: object + properties: + id: + type: string + text: + type: string + required: + - id + - text diff --git a/src/test/kotlin/dev/usbharu/openapispringboot/OpenapiSpringBootApplicationTests.kt b/src/test/kotlin/dev/usbharu/openapispringboot/OpenapiSpringBootApplicationTests.kt new file mode 100644 index 0000000..5a63f87 --- /dev/null +++ b/src/test/kotlin/dev/usbharu/openapispringboot/OpenapiSpringBootApplicationTests.kt @@ -0,0 +1,13 @@ +package dev.usbharu.openapispringboot + +import org.junit.jupiter.api.Test +import org.springframework.boot.test.context.SpringBootTest + +@SpringBootTest +class OpenapiSpringBootApplicationTests { + + @Test + fun contextLoads() { + } + +} diff --git a/templates/api.mustache b/templates/api.mustache new file mode 100644 index 0000000..3d547ad --- /dev/null +++ b/templates/api.mustache @@ -0,0 +1,95 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +{{#swagger2AnnotationLibrary}} +import io.swagger.v3.oas.annotations.* +import io.swagger.v3.oas.annotations.enums.* +import io.swagger.v3.oas.annotations.media.* +import io.swagger.v3.oas.annotations.responses.* +import io.swagger.v3.oas.annotations.security.* +{{/swagger2AnnotationLibrary}} +{{#swagger1AnnotationLibrary}} +import io.swagger.annotations.Api +import io.swagger.annotations.ApiOperation +import io.swagger.annotations.ApiParam +import io.swagger.annotations.ApiResponse +import io.swagger.annotations.ApiResponses +import io.swagger.annotations.Authorization +import io.swagger.annotations.AuthorizationScope +{{/swagger1AnnotationLibrary}} +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity + +import org.springframework.web.bind.annotation.* +{{#useBeanValidation}} +import org.springframework.validation.annotation.Validated +{{/useBeanValidation}} +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.beans.factory.annotation.Autowired + +{{#useBeanValidation}} +import {{javaxPackage}}.validation.Valid +import {{javaxPackage}}.validation.constraints.DecimalMax +import {{javaxPackage}}.validation.constraints.DecimalMin +import {{javaxPackage}}.validation.constraints.Email +import {{javaxPackage}}.validation.constraints.Max +import {{javaxPackage}}.validation.constraints.Min +import {{javaxPackage}}.validation.constraints.NotNull +import {{javaxPackage}}.validation.constraints.Pattern +import {{javaxPackage}}.validation.constraints.Size +{{/useBeanValidation}} + +{{#reactive}} +import kotlinx.coroutines.flow.Flow +{{/reactive}} +import kotlin.collections.List +import kotlin.collections.Map + +@RestController{{#beanQualifiers}}("{{package}}.{{classname}}Controller"){{/beanQualifiers}} +{{#useBeanValidation}} +@Validated +{{/useBeanValidation}} +{{#swagger1AnnotationLibrary}} +@Api(value = "{{{baseName}}}", description = "The {{{baseName}}} API") +{{/swagger1AnnotationLibrary}} +{{=<% %>=}} +@RequestMapping("\${api.base-path:<%contextPath%>}") +<%={{ }}=%> +{{#operations}} +class {{classname}}Controller({{#serviceInterface}}@Autowired(required = true) val service: {{classname}}Service{{/serviceInterface}}) { +{{#operation}} + + {{#swagger2AnnotationLibrary}} + @Operation( + summary = "{{{summary}}}", + operationId = "{{{operationId}}}", + description = """{{{unescapedNotes}}}""", + responses = [{{#responses}} + ApiResponse(responseCode = "{{{code}}}", description = "{{{message}}}"{{#baseType}}, content = [Content({{#isArray}}array = ArraySchema({{/isArray}}schema = Schema(implementation = {{{baseType}}}::class)){{#isArray}}){{/isArray}}]{{/baseType}}){{^-last}},{{/-last}}{{/responses}} ]{{#hasAuthMethods}}, + security = [ {{#authMethods}}SecurityRequirement(name = "{{name}}"{{#isOAuth}}, scopes = [ {{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}} ]{{/isOAuth}}){{^-last}},{{/-last}}{{/authMethods}} ]{{/hasAuthMethods}} + ){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiOperation( + value = "{{{summary}}}", + nickname = "{{{operationId}}}", + notes = "{{{notes}}}"{{#returnBaseType}}, + response = {{{.}}}::class{{/returnBaseType}}{{#returnContainer}}, + responseContainer = "{{{.}}}"{{/returnContainer}}{{#hasAuthMethods}}, + authorizations = [{{#authMethods}}Authorization(value = "{{name}}"{{#isOAuth}}, scopes = [{{#scopes}}AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}}, {{/-last}}{{/scopes}}]{{/isOAuth}}){{^-last}}, {{/-last}}{{/authMethods}}]{{/hasAuthMethods}}) + @ApiResponses( + value = [{{#responses}}ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{#baseType}}, response = {{{.}}}::class{{/baseType}}{{#containerType}}, responseContainer = "{{{.}}}"{{/containerType}}){{^-last}},{{/-last}}{{/responses}}]){{/swagger1AnnotationLibrary}} + @RequestMapping( + method = [RequestMethod.{{httpMethod}}], + value = ["{{#lambda.escapeDoubleQuote}}{{path}}{{/lambda.escapeDoubleQuote}}"]{{#singleContentTypes}}{{#hasProduces}}, + produces = "{{{vendorExtensions.x-accepts}}}"{{/hasProduces}}{{#hasConsumes}}, + consumes = "{{{vendorExtensions.x-content-type}}}"{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}, + produces = [{{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}]{{/hasProduces}}{{#hasConsumes}}, + consumes = [{{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/singleContentTypes}} + ) + {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}): ResponseEntity<{{>returnTypes}}> { + return {{>returnValue}} + } +{{/operation}} +} +{{/operations}} diff --git a/templates/apiController.mustache b/templates/apiController.mustache new file mode 100644 index 0000000..54cd62e --- /dev/null +++ b/templates/apiController.mustache @@ -0,0 +1,25 @@ +package {{package}} + +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestMapping +import java.util.Optional +import dev.usbharu.openapispringboot.JsonOrForm + +{{>generatedAnnotation}} +@Controller{{#beanQualifiers}}("{{package}}.{{classname}}Controller"){{/beanQualifiers}} +{{=<% %>=}} +@RequestMapping("\${openapi.<%title%>.base-path:<%>defaultBasePath%>}") +<%={{ }}=%> +{{#operations}} +class {{classname}}Controller( + @org.springframework.beans.factory.annotation.Autowired(required = false) delegate: {{classname}}Delegate? +) : {{classname}} { + private val delegate: {{classname}}Delegate + + init { + this.delegate = Optional.ofNullable(delegate).orElse(object : {{classname}}Delegate {}) + } + + override fun getDelegate(): {{classname}}Delegate = delegate +} +{{/operations}} diff --git a/templates/apiDelegate.mustache b/templates/apiDelegate.mustache new file mode 100644 index 0000000..3b2955a --- /dev/null +++ b/templates/apiDelegate.mustache @@ -0,0 +1,40 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.core.io.Resource +{{#reactive}} +import kotlinx.coroutines.flow.Flow +{{/reactive}} + +import java.util.Optional +{{#async}} +import java.util.concurrent.CompletableFuture +{{/async}} + +{{#operations}} +/** + * A delegate to be called by the {@link {{classname}}Controller}}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. + */ +{{>generatedAnnotation}} +interface {{classname}}Delegate { + + fun getRequest(): Optional = Optional.empty() +{{#operation}} + + /** + * @see {{classname}}#{{operationId}} + */ + {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{paramName}}: {{^isFile}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}{{#isBodyParam}}Flow<{{{baseType}}}>{{/isBodyParam}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{/isArray}}{{/reactive}}{{/isFile}}{{#isFile}}Resource?{{/isFile}}{{^-last}}, + {{/-last}}{{/allParams}}): {{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} { + {{>methodBody}} + } + +{{/operation}} +} +{{/operations}} diff --git a/templates/apiInterface.mustache b/templates/apiInterface.mustache new file mode 100644 index 0000000..3f96cde --- /dev/null +++ b/templates/apiInterface.mustache @@ -0,0 +1,112 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) ({{{generatorVersion}}}). + * https://openapi-generator.tech + * Do not edit the class manually. +*/ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +{{#swagger2AnnotationLibrary}} +import io.swagger.v3.oas.annotations.* +import io.swagger.v3.oas.annotations.enums.* +import io.swagger.v3.oas.annotations.media.* +import io.swagger.v3.oas.annotations.responses.* +import io.swagger.v3.oas.annotations.security.* +{{/swagger2AnnotationLibrary}} +{{#swagger1AnnotationLibrary}} +import io.swagger.annotations.Api +import io.swagger.annotations.ApiOperation +import io.swagger.annotations.ApiParam +import io.swagger.annotations.ApiResponse +import io.swagger.annotations.ApiResponses +import io.swagger.annotations.Authorization +import io.swagger.annotations.AuthorizationScope +{{/swagger1AnnotationLibrary}} +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity + +import org.springframework.web.bind.annotation.* +{{#useBeanValidation}} +import org.springframework.validation.annotation.Validated +{{/useBeanValidation}} +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.beans.factory.annotation.Autowired + +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.DecimalMax +import {{javaxPackage}}.validation.constraints.DecimalMin +import {{javaxPackage}}.validation.constraints.Email +import {{javaxPackage}}.validation.constraints.Max +import {{javaxPackage}}.validation.constraints.Min +import {{javaxPackage}}.validation.constraints.NotNull +import {{javaxPackage}}.validation.constraints.Pattern +import {{javaxPackage}}.validation.constraints.Size +import {{javaxPackage}}.validation.Valid +{{/useBeanValidation}} + +{{#reactive}} +import kotlinx.coroutines.flow.Flow +{{/reactive}} +import kotlin.collections.List +import kotlin.collections.Map +import dev.usbharu.openapispringboot.JsonOrForm + +{{#useBeanValidation}} +@Validated +{{/useBeanValidation}} +{{#swagger1AnnotationLibrary}} +@Api(value = "{{{baseName}}}", description = "The {{{baseName}}} API") +{{/swagger1AnnotationLibrary}} +{{^useFeignClient}} +{{=<% %>=}} +@RequestMapping("\${api.base-path:<%contextPath%>}") +<%={{ }}=%> +{{/useFeignClient}} +{{#operations}} +interface {{classname}} { +{{#isDelegate}} + + fun getDelegate(): {{classname}}Delegate = object: {{classname}}Delegate {} +{{/isDelegate}} +{{#operation}} + + {{#swagger2AnnotationLibrary}} + @Operation( + summary = "{{{summary}}}", + operationId = "{{{operationId}}}", + description = """{{{unescapedNotes}}}""", + responses = [{{#responses}} + ApiResponse(responseCode = "{{{code}}}", description = "{{{message}}}"{{#baseType}}, content = [Content({{#isArray}}array = ArraySchema({{/isArray}}schema = Schema(implementation = {{{baseType}}}::class)){{#isArray}}){{/isArray}}]{{/baseType}}){{^-last}},{{/-last}}{{/responses}} + ]{{#hasAuthMethods}}, + security = [ {{#authMethods}}SecurityRequirement(name = "{{name}}"{{#isOAuth}}, scopes = [ {{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}} ]{{/isOAuth}}){{^-last}},{{/-last}}{{/authMethods}} ]{{/hasAuthMethods}} + ){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiOperation( + value = "{{{summary}}}", + nickname = "{{{operationId}}}", + notes = "{{{notes}}}"{{#returnBaseType}}, + response = {{{.}}}::class{{/returnBaseType}}{{#returnContainer}}, + responseContainer = "{{{.}}}"{{/returnContainer}}{{#hasAuthMethods}}, + authorizations = [{{#authMethods}}Authorization(value = "{{name}}"{{#isOAuth}}, scopes = [{{#scopes}}AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}}, {{/-last}}{{/scopes}}]{{/isOAuth}}){{^-last}}, {{/-last}}{{/authMethods}}]{{/hasAuthMethods}}) + @ApiResponses( + value = [{{#responses}}ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{#baseType}}, response = {{{.}}}::class{{/baseType}}{{#containerType}}, responseContainer = "{{{.}}}"{{/containerType}}){{^-last}}, {{/-last}}{{/responses}}]){{/swagger1AnnotationLibrary}} + @RequestMapping( + method = [RequestMethod.{{httpMethod}}], + value = ["{{#lambda.escapeDoubleQuote}}{{path}}{{/lambda.escapeDoubleQuote}}"]{{#singleContentTypes}}{{#hasProduces}}, + produces = "{{{vendorExtensions.x-accepts}}}"{{/hasProduces}}{{#hasConsumes}}, + consumes = "{{{vendorExtensions.x-content-type}}}"{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}, + produces = [{{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}]{{/hasProduces}}{{#hasConsumes}}, + consumes = [{{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/singleContentTypes}} + ) + {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}): ResponseEntity<{{>returnTypes}}>{{^skipDefaultInterface}} { + {{^isDelegate}} + return {{>returnValue}} + {{/isDelegate}} + {{#isDelegate}} + return getDelegate().{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) + {{/isDelegate}} + }{{/skipDefaultInterface}} +{{/operation}} +} +{{/operations}} diff --git a/templates/apiUtil.mustache b/templates/apiUtil.mustache new file mode 100644 index 0000000..3bb4c7a --- /dev/null +++ b/templates/apiUtil.mustache @@ -0,0 +1,23 @@ +package {{apiPackage}} + +{{^reactive}} +import org.springframework.web.context.request.NativeWebRequest + +import {{javaxPackage}}.servlet.http.HttpServletResponse +import java.io.IOException +{{/reactive}} + +object ApiUtil { +{{^reactive}} + fun setExampleResponse(req: NativeWebRequest, contentType: String, example: String) { + try { + val res = req.getNativeResponse(HttpServletResponse::class.java) + res?.characterEncoding = "UTF-8" + res?.addHeader("Content-Type", contentType) + res?.writer?.print(example) + } catch (e: IOException) { + throw RuntimeException(e) + } + } +{{/reactive}} +} diff --git a/templates/api_test.mustache b/templates/api_test.mustache new file mode 100644 index 0000000..bf35157 --- /dev/null +++ b/templates/api_test.mustache @@ -0,0 +1,38 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +import org.junit.jupiter.api.Test +{{#reactive}} +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.test.runBlockingTest +{{/reactive}} +import org.springframework.http.ResponseEntity + +class {{classname}}Test { + + {{#serviceInterface}} + private val service: {{classname}}Service = {{classname}}ServiceImpl() + {{/serviceInterface}} + private val api: {{classname}}Controller = {{classname}}Controller({{#serviceInterface}}service{{/serviceInterface}}) + {{#operations}} + {{#operation}} + + /** + * To test {{classname}}Controller.{{operationId}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + fun {{operationId}}Test() {{#reactive}}= runBlockingTest {{/reactive}}{ + {{#allParams}} + val {{{paramName}}}: {{>optionalDataType}} = TODO() + {{/allParams}} + val response: ResponseEntity<{{>returnTypes}}> = api.{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + + // TODO: test validations + } + {{/operation}} + {{/operations}} +} diff --git a/templates/beanValidation.mustache b/templates/beanValidation.mustache new file mode 100644 index 0000000..ee25df4 --- /dev/null +++ b/templates/beanValidation.mustache @@ -0,0 +1,4 @@ +{{#isContainer}}{{^isPrimitiveType}}{{^isEnum}} + @field:Valid{{/isEnum}}{{/isPrimitiveType}}{{/isContainer}}{{! +}}{{^isContainer}}{{^isPrimitiveType}}{{^isNumber}}{{^isUuid}}{{^isDateTime}} + @field:Valid{{/isDateTime}}{{/isUuid}}{{/isNumber}}{{/isPrimitiveType}}{{/isContainer}} \ No newline at end of file diff --git a/templates/beanValidationModel.mustache b/templates/beanValidationModel.mustache new file mode 100644 index 0000000..9963531 --- /dev/null +++ b/templates/beanValidationModel.mustache @@ -0,0 +1,38 @@ +{{! +format: email +}}{{#isEmail}} + @get:Email{{/isEmail}}{{! +pattern set +}}{{#pattern}} + @get:Pattern(regexp="{{{.}}}"){{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}} + @get:Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}} + @get:Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}} + @get:Size(max={{.}}){{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}} + @get:Size(min={{minItems}},max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}} + @get:Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}} + @get:Size(max={{.}}){{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}} + @get:Min({{.}}){{/minimum}}{{#maximum}} + @get:Max({{.}}){{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}} + @get:Min({{.}}L){{/minimum}}{{#maximum}} + @get:Max({{.}}L){{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}} + @get:DecimalMin("{{.}}"){{/minimum}}{{#maximum}} + @get:DecimalMax("{{.}}"){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/templates/beanValidationPath.mustache b/templates/beanValidationPath.mustache new file mode 100644 index 0000000..8eb9029 --- /dev/null +++ b/templates/beanValidationPath.mustache @@ -0,0 +1,22 @@ +{{#isEmail}}@Email {{/isEmail}}{{! +pattern set +}}{{#pattern}}@Pattern(regexp="{{{.}}}") {{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}}@Size(min={{minLength}},max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}}@Size(min={{minLength}}) {{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}}@Size(max={{.}}) {{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}}@Size(min={{minItems}},max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}}@Size(min={{minItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}}@Size(max={{.}}) {{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}}@Min({{.}}){{/minimum}}{{#maximum}} @Max({{.}}) {{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}}@Min({{.}}L){{/minimum}}{{#maximum}} @Max({{.}}L) {{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}}@DecimalMin("{{.}}"){{/minimum}}{{#maximum}} @DecimalMax("{{.}}") {{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/templates/beanValidationPathParams.mustache b/templates/beanValidationPathParams.mustache new file mode 100644 index 0000000..3c57e76 --- /dev/null +++ b/templates/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationPath}} \ No newline at end of file diff --git a/templates/beanValidationQueryParams.mustache b/templates/beanValidationQueryParams.mustache new file mode 100644 index 0000000..cc53bc9 --- /dev/null +++ b/templates/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}}@NotNull {{/required}}{{>beanValidationPath}} \ No newline at end of file diff --git a/templates/bodyParams.mustache b/templates/bodyParams.mustache new file mode 100644 index 0000000..723e7d7 --- /dev/null +++ b/templates/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{^isContainer}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = ["{{{allowableValues}}}"], defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = ["{{{allowableValues}}}"]){{/defaultValue}}{{/allowableValues}}{{/isContainer}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{^isContainer}}{{#allowableValues}}, allowableValues = "{{{.}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @JsonOrForm {{{paramName}}}: {{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}} diff --git a/templates/dataClass.mustache b/templates/dataClass.mustache new file mode 100644 index 0000000..e56f233 --- /dev/null +++ b/templates/dataClass.mustache @@ -0,0 +1,33 @@ +/** + * {{{description}}} +{{#vars}} + * @param {{name}} {{{description}}} +{{/vars}} + */{{#discriminator}} +{{>typeInfoAnnotation}}{{/discriminator}} +{{#discriminator}}interface {{classname}}{{/discriminator}}{{^discriminator}}{{#hasVars}}data {{/hasVars}}class {{classname}}( +{{#requiredVars}} +{{>dataClassReqVar}}{{^-last}}, +{{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, +{{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>dataClassOptVar}}{{^-last}}, +{{/-last}}{{/optionalVars}} +) {{/discriminator}}{{#parent}}: {{{.}}}{{/parent}}{ +{{#discriminator}} + {{#requiredVars}} + {{>interfaceReqVar}} + {{/requiredVars}} + {{#optionalVars}} + {{>interfaceOptVar}} + {{/optionalVars}} +{{/discriminator}} +{{#hasEnums}}{{#vars}}{{#isEnum}} + /** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + */ + enum class {{{nameInCamelCase}}}(val value: {{#isContainer}}{{#items}}{{{dataType}}}{{/items}}{{/isContainer}}{{^isContainer}}{{{dataType}}}{{/isContainer}}) { +{{#allowableValues}}{{#enumVars}} + @JsonProperty({{{value}}}) {{{name}}}({{{value}}}){{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + } +{{/isEnum}}{{/vars}}{{/hasEnums}} +} diff --git a/templates/dataClassOptVar.mustache b/templates/dataClassOptVar.mustache new file mode 100644 index 0000000..211736d --- /dev/null +++ b/templates/dataClassOptVar.mustache @@ -0,0 +1,5 @@ +{{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}} + @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}}{{#deprecated}} + @Deprecated(message = ""){{/deprecated}} + @get:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInCamelCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}} \ No newline at end of file diff --git a/templates/dataClassReqVar.mustache b/templates/dataClassReqVar.mustache new file mode 100644 index 0000000..d8bb06a --- /dev/null +++ b/templates/dataClassReqVar.mustache @@ -0,0 +1,4 @@ +{{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}} + @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} + @get:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInCamelCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}?{{/isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}} \ No newline at end of file diff --git a/templates/enumClass.mustache b/templates/enumClass.mustache new file mode 100644 index 0000000..5728753 --- /dev/null +++ b/templates/enumClass.mustache @@ -0,0 +1,8 @@ +/** +* {{{description}}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +*/ +enum class {{classname}}(val value: {{dataType}}) { +{{#allowableValues}}{{#enumVars}} + @JsonProperty({{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +} diff --git a/templates/exceptions.mustache b/templates/exceptions.mustache new file mode 100644 index 0000000..339e5d0 --- /dev/null +++ b/templates/exceptions.mustache @@ -0,0 +1,29 @@ +package {{apiPackage}} + +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler +import {{javaxPackage}}.servlet.http.HttpServletResponse +import {{javaxPackage}}.validation.ConstraintViolationException + +// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception +sealed class ApiException(msg: String, val code: Int) : Exception(msg) + +class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) + + +@ControllerAdvice +class DefaultExceptionHandler { + + @ExceptionHandler(value = [ApiException::class]) + fun onApiException(ex: ApiException, response: HttpServletResponse): Unit = + response.sendError(ex.code, ex.message) + + @ExceptionHandler(value = [NotImplementedError::class]) + fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.NOT_IMPLEMENTED.value()) + + @ExceptionHandler(value = [ConstraintViolationException::class]) + fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message }) +} diff --git a/templates/formParams.mustache b/templates/formParams.mustache new file mode 100644 index 0000000..ec72b53 --- /dev/null +++ b/templates/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{paramName}}: {{>optionalDataType}} {{/isFile}}{{#isFile}}{{#swagger2AnnotationLibrary}}@Parameter(description = "file detail"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "file detail"){{/swagger1AnnotationLibrary}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("file") {{baseName}}: {{>optionalDataType}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/templates/generatedAnnotation.mustache b/templates/generatedAnnotation.mustache new file mode 100644 index 0000000..1be8e75 --- /dev/null +++ b/templates/generatedAnnotation.mustache @@ -0,0 +1 @@ +@{{javaxPackage}}.annotation.Generated(value = ["{{generatorClass}}"]{{^hideGenerationTimestamp}}, date = "{{generatedDate}}"{{/hideGenerationTimestamp}}) \ No newline at end of file diff --git a/templates/headerParams.mustache b/templates/headerParams.mustache new file mode 100644 index 0000000..9bc3f60 --- /dev/null +++ b/templates/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{#useBeanValidation}}{{>beanValidationPath}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}", `in` = ParameterIn.HEADER{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{paramName}}: {{>optionalDataType}}{{/isHeaderParam}} \ No newline at end of file diff --git a/templates/homeController.mustache b/templates/homeController.mustache new file mode 100644 index 0000000..609ebcd --- /dev/null +++ b/templates/homeController.mustache @@ -0,0 +1,89 @@ +package {{basePackage}} + +import org.springframework.context.annotation.Bean +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestMapping +{{#sourceDocumentationProvider}} +import com.fasterxml.jackson.dataformat.yaml.YAMLMapper +import org.springframework.beans.factory.annotation.Value +import org.springframework.core.io.Resource +import org.springframework.util.StreamUtils +import org.springframework.web.bind.annotation.ResponseBody +import org.springframework.web.bind.annotation.GetMapping +{{/sourceDocumentationProvider}} +{{^sourceDocumentationProvider}} +{{#useSwaggerUI}} +import org.springframework.web.bind.annotation.ResponseBody +import org.springframework.web.bind.annotation.GetMapping +{{/useSwaggerUI}} +{{/sourceDocumentationProvider}} +{{#reactive}} +import org.springframework.web.reactive.function.server.HandlerFunction +import org.springframework.web.reactive.function.server.RequestPredicates.GET +import org.springframework.web.reactive.function.server.RouterFunction +import org.springframework.web.reactive.function.server.RouterFunctions.route +import org.springframework.web.reactive.function.server.ServerResponse +import java.net.URI +{{/reactive}} +{{#sourceDocumentationProvider}} +import java.nio.charset.Charset +{{/sourceDocumentationProvider}} + +/** + * Home redirection to OpenAPI api documentation + */ +@Controller +class HomeController { +{{#useSwaggerUI}} +{{^springDocDocumentationProvider}} +{{#sourceDocumentationProvider}} + private val apiDocsPath = "/openapi.json" +{{/sourceDocumentationProvider}} +{{#springFoxDocumentationProvider}} + private val apiDocsPath = "/v2/api-docs" +{{/springFoxDocumentationProvider}} +{{/springDocDocumentationProvider}} +{{/useSwaggerUI}} +{{#sourceDocumentationProvider}} + private val yamlMapper = YAMLMapper() + + @Value("classpath:/openapi.yaml") + private lateinit var openapi: Resource + + @Bean + fun openapiContent(): String { + return openapi.inputStream.use { + StreamUtils.copyToString(it, Charset.defaultCharset()) + } + } + + @GetMapping(value = ["/openapi.yaml"], produces = ["application/vnd.oai.openapi"]) + @ResponseBody + fun openapiYaml(): String = openapiContent() + + @GetMapping(value = ["/openapi.json"], produces = ["application/json"]) + @ResponseBody + fun openapiJson(): Any = yamlMapper.readValue(openapiContent(), Any::class.java) +{{/sourceDocumentationProvider}} +{{#useSwaggerUI}} +{{^springDocDocumentationProvider}} + + @GetMapping(value = ["/swagger-config.yaml"], produces = ["text/plain"]) + @ResponseBody + fun swaggerConfig(): String = "url: $apiDocsPath\n" +{{/springDocDocumentationProvider}} +{{#reactive}} + + @Bean + fun index(): RouterFunction = route( + GET("/"), HandlerFunction { + ServerResponse.temporaryRedirect(URI.create("swagger-ui.html")).build() + }) +{{/reactive}} +{{^reactive}} + + @RequestMapping("/") + fun index(): String = "redirect:swagger-ui.html" +{{/reactive}} +{{/useSwaggerUI}} +} diff --git a/templates/interfaceOptVar.mustache b/templates/interfaceOptVar.mustache new file mode 100644 index 0000000..00ee2b1 --- /dev/null +++ b/templates/interfaceOptVar.mustache @@ -0,0 +1,4 @@ +{{#swagger2AnnotationLibrary}} + @get:Schema({{#example}}example = "{{{.}}}", {{/example}}{{#required}}requiredMode = Schema.RequiredMode.REQUIRED, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @get:ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} + {{>modelMutable}} {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? {{^discriminator}}= {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}{{/discriminator}} diff --git a/templates/interfaceReqVar.mustache b/templates/interfaceReqVar.mustache new file mode 100644 index 0000000..53c3b9c --- /dev/null +++ b/templates/interfaceReqVar.mustache @@ -0,0 +1,4 @@ +{{#swagger2AnnotationLibrary}} + @get:Schema({{#example}}example = "{{{.}}}", {{/example}}{{#required}}requiredMode = Schema.RequiredMode.REQUIRED, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @get:ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} + {{>modelMutable}} {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} diff --git a/templates/libraries/spring-boot/README.mustache b/templates/libraries/spring-boot/README.mustache new file mode 100644 index 0000000..c75176b --- /dev/null +++ b/templates/libraries/spring-boot/README.mustache @@ -0,0 +1,21 @@ +# {{title}}{{^title}}Generated Kotlin Spring Boot App{{/title}} + +This Kotlin based [Spring Boot](https://spring.io/projects/spring-boot) application has been generated using the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +## Getting Started + +This document assumes you have either maven or gradle available, either via the wrapper or otherwise. This does not come with a gradle / maven wrapper checked in. + +By default a [`pom.xml`](pom.xml) file will be generated. If you specified `gradleBuildFile=true` when generating this project, a `build.gradle.kts` will also be generated. Note this uses [Gradle Kotlin DSL](https://github.com/gradle/kotlin-dsl). + +To build the project using maven, run: +```bash +mvn package && java -jar target/{{artifactId}}-{{artifactVersion}}.jar +``` + +To build the project using gradle, run: +```bash +gradle build && java -jar build/libs/{{artifactId}}-{{artifactVersion}}.jar +``` + +If all builds successfully, the server should run on [http://localhost:8080/](http://localhost:{{serverPort}}/) diff --git a/templates/libraries/spring-boot/application.mustache b/templates/libraries/spring-boot/application.mustache new file mode 100644 index 0000000..9bc4fb4 --- /dev/null +++ b/templates/libraries/spring-boot/application.mustache @@ -0,0 +1,10 @@ +spring: + application: + name: {{title}} + + jackson: + serialization: + WRITE_DATES_AS_TIMESTAMPS: false + +server: + port: {{serverPort}} diff --git a/templates/libraries/spring-boot/buildGradle-sb3-Kts.mustache b/templates/libraries/spring-boot/buildGradle-sb3-Kts.mustache new file mode 100644 index 0000000..7f4a6f3 --- /dev/null +++ b/templates/libraries/spring-boot/buildGradle-sb3-Kts.mustache @@ -0,0 +1,57 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +group = "{{groupId}}" +version = "{{artifactVersion}}" +java.sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenCentral() + maven { url = uri("https://repo.spring.io/milestone") } +} + +tasks.withType { + kotlinOptions.jvmTarget = "17" +} + +plugins { + val kotlinVersion = "1.7.10" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "3.0.2" + id("io.spring.dependency-management") version "1.0.14.RELEASE" +} + +dependencies { +{{#reactive}} val kotlinxCoroutinesVersion = "1.6.1" +{{/reactive}} implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + implementation("org.jetbrains.kotlin:kotlin-reflect"){{^reactive}} + implementation("org.springframework.boot:spring-boot-starter-web"){{/reactive}}{{#reactive}} + implementation("org.springframework.boot:spring-boot-starter-webflux") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinxCoroutinesVersion") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:$kotlinxCoroutinesVersion"){{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + implementation("org.springdoc:springdoc-openapi-starter-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-ui:2.0.0-M5"){{/useSwaggerUI}}{{^useSwaggerUI}} + implementation("org.springdoc:springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core:2.0.0-M5"){{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + implementation("io.springfox:springfox-swagger2:2.9.2"){{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + implementation("org.webjars:swagger-ui:4.10.3") + implementation("org.webjars:webjars-locator-core"){{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + implementation("io.swagger:swagger-annotations:1.6.6"){{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + implementation("io.swagger.core.v3:swagger-annotations:2.2.0"){{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + implementation("com.google.code.findbugs:jsr305:3.0.2") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") +{{#useBeanValidation}} + implementation("jakarta.validation:jakarta.validation-api"){{/useBeanValidation}} + implementation("jakarta.annotation:jakarta.annotation-api:2.1.0") + + testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") + testImplementation("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +{{#reactive}} + testImplementation`("org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlinxCoroutinesVersion") +{{/reactive}} +} diff --git a/templates/libraries/spring-boot/buildGradleKts.mustache b/templates/libraries/spring-boot/buildGradleKts.mustache new file mode 100644 index 0000000..77abd06 --- /dev/null +++ b/templates/libraries/spring-boot/buildGradleKts.mustache @@ -0,0 +1,64 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.6.7") + } +} + +group = "{{groupId}}" +version = "{{artifactVersion}}" + +repositories { + mavenCentral() +} + +tasks.withType { + kotlinOptions.jvmTarget = "1.8" +} + +plugins { + val kotlinVersion = "1.6.21" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "2.6.7" + id("io.spring.dependency-management") version "1.0.11.RELEASE" +} + +dependencies { +{{#reactive}} val kotlinxCoroutinesVersion = "1.6.1" +{{/reactive}} compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + compile("org.jetbrains.kotlin:kotlin-reflect"){{^reactive}} + compile("org.springframework.boot:spring-boot-starter-web"){{/reactive}}{{#reactive}} + compile("org.springframework.boot:spring-boot-starter-webflux") + compile("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinxCoroutinesVersion") + compile("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:$kotlinxCoroutinesVersion"){{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + compile("org.springdoc:springdoc-openapi-{{#reactive}}webflux-{{/reactive}}ui:1.6.8"){{/useSwaggerUI}}{{^useSwaggerUI}} + compile("org.springdoc:springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core:1.6.8"){{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + compile("io.springfox:springfox-swagger2:2.9.2"){{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + compile("org.webjars:swagger-ui:4.10.3") + compile("org.webjars:webjars-locator-core"){{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + compile("io.swagger:swagger-annotations:1.6.6"){{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + compile("io.swagger.core.v3:swagger-annotations:2.2.0"){{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + compile("com.google.code.findbugs:jsr305:3.0.2") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + compile("com.fasterxml.jackson.module:jackson-module-kotlin") +{{#useBeanValidation}} + compile("jakarta.validation:jakarta.validation-api"){{/useBeanValidation}} + compile("jakarta.annotation:jakarta.annotation-api:2.1.0") + + testCompile("org.jetbrains.kotlin:kotlin-test-junit5") + testCompile("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +{{#reactive}} + testCompile("org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlinxCoroutinesVersion") +{{/reactive}} +} diff --git a/templates/libraries/spring-boot/defaultBasePath.mustache b/templates/libraries/spring-boot/defaultBasePath.mustache new file mode 100644 index 0000000..3c7185b --- /dev/null +++ b/templates/libraries/spring-boot/defaultBasePath.mustache @@ -0,0 +1 @@ +{{contextPath}} \ No newline at end of file diff --git a/templates/libraries/spring-boot/pom-sb3.mustache b/templates/libraries/spring-boot/pom-sb3.mustache new file mode 100644 index 0000000..c2daa5a --- /dev/null +++ b/templates/libraries/spring-boot/pom-sb3.mustache @@ -0,0 +1,200 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{#reactive}} + 1.6.1{{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + 2.0.2{{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + 2.9.2{{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + 4.15.5{{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + 1.6.6{{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + 2.2.7{{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + 3.0.2 + 2.1.0 + 1.7.10 + + 1.7.10 + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 3.0.2 + + + + repository.spring.milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + + + + spring-milestones + https://repo.spring.io/milestone + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + {{^interfaceOnly}} + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + {{/interfaceOnly}} + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 17 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + {{^reactive}} + + org.springframework.boot + spring-boot-starter-web + {{/reactive}}{{#reactive}} + + org.springframework.boot + spring-boot-starter-webflux + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + {{/reactive}} + +{{#springDocDocumentationProvider}} + {{#useSwaggerUI}} + + org.springdoc + springdoc-openapi-starter-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-ui + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{^useSwaggerUI}} + + org.springdoc + springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + + + io.springfox + springfox-swagger2 + ${springfox-swagger2.version} + {{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + + org.webjars + swagger-ui + ${swagger-ui.version} + + + org.webjars + webjars-locator-core + {{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + + io.swagger + swagger-annotations + ${swagger-annotations.version} + {{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + + io.swagger.core.v3 + swagger-annotations + ${swagger-annotations.version} + {{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + + + com.google.code.findbugs + jsr305 + ${findbugs-jsr305.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.fasterxml.jackson.module + jackson-module-kotlin + +{{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + {{/useBeanValidation}} + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation.version} + provided + + + org.jetbrains.kotlin + kotlin-test-junit5 + ${kotlin-test-junit5.version} + test + + + diff --git a/templates/libraries/spring-boot/pom.mustache b/templates/libraries/spring-boot/pom.mustache new file mode 100644 index 0000000..dcf1330 --- /dev/null +++ b/templates/libraries/spring-boot/pom.mustache @@ -0,0 +1,187 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{#reactive}} + 1.6.1{{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + 1.6.8{{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + 2.9.2{{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + 4.10.3{{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + 1.6.6{{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + 2.2.0{{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + 3.0.2 + 2.1.0 + 1.6.21 + + 1.6.21 + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + {{^interfaceOnly}} + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + {{/interfaceOnly}} + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 1.8 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + {{^reactive}} + + org.springframework.boot + spring-boot-starter-web + {{/reactive}}{{#reactive}} + + org.springframework.boot + spring-boot-starter-webflux + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + {{/reactive}} + +{{#springDocDocumentationProvider}} + {{#useSwaggerUI}} + + org.springdoc + springdoc-openapi-{{#reactive}}webflux-{{/reactive}}ui + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{^useSwaggerUI}} + + org.springdoc + springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + + + io.springfox + springfox-swagger2 + ${springfox-swagger2.version} + {{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + + org.webjars + swagger-ui + ${swagger-ui.version} + + + org.webjars + webjars-locator-core + {{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + + io.swagger + swagger-annotations + ${swagger-annotations.version} + {{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + + io.swagger.core.v3 + swagger-annotations + ${swagger-annotations.version} + {{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + + + com.google.code.findbugs + jsr305 + ${findbugs-jsr305.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.fasterxml.jackson.module + jackson-module-kotlin + +{{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + {{/useBeanValidation}} + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation.version} + provided + + + org.jetbrains.kotlin + kotlin-test-junit5 + ${kotlin-test-junit5.version} + test + + + diff --git a/templates/libraries/spring-boot/settingsGradle.mustache b/templates/libraries/spring-boot/settingsGradle.mustache new file mode 100644 index 0000000..fd23a36 --- /dev/null +++ b/templates/libraries/spring-boot/settingsGradle.mustache @@ -0,0 +1,15 @@ +pluginManagement { + repositories { + maven { url = uri("https://repo.spring.io/snapshot") } + maven { url = uri("https://repo.spring.io/milestone") } + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + if (requested.id.id == "org.springframework.boot") { + useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") + } + } + } +} +rootProject.name = "{{artifactId}}" diff --git a/templates/libraries/spring-boot/springBootApplication.mustache b/templates/libraries/spring-boot/springBootApplication.mustache new file mode 100644 index 0000000..3692d6d --- /dev/null +++ b/templates/libraries/spring-boot/springBootApplication.mustache @@ -0,0 +1,13 @@ +package {{basePackage}} + +import org.springframework.boot.runApplication +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.context.annotation.ComponentScan + +@SpringBootApplication +@ComponentScan(basePackages = ["{{basePackage}}", "{{apiPackage}}", "{{modelPackage}}"]) +class Application + +fun main(args: Array) { + runApplication(*args) +} diff --git a/templates/libraries/spring-boot/swagger-ui.mustache b/templates/libraries/spring-boot/swagger-ui.mustache new file mode 100644 index 0000000..f85b665 --- /dev/null +++ b/templates/libraries/spring-boot/swagger-ui.mustache @@ -0,0 +1,60 @@ + + + + + + Swagger UI + + + + + + + +
+ + + + + + diff --git a/templates/libraries/spring-cloud/README.mustache b/templates/libraries/spring-cloud/README.mustache new file mode 100644 index 0000000..3550f42 --- /dev/null +++ b/templates/libraries/spring-cloud/README.mustache @@ -0,0 +1,83 @@ +{{^interfaceOnly}} +# {{artifactId}} + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" +``` + +### Others + +At first generate the JAR by executing: + +mvn package + +Then manually install the following JARs: + +* target/{{{artifactId}}}-{{{artifactVersion}}}.jar +* target/lib/*.jar +{{/interfaceOnly}} +{{#interfaceOnly}} +# OpenAPI generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://openapis.org), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` +{{/interfaceOnly}} \ No newline at end of file diff --git a/templates/libraries/spring-cloud/apiClient.mustache b/templates/libraries/spring-cloud/apiClient.mustache new file mode 100644 index 0000000..e900e8b --- /dev/null +++ b/templates/libraries/spring-cloud/apiClient.mustache @@ -0,0 +1,11 @@ +package {{package}} + +import org.springframework.cloud.openfeign.FeignClient +import {{configPackage}}.ClientConfiguration + +@FeignClient( + name="\${{openbrace}}{{classVarName}}.name:{{classVarName}}{{closebrace}}", + {{#useFeignClientUrl}}url="\${{openbrace}}{{classVarName}}.url:{{basePath}}{{closebrace}}", {{/useFeignClientUrl}} + configuration = [ClientConfiguration::class] +) +interface {{classname}}Client : {{classname}} diff --git a/templates/libraries/spring-cloud/apiKeyRequestInterceptor.mustache b/templates/libraries/spring-cloud/apiKeyRequestInterceptor.mustache new file mode 100644 index 0000000..86bd615 --- /dev/null +++ b/templates/libraries/spring-cloud/apiKeyRequestInterceptor.mustache @@ -0,0 +1,19 @@ +package {{configPackage}} + +import feign.RequestInterceptor +import feign.RequestTemplate + +class ApiKeyRequestInterceptor( + private val location: String, + private val name: String, + private val value: String, +) : RequestInterceptor { + + override fun apply(requestTemplate: RequestTemplate) { + if (location == "header") { + requestTemplate.header(name, value) + } else if (location == "query") { + requestTemplate.query(name, value) + } + } +} diff --git a/templates/libraries/spring-cloud/buildGradle-sb3-Kts.mustache b/templates/libraries/spring-cloud/buildGradle-sb3-Kts.mustache new file mode 100644 index 0000000..1bf4d31 --- /dev/null +++ b/templates/libraries/spring-cloud/buildGradle-sb3-Kts.mustache @@ -0,0 +1,68 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +group = "{{groupId}}" +version = "{{artifactVersion}}" +java.sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenCentral() + maven { url = uri("https://repo.spring.io/milestone") } +} + +tasks.withType { + kotlinOptions.jvmTarget = "17" +} + +plugins { + val kotlinVersion = "1.7.10" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "3.0.2" + id("io.spring.dependency-management") version "1.0.14.RELEASE" +} + +tasks.getByName("bootJar") { + enabled = false +} + +tasks.getByName("jar") { + enabled = true +} + +dependencyManagement { + imports { + mavenBom("org.springframework.cloud:spring-cloud-dependencies:2021.0.5") + } +} + +dependencies { +{{#reactive}} val kotlinxCoroutinesVersion = "1.6.1" +{{/reactive}} implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + implementation("org.jetbrains.kotlin:kotlin-reflect"){{^reactive}} + implementation("org.springframework.boot:spring-boot-starter-web"){{/reactive}}{{#reactive}} + implementation("org.springframework.boot:spring-boot-starter-webflux") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinxCoroutinesVersion") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:$kotlinxCoroutinesVersion"){{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + implementation("org.springdoc:springdoc-openapi-starter-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-ui:2.0.0-M5"){{/useSwaggerUI}}{{^useSwaggerUI}} + implementation("org.springdoc:springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core:2.0.0-M5"){{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + implementation("io.springfox:springfox-swagger2:2.9.2"){{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + implementation("org.webjars:swagger-ui:4.10.3") + implementation("org.webjars:webjars-locator-core"){{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + implementation("io.swagger:swagger-annotations:1.6.6"){{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + implementation("io.swagger.core.v3:swagger-annotations:2.2.0"){{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + implementation("com.google.code.findbugs:jsr305:3.0.2") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + + implementation("org.springframework.cloud:spring-cloud-starter-openfeign"){{#hasAuthMethods}} + implementation("org.springframework.cloud:spring-cloud-starter-oauth2:2.2.5.RELEASE"){{/hasAuthMethods}} + +{{#useBeanValidation}} + implementation("jakarta.validation:jakarta.validation-api"){{/useBeanValidation}} + implementation("jakarta.annotation:jakarta.annotation-api:2.1.0") + +} diff --git a/templates/libraries/spring-cloud/buildGradleKts.mustache b/templates/libraries/spring-cloud/buildGradleKts.mustache new file mode 100644 index 0000000..b1a7e08 --- /dev/null +++ b/templates/libraries/spring-cloud/buildGradleKts.mustache @@ -0,0 +1,75 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.6.7") + } +} + +group = "{{groupId}}" +version = "{{artifactVersion}}" + +repositories { + mavenCentral() +} + +tasks.withType { + kotlinOptions.jvmTarget = "1.8" +} + +plugins { + val kotlinVersion = "1.6.21" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "2.6.7" + id("io.spring.dependency-management") version "1.0.11.RELEASE" +} + +tasks.getByName("bootJar") { + enabled = false +} + +tasks.getByName("jar") { + enabled = true +} + +dependencyManagement { + imports { + mavenBom("org.springframework.cloud:spring-cloud-dependencies:2021.0.5") + } +} + +dependencies { +{{#reactive}} val kotlinxCoroutinesVersion = "1.6.1" +{{/reactive}} implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + implementation("org.jetbrains.kotlin:kotlin-reflect"){{^reactive}} + implementation("org.springframework.boot:spring-boot-starter-web"){{/reactive}}{{#reactive}} + implementation("org.springframework.boot:spring-boot-starter-webflux") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinxCoroutinesVersion") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:$kotlinxCoroutinesVersion"){{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + implementation("org.springdoc:springdoc-openapi-{{#reactive}}webflux-{{/reactive}}ui:1.6.8"){{/useSwaggerUI}}{{^useSwaggerUI}} + implementation("org.springdoc:springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core:1.6.8"){{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + implementation("io.springfox:springfox-swagger2:2.9.2"){{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + implementation("org.webjars:swagger-ui:4.10.3") + implementation("org.webjars:webjars-locator-core"){{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + implementation("io.swagger:swagger-annotations:1.6.6"){{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + implementation("io.swagger.core.v3:swagger-annotations:2.2.0"){{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + implementation("com.google.code.findbugs:jsr305:3.0.2") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + + implementation("org.springframework.cloud:spring-cloud-starter-openfeign"){{#hasAuthMethods}} + implementation("org.springframework.cloud:spring-cloud-starter-oauth2:2.2.5.RELEASE"){{/hasAuthMethods}} + +{{#useBeanValidation}} + implementation("jakarta.validation:jakarta.validation-api"){{/useBeanValidation}} + implementation("jakarta.annotation:jakarta.annotation-api:2.1.0") + +} diff --git a/templates/libraries/spring-cloud/clientConfiguration.mustache b/templates/libraries/spring-cloud/clientConfiguration.mustache new file mode 100644 index 0000000..3ea2f62 --- /dev/null +++ b/templates/libraries/spring-cloud/clientConfiguration.mustache @@ -0,0 +1,132 @@ +package {{configPackage}} + +{{#authMethods}} +{{#isBasicBasic}} +import feign.auth.BasicAuthRequestInterceptor +{{/isBasicBasic}} +{{#-first}} +import org.springframework.beans.factory.annotation.Value +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty +{{/-first}} +{{#isOAuth}} +import org.springframework.boot.context.properties.ConfigurationProperties +{{/isOAuth}} +{{/authMethods}} +import org.springframework.boot.context.properties.EnableConfigurationProperties +{{#authMethods}} +{{#-first}} +import org.springframework.context.annotation.Bean +{{/-first}} +{{/authMethods}} +import org.springframework.context.annotation.Configuration +{{#authMethods}} +{{#isOAuth}} +import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext +import org.springframework.security.oauth2.client.OAuth2ClientContext +{{#isApplication}} +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails +{{/isApplication}} +{{#isCode}} +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails +{{/isCode}} +{{#isImplicit}} +import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails +{{/isImplicit}} +{{#isPassword}} +import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails +{{/isPassword}} +{{/isOAuth}} +{{/authMethods}} + +@Configuration +@EnableConfigurationProperties +class ClientConfiguration { + + {{#authMethods}} + {{#isBasicBasic}} + @Value("\${{openbrace}}{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.username:{{closebrace}}") + private lateinit var {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}Username: String + + @Value("\${{openbrace}}{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.password:{{closebrace}}") + private lateinit var {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}Password: String + + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.username") + fun {{{name}}}RequestInterceptor(): BasicAuthRequestInterceptor { + return BasicAuthRequestInterceptor(this.{{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}Username, this.{{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}Password) + } + + {{/isBasicBasic}} + {{#isApiKey}} + @Value("\${{openbrace}}{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.key:{{closebrace}}") + private lateinit var {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}Key: String + + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.key") + fun {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}RequestInterceptor(): ApiKeyRequestInterceptor { + return ApiKeyRequestInterceptor({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{{keyParamName}}}", this.{{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}Key) + } + + {{/isApiKey}} + {{#isOAuth}} + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.client-id") + fun {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}RequestInterceptor(oAuth2ClientContext: OAuth2ClientContext): OAuth2FeignRequestInterceptor { + return OAuth2FeignRequestInterceptor(oAuth2ClientContext, {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}ResourceDetails()) + } + + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.client-id") + fun oAuth2ClientContext(): OAuth2ClientContext { + return DefaultOAuth2ClientContext() + } + + {{#isCode}} + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}") + fun {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}ResourceDetails(): AuthorizationCodeResourceDetails { + val details = AuthorizationCodeResourceDetails() + details.accessTokenUri = "{{{tokenUrl}}}" + details.userAuthorizationUri = "{{{authorizationUrl}}}" + return details + } + + {{/isCode}} + {{#isPassword}} + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}") + fun {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}ResourceDetails(): ResourceOwnerPasswordResourceDetails { + val details = ResourceOwnerPasswordResourceDetails() + details.accessTokenUri = "{{{tokenUrl}}}" + return details + } + + {{/isPassword}} + {{#isApplication}} + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}") + fun {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}ResourceDetails(): ClientCredentialsResourceDetails { + val details = ClientCredentialsResourceDetails() + details.accessTokenUri = "{{{tokenUrl}}}" + return details + } + + {{/isApplication}} + {{#isImplicit}} + @Bean + @ConditionalOnProperty("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{#lambda.lowercase}}{{{title}}}{{/lambda.lowercase}}.security.{{{name}}}") + fun {{#lambda.camelcase}}{{{name}}}{{/lambda.camelcase}}ResourceDetails(): ImplicitResourceDetails { + val details = ImplicitResourceDetails() + details.userAuthorizationUri= "{{{authorizationUrl}}}" + return details + } + + {{/isImplicit}} + {{/isOAuth}} + {{/authMethods}} +} diff --git a/templates/libraries/spring-cloud/pom-sb3.mustache b/templates/libraries/spring-cloud/pom-sb3.mustache new file mode 100644 index 0000000..1462130 --- /dev/null +++ b/templates/libraries/spring-cloud/pom-sb3.mustache @@ -0,0 +1,233 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{#reactive}} + 1.6.1 + {{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + 2.0.2 + {{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + 2.9.2 + {{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + 4.15.5 + {{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + 1.6.6 + {{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + 2.2.7 + {{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + 3.0.2 + 2.1.0 + 1.7.10 + + 1.7.10 + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 3.0.2 + + + + + org.springframework.cloud + spring-cloud-starter-parent + 2021.0.5 + pom + import + + + + + + repository.spring.milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + + + + spring-milestones + https://repo.spring.io/milestone + + + + ${project.basedir}/src/main/kotlin + {{^interfaceOnly}} + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + {{/interfaceOnly}} + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 17 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + {{^reactive}} + + org.springframework.boot + spring-boot-starter-web + {{/reactive}}{{#reactive}} + + org.springframework.boot + spring-boot-starter-webflux + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + {{/reactive}} + + {{#springDocDocumentationProvider}} + {{#useSwaggerUI}} + + org.springdoc + springdoc-openapi-starter-{{#reactive}} + webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-ui + + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{^useSwaggerUI}} + + org.springdoc + springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core + + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + + + io.springfox + springfox-swagger2 + ${springfox-swagger2.version} + {{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + + org.webjars + swagger-ui + ${swagger-ui.version} + + + org.webjars + webjars-locator-core + {{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + + io.swagger + swagger-annotations + ${swagger-annotations.version} + {{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + + io.swagger.core.v3 + swagger-annotations + ${swagger-annotations.version} + {{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + + + com.google.code.findbugs + jsr305 + ${findbugs-jsr305.version} + + + org.springframework.cloud + spring-cloud-starter-openfeign + + {{#hasAuthMethods}} + + org.springframework.cloud + spring-cloud-starter-oauth2 + {{^parentOverridden}} + 2.2.5.RELEASE + {{/parentOverridden}} + + {{/hasAuthMethods}} + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.fasterxml.jackson.module + jackson-module-kotlin + +{{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + {{/useBeanValidation}} + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation.version} + provided + + + org.jetbrains.kotlin + kotlin-test-junit5 + ${kotlin-test-junit5.version} + test + + + diff --git a/templates/libraries/spring-cloud/pom.mustache b/templates/libraries/spring-cloud/pom.mustache new file mode 100644 index 0000000..ddab151 --- /dev/null +++ b/templates/libraries/spring-cloud/pom.mustache @@ -0,0 +1,210 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{#reactive}} + 1.6.1{{/reactive}}{{#springDocDocumentationProvider}}{{#useSwaggerUI}} + 1.6.8{{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + 2.9.2{{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + 4.10.3{{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + 1.6.6{{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + 2.2.0{{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + 3.0.2 + 2.1.0 + 1.6.21 + + 1.6.21 + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + + + org.springframework.cloud + spring-cloud-starter-parent + 2021.0.5 + pom + import + + + + + ${project.basedir}/src/main/kotlin + {{^interfaceOnly}} + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + {{/interfaceOnly}} + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 1.8 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + {{^reactive}} + + org.springframework.boot + spring-boot-starter-web + {{/reactive}}{{#reactive}} + + org.springframework.boot + spring-boot-starter-webflux + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + {{/reactive}} + +{{#springDocDocumentationProvider}} + {{#useSwaggerUI}} + + org.springdoc + springdoc-openapi-{{#reactive}}webflux-{{/reactive}}ui + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{^useSwaggerUI}} + + org.springdoc + springdoc-openapi-{{#reactive}}webflux{{/reactive}}{{^reactive}}webmvc{{/reactive}}-core + ${springdoc-openapi.version} + {{/useSwaggerUI}}{{/springDocDocumentationProvider}}{{#springFoxDocumentationProvider}} + + + io.springfox + springfox-swagger2 + ${springfox-swagger2.version} + {{/springFoxDocumentationProvider}}{{#useSwaggerUI}}{{^springDocDocumentationProvider}} + + org.webjars + swagger-ui + ${swagger-ui.version} + + + org.webjars + webjars-locator-core + {{/springDocDocumentationProvider}}{{/useSwaggerUI}}{{^springFoxDocumentationProvider}}{{^springDocDocumentationProvider}}{{#swagger1AnnotationLibrary}} + + io.swagger + swagger-annotations + ${swagger-annotations.version} + {{/swagger1AnnotationLibrary}}{{#swagger2AnnotationLibrary}} + + io.swagger.core.v3 + swagger-annotations + ${swagger-annotations.version} + {{/swagger2AnnotationLibrary}}{{/springDocDocumentationProvider}}{{/springFoxDocumentationProvider}} + + + + com.google.code.findbugs + jsr305 + ${findbugs-jsr305.version} + + + org.springframework.cloud + spring-cloud-starter-openfeign + + {{#hasAuthMethods}} + + org.springframework.cloud + spring-cloud-starter-oauth2 + {{^parentOverridden}} + 2.2.5.RELEASE + {{/parentOverridden}} + + {{/hasAuthMethods}} + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.fasterxml.jackson.module + jackson-module-kotlin + +{{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + {{/useBeanValidation}} + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation.version} + provided + + + org.jetbrains.kotlin + kotlin-test-junit5 + ${kotlin-test-junit5.version} + test + + + diff --git a/templates/libraries/spring-cloud/settingsGradle.mustache b/templates/libraries/spring-cloud/settingsGradle.mustache new file mode 100644 index 0000000..fd23a36 --- /dev/null +++ b/templates/libraries/spring-cloud/settingsGradle.mustache @@ -0,0 +1,15 @@ +pluginManagement { + repositories { + maven { url = uri("https://repo.spring.io/snapshot") } + maven { url = uri("https://repo.spring.io/milestone") } + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + if (requested.id.id == "org.springframework.boot") { + useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") + } + } + } +} +rootProject.name = "{{artifactId}}" diff --git a/templates/methodBody.mustache b/templates/methodBody.mustache new file mode 100644 index 0000000..3e3b63e --- /dev/null +++ b/templates/methodBody.mustache @@ -0,0 +1,28 @@ +{{^reactive}} +{{#examples}} + {{#-first}} + {{#async}} +return CompletableFuture.supplyAsync(()-> { + {{/async}}getRequest().ifPresent { request -> +{{#async}} {{/async}} for (mediaType in MediaType.parseMediaTypes(request.getHeader("Accept"))) { + {{/-first}} +{{#async}} {{/async}}{{^async}} {{/async}} if (mediaType.isCompatibleWith(MediaType.valueOf("{{{contentType}}}"))) { +{{#async}} {{/async}}{{^async}} {{/async}} ApiUtil.setExampleResponse(request, "{{{contentType}}}", "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}") +{{#async}} {{/async}}{{^async}} {{/async}} break +{{#async}} {{/async}}{{^async}} {{/async}} } + {{#-last}} +{{#async}} {{/async}}{{^async}} {{/async}} } +{{#async}} {{/async}} } +{{#async}} {{/async}} return ResponseEntity({{#returnSuccessCode}}HttpStatus.valueOf({{{statusCode}}}){{/returnSuccessCode}}{{^returnSuccessCode}}HttpStatus.NOT_IMPLEMENTED{{/returnSuccessCode}}) + {{#async}} + }, Runnable::run) + {{/async}} + {{/-last}} +{{/examples}} +{{^examples}} +return {{#async}}CompletableFuture.completedFuture({{/async}}ResponseEntity({{#returnSuccessCode}}HttpStatus.OK{{/returnSuccessCode}}{{^returnSuccessCode}}HttpStatus.NOT_IMPLEMENTED{{/returnSuccessCode}}) +{{/examples}} +{{/reactive}} +{{#reactive}} +return ResponseEntity({{#returnSuccessCode}}HttpStatus.OK{{/returnSuccessCode}}{{^returnSuccessCode}}HttpStatus.NOT_IMPLEMENTED{{/returnSuccessCode}}) +{{/reactive}} \ No newline at end of file diff --git a/templates/model.mustache b/templates/model.mustache new file mode 100644 index 0000000..f6005b5 --- /dev/null +++ b/templates/model.mustache @@ -0,0 +1,28 @@ +package {{package}} + +import java.util.Objects +{{#imports}}import {{import}} +{{/imports}} +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.DecimalMax +import {{javaxPackage}}.validation.constraints.DecimalMin +import {{javaxPackage}}.validation.constraints.Email +import {{javaxPackage}}.validation.constraints.Max +import {{javaxPackage}}.validation.constraints.Min +import {{javaxPackage}}.validation.constraints.NotNull +import {{javaxPackage}}.validation.constraints.Pattern +import {{javaxPackage}}.validation.constraints.Size +import {{javaxPackage}}.validation.Valid +{{/useBeanValidation}} +{{#swagger2AnnotationLibrary}} +import io.swagger.v3.oas.annotations.media.Schema +{{/swagger2AnnotationLibrary}} +{{#swagger1AnnotationLibrary}} +import io.swagger.annotations.ApiModelProperty +{{/swagger1AnnotationLibrary}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>enumClass}}{{/isEnum}}{{^isEnum}}{{>dataClass}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/templates/modelMutable.mustache b/templates/modelMutable.mustache new file mode 100644 index 0000000..4c7f390 --- /dev/null +++ b/templates/modelMutable.mustache @@ -0,0 +1 @@ +{{#modelMutable}}var{{/modelMutable}}{{^modelMutable}}val{{/modelMutable}} \ No newline at end of file diff --git a/templates/openapi.mustache b/templates/openapi.mustache new file mode 100644 index 0000000..51ebafb --- /dev/null +++ b/templates/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/templates/optionalDataType.mustache b/templates/optionalDataType.mustache new file mode 100644 index 0000000..7c026fa --- /dev/null +++ b/templates/optionalDataType.mustache @@ -0,0 +1 @@ +{{#required}}{{{dataType}}}{{/required}}{{^required}}{{#defaultValue}}{{{dataType}}}{{/defaultValue}}{{^defaultValue}}{{{dataType}}}?{{/defaultValue}}{{/required}} \ No newline at end of file diff --git a/templates/pathParams.mustache b/templates/pathParams.mustache new file mode 100644 index 0000000..957ca22 --- /dev/null +++ b/templates/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeDoubleQuote}}{{{value}}}{{/lambdaEscapeDoubleQuote}}"{{^-last}}, {{/-last}}{{/enumVars}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeDoubleQuote}}{{{value}}}{{/lambdaEscapeDoubleQuote}}"{{^-last}}, {{/-last}}{{/enumVars}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{#lambda.escapeDoubleQuote}}{{{value}}}{{/lambda.escapeDoubleQuote}}{{^-last}}, {{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @PathVariable("{{baseName}}") {{paramName}}: {{>optionalDataType}}{{/isPathParam}} \ No newline at end of file diff --git a/templates/queryParams.mustache b/templates/queryParams.mustache new file mode 100644 index 0000000..3c254c5 --- /dev/null +++ b/templates/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/swagger1AnnotationLibrary}}{{#useBeanValidation}} @Valid{{/useBeanValidation}}{{^isModel}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/isModel}}{{#isDate}} @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE){{/isDate}}{{#isDateTime}} @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME){{/isDateTime}} {{paramName}}: {{>optionalDataType}}{{/isQueryParam}} \ No newline at end of file diff --git a/templates/returnTypes.mustache b/templates/returnTypes.mustache new file mode 100644 index 0000000..12a74e5 --- /dev/null +++ b/templates/returnTypes.mustache @@ -0,0 +1 @@ +{{#isMap}}Map{{/isMap}}{{#isArray}}{{#reactive}}Flow{{/reactive}}{{^reactive}}{{{returnContainer}}}{{/reactive}}<{{{returnType}}}>{{/isArray}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}} \ No newline at end of file diff --git a/templates/returnValue.mustache b/templates/returnValue.mustache new file mode 100644 index 0000000..8c7c1aa --- /dev/null +++ b/templates/returnValue.mustache @@ -0,0 +1 @@ +{{#serviceInterface}}ResponseEntity(service.{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}), {{#responses}}{{#-first}}HttpStatus.valueOf({{code}}){{/-first}}{{/responses}}){{/serviceInterface}}{{^serviceInterface}}ResponseEntity(HttpStatus.NOT_IMPLEMENTED){{/serviceInterface}} \ No newline at end of file diff --git a/templates/service.mustache b/templates/service.mustache new file mode 100644 index 0000000..1f2a0d0 --- /dev/null +++ b/templates/service.mustache @@ -0,0 +1,36 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +{{#reactive}} +import kotlinx.coroutines.flow.Flow +{{/reactive}} + +{{#operations}} +interface {{classname}}Service { +{{#operation}} + + /** + * {{httpMethod}} {{{path}}}{{#summary}} : {{.}}{{/summary}} + {{#notes}} + * {{.}} + {{/notes}} + * + {{#allParams}} + * @param {{{paramName}}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + * @return {{#responses}}{{message}} (status code {{code}}){{^-last}} + * or {{/-last}}{{/responses}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + * @see {{classname}}#{{operationId}} + */ + {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{^-last}}, {{/-last}}{{/allParams}}): {{>returnTypes}} +{{/operation}} +} +{{/operations}} diff --git a/templates/serviceImpl.mustache b/templates/serviceImpl.mustache new file mode 100644 index 0000000..75f4fda --- /dev/null +++ b/templates/serviceImpl.mustache @@ -0,0 +1,19 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +{{#reactive}} +import kotlinx.coroutines.flow.Flow +{{/reactive}} +import org.springframework.stereotype.Service +@Service +{{#operations}} +class {{classname}}ServiceImpl : {{classname}}Service { +{{#operation}} + + override {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{paramName}}: {{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{^-last}}, {{/-last}}{{/allParams}}): {{>returnTypes}} { + TODO("Implement me") + } +{{/operation}} +} +{{/operations}} diff --git a/templates/springdocDocumentationConfig.mustache b/templates/springdocDocumentationConfig.mustache new file mode 100644 index 0000000..91b4cd7 --- /dev/null +++ b/templates/springdocDocumentationConfig.mustache @@ -0,0 +1,53 @@ +package {{basePackage}} + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration + +import io.swagger.v3.oas.models.OpenAPI +import io.swagger.v3.oas.models.info.Info +import io.swagger.v3.oas.models.info.Contact +import io.swagger.v3.oas.models.info.License +import io.swagger.v3.oas.models.Components +import io.swagger.v3.oas.models.security.SecurityScheme + +@Configuration +class SpringDocConfiguration { + + @Bean + fun apiInfo(): OpenAPI { + return OpenAPI() + .info( + Info(){{#appName}} + .title("{{appName}}"){{/appName}} + .description("{{{appDescription}}}"){{#termsOfService}} + .termsOfService("{{termsOfService}}"){{/termsOfService}}{{#openAPI}}{{#info}}{{#contact}} + .contact( + Contact(){{#infoName}} + .name("{{infoName}}"){{/infoName}}{{#infoUrl}} + .url("{{infoUrl}}"){{/infoUrl}}{{#infoEmail}} + .email("{{infoEmail}}"){{/infoEmail}} + ){{/contact}}{{#license}} + .license( + License() + {{#licenseInfo}}.name("{{licenseInfo}}") + {{/licenseInfo}}{{#licenseUrl}}.url("{{licenseUrl}}") + {{/licenseUrl}} + ){{/license}}{{/info}}{{/openAPI}} + .version("{{appVersion}}") + ){{#hasAuthMethods}} + .components( + Components(){{#authMethods}} + .addSecuritySchemes("{{name}}", SecurityScheme(){{#isBasic}} + .type(SecurityScheme.Type.HTTP) + .scheme("{{scheme}}"){{#bearerFormat}} + .bearerFormat("{{bearerFormat}}"){{/bearerFormat}}{{/isBasic}}{{#isApiKey}} + .type(SecurityScheme.Type.APIKEY){{#isKeyInHeader}} + .`in`(SecurityScheme.In.HEADER){{/isKeyInHeader}}{{#isKeyInQuery}} + .`in`(SecurityScheme.In.QUERY){{/isKeyInQuery}}{{#isKeyInCookie}} + .`in`(SecurityScheme.In.COOKIE){{/isKeyInCookie}} + .name("{{keyParamName}}"){{/isApiKey}}{{#isOAuth}} + .type(SecurityScheme.Type.OAUTH2){{/isOAuth}} + ){{/authMethods}} + ){{/hasAuthMethods}} + } +} diff --git a/templates/springfoxDocumentationConfig.mustache b/templates/springfoxDocumentationConfig.mustache new file mode 100644 index 0000000..f129a93 --- /dev/null +++ b/templates/springfoxDocumentationConfig.mustache @@ -0,0 +1,66 @@ +package {{basePackage}} + +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.util.UriComponentsBuilder +import springfox.documentation.builders.ApiInfoBuilder +import springfox.documentation.builders.RequestHandlerSelectors +import springfox.documentation.service.ApiInfo +import springfox.documentation.service.Contact +import springfox.documentation.spi.DocumentationType +import springfox.documentation.spring.web.paths.Paths +import springfox.documentation.spring.web.paths.RelativePathProvider +import springfox.documentation.spring.web.plugins.Docket +import springfox.documentation.swagger2.annotations.EnableSwagger2 +import {{javaxPackage}}.servlet.ServletContext + + +{{>generatedAnnotation}} +@Configuration +@EnableSwagger2 +class SpringFoxConfiguration { + + fun apiInfo(): ApiInfo { + return ApiInfoBuilder() + .title("{{appName}}") + .description("{{{appDescription}}}") + .license("{{licenseInfo}}") + .licenseUrl("{{licenseUrl}}") + .termsOfServiceUrl("{{infoUrl}}") + .version("{{appVersion}}") + .contact(Contact("", "", "{{infoEmail}}")) + .build() + } + + @Bean +{{=<% %>=}} + fun customImplementation(servletContext: ServletContext, @Value("\${openapi.<%title%>.base-path:<%>defaultBasePath%>}") basePath: String): Docket { +<%={{ }}=%> + return Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) + .build() + .pathProvider(BasePathAwareRelativePathProvider(servletContext, basePath)) + .directModelSubstitute(java.time.LocalDate::class.java, java.sql.Date::class.java) + .directModelSubstitute(java.time.OffsetDateTime::class.java, java.util.Date::class.java) + .apiInfo(apiInfo()) + } + + class BasePathAwareRelativePathProvider(servletContext: ServletContext, private val basePath: String) : + RelativePathProvider(servletContext) { + + override fun applicationPath(): String { + return Paths.removeAdjacentForwardSlashes( + UriComponentsBuilder.fromPath(super.applicationPath()).path(basePath).build().toString() + ) + } + + override fun getOperationPath(operationPath: String): String { + val uriComponentsBuilder = UriComponentsBuilder.fromPath("/") + return Paths.removeAdjacentForwardSlashes( + uriComponentsBuilder.path(operationPath.replaceFirst("^$basePath", "")).build().toString() + ) + } + } +} diff --git a/templates/typeInfoAnnotation.mustache b/templates/typeInfoAnnotation.mustache new file mode 100644 index 0000000..35d740a --- /dev/null +++ b/templates/typeInfoAnnotation.mustache @@ -0,0 +1,8 @@ +{{#jackson}} + +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{{discriminator.propertyBaseName}}}", visible = true) +@JsonSubTypes( + {{#discriminator.mappedModels}} + JsonSubTypes.Type(value = {{modelName}}::class, name = "{{^vendorExtensions.x-discriminator-value}}{{mappingName}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"){{^-last}},{{/-last}} + {{/discriminator.mappedModels}} +){{/jackson}}