├── .github └── workflows │ └── ci-pipeline.yml ├── .gitignore ├── LICENSE ├── README.md ├── spring-boot-docker-compose ├── .gitignore ├── .sdkmanrc ├── build.gradle ├── compose.yml ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── thomasvitale │ │ │ └── bookservice │ │ │ └── BookServiceApplication.java │ └── resources │ │ ├── application.yml │ │ └── db │ │ └── migration │ │ └── V1__Init_schema.sql │ └── test │ └── java │ └── com │ └── thomasvitale │ └── bookservice │ ├── BookJsonTests.java │ ├── BookServiceApplicationTests.java │ └── TestEnvironmentConfiguration.java ├── spring-boot-https ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── thomasvitale │ │ │ └── application │ │ │ ├── Application.java │ │ │ └── config │ │ │ ├── SecurityConfig.java │ │ │ └── ServerConfig.java │ └── resources │ │ ├── application.yml │ │ ├── myCertificate.crt │ │ └── springboot.p12 │ └── test │ └── java │ └── com │ └── thomasvitale │ └── application │ └── ApplicationTests.java ├── spring-boot-multitenancy-schema ├── .gitignore ├── Readme.MD ├── build.gradle ├── db │ ├── docker-compose.yml │ └── init │ │ ├── data.sql │ │ ├── db_init.sh │ │ └── schema.sql ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── thomasvitale │ │ │ └── application │ │ │ ├── Application.java │ │ │ ├── business │ │ │ ├── NoteDTO.java │ │ │ └── NoteService.java │ │ │ ├── config │ │ │ └── WebConfig.java │ │ │ ├── data │ │ │ ├── Note.java │ │ │ └── NoteRepository.java │ │ │ ├── multitenancy │ │ │ ├── CurrentTenantIdentifierResolverImpl.java │ │ │ ├── JpaConfig.java │ │ │ ├── MultiTenantConnectionProviderImpl.java │ │ │ ├── TenantContext.java │ │ │ └── TenantInterceptor.java │ │ │ └── web │ │ │ └── NoteRestController.java │ └── resources │ │ ├── application.yml │ │ └── static │ │ └── index.html │ └── test │ └── java │ └── com │ └── thomasvitale │ └── application │ ├── ApplicationTests.java │ └── web │ └── NoteRestControllerTest.java ├── spring-boot-testcontainers ├── .gitignore ├── .sdkmanrc ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── thomasvitale │ │ │ └── bookservice │ │ │ └── BookServiceApplication.java │ └── resources │ │ ├── application.yml │ │ └── db │ │ └── migration │ │ └── V1__Init_schema.sql │ └── test │ └── java │ └── com │ └── thomasvitale │ └── bookservice │ ├── BookJsonTests.java │ ├── BookServiceApplicationTests.java │ └── TestBookServiceApplication.java ├── spring-cloud-config ├── .gitignore ├── README.md ├── config-server │ ├── .gitignore │ ├── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── thomasvitale │ │ │ │ └── configserver │ │ │ │ └── ConfigServerApplication.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── thomasvitale │ │ └── configserver │ │ └── ConfigServerApplicationTests.java └── greeting-service │ ├── .gitignore │ ├── build.gradle │ ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── thomasvitale │ │ │ └── greetingservice │ │ │ ├── GreetingController.java │ │ │ └── GreetingServiceApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── thomasvitale │ └── greetingservice │ └── GreetingServiceApplicationTests.java └── spring-native-graalvm ├── .gitignore ├── README.md ├── build.gradle ├── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── thomasvitale │ │ └── demo │ │ └── SpringNativeGraalvmApplication.java └── resources │ └── application.yml └── test └── java └── com └── thomasvitale └── demo └── SpringNativeGraalvmApplicationTests.java /.github/workflows/ci-pipeline.yml: -------------------------------------------------------------------------------- 1 | name: CI Pipeline 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build-spring-boot-https: 7 | name: Spring Boot HTTPS - Compile and test 8 | runs-on: ubuntu-20.04 9 | steps: 10 | - name: Checkout repository 11 | uses: actions/checkout@v2 12 | - name: Set up JDK 16 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 16 16 | - name: Compile and test 17 | run: | 18 | cd spring-boot-https 19 | chmod +x gradlew 20 | ./gradlew clean build 21 | build-cloud-config: 22 | name: Spring Cloud Config - Compile and test 23 | runs-on: ubuntu-20.04 24 | steps: 25 | - name: Checkout repository 26 | uses: actions/checkout@v2 27 | - name: Set up JDK 17 28 | uses: actions/setup-java@v1 29 | with: 30 | java-version: 17 31 | - name: Compile and test config-server 32 | run: | 33 | cd spring-cloud-config/config-server 34 | chmod +x gradlew 35 | ./gradlew build 36 | - name: Compile and test greeting-service 37 | run: | 38 | cd spring-cloud-config/greeting-service 39 | chmod +x gradlew 40 | ./gradlew build 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | ################################ 26 | ############ MAC ############### 27 | ################################ 28 | 29 | # General 30 | .DS_Store 31 | .AppleDouble 32 | .LSOverride 33 | 34 | # Icon must end with two \r 35 | Icon 36 | 37 | # Thumbnails 38 | ._* 39 | 40 | # Files that might appear in the root of a volume 41 | .DocumentRevisions-V100 42 | .fseventsd 43 | .Spotlight-V100 44 | .TemporaryItems 45 | .Trashes 46 | .VolumeIcon.icns 47 | .com.apple.timemachine.donotpresent 48 | 49 | # Directories potentially created on remote AFP share 50 | .AppleDB 51 | .AppleDesktop 52 | Network Trash Folder 53 | Temporary Items 54 | .apdisk -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Thomas Vitale 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 Tutorials 2 | 3 | The repo for my articles, tutorials and guides about the Spring Framework. 4 | 5 | ## How to enable HTTPS in a Spring Boot Java application 6 | 7 | * Article: [How to enable HTTPS in a Spring Boot Java application](https://www.thomasvitale.com/https-spring-boot-ssl-certificate/) 8 | * Project: [`spring-boot-https`](https://github.com/ThomasVitale/spring-tutorials/tree/master/spring-boot-https) 9 | 10 | ## Multitenancy in a Spring Boot application (work in progress) 11 | 12 | * Article: _Work in progress_ 13 | * Project: [`spring-boot-multitenancy`](https://github.com/ThomasVitale/spring-tutorials/tree/master/spring-boot-multitenancy) 14 | 15 | ## Centralized Configuration with Spring Cloud Config 16 | 17 | * Article: [Centralized Configuration with Spring Cloud Config](https://www.thomasvitale.com/spring-cloud-config-basics/) 18 | * Project: [`spring-cloud-config`](https://github.com/ThomasVitale/spring-tutorials/tree/master/spring-cloud-config) 19 | 20 | ## Spring Native: Getting started with GraalVM native images 21 | 22 | * Article: [Spring Native: Getting started with GraalVM native images](https://www.thomasvitale.com/spring-native-graalvm-getting-started/) 23 | * Project: [`spring-native-graalvm`](https://github.com/ThomasVitale/spring-tutorials/tree/master/spring-native-graalvm) 24 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/.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 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/.sdkmanrc: -------------------------------------------------------------------------------- 1 | # Enable auto-env through the sdkman_auto_env config 2 | # Add key=value pairs of SDKs to use below 3 | java=23-graalce 4 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.4.2' 4 | id 'io.spring.dependency-management' version '1.1.7' 5 | } 6 | 7 | group = 'com.thomasvitale' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | toolchain { 12 | languageVersion = JavaLanguageVersion.of(23) 13 | } 14 | } 15 | 16 | repositories { 17 | mavenCentral() 18 | } 19 | 20 | dependencies { 21 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 22 | implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' 23 | implementation 'org.springframework.boot:spring-boot-starter-validation' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | 26 | implementation 'org.flywaydb:flyway-core' 27 | implementation 'org.flywaydb:flyway-database-postgresql' 28 | 29 | developmentOnly 'org.springframework.boot:spring-boot-docker-compose' 30 | 31 | runtimeOnly 'org.postgresql:postgresql' 32 | 33 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 34 | testImplementation 'org.springframework.boot:spring-boot-starter-webflux' 35 | testImplementation 'org.springframework.boot:spring-boot-testcontainers' 36 | testImplementation 'org.testcontainers:junit-jupiter' 37 | testImplementation 'org.testcontainers:postgresql' 38 | } 39 | 40 | tasks.named('test') { 41 | useJUnitPlatform() 42 | } 43 | 44 | tasks.named('bootBuildImage') { 45 | builder = "docker.io/paketobuildpacks/builder-noble-java-tiny" 46 | } 47 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | 3 | postgres: 4 | image: "postgres:17" 5 | container_name: postgres 6 | ports: 7 | - 5432:5432 8 | environment: 9 | - POSTGRES_USER=user 10 | - POSTGRES_PASSWORD=password 11 | - POSTGRES_DB=books 12 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-boot-docker-compose/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-docker-compose/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/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 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 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 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | org.gradle.wrapper.GradleWrapperMain \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/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 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'book-service' 2 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/src/main/java/com/thomasvitale/bookservice/BookServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.data.annotation.Id; 9 | import org.springframework.data.repository.ListCrudRepository; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.ResponseStatus; 17 | import org.springframework.web.bind.annotation.RestController; 18 | 19 | import jakarta.validation.Valid; 20 | import jakarta.validation.constraints.NotEmpty; 21 | 22 | @SpringBootApplication 23 | public class BookServiceApplication { 24 | 25 | public static void main(String[] args) { 26 | SpringApplication.run(BookServiceApplication.class, args); 27 | } 28 | 29 | } 30 | 31 | @RestController 32 | @RequestMapping("/books") 33 | class BookController { 34 | private final BookRepository bookRepository; 35 | 36 | BookController(BookRepository bookRepository) { 37 | this.bookRepository = bookRepository; 38 | } 39 | 40 | @GetMapping 41 | List getBooks() { 42 | return bookRepository.findAll(); 43 | } 44 | 45 | @GetMapping("{id}") 46 | Optional getBookById(@PathVariable Long id) { 47 | return bookRepository.findById(id); 48 | } 49 | 50 | @PostMapping 51 | @ResponseStatus(HttpStatus.CREATED) 52 | Book addBook(@RequestBody @Valid Book book) { 53 | return bookRepository.save(book); 54 | } 55 | } 56 | 57 | record Book(@Id Long id, @NotEmpty String title){} 58 | 59 | interface BookRepository extends ListCrudRepository{} 60 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | spring: 5 | application: 6 | name: book-service 7 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/src/main/resources/db/migration/V1__Init_schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE book( 2 | id BIGSERIAL PRIMARY KEY, 3 | title VARCHAR(255) NOT NULL 4 | ); 5 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/src/test/java/com/thomasvitale/bookservice/BookJsonTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.json.JsonTest; 7 | import org.springframework.boot.test.json.JacksonTester; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | @JsonTest 12 | public class BookJsonTests { 13 | 14 | @Autowired 15 | private JacksonTester json; 16 | 17 | @Test 18 | void testSerialize() throws Exception { 19 | var book = new Book(394L, "Creative Book Title"); 20 | var jsonContent = json.write(book); 21 | assertThat(jsonContent).extractingJsonPathNumberValue("@.id") 22 | .isEqualTo(book.id().intValue()); 23 | assertThat(jsonContent).extractingJsonPathStringValue("@.title") 24 | .isEqualTo(book.title()); 25 | } 26 | 27 | @Test 28 | void testDeserialize() throws Exception { 29 | var content = """ 30 | { 31 | "id": 394, 32 | "title": "Creative Book Title" 33 | } 34 | """; 35 | assertThat(json.parse(content)) 36 | .usingRecursiveComparison() 37 | .isEqualTo(new Book(394L, "Creative Book Title")); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/src/test/java/com/thomasvitale/bookservice/BookServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 9 | import org.springframework.context.annotation.Import; 10 | import org.springframework.test.web.reactive.server.WebTestClient; 11 | 12 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) 13 | @Import(TestEnvironmentConfiguration.class) 14 | class BookServiceApplicationTests { 15 | 16 | @Autowired 17 | private WebTestClient webTestClient; 18 | 19 | @Test 20 | void whenGetRequestWithIdThenBookReturned() { 21 | var bookToCreate = new Book(null, "Title"); 22 | Book expectedBook = webTestClient 23 | .post() 24 | .uri("/books") 25 | .bodyValue(bookToCreate) 26 | .exchange() 27 | .expectStatus().isCreated() 28 | .expectBody(Book.class).value(book -> assertThat(book).isNotNull()) 29 | .returnResult().getResponseBody(); 30 | 31 | webTestClient 32 | .get() 33 | .uri("/books/" + expectedBook.id()) 34 | .exchange() 35 | .expectStatus().is2xxSuccessful() 36 | .expectBody(Book.class).value(actualBook -> { 37 | assertThat(actualBook).isNotNull(); 38 | assertThat(actualBook.title()).isEqualTo(expectedBook.title()); 39 | }); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-docker-compose/src/test/java/com/thomasvitale/bookservice/TestEnvironmentConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import org.springframework.boot.test.context.TestConfiguration; 4 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 5 | import org.springframework.context.annotation.Bean; 6 | import org.testcontainers.containers.PostgreSQLContainer; 7 | 8 | @TestConfiguration(proxyBeanMethods = false) 9 | class TestEnvironmentConfiguration { 10 | 11 | @Bean 12 | @ServiceConnection 13 | PostgreSQLContainer postgreSQLContainer() { 14 | return new PostgreSQLContainer<>("postgres:17"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-https/.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse 2 | .project 3 | .classpath 4 | .settings/ 5 | bin/ 6 | 7 | # STS 8 | .apt_generated 9 | .factorypath 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | # IntelliJ 15 | .idea 16 | *.ipr 17 | *.iml 18 | *.iws 19 | /out/ 20 | 21 | # NetBeans 22 | nb-configuration.xml 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | 29 | # Visual Studio Code 30 | .vscode 31 | 32 | # OSX 33 | .DS_Store 34 | 35 | # Vim 36 | *.swp 37 | *.swo 38 | 39 | # patch 40 | *.orig 41 | *.rej 42 | 43 | # Gradle 44 | .gradle/ 45 | build/ 46 | !gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-https/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.5.2' 3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.example' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '16' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-security' 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | 19 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 20 | testImplementation 'org.springframework.security:spring-security-test' 21 | } 22 | 23 | test { 24 | useJUnitPlatform() 25 | } 26 | -------------------------------------------------------------------------------- /spring-boot-https/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-boot-https/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-https/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /spring-boot-https/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 | -------------------------------------------------------------------------------- /spring-boot-https/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 | -------------------------------------------------------------------------------- /spring-boot-https/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-boot-https' 2 | 3 | -------------------------------------------------------------------------------- /spring-boot-https/src/main/java/com/thomasvitale/application/Application.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @SpringBootApplication 9 | public class Application { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(Application.class, args); 13 | } 14 | 15 | } 16 | 17 | @RestController 18 | class GreetingController { 19 | 20 | @GetMapping("/") 21 | public String getGreeting() { 22 | return "Welcome to Spring Boot on HTTPS!"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /spring-boot-https/src/main/java/com/thomasvitale/application/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.web.SecurityFilterChain; 7 | 8 | @Configuration 9 | public class SecurityConfig { 10 | 11 | @Bean 12 | SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 13 | return http 14 | .requiresChannel(channel -> channel.anyRequest().requiresSecure()) 15 | .authorizeRequests(authorize -> authorize.anyRequest().permitAll()) 16 | .build(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /spring-boot-https/src/main/java/com/thomasvitale/application/config/ServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.config; 2 | 3 | import org.apache.catalina.Context; 4 | import org.apache.catalina.connector.Connector; 5 | import org.apache.tomcat.util.descriptor.web.SecurityCollection; 6 | import org.apache.tomcat.util.descriptor.web.SecurityConstraint; 7 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 8 | import org.springframework.boot.web.servlet.server.ServletWebServerFactory; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | @Configuration 13 | public class ServerConfig { 14 | 15 | @Bean 16 | public ServletWebServerFactory servletContainer() { 17 | TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { 18 | @Override 19 | protected void postProcessContext(Context context) { 20 | var securityConstraint = new SecurityConstraint(); 21 | securityConstraint.setUserConstraint("CONFIDENTIAL"); 22 | var collection = new SecurityCollection(); 23 | collection.addPattern("/*"); 24 | securityConstraint.addCollection(collection); 25 | context.addConstraint(securityConstraint); 26 | } 27 | }; 28 | tomcat.addAdditionalTomcatConnectors(getHttpConnector()); 29 | return tomcat; 30 | } 31 | 32 | private Connector getHttpConnector() { 33 | var connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); 34 | connector.setScheme("http"); 35 | connector.setPort(8080); 36 | connector.setSecure(false); 37 | connector.setRedirectPort(8443); 38 | return connector; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /spring-boot-https/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | # TLS configuration 3 | ssl: 4 | # The path to the key store that holds the SSL certificate (a jks or p12 file). 5 | key-store: classpath:springboot.p12 6 | # The password used to access the key store. 7 | key-store-password: password 8 | # The type of the key store. 9 | key-store-type: pkcs12 10 | # The alias that identifies the key in the key store. 11 | key-alias: springboot 12 | # The password used to access the key in the key store. 13 | key-password: password 14 | # The port this server is listening on 15 | port: 8443 16 | -------------------------------------------------------------------------------- /spring-boot-https/src/main/resources/myCertificate.crt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-boot-https/src/main/resources/myCertificate.crt -------------------------------------------------------------------------------- /spring-boot-https/src/main/resources/springboot.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-boot-https/src/main/resources/springboot.p12 -------------------------------------------------------------------------------- /spring-boot-https/src/test/java/com/thomasvitale/application/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | 7 | @SpringBootTest 8 | class ApplicationTests { 9 | 10 | @Test 11 | void contextLoads() { 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse 2 | .project 3 | .classpath 4 | .settings/ 5 | bin/ 6 | 7 | # STS 8 | .apt_generated 9 | .factorypath 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | # IntelliJ 15 | .idea 16 | *.ipr 17 | *.iml 18 | *.iws 19 | /out/ 20 | 21 | # NetBeans 22 | nb-configuration.xml 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | 29 | # Visual Studio Code 30 | .vscode 31 | 32 | # OSX 33 | .DS_Store 34 | 35 | # Vim 36 | *.swp 37 | *.swo 38 | 39 | # patch 40 | *.orig 41 | *.rej 42 | 43 | # Gradle 44 | .gradle/ 45 | build/ 46 | !gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/Readme.MD: -------------------------------------------------------------------------------- 1 | # Spring Boot - Multitenancy 2 | 3 | This project aims at showing how to add multitenancy functionality to a Spring Boot application. 4 | 5 | The multitenancy method used in the project is the one using one single database, but multiple schemas (one per tenant). 6 | 7 | Two tenants are defined: 8 | * Argus -> TENANT_ARGUS 9 | * Acme -> TENANT_ACME 10 | 11 | The default schema is defined as a property in application.yml. In this demo the default tenant identifier is "MASTER". 12 | 13 | ## Prerequisites 14 | 15 | Both the application and the tests rely on a PostgreSQL database up and running, and initialized with the provided schema and data. 16 | 17 | 1. Open a Terminal window, navigate to the `db` folder and run the command: 18 | 19 | ```bash 20 | docker-compose up -d 21 | ``` 22 | 23 | The command will start a new PostgreSQL Docker container as defined in `db/docker-compose.yml`. 24 | 25 | 2. Open a Terminal window, navigate to the `db/init` folder and run the command: 26 | 27 | ```bash 28 | ./db_init.sh 29 | ``` 30 | 31 | The command will create the database schemas defined in `db/init/schema.sql` and load the data defined in `db/init/data`. 32 | 33 | If you get an error message due to the lack of permissions to execute the command above, then run this first: 34 | 35 | ```bash 36 | chmod +x db_init.sh 37 | ``` 38 | 39 | ## Testing the application 40 | 41 | To test the application you can either run the auto tests or run the application and test the rest endpoints. 42 | 43 | Remember to add a `X-TenantId` HTTP header with the value of the tenant you want to use (TENANT_ACME or TENANT_ARGUS). -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.2.4.RELEASE' 3 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.thomasvitale' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = JavaVersion.VERSION_11 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | runtimeOnly 'org.postgresql:postgresql' 19 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 20 | exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 21 | } 22 | } 23 | 24 | test { 25 | useJUnitPlatform() 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/db/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | database: 4 | image: "postgres" 5 | environment: 6 | - POSTGRES_USER=james_bond 7 | - POSTGRES_PASSWORD=secret_password 8 | - POSTGRES_DB=secret_database 9 | ports: 10 | - "5432:5432" 11 | volumes: 12 | - db-data:/var/lib/postgresql/data/ 13 | volumes: 14 | db-data: -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/db/init/data.sql: -------------------------------------------------------------------------------- 1 | -- Acme data 2 | INSERT INTO TENANT_ACME.NOTE (TITLE, CONTENT) values ('Acme Note 1', 'Some funny note.'); 3 | INSERT INTO TENANT_ACME.NOTE (TITLE, CONTENT) values ('Acme Note 2', 'Another funny note.'); 4 | 5 | -- Argus data 6 | INSERT INTO TENANT_ARGUS.NOTE (TITLE, CONTENT) values ('Argus Note 1', 'Some secret note.'); 7 | INSERT INTO TENANT_ARGUS.NOTE (TITLE, CONTENT) values ('Argus Note 2', 'Another secret note.'); -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/db/init/db_init.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | which psql > /dev/null || (echoerr "The PostgreSQL client is not in your PATH" && exit 1) 5 | 6 | export PGPASSWORD=secret_password 7 | psql -U james_bond -d secret_database -h localhost -f schema.sql 8 | psql -U james_bond -d secret_database -h localhost -f data.sql -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/db/init/schema.sql: -------------------------------------------------------------------------------- 1 | -- Create master and tenant schemas 2 | CREATE SCHEMA IF NOT EXISTS MASTER AUTHORIZATION james_bond; 3 | CREATE SCHEMA IF NOT EXISTS TENANT_ACME AUTHORIZATION james_bond; 4 | CREATE SCHEMA IF NOT EXISTS TENANT_ARGUS AUTHORIZATION james_bond; 5 | 6 | -- Tables for tenant schemas 7 | CREATE TABLE IF NOT EXISTS TENANT_ACME.NOTE( 8 | ID BIGSERIAL PRIMARY KEY, 9 | TITLE VARCHAR(32) NOT NULL, 10 | CONTENT VARCHAR(64) 11 | ); 12 | 13 | CREATE TABLE IF NOT EXISTS TENANT_ARGUS.NOTE( 14 | ID BIGSERIAL PRIMARY KEY, 15 | TITLE VARCHAR(32) NOT NULL, 16 | CONTENT VARCHAR(64) 17 | ); -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-boot-multitenancy-schema/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-boot-multitenancy-schema' 2 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/Application.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/business/NoteDTO.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.business; 2 | 3 | public class NoteDTO { 4 | private String title; 5 | private String content; 6 | 7 | public NoteDTO(String title, String content) { 8 | this.title = title; 9 | this.content = content; 10 | } 11 | 12 | public String getTitle() { 13 | return title; 14 | } 15 | 16 | public void setTitle(String title) { 17 | this.title = title; 18 | } 19 | 20 | public String getContent() { 21 | return content; 22 | } 23 | 24 | public void setContent(String content) { 25 | this.content = content; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/business/NoteService.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.business; 2 | 3 | import com.thomasvitale.application.data.NoteRepository; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | @Service 11 | public class NoteService { 12 | private final NoteRepository noteRepository; 13 | 14 | @Autowired 15 | public NoteService(NoteRepository noteRepository) { 16 | this.noteRepository = noteRepository; 17 | } 18 | 19 | public List getAllNotes() { 20 | List noteDTOS = new ArrayList<>(); 21 | noteRepository.findAll().forEach(organization -> 22 | noteDTOS.add(new NoteDTO(organization.getTitle(), organization.getContent())) 23 | ); 24 | return noteDTOS; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.config; 2 | 3 | import com.thomasvitale.application.multitenancy.TenantInterceptor; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | @Configuration 10 | public class WebConfig implements WebMvcConfigurer { 11 | private final TenantInterceptor tenantInterceptor; 12 | 13 | @Autowired 14 | public WebConfig(TenantInterceptor tenantInterceptor) { 15 | this.tenantInterceptor = tenantInterceptor; 16 | } 17 | 18 | @Override 19 | public void addInterceptors(InterceptorRegistry registry) { 20 | registry.addInterceptor(tenantInterceptor); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/data/Note.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.data; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class Note { 10 | 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.AUTO) 13 | private Long id; 14 | private String title; 15 | private String content; 16 | 17 | public Long getId() { 18 | return id; 19 | } 20 | 21 | public void setId(Long id) { 22 | this.id = id; 23 | } 24 | 25 | public String getTitle() { 26 | return title; 27 | } 28 | 29 | public void setTitle(String name) { 30 | this.title = name; 31 | } 32 | 33 | public String getContent() { 34 | return content; 35 | } 36 | 37 | public void setContent(String description) { 38 | this.content = description; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/data/NoteRepository.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.data; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | @Repository 7 | public interface NoteRepository extends CrudRepository { 8 | } 9 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/multitenancy/CurrentTenantIdentifierResolverImpl.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.multitenancy; 2 | 3 | import org.hibernate.context.spi.CurrentTenantIdentifierResolver; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.Objects; 8 | 9 | /** 10 | * Provides Hibernate with a strategy to resolve the tenant schema. 11 | */ 12 | @Component 13 | public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver { 14 | 15 | @Value("${multitenancy.default-tenant-id}") 16 | private String defaultTenantIdentifier; 17 | 18 | @Override 19 | public String resolveCurrentTenantIdentifier() { 20 | return Objects.requireNonNullElse(TenantContext.getCurrentTenant(), defaultTenantIdentifier); 21 | } 22 | 23 | @Override 24 | public boolean validateExistingCurrentSessions() { 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/multitenancy/JpaConfig.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.multitenancy; 2 | 3 | import com.thomasvitale.application.Application; 4 | import org.hibernate.MultiTenancyStrategy; 5 | import org.hibernate.cfg.Environment; 6 | import org.hibernate.context.spi.CurrentTenantIdentifierResolver; 7 | import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.orm.jpa.JpaVendorAdapter; 13 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 14 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 15 | 16 | import javax.sql.DataSource; 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | 20 | /** 21 | * Configure JPA with Hibernate-specific configuration 22 | * to support multitenancy. 23 | */ 24 | @Configuration 25 | public class JpaConfig { 26 | private final JpaProperties jpaProperties; 27 | 28 | @Autowired 29 | public JpaConfig(JpaProperties jpaProperties) { 30 | this.jpaProperties = jpaProperties; 31 | } 32 | 33 | @Bean 34 | public JpaVendorAdapter jpaVendorAdapter() { 35 | return new HibernateJpaVendorAdapter(); 36 | } 37 | 38 | @Bean 39 | public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, 40 | MultiTenantConnectionProvider multiTenantConnectionProviderImpl, 41 | CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl 42 | ) { 43 | // Combine JPA properties defined in application.yml with multitenancy properties defined here. 44 | Map properties = new HashMap<>(jpaProperties.getProperties()); 45 | properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA); 46 | properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl); 47 | properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl); 48 | 49 | LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); 50 | em.setDataSource(dataSource); 51 | em.setPackagesToScan(Application.class.getPackageName()); 52 | em.setJpaVendorAdapter(jpaVendorAdapter()); 53 | em.setJpaPropertyMap(properties); 54 | return em; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/multitenancy/MultiTenantConnectionProviderImpl.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.multitenancy; 2 | 3 | import org.hibernate.HibernateException; 4 | import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.stereotype.Component; 8 | 9 | import javax.sql.DataSource; 10 | import java.sql.Connection; 11 | import java.sql.SQLException; 12 | import java.sql.Statement; 13 | 14 | /** 15 | * Provides tenant-aware connection to the data source, 16 | * using the schema of the relevant tenant. 17 | */ 18 | @Component 19 | public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider { 20 | private final transient DataSource dataSource; 21 | 22 | @Value("${multitenancy.default-tenant-id}") 23 | private String defaultTenantIdentifier; 24 | 25 | @Autowired 26 | public MultiTenantConnectionProviderImpl(DataSource dataSource) { 27 | this.dataSource = dataSource; 28 | } 29 | 30 | @Override 31 | public Connection getAnyConnection() throws SQLException { 32 | return dataSource.getConnection(); 33 | } 34 | 35 | @Override 36 | public void releaseAnyConnection(Connection connection) throws SQLException { 37 | connection.close(); 38 | } 39 | 40 | @Override 41 | public Connection getConnection(String tenantIdentifier) throws SQLException { 42 | final Connection connection = getAnyConnection(); 43 | try (Statement statement = connection.createStatement()) { 44 | // SQL statement specific for PostgreSQL 45 | statement.execute(String.format("SET search_path to %s;", tenantIdentifier)); 46 | } catch (SQLException ex) { 47 | throw new HibernateException("Could not set the schema for the specified tenant: " + tenantIdentifier, ex); 48 | } 49 | 50 | return connection; 51 | } 52 | 53 | @Override 54 | public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException { 55 | try (Statement statement = connection.createStatement()) { 56 | // SQL statement specific for PostgreSQL 57 | statement.execute(String.format("SET search_path to %s;", defaultTenantIdentifier)); 58 | } catch (SQLException ex) { 59 | // Throw an exception to make sure the connection is not returned to the pool, 60 | // when not possible to reset the tenant schema usage. 61 | throw new HibernateException("Could not release the schema for the specified tenant: " + tenantIdentifier, ex); 62 | } 63 | 64 | connection.close(); 65 | } 66 | 67 | @Override 68 | public boolean supportsAggressiveRelease() { 69 | return true; 70 | } 71 | 72 | @Override 73 | public boolean isUnwrappableAs(Class unwrapType) { 74 | return false; 75 | } 76 | 77 | @Override 78 | public T unwrap(Class unwrapType) { 79 | return null; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/multitenancy/TenantContext.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.multitenancy; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | /** 7 | * A shared, thread-local context for the current tenant. 8 | * It is set before each request and removed after. 9 | * 10 | * The value is stored as an InheritableThreadLocal for two reasons: 11 | * - the application can serve multiple tenants at the same time, 12 | * so the context should be defined per thread; 13 | * - being inheritable, any child thread can inherit the tenant context 14 | * from the parent thread. 15 | */ 16 | public class TenantContext { 17 | private static Logger logger = LoggerFactory.getLogger(TenantContext.class.getName()); 18 | private static ThreadLocal currentTenant = new InheritableThreadLocal<>(); 19 | 20 | private TenantContext() {} 21 | 22 | public static void setCurrentTenant(String tenant) { 23 | logger.info("Setting tenant to {}", tenant); 24 | currentTenant.set(tenant); 25 | } 26 | 27 | public static String getCurrentTenant() { 28 | return currentTenant.get(); 29 | } 30 | 31 | public static void clear() { 32 | currentTenant.remove(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/multitenancy/TenantInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.multitenancy; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.servlet.ModelAndView; 6 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.util.Objects; 11 | 12 | /** 13 | * An interceptor that reads the tenant header for each HTTP request 14 | * and sets the tenant context. 15 | * After the request has been handled, it clears the tenant context. 16 | */ 17 | @Component 18 | public class TenantInterceptor extends HandlerInterceptorAdapter { 19 | 20 | @Value("${multitenancy.http-header}") 21 | private String tenantHttpHeader; 22 | 23 | @Value("${multitenancy.default-tenant-id}") 24 | private String defaultTenantIdentifier; 25 | 26 | @Override 27 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { 28 | String tenantId = request.getHeader(this.tenantHttpHeader); 29 | TenantContext.setCurrentTenant(Objects.requireNonNullElse(tenantId, defaultTenantIdentifier)); 30 | return true; 31 | } 32 | 33 | @Override 34 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { 35 | TenantContext.clear(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/java/com/thomasvitale/application/web/NoteRestController.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.web; 2 | 3 | import com.thomasvitale.application.business.NoteDTO; 4 | import com.thomasvitale.application.business.NoteService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import java.util.List; 11 | 12 | @RestController 13 | @RequestMapping("/api/notes") 14 | public class NoteRestController { 15 | private final NoteService noteService; 16 | 17 | @Autowired 18 | public NoteRestController(NoteService noteService) { 19 | this.noteService = noteService; 20 | } 21 | 22 | @GetMapping 23 | public List getNotes() { 24 | return noteService.getAllNotes(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # Spring Boot 2 | spring: 3 | # Data Source 4 | datasource: 5 | platform: postgres 6 | url: jdbc:postgresql://localhost:5432/secret_database 7 | username: james_bond 8 | password: secret_password 9 | hikari: 10 | maximum-pool-size: 5 11 | initialization-fail-timeout: 0 12 | # JPA/Hibernate 13 | jpa: 14 | database: postgresql 15 | hibernate: 16 | ddl-auto: none 17 | naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 18 | show-sql: true 19 | 20 | # Multitenancy 21 | multitenancy: 22 | http-header: X-TenantId 23 | default-tenant-id: MASTER 24 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Hello 6 | 7 | 8 | 9 |

