├── .gitignore ├── LICENSE ├── README.md ├── rest-json-wrapper ├── .gitignore ├── build.gradle.kts ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src │ └── main │ ├── kotlin │ └── com │ │ └── example │ │ └── demo │ │ ├── Data.kt │ │ ├── DemoApplication.kt │ │ ├── JSONFilter.kt │ │ └── Routes.kt │ └── resources │ └── application.properties ├── rest-jwt-jpa ├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src │ └── main │ ├── kotlin │ └── com │ │ └── example │ │ └── demo │ │ ├── DemoApplication.kt │ │ ├── config │ │ ├── AuthExt.kt │ │ ├── JwtEncodingConfig.kt │ │ └── SecurityConfig.kt │ │ ├── controller │ │ ├── AuthController.kt │ │ └── ItemController.kt │ │ ├── dto │ │ ├── Mapper.kt │ │ ├── Request.kt │ │ └── Response.kt │ │ ├── model │ │ ├── Item.kt │ │ └── User.kt │ │ ├── repository │ │ ├── ItemRepo.kt │ │ └── UserRepo.kt │ │ └── service │ │ ├── HashService.kt │ │ ├── ItemService.kt │ │ ├── TokenService.kt │ │ └── UserService.kt │ └── resources │ ├── application.properties │ └── db │ └── migration │ └── V1__Init.sql ├── rest-r2dbc-flyway ├── .gitignore ├── build.gradle.kts ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src │ ├── main │ ├── kotlin │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── DemoApplication.kt │ │ │ ├── Dto.kt │ │ │ ├── FlywayConfig.kt │ │ │ ├── controller │ │ │ └── PersonController.kt │ │ │ └── database │ │ │ └── Person.kt │ └── resources │ │ ├── application.properties │ │ └── db │ │ └── migration │ │ └── V1__Initial.sql │ └── test │ └── kotlin │ └── com │ └── example │ └── demo │ └── DemoApplicationTests.kt └── rest ├── .gitignore ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main ├── kotlin └── com │ └── example │ └── demo │ ├── Data.kt │ ├── DemoApplication.kt │ ├── NestedRoutes.kt │ └── Routes.kt └── resources └── application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020-2022 Tienisto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-kotlin 2 | Backend examples written in Kotlin and Spring Boot 3 | 4 | ## Content 5 | 6 | 1. REST 7 | 1. [Simple REST API](rest) 8 | 2. [Wrap JSON responses](rest-json-wrapper) 9 | 3. [Simple JWT with users](rest-jwt-jpa) 10 | 4. [Webflux using R2DBC](rest-r2dbc-flyway) 11 | 2. GraphQL 12 | 1. WIP 13 | -------------------------------------------------------------------------------- /rest-json-wrapper/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | -------------------------------------------------------------------------------- /rest-json-wrapper/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.2.6.RELEASE" 5 | id("io.spring.dependency-management") version "1.0.9.RELEASE" 6 | kotlin("jvm") version "1.3.71" 7 | kotlin("plugin.spring") version "1.3.71" 8 | } 9 | 10 | group = "com.example" 11 | version = "0.0.1-SNAPSHOT" 12 | java.sourceCompatibility = JavaVersion.VERSION_1_8 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation("org.springframework.boot:spring-boot-starter-web") 20 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 21 | implementation("org.jetbrains.kotlin:kotlin-reflect") 22 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 23 | } 24 | 25 | tasks.withType { 26 | useJUnitPlatform() 27 | } 28 | 29 | tasks.withType { 30 | kotlinOptions { 31 | freeCompilerArgs = listOf("-Xjsr305=strict") 32 | jvmTarget = "1.8" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /rest-json-wrapper/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tienisto/spring-boot-kotlin/102593dc94f21855d8ad8cbce2204d5c9e9d571f/rest-json-wrapper/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /rest-json-wrapper/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /rest-json-wrapper/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /rest-json-wrapper/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /rest-json-wrapper/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "demo" 2 | -------------------------------------------------------------------------------- /rest-json-wrapper/src/main/kotlin/com/example/demo/Data.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude 4 | 5 | object Request { 6 | data class User(val name: String, val age: Int) 7 | } 8 | 9 | object Response { 10 | 11 | // all responses will be wrapped 12 | @JsonInclude(JsonInclude.Include.NON_NULL) 13 | data class Wrapper(val success: Boolean = true, 14 | val token: String? = null, 15 | val data: Any?) 16 | } -------------------------------------------------------------------------------- /rest-json-wrapper/src/main/kotlin/com/example/demo/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class DemoApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /rest-json-wrapper/src/main/kotlin/com/example/demo/JSONFilter.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.core.MethodParameter 4 | import org.springframework.http.MediaType 5 | import org.springframework.http.converter.HttpMessageConverter 6 | import org.springframework.http.server.ServerHttpRequest 7 | import org.springframework.http.server.ServerHttpResponse 8 | import org.springframework.web.bind.annotation.ControllerAdvice 9 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice 10 | 11 | /** 12 | * wraps the JSON response in { success: true, data: } 13 | */ 14 | 15 | @ControllerAdvice(basePackages = ["com.example.demo"]) 16 | class JSONFilter : ResponseBodyAdvice { 17 | 18 | // only wraps responses which has not been wrapped 19 | override fun supports(returnType: MethodParameter, converterType: Class>): Boolean { 20 | return returnType.genericParameterType != Response.Wrapper::class.java 21 | } 22 | 23 | override fun beforeBodyWrite(body: Any?, returnType: MethodParameter, selectedContentType: MediaType, selectedConverterType: Class>, request: ServerHttpRequest, response: ServerHttpResponse): Any? { 24 | return Response.Wrapper(data = body) // the actual wrap 25 | } 26 | } -------------------------------------------------------------------------------- /rest-json-wrapper/src/main/kotlin/com/example/demo/Routes.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.web.bind.annotation.* 4 | 5 | @RestController 6 | class Routes { 7 | 8 | @GetMapping("/") 9 | fun getDefaultWrapper() {} 10 | 11 | @GetMapping("/number") 12 | fun getWrapperWithMessage(): Int { 13 | return 42 14 | } 15 | 16 | @GetMapping("/explicit/{message}") 17 | fun getExplicitWrapper(@PathVariable message: String): Response.Wrapper { 18 | return Response.Wrapper(true, "abc", "the message: $message") 19 | } 20 | 21 | @PostMapping("/update") 22 | fun updateSomething(@RequestBody request: Request.User): Request.User { 23 | // some database operations 24 | return request 25 | } 26 | } -------------------------------------------------------------------------------- /rest-json-wrapper/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /rest-jwt-jpa/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /rest-jwt-jpa/README.md: -------------------------------------------------------------------------------- 1 | # API 2 | 3 | ```text 4 | > POST /api/register 5 | 6 | { 7 | "name": "max", 8 | "password": "123" 9 | } 10 | ``` 11 | 12 | ```text 13 | > POST /api/login 14 | 15 | { 16 | "name": "max", 17 | "password": "123" 18 | } 19 | ``` 20 | 21 | ```text 22 | > POST /api/items 23 | > Authorization: 24 | 25 | { 26 | "name": "Apple", 27 | "count": 42, 28 | "note": "Important apple" 29 | } 30 | ``` 31 | 32 | ```text 33 | > PUT /api/items 34 | > Authorization: 35 | 36 | { 37 | "id": 1, 38 | "name": "Apple", 39 | "count": 22, 40 | "note": "Very important apple" 41 | } 42 | ``` 43 | 44 | ```text 45 | > GET /api/items 46 | > Authorization: 47 | ``` 48 | 49 | ```text 50 | > DELETE /api/items?itemId=1 51 | > Authorization: 52 | ``` 53 | -------------------------------------------------------------------------------- /rest-jwt-jpa/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "3.0.0" 5 | id("io.spring.dependency-management") version "1.1.0" 6 | kotlin("jvm") version "1.7.21" 7 | kotlin("plugin.spring") version "1.7.21" 8 | kotlin("plugin.jpa") version "1.7.21" 9 | } 10 | 11 | group = "com.example" 12 | version = "0.0.1-SNAPSHOT" 13 | java.sourceCompatibility = JavaVersion.VERSION_17 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 21 | implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server") 22 | implementation("org.springframework.boot:spring-boot-starter-web") 23 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 24 | implementation("org.flywaydb:flyway-core") 25 | implementation("org.jetbrains.kotlin:kotlin-reflect") 26 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 27 | runtimeOnly("org.postgresql:postgresql") 28 | testImplementation("org.springframework.boot:spring-boot-starter-test") 29 | } 30 | 31 | tasks.withType { 32 | kotlinOptions { 33 | freeCompilerArgs = listOf("-Xjsr305=strict") 34 | jvmTarget = "17" 35 | } 36 | } 37 | 38 | tasks.withType { 39 | useJUnitPlatform() 40 | } 41 | -------------------------------------------------------------------------------- /rest-jwt-jpa/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tienisto/spring-boot-kotlin/102593dc94f21855d8ad8cbce2204d5c9e9d571f/rest-jwt-jpa/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /rest-jwt-jpa/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /rest-jwt-jpa/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /rest-jwt-jpa/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /rest-jwt-jpa/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "demo" 2 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class DemoApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/config/AuthExt.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.config 2 | 3 | import com.example.demo.model.User 4 | import org.springframework.security.core.Authentication 5 | 6 | /** 7 | * Shorthand for controllers accessing the authenticated user. 8 | */ 9 | fun Authentication.toUser(): User { 10 | return principal as User 11 | } 12 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/config/JwtEncodingConfig.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.config 2 | 3 | import com.nimbusds.jose.jwk.source.ImmutableSecret 4 | import com.nimbusds.jose.proc.SecurityContext 5 | import org.springframework.beans.factory.annotation.Value 6 | import org.springframework.context.annotation.Bean 7 | import org.springframework.context.annotation.Configuration 8 | import org.springframework.security.oauth2.jwt.JwtDecoder 9 | import org.springframework.security.oauth2.jwt.JwtEncoder 10 | import org.springframework.security.oauth2.jwt.NimbusJwtDecoder 11 | import org.springframework.security.oauth2.jwt.NimbusJwtEncoder 12 | import javax.crypto.spec.SecretKeySpec 13 | 14 | /** 15 | * This class just sets the encoding settings for JWT. 16 | */ 17 | @Configuration 18 | class JwtEncodingConfig( 19 | @Value("\${security.key}") 20 | private val jwtKey: String, 21 | ) { 22 | private val secretKey = SecretKeySpec(jwtKey.toByteArray(), "HmacSHA256") 23 | 24 | @Bean 25 | fun jwtDecoder(): JwtDecoder { 26 | return NimbusJwtDecoder.withSecretKey(secretKey).build() 27 | } 28 | 29 | @Bean 30 | fun jwtEncoder(): JwtEncoder { 31 | val secret = ImmutableSecret(secretKey) 32 | return NimbusJwtEncoder(secret) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/config/SecurityConfig.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.config 2 | 3 | import com.example.demo.service.TokenService 4 | import org.springframework.context.annotation.Bean 5 | import org.springframework.context.annotation.Configuration 6 | import org.springframework.http.HttpMethod 7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 10 | import org.springframework.security.config.http.SessionCreationPolicy 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority 12 | import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException 13 | import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken 14 | import org.springframework.security.web.SecurityFilterChain 15 | import org.springframework.web.cors.CorsConfiguration 16 | import org.springframework.web.cors.CorsConfigurationSource 17 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource 18 | 19 | /** 20 | * This class sets all security related configuration. 21 | */ 22 | @Configuration 23 | @EnableWebSecurity 24 | class SecurityConfig ( 25 | private val tokenService: TokenService, 26 | ) { 27 | @Bean 28 | fun filterChain(http: HttpSecurity): SecurityFilterChain { 29 | // Define public and private routes 30 | http.authorizeHttpRequests() 31 | .requestMatchers(HttpMethod.POST, "/api/login").permitAll() 32 | .requestMatchers(HttpMethod.POST, "/api/register").permitAll() 33 | .requestMatchers("/api/**").authenticated() 34 | .anyRequest().permitAll() 35 | 36 | // Configure JWT 37 | http.oauth2ResourceServer().jwt() 38 | http.authenticationManager { auth -> 39 | val jwt = auth as BearerTokenAuthenticationToken 40 | val user = tokenService.parseToken(jwt.token) ?: throw InvalidBearerTokenException("Invalid token") 41 | UsernamePasswordAuthenticationToken(user, "", listOf(SimpleGrantedAuthority("USER"))) 42 | } 43 | 44 | // Other configuration 45 | http.cors() 46 | http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 47 | http.csrf().disable() 48 | http.headers().frameOptions().disable() 49 | http.headers().xssProtection().disable() 50 | 51 | return http.build() 52 | } 53 | 54 | @Bean 55 | fun corsConfigurationSource(): CorsConfigurationSource { 56 | // allow localhost for dev purposes 57 | val configuration = CorsConfiguration() 58 | configuration.allowedOrigins = listOf("http://localhost:3000", "http://localhost:8080") 59 | configuration.allowedMethods = listOf("GET", "POST", "PUT", "DELETE") 60 | configuration.allowedHeaders = listOf("authorization", "content-type") 61 | val source = UrlBasedCorsConfigurationSource() 62 | source.registerCorsConfiguration("/**", configuration) 63 | return source 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/controller/AuthController.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller 2 | 3 | import com.example.demo.dto.ApiException 4 | import com.example.demo.dto.LoginDto 5 | import com.example.demo.dto.LoginResponseDto 6 | import com.example.demo.dto.RegisterDto 7 | import com.example.demo.model.User 8 | import com.example.demo.service.HashService 9 | import com.example.demo.service.TokenService 10 | import com.example.demo.service.UserService 11 | import org.springframework.web.bind.annotation.PostMapping 12 | import org.springframework.web.bind.annotation.RequestBody 13 | import org.springframework.web.bind.annotation.RequestMapping 14 | import org.springframework.web.bind.annotation.RestController 15 | 16 | /** 17 | * This controller handles login and register requests. 18 | * Both routes are public as specified in SecurityConfig. 19 | */ 20 | @RestController 21 | @RequestMapping("/api") 22 | class AuthController( 23 | private val hashService: HashService, 24 | private val tokenService: TokenService, 25 | private val userService: UserService, 26 | ) { 27 | @PostMapping("/login") 28 | fun login(@RequestBody payload: LoginDto): LoginResponseDto { 29 | val user = userService.findByName(payload.name) ?: throw ApiException(400, "Login failed") 30 | 31 | if (!hashService.checkBcrypt(payload.password, user.password)) { 32 | throw ApiException(400, "Login failed") 33 | } 34 | 35 | return LoginResponseDto( 36 | token = tokenService.createToken(user), 37 | ) 38 | } 39 | 40 | @PostMapping("/register") 41 | fun register(@RequestBody payload: RegisterDto): LoginResponseDto { 42 | if (userService.existsByName(payload.name)) { 43 | throw ApiException(400, "Name already exists") 44 | } 45 | 46 | val user = User( 47 | name = payload.name, 48 | password = hashService.hashBcrypt(payload.password), 49 | ) 50 | 51 | val savedUser = userService.save(user) 52 | 53 | return LoginResponseDto( 54 | token = tokenService.createToken(savedUser), 55 | ) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/controller/ItemController.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller 2 | 3 | import com.example.demo.config.toUser 4 | import com.example.demo.dto.* 5 | import com.example.demo.model.Item 6 | import com.example.demo.service.ItemService 7 | import org.springframework.security.core.Authentication 8 | import org.springframework.web.bind.annotation.* 9 | 10 | /** 11 | * This controller handles requests for managing items of the authenticated user. 12 | */ 13 | @RestController 14 | @RequestMapping("/api/items") 15 | class ItemController( 16 | private val itemService: ItemService, 17 | ) { 18 | 19 | @GetMapping 20 | fun getItems(authentication: Authentication): List { 21 | val authUser = authentication.toUser() 22 | 23 | return itemService.findByUser(authUser).map { item -> item.toDto() } 24 | } 25 | 26 | @PostMapping 27 | fun createItem(authentication: Authentication, @RequestBody payload: CreateItemDto) { 28 | val authUser = authentication.toUser() 29 | 30 | if (itemService.existsByNameAndUser(payload.name, authUser)) { 31 | throw ApiException(409, "Item name already exists") 32 | } 33 | 34 | val item = Item( 35 | user = authUser, 36 | name = payload.name, 37 | count = payload.count, 38 | note = payload.note, 39 | ) 40 | 41 | itemService.save(item) 42 | } 43 | 44 | @PutMapping 45 | fun updateItem(authentication: Authentication, @RequestBody payload: UpdateItemDto) { 46 | val authUser = authentication.toUser() 47 | 48 | val item = itemService.findById(payload.id) ?: throw ApiException(404, "Item not found") 49 | if (item.user.id != authUser.id) { 50 | throw ApiException(403, "Not your item") 51 | } 52 | 53 | val existingItem = itemService.findByNameAndUser(payload.name, authUser) 54 | if (existingItem != null && existingItem.id != payload.id) { 55 | throw ApiException(409, "Item name already exists") 56 | } 57 | 58 | item.name = payload.name 59 | item.count = payload.count 60 | item.note = payload.note 61 | 62 | itemService.save(item) 63 | } 64 | 65 | @DeleteMapping 66 | fun deleteItem(authentication: Authentication, @RequestParam itemId: Long) { 67 | val authUser = authentication.toUser() 68 | val item = itemService.findById(itemId) ?: throw ApiException(404, "Item not found") 69 | if (item.user.id != authUser.id) { 70 | throw ApiException(403, "Not your item") 71 | } 72 | 73 | itemService.delete(item) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/dto/Mapper.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.dto 2 | 3 | import com.example.demo.model.Item 4 | 5 | /** 6 | * This file contains all mapping extension methods for DTOs. 7 | * In this simple example, there is only [Item] and [ItemDto]. 8 | */ 9 | fun Item.toDto(): ItemDto { 10 | return ItemDto(id, name, count, note) 11 | } 12 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/dto/Request.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.dto 2 | 3 | /** 4 | * This file contains all incoming DTOs. 5 | * Here, [LoginDto] is a data class containing immutable class members 6 | */ 7 | data class LoginDto( 8 | val name: String, 9 | val password: String, 10 | ) 11 | 12 | data class RegisterDto( 13 | val name: String, 14 | val password: String, 15 | ) 16 | 17 | data class CreateItemDto( 18 | val name: String, 19 | val count: Int, 20 | val note: String?, 21 | ) 22 | 23 | data class UpdateItemDto( 24 | val id: Long, 25 | val name: String, 26 | val count: Int, 27 | val note: String?, 28 | ) 29 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/dto/Response.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.dto 2 | 3 | import org.springframework.web.server.ResponseStatusException 4 | 5 | /** 6 | * This file contains all outgoing DTOs. 7 | * [ApiException] is used to easily throw exceptions. 8 | */ 9 | class ApiException(code: Int, message: String) : ResponseStatusException(code, message, null) 10 | 11 | data class LoginResponseDto( 12 | val token: String, 13 | ) 14 | 15 | data class ItemDto( 16 | val id: Long, 17 | val name: String, 18 | val count: Int, 19 | val note: String?, 20 | ) 21 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/model/Item.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.model 2 | 3 | import jakarta.persistence.* 4 | 5 | @Entity 6 | data class Item ( 7 | @Id 8 | @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "item_id_seq") 9 | @SequenceGenerator(name = "item_id_seq", allocationSize = 1) 10 | var id: Long = 0, 11 | 12 | @ManyToOne 13 | var user: User = User(), 14 | 15 | @Column 16 | var name: String = "", 17 | 18 | @Column 19 | var count: Int = 0, 20 | 21 | @Column 22 | var note: String? = null, 23 | ) 24 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/model/User.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.model 2 | 3 | import jakarta.persistence.* 4 | 5 | @Entity 6 | @Table(name = "api_user") 7 | data class User ( 8 | @Id 9 | @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "api_user_id_seq") 10 | @SequenceGenerator(name = "api_user_id_seq", allocationSize = 1) 11 | var id: Long = 0, 12 | 13 | @Column 14 | var name: String = "", 15 | 16 | @Column 17 | var password: String = "", 18 | ) 19 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/repository/ItemRepo.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository 2 | 3 | import com.example.demo.model.Item 4 | import com.example.demo.model.User 5 | import org.springframework.data.repository.CrudRepository 6 | 7 | interface ItemRepo : CrudRepository { 8 | fun findByUser(user: User): List 9 | fun findByNameAndUser(name: String, user: User): Item? 10 | 11 | fun existsByNameAndUser(name: String, user: User): Boolean 12 | } 13 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/repository/UserRepo.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository 2 | 3 | import com.example.demo.model.User 4 | import org.springframework.data.repository.CrudRepository 5 | 6 | interface UserRepo : CrudRepository { 7 | fun findByName(name: String): User? 8 | fun existsByName(name: String): Boolean 9 | } 10 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/service/HashService.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.service 2 | 3 | import org.springframework.security.crypto.bcrypt.BCrypt 4 | import org.springframework.stereotype.Service 5 | 6 | /** 7 | * hashes the strings and checks them 8 | */ 9 | @Service 10 | class HashService { 11 | 12 | /** 13 | * checks whether the string matches the hash 14 | * @param input the string to be checked 15 | * @param hash the hashed string 16 | * @return true if hash(input) == hash, otherwise false 17 | */ 18 | fun checkBcrypt(input: String, hash: String): Boolean { 19 | return BCrypt.checkpw(input, hash) 20 | } 21 | 22 | /** 23 | * hashes the string 24 | * @param input the string to be hashed 25 | * @return the hashed string 26 | */ 27 | fun hashBcrypt(input: String): String { 28 | return BCrypt.hashpw(input, BCrypt.gensalt(10)) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/service/ItemService.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.service 2 | 3 | import com.example.demo.model.Item 4 | import com.example.demo.model.User 5 | import com.example.demo.repository.ItemRepo 6 | import org.springframework.data.repository.findByIdOrNull 7 | import org.springframework.stereotype.Service 8 | 9 | @Service 10 | class ItemService( 11 | private val itemRepo: ItemRepo, 12 | ) { 13 | fun findById(id: Long): Item? { 14 | return itemRepo.findByIdOrNull(id) 15 | } 16 | 17 | fun findByUser(user: User): List { 18 | return itemRepo.findByUser(user) 19 | } 20 | 21 | fun findByNameAndUser(name: String, user: User): Item? { 22 | return itemRepo.findByNameAndUser(name, user) 23 | } 24 | 25 | fun existsByNameAndUser(name: String, user: User): Boolean { 26 | return itemRepo.existsByNameAndUser(name, user) 27 | } 28 | 29 | fun save(item: Item): Item { 30 | return itemRepo.save(item) 31 | } 32 | 33 | fun delete(item: Item) { 34 | return itemRepo.delete(item) 35 | } 36 | } -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/service/TokenService.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.service 2 | 3 | import com.example.demo.model.User 4 | import org.springframework.security.oauth2.jwt.JwsHeader 5 | import org.springframework.security.oauth2.jwt.JwtClaimsSet 6 | import org.springframework.security.oauth2.jwt.JwtDecoder 7 | import org.springframework.security.oauth2.jwt.JwtEncoder 8 | import org.springframework.security.oauth2.jwt.JwtEncoderParameters 9 | import org.springframework.stereotype.Service 10 | import java.lang.Exception 11 | import java.time.Instant 12 | import java.time.temporal.ChronoUnit 13 | 14 | /** 15 | * This service creates and parses tokens. 16 | * It will do database operations. 17 | */ 18 | @Service 19 | class TokenService( 20 | private val jwtDecoder: JwtDecoder, 21 | private val jwtEncoder: JwtEncoder, 22 | private val userService: UserService, 23 | ) { 24 | fun createToken(user: User): String { 25 | val jwsHeader = JwsHeader.with { "HS256" }.build() 26 | val claims = JwtClaimsSet.builder() 27 | .issuedAt(Instant.now()) 28 | .expiresAt(Instant.now().plus(30L, ChronoUnit.DAYS)) 29 | .subject(user.name) 30 | .claim("userId", user.id) 31 | .build() 32 | return jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).tokenValue 33 | } 34 | 35 | fun parseToken(token: String): User? { 36 | return try { 37 | val jwt = jwtDecoder.decode(token) 38 | val userId = jwt.claims["userId"] as Long 39 | userService.findById(userId) 40 | } catch (e: Exception) { 41 | null 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/kotlin/com/example/demo/service/UserService.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.service 2 | 3 | import com.example.demo.model.User 4 | import com.example.demo.repository.UserRepo 5 | import org.springframework.data.repository.findByIdOrNull 6 | import org.springframework.stereotype.Service 7 | 8 | @Service 9 | class UserService( 10 | private val userRepo: UserRepo, 11 | ) { 12 | fun findById(id: Long): User? { 13 | return userRepo.findByIdOrNull(id) 14 | } 15 | 16 | fun findByName(name: String): User? { 17 | return userRepo.findByName(name) 18 | } 19 | 20 | fun existsByName(name: String): Boolean { 21 | return userRepo.existsByName(name) 22 | } 23 | 24 | fun save(user: User): User { 25 | return userRepo.save(user) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:postgresql://localhost:5432/exampledatabase 2 | spring.datasource.username=exampleuser 3 | spring.datasource.password=123456 4 | 5 | security.key=somerandomkeywhichislongenoughtoalignwiththejwtspecification 6 | 7 | # show error message in response 8 | server.error.include-message=always 9 | -------------------------------------------------------------------------------- /rest-jwt-jpa/src/main/resources/db/migration/V1__Init.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE api_user 2 | ( 3 | id BIGSERIAL PRIMARY KEY, 4 | name TEXT NOT NULL, 5 | password TEXT NOT NULL 6 | ); 7 | 8 | CREATE TABLE item 9 | ( 10 | id BIGSERIAL PRIMARY KEY, 11 | user_id BIGINT NOT NULL REFERENCES api_user (id) ON DELETE CASCADE, 12 | name TEXT NOT NULL, 13 | count INTEGER NOT NULL, 14 | note TEXT 15 | ); 16 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.4.0" 5 | id("io.spring.dependency-management") version "1.0.10.RELEASE" 6 | kotlin("jvm") version "1.4.10" 7 | kotlin("plugin.spring") version "1.4.10" 8 | } 9 | 10 | group = "com.example" 11 | version = "0.0.1-SNAPSHOT" 12 | java.sourceCompatibility = JavaVersion.VERSION_11 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation("org.springframework.boot:spring-boot-starter-data-r2dbc") 20 | implementation("org.springframework.boot:spring-boot-starter-webflux") 21 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 22 | implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") 23 | implementation("org.flywaydb:flyway-core") 24 | implementation("org.jetbrains.kotlin:kotlin-reflect") 25 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 26 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") 27 | runtimeOnly("io.r2dbc:r2dbc-postgresql") 28 | runtimeOnly("org.postgresql:postgresql") 29 | testImplementation("org.springframework.boot:spring-boot-starter-test") 30 | testImplementation("io.projectreactor:reactor-test") 31 | } 32 | 33 | tasks.withType { 34 | useJUnitPlatform() 35 | } 36 | 37 | tasks.withType { 38 | kotlinOptions { 39 | freeCompilerArgs = listOf("-Xjsr305=strict") 40 | jvmTarget = "11" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tienisto/spring-boot-kotlin/102593dc94f21855d8ad8cbce2204d5c9e9d571f/rest-r2dbc-flyway/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /rest-r2dbc-flyway/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "demo" 2 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/kotlin/com/example/demo/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class DemoApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/kotlin/com/example/demo/Dto.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | object Request { 4 | data class CreatePerson(val name: String, val age: Int) 5 | data class UpdatePerson(val id: Int, val name: String, val age: Int) 6 | } -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/kotlin/com/example/demo/FlywayConfig.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.flywaydb.core.Flyway 4 | import org.springframework.context.annotation.Bean 5 | import org.springframework.context.annotation.Configuration 6 | import org.springframework.core.env.Environment 7 | 8 | // https://stackoverflow.com/a/61412233 9 | @Configuration 10 | class FlywayConfig ( 11 | private val env: Environment 12 | ) { 13 | 14 | @Bean(initMethod = "migrate") 15 | fun flyway(): Flyway { 16 | val url = "jdbc:" + env.getRequiredProperty("db.url") 17 | val user = env.getRequiredProperty("db.user") 18 | val password = env.getRequiredProperty("db.password") 19 | val config = Flyway 20 | .configure() 21 | .dataSource(url, user, password) 22 | return Flyway(config) 23 | } 24 | } -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/kotlin/com/example/demo/controller/PersonController.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller 2 | 3 | import com.example.demo.Request 4 | import com.example.demo.database.Person 5 | import com.example.demo.database.PersonRepo 6 | import kotlinx.coroutines.flow.toList 7 | import org.springframework.http.HttpStatus 8 | import org.springframework.http.ResponseEntity 9 | import org.springframework.web.bind.annotation.* 10 | 11 | @RestController 12 | @RequestMapping("/people") 13 | class PersonController ( 14 | private val personRepo: PersonRepo 15 | ) { 16 | 17 | // GET /people 18 | @GetMapping 19 | suspend fun getPeople(): List { 20 | return personRepo.findAll().toList() 21 | } 22 | 23 | // GET /people/search?name=tom 24 | @GetMapping("/search") 25 | suspend fun getPeopleByName(@RequestParam name: String): List { 26 | return personRepo.findByNameContains(name) 27 | } 28 | 29 | // GET /people/adults 30 | @GetMapping("/adults") 31 | suspend fun getAdults(): List { 32 | return personRepo.findByAgeGreaterThanEqual(18) 33 | } 34 | 35 | // POST /people 36 | @PostMapping 37 | suspend fun createPerson(@RequestBody request: Request.CreatePerson) { 38 | val person = Person(0, request.name, request.age) 39 | personRepo.save(person) 40 | } 41 | 42 | // PUT /people 43 | @PutMapping 44 | suspend fun updatePerson(@RequestBody request: Request.UpdatePerson): ResponseEntity { 45 | val person = personRepo.findById(request.id) 46 | ?: return ResponseEntity(HttpStatus.NOT_FOUND) 47 | person.name = request.name 48 | person.age = request.age 49 | personRepo.save(person) 50 | return ResponseEntity(HttpStatus.OK) 51 | } 52 | 53 | // DELETE /people/352 54 | @DeleteMapping("/{id}") 55 | suspend fun deletePerson(@PathVariable id: Int): ResponseEntity { 56 | val person = personRepo.findById(id) 57 | ?: return ResponseEntity(HttpStatus.NOT_FOUND) 58 | personRepo.delete(person) 59 | return ResponseEntity(HttpStatus.OK) 60 | } 61 | } -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/kotlin/com/example/demo/database/Person.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.database 2 | 3 | import org.springframework.data.annotation.Id 4 | import org.springframework.data.r2dbc.repository.Query 5 | import org.springframework.data.relational.core.mapping.Table 6 | import org.springframework.data.repository.kotlin.CoroutineCrudRepository 7 | 8 | @Table 9 | data class Person(@Id var id: Int = 0, 10 | var name: String = "", 11 | var age: Int = 0) 12 | 13 | interface PersonRepo: CoroutineCrudRepository { 14 | 15 | // SELECT * FROM person WHERE name LIKE '%tom%' 16 | suspend fun findByNameContains(name: String): List 17 | 18 | // SELECT * FROM person WHERE age >= 42 19 | suspend fun findByAgeGreaterThanEqual(age: Int): List 20 | 21 | // This is how to implement a custom query 22 | @Query("SELECT * FROM person WHERE age = :age AND name LIKE '%a%'") 23 | suspend fun findCustom(age: Int): List 24 | } -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | db.url=postgresql://localhost:5432/test 2 | db.user=test 3 | db.password=123456 4 | 5 | spring.r2dbc.url=r2dbc:${db.url} 6 | spring.r2dbc.username=${db.user} 7 | spring.r2dbc.password=${db.password} 8 | -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/main/resources/db/migration/V1__Initial.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE person ( 2 | id SERIAL PRIMARY KEY, 3 | name TEXT NOT NULL, 4 | age INT NOT NULL 5 | ); -------------------------------------------------------------------------------- /rest-r2dbc-flyway/src/test/kotlin/com/example/demo/DemoApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.boot.test.context.SpringBootTest 5 | 6 | @SpringBootTest 7 | class DemoApplicationTests { 8 | 9 | @Test 10 | fun contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /rest/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | -------------------------------------------------------------------------------- /rest/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.2.6.RELEASE" 5 | id("io.spring.dependency-management") version "1.0.9.RELEASE" 6 | kotlin("jvm") version "1.3.71" 7 | kotlin("plugin.spring") version "1.3.71" 8 | } 9 | 10 | group = "com.example" 11 | version = "0.0.1-SNAPSHOT" 12 | java.sourceCompatibility = JavaVersion.VERSION_1_8 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation("org.springframework.boot:spring-boot-starter-web") 20 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 21 | implementation("org.jetbrains.kotlin:kotlin-reflect") 22 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 23 | } 24 | 25 | tasks.withType { 26 | useJUnitPlatform() 27 | } 28 | 29 | tasks.withType { 30 | kotlinOptions { 31 | freeCompilerArgs = listOf("-Xjsr305=strict") 32 | jvmTarget = "1.8" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /rest/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tienisto/spring-boot-kotlin/102593dc94f21855d8ad8cbce2204d5c9e9d571f/rest/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /rest/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /rest/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /rest/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /rest/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "demo" 2 | -------------------------------------------------------------------------------- /rest/src/main/kotlin/com/example/demo/Data.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | object Request { 4 | data class User(val name: String, val age: Int) 5 | } 6 | 7 | object Response { 8 | 9 | data class Message(val message: String) 10 | data class MessageWithUser(val message: String, val user: Request.User) 11 | } -------------------------------------------------------------------------------- /rest/src/main/kotlin/com/example/demo/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class DemoApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /rest/src/main/kotlin/com/example/demo/NestedRoutes.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.web.bind.annotation.GetMapping 4 | import org.springframework.web.bind.annotation.RequestMapping 5 | import org.springframework.web.bind.annotation.RestController 6 | 7 | @RestController 8 | @RequestMapping("/nested") 9 | class NestedRoutes { 10 | 11 | @GetMapping("/first") 12 | fun first(): Response.Message { 13 | return Response.Message("First message") 14 | } 15 | 16 | @GetMapping("/second") 17 | fun second(): Response.Message { 18 | return Response.Message("Second message") 19 | } 20 | } -------------------------------------------------------------------------------- /rest/src/main/kotlin/com/example/demo/Routes.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.springframework.web.bind.annotation.* 4 | 5 | @RestController 6 | class Routes { 7 | 8 | @GetMapping("/") 9 | fun getRoot(): Response.Message { 10 | return Response.Message("Hello World") 11 | } 12 | 13 | // e.g. /hello 14 | @GetMapping("/{message}") 15 | fun getWithPathParameter(@PathVariable message: String): Response.Message { 16 | return Response.Message("You typed in: $message") 17 | } 18 | 19 | // e.g. /query?message=hello 20 | @GetMapping("/query") 21 | fun getWithQueryParameter(@RequestParam message: String): Response.Message { 22 | return Response.Message("You typed in the query: $message") 23 | } 24 | 25 | @PostMapping("/update") 26 | fun updateSomething(@RequestBody request: Request.User): Response.MessageWithUser { 27 | 28 | // some database operations 29 | 30 | return Response.MessageWithUser("User saved.", request) 31 | } 32 | 33 | @DeleteMapping("/{id}") 34 | fun deleteSomething(@PathVariable id: Int): Response.Message { 35 | 36 | // delete the user by the id 37 | println("Deleting user with id $id.") 38 | 39 | return Response.Message("User deleted. (id = $id)") 40 | } 41 | } -------------------------------------------------------------------------------- /rest/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------