Hello World!

10 | 11 | 12 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/test/java/com/thomasvitale/application/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-multitenancy-schema/src/test/java/com/thomasvitale/application/web/NoteRestControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.application.web; 2 | 3 | import com.thomasvitale.application.Application; 4 | import org.json.JSONException; 5 | import org.junit.jupiter.api.Test; 6 | import org.skyscreamer.jsonassert.JSONAssert; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.web.client.TestRestTemplate; 11 | import org.springframework.boot.web.server.LocalServerPort; 12 | import org.springframework.http.HttpEntity; 13 | import org.springframework.http.HttpHeaders; 14 | import org.springframework.http.HttpMethod; 15 | import org.springframework.http.ResponseEntity; 16 | 17 | @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 18 | public class NoteRestControllerTest { 19 | private static final String ENDPOINT = "/api/notes"; 20 | 21 | @Autowired 22 | private TestRestTemplate restTemplate; 23 | 24 | @LocalServerPort 25 | private int port; 26 | 27 | @Value("${multitenancy.http-header}") 28 | private String tenantHeader; 29 | 30 | @Test 31 | public void getNotesForTenantAcme() throws JSONException { 32 | HttpHeaders headers = new HttpHeaders(); 33 | headers.add(tenantHeader, "TENANT_ACME"); 34 | HttpEntity entity = new HttpEntity<>(null, headers); 35 | ResponseEntity response = restTemplate.exchange( 36 | buildUrlWithPort(ENDPOINT), 37 | HttpMethod.GET, 38 | entity, 39 | String.class 40 | ); 41 | 42 | String expected = "[{\"title\":\"Acme Note 1\",\"content\":\"Some funny note.\"},{\"title\":\"Acme Note 2\",\"content\":\"Another funny note.\"}]"; 43 | 44 | JSONAssert.assertEquals(expected, response.getBody(), false); 45 | } 46 | 47 | @Test 48 | public void getNotesForTenantArgus() throws JSONException { 49 | HttpHeaders headers = new HttpHeaders(); 50 | headers.add(tenantHeader, "TENANT_ARGUS"); 51 | HttpEntity entity = new HttpEntity<>(null, headers); 52 | ResponseEntity response = restTemplate.exchange( 53 | buildUrlWithPort(ENDPOINT), 54 | HttpMethod.GET, 55 | entity, 56 | String.class 57 | ); 58 | 59 | String expected = "[{\"title\":\"Argus Note 1\",\"content\":\"Some secret note.\"},{\"title\":\"Argus Note 2\",\"content\":\"Another secret note.\"}]"; 60 | 61 | JSONAssert.assertEquals(expected, response.getBody(), false); 62 | } 63 | 64 | private String buildUrlWithPort(String uri) { 65 | return "http://localhost:" + port + uri; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/.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 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/.sdkmanrc: -------------------------------------------------------------------------------- 1 | # Enable auto-env through the sdkman_auto_env config 2 | # Add key=value pairs of SDKs to use below 3 | java=23-graalce 4 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.4.2' 4 | id 'io.spring.dependency-management' version '1.1.7' 5 | } 6 | 7 | group = 'com.thomasvitale' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | toolchain { 12 | languageVersion = JavaLanguageVersion.of(23) 13 | } 14 | } 15 | 16 | repositories { 17 | mavenCentral() 18 | } 19 | 20 | dependencies { 21 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 22 | implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' 23 | implementation 'org.springframework.boot:spring-boot-starter-validation' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | 26 | implementation 'org.flywaydb:flyway-core' 27 | implementation 'org.flywaydb:flyway-database-postgresql' 28 | 29 | developmentOnly 'org.springframework.boot:spring-boot-devtools' 30 | 31 | runtimeOnly 'org.postgresql:postgresql' 32 | 33 | testAndDevelopmentOnly 'org.springframework.boot:spring-boot-devtools' 34 | 35 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 36 | testImplementation 'org.springframework.boot:spring-boot-starter-webflux' 37 | testImplementation 'org.springframework.boot:spring-boot-testcontainers' 38 | testImplementation 'org.testcontainers:junit-jupiter' 39 | testImplementation 'org.testcontainers:postgresql' 40 | } 41 | 42 | tasks.named('test') { 43 | useJUnitPlatform() 44 | } 45 | 46 | tasks.named('bootBuildImage') { 47 | builder = "docker.io/paketobuildpacks/builder-noble-java-tiny" 48 | } 49 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-boot-testcontainers/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-testcontainers/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/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 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 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 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | org.gradle.wrapper.GradleWrapperMain \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/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 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'book-service' 2 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/src/main/java/com/thomasvitale/bookservice/BookServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.data.annotation.Id; 9 | import org.springframework.data.repository.ListCrudRepository; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.ResponseStatus; 17 | import org.springframework.web.bind.annotation.RestController; 18 | 19 | import jakarta.validation.Valid; 20 | import jakarta.validation.constraints.NotEmpty; 21 | 22 | @SpringBootApplication 23 | public class BookServiceApplication { 24 | 25 | public static void main(String[] args) { 26 | SpringApplication.run(BookServiceApplication.class, args); 27 | } 28 | 29 | } 30 | 31 | @RestController 32 | @RequestMapping("/books") 33 | class BookController { 34 | private final BookRepository bookRepository; 35 | 36 | BookController(BookRepository bookRepository) { 37 | this.bookRepository = bookRepository; 38 | } 39 | 40 | @GetMapping 41 | List getBooks() { 42 | return bookRepository.findAll(); 43 | } 44 | 45 | @GetMapping("{id}") 46 | Optional getBookById(@PathVariable Long id) { 47 | return bookRepository.findById(id); 48 | } 49 | 50 | @PostMapping 51 | @ResponseStatus(HttpStatus.CREATED) 52 | Book addBook(@RequestBody @Valid Book book) { 53 | return bookRepository.save(book); 54 | } 55 | } 56 | 57 | record Book(@Id Long id, @NotEmpty String title){} 58 | 59 | interface BookRepository extends ListCrudRepository{} 60 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | spring: 5 | application: 6 | name: book-service 7 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/src/main/resources/db/migration/V1__Init_schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE book( 2 | id BIGSERIAL PRIMARY KEY, 3 | title VARCHAR(255) NOT NULL 4 | ); 5 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/src/test/java/com/thomasvitale/bookservice/BookJsonTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.json.JsonTest; 7 | import org.springframework.boot.test.json.JacksonTester; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | @JsonTest 12 | public class BookJsonTests { 13 | 14 | @Autowired 15 | private JacksonTester json; 16 | 17 | @Test 18 | void testSerialize() throws Exception { 19 | var book = new Book(394L, "Creative Book Title"); 20 | var jsonContent = json.write(book); 21 | assertThat(jsonContent).extractingJsonPathNumberValue("@.id") 22 | .isEqualTo(book.id().intValue()); 23 | assertThat(jsonContent).extractingJsonPathStringValue("@.title") 24 | .isEqualTo(book.title()); 25 | } 26 | 27 | @Test 28 | void testDeserialize() throws Exception { 29 | var content = """ 30 | { 31 | "id": 394, 32 | "title": "Creative Book Title" 33 | } 34 | """; 35 | assertThat(json.parse(content)) 36 | .usingRecursiveComparison() 37 | .isEqualTo(new Book(394L, "Creative Book Title")); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/src/test/java/com/thomasvitale/bookservice/BookServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 9 | import org.springframework.context.annotation.Import; 10 | import org.springframework.test.web.reactive.server.WebTestClient; 11 | 12 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) 13 | @Import(TestBookServiceApplication.class) 14 | class BookServiceApplicationTests { 15 | 16 | @Autowired 17 | private WebTestClient webTestClient; 18 | 19 | @Test 20 | void whenGetRequestWithIdThenBookReturned() { 21 | var bookToCreate = new Book(null, "Title"); 22 | Book expectedBook = webTestClient 23 | .post() 24 | .uri("/books") 25 | .bodyValue(bookToCreate) 26 | .exchange() 27 | .expectStatus().isCreated() 28 | .expectBody(Book.class).value(book -> assertThat(book).isNotNull()) 29 | .returnResult().getResponseBody(); 30 | 31 | webTestClient 32 | .get() 33 | .uri("/books/" + expectedBook.id()) 34 | .exchange() 35 | .expectStatus().is2xxSuccessful() 36 | .expectBody(Book.class).value(actualBook -> { 37 | assertThat(actualBook).isNotNull(); 38 | assertThat(actualBook.title()).isEqualTo(expectedBook.title()); 39 | }); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-testcontainers/src/test/java/com/thomasvitale/bookservice/TestBookServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.bookservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.devtools.restart.RestartScope; 5 | import org.springframework.boot.test.context.TestConfiguration; 6 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 7 | import org.springframework.context.annotation.Bean; 8 | import org.testcontainers.containers.PostgreSQLContainer; 9 | 10 | @TestConfiguration(proxyBeanMethods = false) 11 | public class TestBookServiceApplication { 12 | 13 | @Bean 14 | @RestartScope 15 | @ServiceConnection 16 | PostgreSQLContainer postgreSQLContainer() { 17 | return new PostgreSQLContainer<>("postgres:17"); 18 | } 19 | 20 | public static void main(String[] args) { 21 | SpringApplication.from(BookServiceApplication::main) 22 | .with(TestBookServiceApplication.class) 23 | .run(args); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /spring-cloud-config/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | ################################ 26 | ############ MAC ############### 27 | ################################ 28 | 29 | # General 30 | .DS_Store 31 | .AppleDouble 32 | .LSOverride 33 | 34 | # Icon must end with two \r 35 | Icon 36 | 37 | # Thumbnails 38 | ._* 39 | 40 | # Files that might appear in the root of a volume 41 | .DocumentRevisions-V100 42 | .fseventsd 43 | .Spotlight-V100 44 | .TemporaryItems 45 | .Trashes 46 | .VolumeIcon.icns 47 | .com.apple.timemachine.donotpresent 48 | 49 | # Directories potentially created on remote AFP share 50 | .AppleDB 51 | .AppleDesktop 52 | Network Trash Folder 53 | Temporary Items 54 | .apdisk 55 | 56 | ################################ 57 | ############ JAVA ############## 58 | ################################ 59 | 60 | HELP.md 61 | .gradle 62 | build/ 63 | !gradle/wrapper/gradle-wrapper.jar 64 | !**/src/main/** 65 | !**/src/test/** 66 | gradle.properties 67 | 68 | ### STS ### 69 | .apt_generated 70 | .classpath 71 | .factorypath 72 | .project 73 | .settings 74 | .springBeans 75 | .sts4-cache 76 | 77 | ### IntelliJ IDEA ### 78 | .idea 79 | *.iws 80 | *.iml 81 | *.ipr 82 | out/ 83 | 84 | ### NetBeans ### 85 | /nbproject/private/ 86 | /nbbuild/ 87 | /dist/ 88 | /nbdist/ 89 | /.nb-gradle/ 90 | 91 | ### VS Code ### 92 | .vscode/ -------------------------------------------------------------------------------- /spring-cloud-config/README.md: -------------------------------------------------------------------------------- 1 | # Spring Cloud Config 2 | 3 | * Config Server (Spring Cloud Config Server) 4 | * Greeting Service (Spring Boot + Spring Cloud Config Client) -------------------------------------------------------------------------------- /spring-cloud-config/config-server/.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 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.6.0-M3' 3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.thomasvitale' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | repositories { 12 | mavenCentral() 13 | maven { url 'https://repo.spring.io/milestone' } 14 | } 15 | 16 | ext { 17 | set('springCloudVersion', "2021.0.0-M3") 18 | } 19 | 20 | dependencies { 21 | implementation 'org.springframework.cloud:spring-cloud-config-server' 22 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 23 | } 24 | 25 | dependencyManagement { 26 | imports { 27 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 28 | } 29 | } 30 | 31 | test { 32 | useJUnitPlatform() 33 | } 34 | 35 | bootBuildImage { 36 | imageName = "thomasvitale/${project.name}:${project.version}" 37 | environment = ["BP_JVM_VERSION" : "17.*"] 38 | } 39 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-cloud-config/config-server/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-cloud-config/config-server/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/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 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/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 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { url 'https://repo.spring.io/milestone' } 4 | gradlePluginPortal() 5 | } 6 | resolutionStrategy { 7 | eachPlugin { 8 | if (requested.id.id == 'org.springframework.boot') { 9 | useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") 10 | } 11 | } 12 | } 13 | } 14 | 15 | rootProject.name = 'config-server' 16 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/src/main/java/com/thomasvitale/configserver/ConfigServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.configserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.config.server.EnableConfigServer; 6 | 7 | @SpringBootApplication 8 | @EnableConfigServer 9 | public class ConfigServerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ConfigServerApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8888 3 | 4 | spring: 5 | application: 6 | name: config-server 7 | cloud: 8 | config: 9 | server: 10 | git: 11 | uri: https://github.com/ThomasVitale/config-repo 12 | -------------------------------------------------------------------------------- /spring-cloud-config/config-server/src/test/java/com/thomasvitale/configserver/ConfigServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.configserver; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.boot.test.web.client.TestRestTemplate; 7 | import org.springframework.boot.web.server.LocalServerPort; 8 | import org.springframework.cloud.config.environment.Environment; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 15 | class ConfigServerApplicationTests { 16 | 17 | @LocalServerPort 18 | private int port; 19 | 20 | @Autowired 21 | private TestRestTemplate restTemplate; 22 | 23 | @Test 24 | void defaultConfigurationAvailable() { 25 | ResponseEntity entity = restTemplate 26 | .getForEntity("http://localhost:" + port + "/application/default", Environment.class); 27 | assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); 28 | } 29 | 30 | @Test 31 | void greetingServiceConfigurationAvailable() { 32 | ResponseEntity entity = restTemplate 33 | .getForEntity("http://localhost:" + port + "/application/greeting-service", Environment.class); 34 | assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | ################################ 26 | ############ MAC ############### 27 | ################################ 28 | 29 | # General 30 | .DS_Store 31 | .AppleDouble 32 | .LSOverride 33 | 34 | # Icon must end with two \r 35 | Icon 36 | 37 | # Thumbnails 38 | ._* 39 | 40 | # Files that might appear in the root of a volume 41 | .DocumentRevisions-V100 42 | .fseventsd 43 | .Spotlight-V100 44 | .TemporaryItems 45 | .Trashes 46 | .VolumeIcon.icns 47 | .com.apple.timemachine.donotpresent 48 | 49 | # Directories potentially created on remote AFP share 50 | .AppleDB 51 | .AppleDesktop 52 | Network Trash Folder 53 | Temporary Items 54 | .apdisk 55 | 56 | ################################ 57 | ############ JAVA ############## 58 | ################################ 59 | 60 | HELP.md 61 | .gradle 62 | build/ 63 | !gradle/wrapper/gradle-wrapper.jar 64 | !**/src/main/** 65 | !**/src/test/** 66 | gradle.properties 67 | 68 | ### STS ### 69 | .apt_generated 70 | .classpath 71 | .factorypath 72 | .project 73 | .settings 74 | .springBeans 75 | .sts4-cache 76 | 77 | ### IntelliJ IDEA ### 78 | .idea 79 | *.iws 80 | *.iml 81 | *.ipr 82 | out/ 83 | 84 | ### NetBeans ### 85 | /nbproject/private/ 86 | /nbbuild/ 87 | /dist/ 88 | /nbdist/ 89 | /.nb-gradle/ 90 | 91 | ### VS Code ### 92 | .vscode/ -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.6.0-M3' 3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.thomasvitale' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | repositories { 12 | mavenCentral() 13 | maven { url 'https://repo.spring.io/milestone' } 14 | } 15 | 16 | ext { 17 | set('springCloudVersion', "2021.0.0-M3") 18 | } 19 | 20 | dependencies { 21 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 22 | implementation 'org.springframework.boot:spring-boot-starter-web' 23 | implementation 'org.springframework.cloud:spring-cloud-starter-config' 24 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 25 | } 26 | 27 | dependencyManagement { 28 | imports { 29 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 30 | } 31 | } 32 | 33 | test { 34 | useJUnitPlatform() 35 | } 36 | 37 | bootBuildImage { 38 | imageName = "thomasvitale/${project.name}:${project.version}" 39 | environment = ["BP_JVM_VERSION" : "17.*"] 40 | } 41 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-cloud-config/greeting-service/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/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 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/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 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { url 'https://repo.spring.io/milestone' } 4 | gradlePluginPortal() 5 | } 6 | resolutionStrategy { 7 | eachPlugin { 8 | if (requested.id.id == 'org.springframework.boot') { 9 | useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") 10 | } 11 | } 12 | } 13 | } 14 | 15 | rootProject.name = 'greeting-service' 16 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/src/main/java/com/thomasvitale/greetingservice/GreetingController.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.greetingservice; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.cloud.context.config.annotation.RefreshScope; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @RefreshScope 10 | public class GreetingController { 11 | 12 | @Value("${greeting}") 13 | private String greeting; 14 | 15 | @GetMapping("greeting") 16 | public String getGreeting() { 17 | return greeting; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/src/main/java/com/thomasvitale/greetingservice/GreetingServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.greetingservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GreetingServiceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GreetingServiceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | greeting: "Hello Local!" 5 | 6 | spring: 7 | application: 8 | name: greeting-service 9 | config: 10 | import: "optional:configserver:" 11 | cloud: 12 | config: 13 | uri: http://localhost:8888 14 | 15 | management: 16 | endpoints: 17 | web: 18 | exposure: 19 | include: refresh 20 | -------------------------------------------------------------------------------- /spring-cloud-config/greeting-service/src/test/java/com/thomasvitale/greetingservice/GreetingServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.greetingservice; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class GreetingServiceApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-native-graalvm/.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 | -------------------------------------------------------------------------------- /spring-native-graalvm/README.md: -------------------------------------------------------------------------------- 1 | # Spring Native GraalVM 2 | 3 | This tutorial is for demonstrating the usage of Spring Native for compiling Spring Boot applications 4 | to native executables using GraalVM native-image compiler. 5 | 6 | Check the [official documentation](https://docs.spring.io/spring-native/docs/current/reference/htmlsingle/) 7 | for more information about the project. 8 | 9 | ## How to run it 10 | 11 | Build the Spring Boot application as a native GraalVM image: 12 | 13 | ```bash 14 | ./gradlew bootBuildImage 15 | ``` 16 | 17 | Run the native image: 18 | 19 | ```bash 20 | docker-compose up -d 21 | ``` 22 | 23 | Call the application REST endpoint: 24 | 25 | ```bash 26 | http :8080 27 | ``` -------------------------------------------------------------------------------- /spring-native-graalvm/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.4.3' 3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 | id 'java' 5 | id 'org.springframework.experimental.aot' version '0.9.0' 6 | } 7 | 8 | group = 'com.thomasvitale' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '11' 11 | 12 | repositories { 13 | maven { url 'https://repo.spring.io/release' } 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 19 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 20 | testImplementation 'io.projectreactor:reactor-test' 21 | } 22 | 23 | test { 24 | useJUnitPlatform() 25 | } 26 | 27 | bootBuildImage { 28 | builder = 'paketobuildpacks/builder:tiny' 29 | environment = ['BP_NATIVE_IMAGE': 'true'] 30 | } 31 | -------------------------------------------------------------------------------- /spring-native-graalvm/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | services: 3 | spring-native-graalvm: 4 | image: "spring-native-graalvm:1.0.0" 5 | container_name: "spring-native-graalvm" 6 | ports: 7 | - 8080:8080 8 | -------------------------------------------------------------------------------- /spring-native-graalvm/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThomasVitale/spring-tutorials/b998faa1288ec11e9a2045f343c8f7e5bb243a1a/spring-native-graalvm/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-native-graalvm/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /spring-native-graalvm/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 | 133 | JAVACMD=$(cygpath --unix "$JAVACMD") 134 | 135 | # We build the pattern for arguments to be converted via cygpath 136 | ROOTDIRSRAW=$(find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null) 137 | SEP="" 138 | for dir in $ROOTDIRSRAW; do 139 | ROOTDIRS="$ROOTDIRS$SEP$dir" 140 | SEP="|" 141 | done 142 | OURCYGPATTERN="(^($ROOTDIRS))" 143 | # Add a user-defined pattern to the cygpath arguments 144 | if [ "$GRADLE_CYGPATTERN" != "" ]; then 145 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 146 | fi 147 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 148 | i=0 149 | for arg in "$@"; do 150 | CHECK=$(echo "$arg" | egrep -c "$OURCYGPATTERN" -) 151 | CHECK2=$(echo "$arg" | egrep -c "^-") ### Determine if an option 152 | 153 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ]; then ### Added a condition 154 | eval $(echo args$i)=$(cygpath --path --ignore --mixed "$arg") 155 | else 156 | eval $(echo args$i)="\"$arg\"" 157 | fi 158 | i=$(expr $i + 1) 159 | done 160 | case $i in 161 | 0) set -- ;; 162 | 1) set -- "$args0" ;; 163 | 2) set -- "$args0" "$args1" ;; 164 | 3) set -- "$args0" "$args1" "$args2" ;; 165 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 166 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 167 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 168 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 169 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 170 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 171 | esac 172 | fi 173 | 174 | # Escape application args 175 | save() { 176 | for i; do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"; done 177 | echo " " 178 | } 179 | APP_ARGS=$(save "$@") 180 | 181 | # Collect all arguments for the java command, following the shell quoting and substitution rules 182 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 183 | 184 | exec "$JAVACMD" "$@" 185 | -------------------------------------------------------------------------------- /spring-native-graalvm/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 | -------------------------------------------------------------------------------- /spring-native-graalvm/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { url 'https://repo.spring.io/release' } 4 | gradlePluginPortal() 5 | } 6 | } 7 | rootProject.name = 'spring-native-graalvm' 8 | -------------------------------------------------------------------------------- /spring-native-graalvm/src/main/java/com/thomasvitale/demo/SpringNativeGraalvmApplication.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.demo; 2 | 3 | import reactor.core.publisher.Mono; 4 | 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.web.reactive.function.server.RouterFunction; 9 | import org.springframework.web.reactive.function.server.ServerResponse; 10 | 11 | import static org.springframework.web.reactive.function.server.RouterFunctions.route; 12 | import static org.springframework.web.reactive.function.server.ServerResponse.ok; 13 | 14 | @SpringBootApplication 15 | public class SpringNativeGraalvmApplication { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(SpringNativeGraalvmApplication.class, args); 19 | } 20 | 21 | @Bean 22 | RouterFunction routes() { 23 | return route() 24 | .GET("/", request -> ok().body(Mono.just("Spring Native and Beyond!"), String.class)) 25 | .build(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-native-graalvm/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | -------------------------------------------------------------------------------- /spring-native-graalvm/src/test/java/com/thomasvitale/demo/SpringNativeGraalvmApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.thomasvitale.demo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.web.reactive.server.WebTestClient; 9 | 10 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 11 | @AutoConfigureWebTestClient 12 | class SpringNativeGraalvmApplicationTests { 13 | 14 | @Autowired 15 | private WebTestClient webClient; 16 | 17 | @Test 18 | void whenGetBooksThenReturn() { 19 | webClient 20 | .get().uri("/") 21 | .exchange() 22 | .expectStatus().is2xxSuccessful() 23 | .expectBody(String.class).isEqualTo("Spring Native and Beyond!"); 24 | } 25 | } 26 | --------------------------------------------------------------------------------