diff --git a/.github/workflows/label.yml b/.github/workflows/label.yml index c5b704e..c9c52fe 100644 --- a/.github/workflows/label.yml +++ b/.github/workflows/label.yml @@ -1,10 +1,3 @@ -# This workflow will triage pull requests and apply a label based on the -# paths that are modified in the pull request. -# -# To use this workflow, you will need to set up a .github/labeler.yml -# file with configuration. For more information, see: -# https://github.com/actions/labeler - name: Labeler on: [pull_request_target] diff --git a/.github/workflows/spring-mysql-example.yml b/.github/workflows/spring-mysql-example.yml new file mode 100644 index 0000000..be82069 --- /dev/null +++ b/.github/workflows/spring-mysql-example.yml @@ -0,0 +1,68 @@ +name: spring-mysql-example CI Build + +on: + pull_request: + branches: [master] + paths: + - "spring-mysql-example/**" + types: + - opened + - synchronize + - reopened + +jobs: + + integration-tests: + name: Run Unit & Integration Tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: spring-mysql-example + strategy: + matrix: + distribution: [ 'temurin' ] + java: [ '21' ] + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v5.0.0 + with: + java-version: ${{ matrix.java }} + distribution: ${{ matrix.distribution }} + cache: 'maven' + - name: Build and analyze + run: ./mvnw clean verify + + health-check: + name: Health Check on Services + runs-on: ubuntu-latest + steps: + - name: Checkout repository and submodules + uses: actions/checkout@v5 + with: + submodules: true + + - name: Extract service names from docker compose + id: services + run: | + echo "services<> $GITHUB_OUTPUT + docker compose -f ./spring-mysql-example/compose.yaml config --services >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Start containers with Compose Action + uses: hoverkraft-tech/compose-action@v2.4.1 + with: + compose-file: './spring-mysql-example/compose.yaml' + services: ${{ steps.services.outputs.services }} + up-flags: '--build' + down-flags: '--volumes' + + - name: Wait for containers to initialize + run: sleep 30 + + - name: Check container health + run: | + ./.github/scripts/check-container-health.sh "${{ steps.services.outputs.services }}" diff --git a/.github/workflows/spring-postgres-example.yml b/.github/workflows/spring-postgres-example.yml new file mode 100644 index 0000000..19eeddf --- /dev/null +++ b/.github/workflows/spring-postgres-example.yml @@ -0,0 +1,68 @@ +name: spring-postgres-example CI Build + +on: + pull_request: + branches: [master] + paths: + - "spring-postgres-example/**" + types: + - opened + - synchronize + - reopened + +jobs: + + integration-tests: + name: Run Unit & Integration Tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: spring-postgres-example + strategy: + matrix: + distribution: [ 'temurin' ] + java: [ '21' ] + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v5.0.0 + with: + java-version: ${{ matrix.java }} + distribution: ${{ matrix.distribution }} + cache: 'maven' + - name: Build and analyze + run: ./mvnw clean verify + + health-check: + name: Health Check on Services + runs-on: ubuntu-latest + steps: + - name: Checkout repository and submodules + uses: actions/checkout@v5 + with: + submodules: true + + - name: Extract service names from docker compose + id: services + run: | + echo "services<> $GITHUB_OUTPUT + docker compose -f ./spring-postgres-example/compose.yaml config --services >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Start containers with Compose Action + uses: hoverkraft-tech/compose-action@v2.4.1 + with: + compose-file: './spring-postgres-example/compose.yaml' + services: ${{ steps.services.outputs.services }} + up-flags: '--build' + down-flags: '--volumes' + + - name: Wait for containers to initialize + run: sleep 30 + + - name: Check container health + run: | + ./.github/scripts/check-container-health.sh "${{ steps.services.outputs.services }}" diff --git a/README.md b/README.md index c849302..ef02904 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,8 @@ Below you will find a summary table of each subproject. For more details, please | [Spring Boot + Kafka](./spring-kafka-example) | Demonstrates a basic integration between Spring Boot and Apache Kafka. | | [Spring Boot + Keycloak](./spring-keycloak-example) | Demonstrates a basic integration between Spring Boot and Keycloak. | | [Spring Boot + Oracle](./spring-oracle-example) | Demonstrates a basic integration between Spring Boot and Oracle. | +| [Spring Boot + Postgres](./spring-postgres-example) | Demonstrates a basic integration between Spring Boot and Postgres. | +| [Spring Boot + Mysql](./spring-mysql-example) | Demonstrates a basic integration between Spring Boot and Mysql. | | [Spring Boot + Grafana + Prometheus](./spring-prometheus-grafana-example) | Demonstrates a basic integration between Spring Boot With Grafana and Prometheus. | --- diff --git a/pom.xml b/pom.xml index a7d1121..cc729d4 100644 --- a/pom.xml +++ b/pom.xml @@ -16,8 +16,10 @@ spring-prometheus-grafana-example spring-keycloak-example spring-jasper-example - spring-oracle-example spring-multimodule-example + spring-mysql-example + spring-postgres-example + spring-oracle-example \ No newline at end of file diff --git a/spring-multimodule-example/.gitignore b/spring-multimodule-example/.gitignore new file mode 100644 index 0000000..c487cab --- /dev/null +++ b/spring-multimodule-example/.gitignore @@ -0,0 +1,31 @@ +!**/src/main/**/target/ +!**/src/test/**/target/ +!**/.idea + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/spring-mysql-example/.dockerignore b/spring-mysql-example/.dockerignore new file mode 100644 index 0000000..8893889 --- /dev/null +++ b/spring-mysql-example/.dockerignore @@ -0,0 +1,62 @@ +# Include any files or directories that you don't want to be copied to your +# container here (e.g., local build artifacts, temporary files, etc.). +# +# For more help, visit the .dockerignore file reference guide at +# https://docs.docker.com/go/build-context-dockerignore/ + +**/.DS_Store +**/.classpath +**/.dockerignore +**/.env +**/.factorypath +**/.git +**/.gitignore +**/.idea +**/.project +**/.sts4-cache +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.next +**/.cache +**/*.dbmdl +**/*.jfm +**/charts +**/docker-compose* +**/compose.y*ml +**/Dockerfile* +**/secrets.dev.yaml +**/values.dev.yaml +**/vendor +LICENSE +README.md +**/*.class +**/*.iml +**/*.ipr +**/*.iws +**/*.log +**/.apt_generated +**/.gradle +**/.gradletasknamecache +**/.nb-gradle +**/.springBeans +**/build +**/dist +**/gradle-app.setting +**/nbbuild +**/nbdist +**/nbproject/private +**/target +*.ctxt +.mtj.tmp +.mvn/timing.properties +buildNumber.properties +dependency-reduced-pom.xml +hs_err_pid* +pom.xml.next +pom.xml.releaseBackup +pom.xml.tag +pom.xml.versionsBackup +release.properties +replay_pid* \ No newline at end of file diff --git a/spring-mysql-example/.github/workflows/maven.yml b/spring-mysql-example/.github/workflows/maven.yml new file mode 100644 index 0000000..16d1a66 --- /dev/null +++ b/spring-mysql-example/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +name: CI Build + +on: + push: + branches: + - "**" + +jobs: + build: + name: Build + runs-on: ubuntu-latest + strategy: + matrix: + distribution: [ 'temurin' ] + java: [ '21' ] + steps: + - uses: actions/checkout@v5 + + - name: Setup Java 21 + uses: actions/setup-java@v5 + with: + java-version: ${{ matrix.java }} + distribution: ${{ matrix.distribution }} + cache: 'maven' + + - name: Grant execute permission for mvnw + run: chmod +x mvnw + + - name: Build with Maven + run: ./mvnw clean verify \ No newline at end of file diff --git a/spring-mysql-example/.gitignore b/spring-mysql-example/.gitignore new file mode 100644 index 0000000..a71cd2b --- /dev/null +++ b/spring-mysql-example/.gitignore @@ -0,0 +1,32 @@ +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/spring-mysql-example/.mvn/wrapper/maven-wrapper.properties b/spring-mysql-example/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/spring-mysql-example/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/spring-mysql-example/Dockerfile b/spring-mysql-example/Dockerfile new file mode 100644 index 0000000..dbedc62 --- /dev/null +++ b/spring-mysql-example/Dockerfile @@ -0,0 +1,47 @@ +FROM eclipse-temurin:21-jdk-jammy as deps + +WORKDIR /build + +COPY --chmod=0755 mvnw mvnw +COPY .mvn/ .mvn/ + +RUN --mount=type=bind,source=pom.xml,target=pom.xml \ + --mount=type=cache,target=/root/.m2 ./mvnw dependency:go-offline -DskipTests + +FROM deps as package + +WORKDIR /build + +COPY ./src src/ +RUN --mount=type=bind,source=pom.xml,target=pom.xml \ + --mount=type=cache,target=/root/.m2 \ + ./mvnw package -DskipTests && \ + mv target/$(./mvnw help:evaluate -Dexpression=project.artifactId -q -DforceStdout)-$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout).jar target/app.jar + +FROM package as extract + +WORKDIR /build + +RUN java -Djarmode=layertools -jar target/app.jar extract --destination target/extracted + +FROM eclipse-temurin:21-jre-jammy AS final + +ARG UID=10001 +RUN adduser \ + --disabled-password \ + --gecos "" \ + --home "/nonexistent" \ + --shell "/sbin/nologin" \ + --no-create-home \ + --uid "${UID}" \ + appuser +USER appuser + +COPY --from=extract build/target/extracted/dependencies/ ./ +COPY --from=extract build/target/extracted/spring-boot-loader/ ./ +COPY --from=extract build/target/extracted/snapshot-dependencies/ ./ +COPY --from=extract build/target/extracted/application/ ./ + +EXPOSE 8080 + +ENTRYPOINT [ "java", "org.springframework.boot.loader.launch.JarLauncher" ] diff --git a/spring-mysql-example/compose.yaml b/spring-mysql-example/compose.yaml new file mode 100644 index 0000000..803695d --- /dev/null +++ b/spring-mysql-example/compose.yaml @@ -0,0 +1,28 @@ + +services: + + app-mysql: + container_name: app-mysql + build: + context: . + ports: + - "8080:8080" + environment: + SPRING_PROFILES_ACTIVE: prd + SPRING_DATASOURCE_URL: jdbc:mysql://mysql-db:3306/myapp_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC + SPRING_DATASOURCE_USERNAME: myapp_user + SPRING_DATASOURCE_PASSWORD: user123 + SPRING_DATASOURCE_DRIVER: com.mysql.cj.jdbc.Driver + SPRING_JPA_HIBERNATE_DDL_AUTO: none + SPRING_JPA_SHOW_SQL: false + + mysql-db: + image: mysql:8.1 + container_name: mysql-db + ports: + - "3306:3306" + environment: + MYSQL_ROOT_PASSWORD: root123 + MYSQL_DATABASE: myapp_db + MYSQL_USER: myapp_user + MYSQL_PASSWORD: user123 \ No newline at end of file diff --git a/spring-mysql-example/mvnw b/spring-mysql-example/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/spring-mysql-example/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/spring-mysql-example/mvnw.cmd b/spring-mysql-example/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/spring-mysql-example/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/spring-mysql-example/pom.xml b/spring-mysql-example/pom.xml new file mode 100644 index 0000000..d3f5177 --- /dev/null +++ b/spring-mysql-example/pom.xml @@ -0,0 +1,100 @@ + + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.5.7 + + + + com.io + spring-mysql-example + 1.0.0 + spring-mysql-example + Example project using Java + Mysql + + + 21 + 3.5.7 + 3.14.1 + 9.4.0 + 2.4.240 + + + + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring.boot.version} + + + + com.mysql + mysql-connector-j + runtime + ${mysql.version} + + + + org.springframework.boot + spring-boot-starter-test + test + ${spring.boot.version} + + + + com.h2database + h2 + test + ${h2database.version} + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + + + org.projectlombok + lombok + + + + + + + + + + + diff --git a/spring-mysql-example/src/main/java/com/io/example/SpringMysqlExampleApplication.java b/spring-mysql-example/src/main/java/com/io/example/SpringMysqlExampleApplication.java new file mode 100644 index 0000000..9b65eb9 --- /dev/null +++ b/spring-mysql-example/src/main/java/com/io/example/SpringMysqlExampleApplication.java @@ -0,0 +1,13 @@ +package com.io.example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringMysqlExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringMysqlExampleApplication.class, args); + } + +} diff --git a/spring-mysql-example/src/main/resources/application-default.yml b/spring-mysql-example/src/main/resources/application-default.yml new file mode 100644 index 0000000..f7a0c68 --- /dev/null +++ b/spring-mysql-example/src/main/resources/application-default.yml @@ -0,0 +1,29 @@ +server: + port: 8080 + +spring: + application: + name: spring-mysql-example-dev + + datasource: + url: jdbc:mysql://localhost:3306/myapp_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC + username: myapp_user + password: user123 + driver-class-name: com.mysql.cj.jdbc.Driver + + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: MySQLHikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: none + show-sql: true \ No newline at end of file diff --git a/spring-mysql-example/src/main/resources/application-prd.yml b/spring-mysql-example/src/main/resources/application-prd.yml new file mode 100644 index 0000000..b20afad --- /dev/null +++ b/spring-mysql-example/src/main/resources/application-prd.yml @@ -0,0 +1,26 @@ +spring: + application: + name: spring-mysql-example-prd + + datasource: + url: ${SPRING_DATASOURCE_URL} + username: ${SPRING_DATASOURCE_USERNAME} + password: ${SPRING_DATASOURCE_PASSWORD} + driver-class-name: ${SPRING_DATASOURCE_DRIVER} + + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: MySQLHikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: ${SPRING_JPA_HIBERNATE_DDL_AUTO} + show-sql: ${SPRING_JPA_SHOW_SQL} \ No newline at end of file diff --git a/spring-mysql-example/src/test/java/com/io/example/SpringMysqlExampleApplicationTest.java b/spring-mysql-example/src/test/java/com/io/example/SpringMysqlExampleApplicationTest.java new file mode 100644 index 0000000..d448037 --- /dev/null +++ b/spring-mysql-example/src/test/java/com/io/example/SpringMysqlExampleApplicationTest.java @@ -0,0 +1,16 @@ +package com.io.example; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest +@ActiveProfiles("test") +public class SpringMysqlExampleApplicationTest { + + @Test + void contextLoads() { + } + + +} diff --git a/spring-mysql-example/src/test/resources/application-test.yml b/spring-mysql-example/src/test/resources/application-test.yml new file mode 100644 index 0000000..1b4b33a --- /dev/null +++ b/spring-mysql-example/src/test/resources/application-test.yml @@ -0,0 +1,29 @@ +spring: + application: + name: spring-mysql-example-test + + datasource: + url: jdbc:h2:mem:mydb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + driver-class-name: org.h2.Driver + username: sa + password: + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: H2HikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: update + show-sql: true + + h2: + console: + enabled: false diff --git a/spring-oracle-example/.dockerignore b/spring-oracle-example/.dockerignore index 8893889..bd16727 100644 --- a/spring-oracle-example/.dockerignore +++ b/spring-oracle-example/.dockerignore @@ -1,9 +1,3 @@ -# Include any files or directories that you don't want to be copied to your -# container here (e.g., local build artifacts, temporary files, etc.). -# -# For more help, visit the .dockerignore file reference guide at -# https://docs.docker.com/go/build-context-dockerignore/ - **/.DS_Store **/.classpath **/.dockerignore diff --git a/spring-oracle-example/.gitattributes b/spring-oracle-example/.gitattributes deleted file mode 100644 index 3b41682..0000000 --- a/spring-oracle-example/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -/mvnw text eol=lf -*.cmd text eol=crlf diff --git a/spring-oracle-example/.mvn/wrapper/maven-wrapper.properties b/spring-oracle-example/.mvn/wrapper/maven-wrapper.properties index 44f3cf2..ffcab66 100644 --- a/spring-oracle-example/.mvn/wrapper/maven-wrapper.properties +++ b/spring-oracle-example/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,3 @@ +wrapperVersion=3.3.4 distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/spring-oracle-example/Dockerfile b/spring-oracle-example/Dockerfile index 664349f..d96e121 100644 --- a/spring-oracle-example/Dockerfile +++ b/spring-oracle-example/Dockerfile @@ -1,4 +1,4 @@ -FROM eclipse-temurin:25-jdk-jammy as deps +FROM eclipse-temurin:21-jdk-jammy as deps WORKDIR /build @@ -18,24 +18,26 @@ RUN --mount=type=bind,source=pom.xml,target=pom.xml \ ./mvnw package -DskipTests && \ mv target/$(./mvnw help:evaluate -Dexpression=project.artifactId -q -DforceStdout)-$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout).jar target/app.jar -FROM package as extract - -WORKDIR /build - -RUN java -Djarmode=layertools -jar target/app.jar extract --destination target/extracted - -FROM eclipse-temurin:25-jre-jammy AS final +FROM eclipse-temurin:21-jre-jammy AS final ARG UID=10001 - -COPY --from=extract build/target/extracted/dependencies/ ./ -COPY --from=extract build/target/extracted/spring-boot-loader/ ./ -COPY --from=extract build/target/extracted/snapshot-dependencies/ ./ -COPY --from=extract build/target/extracted/application/ ./ +RUN adduser \ + --disabled-password \ + --gecos "" \ + --home "/nonexistent" \ + --shell "/sbin/nologin" \ + --no-create-home \ + --uid "${UID}" \ + appuser +USER appuser + +COPY --from=package build/target/app.jar app.jar COPY docker/java/entrypoint.sh /entrypoint.sh +USER root RUN chmod +x /entrypoint.sh +USER appuser -EXPOSE 8080 +EXPOSE 8082 -ENTRYPOINT ["/entrypoint.sh"] \ No newline at end of file +ENTRYPOINT ["/entrypoint.sh"] diff --git a/spring-oracle-example/README.md b/spring-oracle-example/README.md deleted file mode 100644 index d1098de..0000000 --- a/spring-oracle-example/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# spring-oracle-example - -This project is a simple demonstration of connecting to an Oracle database using Docker. - -It showcases: - -- Running an Oracle Database container (XE 21c). -- Basic demonstration of database connectivity from a client or Java application. \ No newline at end of file diff --git a/spring-oracle-example/compose.yaml b/spring-oracle-example/compose.yaml index ad68a1d..a57ade5 100644 --- a/spring-oracle-example/compose.yaml +++ b/spring-oracle-example/compose.yaml @@ -1,23 +1,21 @@ + services: - app: - container_name: app + app-oracle: + container_name: app-oracle build: context: . - depends_on: - - oracle-db + ports: + - "8082:8082" environment: - SPRING_PROFILES_ACTIVE: default - SERVER_PORT: 8080 + SPRING_PROFILES_ACTIVE: prd + SERVER_PORT: 8082 SPRING_DATASOURCE_URL: jdbc:oracle:thin:@oracle-db:1521 SPRING_DATASOURCE_USERNAME: developer SPRING_DATASOURCE_PASSWORD: developer SPRING_DATASOURCE_DRIVER: oracle.jdbc.OracleDriver SPRING_JPA_HIBERNATE_DDL_AUTO: none SPRING_JPA_SHOW_SQL: true - SPRING_HIBERNATE_DIALECT: org.hibernate.dialect.OracleDialect - ports: - - "8080:8080" oracle-db: container_name: oracle-db @@ -28,5 +26,4 @@ services: ORACLE_PASSWORD: "Admin123" shm_size: 1g volumes: - - ./docker/oracle:/docker-entrypoint-initdb.d - - ./src/main/resources/sql:/docker-entrypoint-initdb.d \ No newline at end of file + - ./docker/oracle:/docker-entrypoint-initdb.d \ No newline at end of file diff --git a/spring-oracle-example/docker/java/entrypoint.sh b/spring-oracle-example/docker/java/entrypoint.sh index 2bbbbb1..eb5f957 100644 --- a/spring-oracle-example/docker/java/entrypoint.sh +++ b/spring-oracle-example/docker/java/entrypoint.sh @@ -5,4 +5,4 @@ echo "Waiting 30 seconds..." sleep 30 echo "Starting the application..." -exec java org.springframework.boot.loader.launch.JarLauncher \ No newline at end of file +exec java -jar app.jar \ No newline at end of file diff --git a/spring-oracle-example/src/main/resources/sql/01_init.sql b/spring-oracle-example/docker/oracle/init.sql similarity index 98% rename from spring-oracle-example/src/main/resources/sql/01_init.sql rename to spring-oracle-example/docker/oracle/init.sql index 4814b08..6451747 100644 --- a/spring-oracle-example/src/main/resources/sql/01_init.sql +++ b/spring-oracle-example/docker/oracle/init.sql @@ -22,4 +22,4 @@ GRANT DELETE ANY TABLE TO developer; ALTER USER developer QUOTA UNLIMITED ON USERS; -COMMIT; +COMMIT; \ No newline at end of file diff --git a/spring-oracle-example/pom.xml b/spring-oracle-example/pom.xml index 1ead1d4..0c2f65d 100644 --- a/spring-oracle-example/pom.xml +++ b/spring-oracle-example/pom.xml @@ -1,38 +1,37 @@ - - + + 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 3.5.7 - - - - com.io - spring-oracle-example - 1.0.0 - spring-oracle-example - Demo project for Spring Boot using OracleDB - - - 21 + + org.springframework.boot + spring-boot-starter-parent + 3.5.7 + + + + com.io + spring-oracle-example + 1.0.0 + spring-oracle-example + Example project using Java + Oracle + + + 21 3.5.7 1.18.42 23.26.0.0.0 3.14.1 - 5.5.1 - + 2.4.240 + - + - - org.springframework.boot - spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-web ${spring.boot.version} - + org.springframework.boot @@ -40,67 +39,63 @@ ${spring.boot.version} - - com.oracle.database.jdbc - ojdbc11 - runtime + + com.oracle.database.jdbc + ojdbc11 + runtime ${oracle.database.version} - - - - org.projectlombok - lombok - true - ${lombok.version} - + - org.instancio - instancio-core - ${instancio.version} + org.springframework.boot + spring-boot-starter-test + test + ${spring.boot.version} - - org.springframework.boot - spring-boot-starter-test - test - ${spring.boot.version} - + + com.h2database + h2 + test + ${h2database.version} + - + - - + + - - org.apache.maven.plugins - maven-compiler-plugin + + org.apache.maven.plugins + maven-compiler-plugin ${maven.compiler.plugin.version} - - - - org.projectlombok - lombok - - - - - - - org.springframework.boot - spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin ${spring.boot.version} - - - - org.projectlombok - lombok - - - - - - - + + + + org.projectlombok + lombok + + + + + + + + + diff --git a/spring-oracle-example/src/main/java/com/io/example/config/DatabaseConfig.java b/spring-oracle-example/src/main/java/com/io/example/config/DatabaseConfig.java deleted file mode 100644 index 6942a2d..0000000 --- a/spring-oracle-example/src/main/java/com/io/example/config/DatabaseConfig.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.io.example.config; - -import javax.sql.DataSource; - -import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.jdbc.core.simple.JdbcClient; - -@Configuration -public class DatabaseConfig { - - @Bean - @Primary - @ConfigurationProperties("spring.datasource") - public DataSourceProperties dataSourceProperties() { - return new DataSourceProperties(); - } - - @Bean - @Primary - public DataSource dataSource(DataSourceProperties properties) { - return properties.initializeDataSourceBuilder() - .build(); - } - - @Bean - @Primary - public JdbcClient jdbcClient(DataSource dataSource) { - return JdbcClient.create(dataSource); - } - -} diff --git a/spring-oracle-example/src/main/java/com/io/example/dao/JdbcClientCrudExampleDao.java b/spring-oracle-example/src/main/java/com/io/example/dao/JdbcClientCrudExampleDao.java deleted file mode 100644 index 808fbd7..0000000 --- a/spring-oracle-example/src/main/java/com/io/example/dao/JdbcClientCrudExampleDao.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.io.example.dao; - -import com.io.example.dto.JdbcClientCrudExampleDto; -import com.io.example.exception.JdbcClientCrudExampleException; -import lombok.RequiredArgsConstructor; -import org.springframework.jdbc.core.simple.JdbcClient; -import org.springframework.stereotype.Component; -import java.util.List; - -@Component -@RequiredArgsConstructor -public class JdbcClientCrudExampleDao { - - private final JdbcClient jdbc; - - public void create(JdbcClientCrudExampleDto record) { - try { - jdbc.sql(""" - INSERT INTO developer.records_example (id, name, value) - VALUES (?, ?, ?) - """) - .param(record.getId()) - .param(record.getName()) - .param(record.getValue()) - .update(); - } catch (Exception e) { - throw new JdbcClientCrudExampleException("Failed to insert record: " + record, e); - } - } - - public List findAll() { - try { - return jdbc.sql(""" - SELECT id, name, value, created_at - FROM developer.records_example - """) - .query(JdbcClientCrudExampleDto.class) - .list(); - } catch (Exception e) { - throw new JdbcClientCrudExampleException("Failed to retrieve all records", e); - } - } - - public JdbcClientCrudExampleDto findById(Long id) { - try { - return jdbc.sql(""" - SELECT id, name, value, created_at - FROM developer.records_example - WHERE id = ? - """) - .param(id) - .query(JdbcClientCrudExampleDto.class) - .optional() - .orElseThrow(() -> new JdbcClientCrudExampleException("No record found for id = " + id)); - } catch (Exception e) { - throw new JdbcClientCrudExampleException("Failed to retrieve record for id = " + id, e); - } - } - - public void update(Long id, String name, String value) { - try { - int affected = jdbc.sql(""" - UPDATE developer.records_example - SET name = ?, value = ? - WHERE id = ? - """) - .param(name) - .param(value) - .param(id) - .update(); - - if (affected == 0) { - throw new JdbcClientCrudExampleException("No record found to update for id = " + id); - } - - } catch (Exception e) { - throw new JdbcClientCrudExampleException("Failed to update record with id = " + id, e); - } - } - - public void delete(Long id) { - try { - int affected = jdbc.sql(""" - DELETE FROM developer.records_example - WHERE id = ? - """) - .param(id) - .update(); - - if (affected == 0) { - throw new JdbcClientCrudExampleException("No record found to delete for id = " + id); - } - - } catch (Exception e) { - throw new JdbcClientCrudExampleException("Failed to delete record with id = " + id, e); - } - } - -} diff --git a/spring-oracle-example/src/main/java/com/io/example/dto/JdbcClientCrudExampleDto.java b/spring-oracle-example/src/main/java/com/io/example/dto/JdbcClientCrudExampleDto.java deleted file mode 100644 index 2ebbf7d..0000000 --- a/spring-oracle-example/src/main/java/com/io/example/dto/JdbcClientCrudExampleDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.io.example.dto; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import java.time.LocalDateTime; - -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class JdbcClientCrudExampleDto { - - private Long id; - private String name; - private String value; - private LocalDateTime createdAt; - -} \ No newline at end of file diff --git a/spring-oracle-example/src/main/java/com/io/example/exception/JdbcClientCrudExampleException.java b/spring-oracle-example/src/main/java/com/io/example/exception/JdbcClientCrudExampleException.java deleted file mode 100644 index f742246..0000000 --- a/spring-oracle-example/src/main/java/com/io/example/exception/JdbcClientCrudExampleException.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.io.example.exception; - -public class JdbcClientCrudExampleException extends RuntimeException { - - public JdbcClientCrudExampleException(String message) { - super(message); - } - - public JdbcClientCrudExampleException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/spring-oracle-example/src/main/java/com/io/example/init/JdbcClientCrudExampleInit.java b/spring-oracle-example/src/main/java/com/io/example/init/JdbcClientCrudExampleInit.java deleted file mode 100644 index dc32d0d..0000000 --- a/spring-oracle-example/src/main/java/com/io/example/init/JdbcClientCrudExampleInit.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.io.example.init; - -import com.io.example.dao.JdbcClientCrudExampleDao; -import com.io.example.dto.JdbcClientCrudExampleDto; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.CommandLineRunner; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -@RequiredArgsConstructor -public class JdbcClientCrudExampleInit implements CommandLineRunner { - - private final JdbcClientCrudExampleDao dao; - - @Override - public void run(String... args) { - - var entity = JdbcClientCrudExampleDto.builder() - .id(1L) - .name("Test Name") - .value("Some value") - .build(); - - dao.create(entity); - log.info("Inserted: {}", entity); - - JdbcClientCrudExampleDto fetched = dao.findById(1L); - log.info("Fetched: {}", fetched); - - fetched.setName("Updated Name"); - fetched.setValue("Updated value"); - - dao.update(fetched.getId(), fetched.getName(), fetched.getValue()); - log.info("Updated: {}", fetched); - - dao.delete(1L); - log.info("Deleted entity with id 1"); - - } - -} diff --git a/spring-oracle-example/src/main/resources/application-default.yml b/spring-oracle-example/src/main/resources/application-default.yml new file mode 100644 index 0000000..53b2d3b --- /dev/null +++ b/spring-oracle-example/src/main/resources/application-default.yml @@ -0,0 +1,29 @@ +server: + port: 8082 + +spring: + application: + name: spring-oracle-example-dev + + datasource: + url: jdbc:oracle:thin:@localhost:1521 + username: developer + password: developer + driver-class-name: oracle.jdbc.OracleDriver + + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: OracleHikariPool + connection-test-query: SELECT 1 FROM DUAL + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: none + show-sql: true \ No newline at end of file diff --git a/spring-oracle-example/src/main/resources/application-dev.yml b/spring-oracle-example/src/main/resources/application-dev.yml deleted file mode 100644 index 48f21fe..0000000 --- a/spring-oracle-example/src/main/resources/application-dev.yml +++ /dev/null @@ -1,17 +0,0 @@ -spring: - application: - name: spring-oracle-example-dev - - datasource: - url: ${SPRING_DATASOURCE_URL:jdbc:oracle:thin:@localhost:1521} - username: ${SPRING_DATASOURCE_USERNAME:developer} - password: ${SPRING_DATASOURCE_PASSWORD:developer} - driver-class-name: ${SPRING_DATASOURCE_DRIVER:oracle.jdbc.OracleDriver} - - jpa: - hibernate: - ddl-auto: ${SPRING_JPA_HIBERNATE_DDL_AUTO:none} - show-sql: ${SPRING_JPA_SHOW_SQL:true} - properties: - hibernate: - dialect: ${SPRING_HIBERNATE_DIALECT:org.hibernate.dialect.OracleDialect} diff --git a/spring-oracle-example/src/main/resources/application-prd.yml b/spring-oracle-example/src/main/resources/application-prd.yml new file mode 100644 index 0000000..ea9b5e8 --- /dev/null +++ b/spring-oracle-example/src/main/resources/application-prd.yml @@ -0,0 +1,26 @@ +spring: + application: + name: spring-oracle-example-prd + + datasource: + url: ${SPRING_DATASOURCE_URL} + username: ${SPRING_DATASOURCE_USERNAME} + password: ${SPRING_DATASOURCE_PASSWORD} + driver-class-name: ${SPRING_DATASOURCE_DRIVER} + + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: OracleHikariPool + connection-test-query: SELECT 1 FROM DUAL + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: ${SPRING_JPA_HIBERNATE_DDL_AUTO} + show-sql: ${SPRING_JPA_SHOW_SQL} \ No newline at end of file diff --git a/spring-oracle-example/src/main/resources/application.yml b/spring-oracle-example/src/main/resources/application.yml deleted file mode 100644 index 584aabc..0000000 --- a/spring-oracle-example/src/main/resources/application.yml +++ /dev/null @@ -1,17 +0,0 @@ -spring: - application: - name: spring-oracle-example-prd - - datasource: - url: ${SPRING_DATASOURCE_URL} - username: ${SPRING_DATASOURCE_USERNAME} - password: ${SPRING_DATASOURCE_PASSWORD} - driver-class-name: ${SPRING_DATASOURCE_DRIVER} - - jpa: - hibernate: - ddl-auto: ${SPRING_JPA_HIBERNATE_DDL_AUTO} - show-sql: ${SPRING_JPA_SHOW_SQL} - properties: - hibernate: - dialect: ${SPRING_HIBERNATE_DIALECT} \ No newline at end of file diff --git a/spring-oracle-example/src/main/resources/banner.txt b/spring-oracle-example/src/main/resources/banner.txt deleted file mode 100644 index ec72b60..0000000 --- a/spring-oracle-example/src/main/resources/banner.txt +++ /dev/null @@ -1,7 +0,0 @@ - - ,---. ,------. ,------. ,--.,--. ,--. ,----. ,-----. ,------. ,---. ,-----.,--. ,------. -' .-'| .--. '| .--. '| || ,'.| |' .-./ ,-----.' .-. '| .--. ' / O \ ' .--./| | | .---' -`. `-.| '--' || '--'.'| || |' ' || | .---.'-----'| | | || '--'.'| .-. || | | | | `--, -.-' | | --' | |\ \ | || | ` |' '--' | ' '-' '| |\ \ | | | |' '--'\| '--.| `---. -`-----'`--' `--' '--'`--'`--' `--' `------' `-----' `--' '--'`--' `--' `-----'`-----'`------' - SPRING-ORACLE-EXAMPLE \ No newline at end of file diff --git a/spring-oracle-example/src/main/resources/sql/02_jdbc_client_crud_example.sql b/spring-oracle-example/src/main/resources/sql/02_jdbc_client_crud_example.sql deleted file mode 100644 index 1db609f..0000000 --- a/spring-oracle-example/src/main/resources/sql/02_jdbc_client_crud_example.sql +++ /dev/null @@ -1,10 +0,0 @@ -ALTER SESSION SET "_ORACLE_SCRIPT"=true; - -CREATE TABLE developer.records_example ( - id NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, - name VARCHAR2(100) NOT NULL, - value VARCHAR2(255), - created_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL -); - -COMMIT; \ No newline at end of file diff --git a/spring-oracle-example/src/test/java/com/io/example/SpringOracleExampleApplicationTest.java b/spring-oracle-example/src/test/java/com/io/example/SpringOracleExampleApplicationTest.java new file mode 100644 index 0000000..428dcf8 --- /dev/null +++ b/spring-oracle-example/src/test/java/com/io/example/SpringOracleExampleApplicationTest.java @@ -0,0 +1,16 @@ +package com.io.example; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest +@ActiveProfiles("test") +public class SpringOracleExampleApplicationTest { + + @Test + void contextLoads() { + } + + +} diff --git a/spring-oracle-example/src/test/java/com/io/example/dao/JdbcClientCrudExampleDaoTest.java b/spring-oracle-example/src/test/java/com/io/example/dao/JdbcClientCrudExampleDaoTest.java deleted file mode 100644 index e7324ee..0000000 --- a/spring-oracle-example/src/test/java/com/io/example/dao/JdbcClientCrudExampleDaoTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.io.example.dao; - -import com.io.example.dto.JdbcClientCrudExampleDto; -import com.io.example.exception.JdbcClientCrudExampleException; -import org.instancio.Instancio; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.jdbc.core.simple.JdbcClient; - -import java.util.List; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class JdbcClientCrudExampleDaoTest { - - private static final JdbcClientCrudExampleDto DTO = Instancio.create(JdbcClientCrudExampleDto.class); - private static final Long ID = Instancio.create(Long.class); - private static final List DTO_LIST = Instancio.ofList(JdbcClientCrudExampleDto.class).size(3).create(); - - @Mock - private JdbcClient jdbc; - - @Mock - private JdbcClient.StatementSpec statementSpec; - - @Mock - private JdbcClient.MappedQuerySpec selectSpec; - - @InjectMocks - private JdbcClientCrudExampleDao dao; - - @Test - @DisplayName("should insert record successfully") - void shouldInsertRecordSuccessfully() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getId())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getName())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getValue())).thenReturn(statementSpec); - when(statementSpec.update()).thenReturn(1); - - dao.create(DTO); - - verify(statementSpec).update(); - } - - @Test - @DisplayName("should retrieve all records successfully") - void shouldRetrieveAllRecordsSuccessfully() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.query(JdbcClientCrudExampleDto.class)).thenReturn(selectSpec); - when(selectSpec.list()).thenReturn(DTO_LIST); - - List result = dao.findAll(); - - assertThat(result).hasSize(3).isEqualTo(DTO_LIST); - } - - @Test - @DisplayName("should retrieve record by id successfully") - void shouldRetrieveRecordByIdSuccessfully() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getId())).thenReturn(statementSpec); - when(statementSpec.query(JdbcClientCrudExampleDto.class)).thenReturn(selectSpec); - when(selectSpec.optional()).thenReturn(Optional.of(DTO)); - - JdbcClientCrudExampleDto result = dao.findById(DTO.getId()); - - assertThat(result).isEqualTo(DTO); - } - - @Test - @DisplayName("should throw exception when record not found by id") - void shouldThrowExceptionWhenRecordNotFoundById() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(ID)).thenReturn(statementSpec); - when(statementSpec.query(JdbcClientCrudExampleDto.class)).thenReturn(selectSpec); - when(selectSpec.optional()).thenReturn(Optional.empty()); - - assertThatThrownBy(() -> dao.findById(ID)) - .isInstanceOf(JdbcClientCrudExampleException.class) - .hasMessageContaining("Failed to retrieve record for id = " + ID); - } - - @Test - @DisplayName("should update record successfully") - void shouldUpdateRecordSuccessfully() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getName())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getValue())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getId())).thenReturn(statementSpec); - when(statementSpec.update()).thenReturn(1); - - dao.update(DTO.getId(), DTO.getName(), DTO.getValue()); - - verify(statementSpec).update(); - } - - @Test - @DisplayName("should throw exception when updating non-existent record") - void shouldThrowExceptionWhenUpdatingNonExistentRecord() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getName())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getValue())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getId())).thenReturn(statementSpec); - when(statementSpec.update()).thenReturn(0); - - assertThatThrownBy(() -> dao.update(DTO.getId(), DTO.getName(), DTO.getValue())) - .isInstanceOf(JdbcClientCrudExampleException.class) - .hasMessageContaining("Failed to update record with id = " + DTO.getId()); - } - - @Test - @DisplayName("should delete record successfully") - void shouldDeleteRecordSuccessfully() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getId())).thenReturn(statementSpec); - when(statementSpec.update()).thenReturn(1); - - dao.delete(DTO.getId()); - - verify(statementSpec).update(); - } - - @Test - @DisplayName("should throw exception when deleting non-existent record") - void shouldThrowExceptionWhenDeletingNonExistentRecord() { - when(jdbc.sql(anyString())).thenReturn(statementSpec); - when(statementSpec.param(DTO.getId())).thenReturn(statementSpec); - when(statementSpec.update()).thenReturn(0); - - assertThatThrownBy(() -> dao.delete(DTO.getId())) - .isInstanceOf(JdbcClientCrudExampleException.class) - .hasMessageContaining("Failed to delete record with id = " + DTO.getId()); - } - -} \ No newline at end of file diff --git a/spring-oracle-example/src/test/resources/application-test.yml b/spring-oracle-example/src/test/resources/application-test.yml new file mode 100644 index 0000000..8e86e94 --- /dev/null +++ b/spring-oracle-example/src/test/resources/application-test.yml @@ -0,0 +1,29 @@ +spring: + application: + name: spring-postgres-example-test + + datasource: + url: jdbc:h2:mem:mydb;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + driver-class-name: org.h2.Driver + username: sa + password: + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: H2HikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: update + show-sql: true + + h2: + console: + enabled: false diff --git a/spring-postgres-example/.dockerignore b/spring-postgres-example/.dockerignore new file mode 100644 index 0000000..bd16727 --- /dev/null +++ b/spring-postgres-example/.dockerignore @@ -0,0 +1,56 @@ +**/.DS_Store +**/.classpath +**/.dockerignore +**/.env +**/.factorypath +**/.git +**/.gitignore +**/.idea +**/.project +**/.sts4-cache +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.next +**/.cache +**/*.dbmdl +**/*.jfm +**/charts +**/docker-compose* +**/compose.y*ml +**/Dockerfile* +**/secrets.dev.yaml +**/values.dev.yaml +**/vendor +LICENSE +README.md +**/*.class +**/*.iml +**/*.ipr +**/*.iws +**/*.log +**/.apt_generated +**/.gradle +**/.gradletasknamecache +**/.nb-gradle +**/.springBeans +**/build +**/dist +**/gradle-app.setting +**/nbbuild +**/nbdist +**/nbproject/private +**/target +*.ctxt +.mtj.tmp +.mvn/timing.properties +buildNumber.properties +dependency-reduced-pom.xml +hs_err_pid* +pom.xml.next +pom.xml.releaseBackup +pom.xml.tag +pom.xml.versionsBackup +release.properties +replay_pid* \ No newline at end of file diff --git a/spring-postgres-example/.github/workflows/maven.yml b/spring-postgres-example/.github/workflows/maven.yml new file mode 100644 index 0000000..16d1a66 --- /dev/null +++ b/spring-postgres-example/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +name: CI Build + +on: + push: + branches: + - "**" + +jobs: + build: + name: Build + runs-on: ubuntu-latest + strategy: + matrix: + distribution: [ 'temurin' ] + java: [ '21' ] + steps: + - uses: actions/checkout@v5 + + - name: Setup Java 21 + uses: actions/setup-java@v5 + with: + java-version: ${{ matrix.java }} + distribution: ${{ matrix.distribution }} + cache: 'maven' + + - name: Grant execute permission for mvnw + run: chmod +x mvnw + + - name: Build with Maven + run: ./mvnw clean verify \ No newline at end of file diff --git a/spring-postgres-example/.gitignore b/spring-postgres-example/.gitignore new file mode 100644 index 0000000..a71cd2b --- /dev/null +++ b/spring-postgres-example/.gitignore @@ -0,0 +1,32 @@ +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/spring-postgres-example/.mvn/wrapper/maven-wrapper.properties b/spring-postgres-example/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/spring-postgres-example/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/spring-postgres-example/Dockerfile b/spring-postgres-example/Dockerfile new file mode 100644 index 0000000..e5e711a --- /dev/null +++ b/spring-postgres-example/Dockerfile @@ -0,0 +1,38 @@ +FROM eclipse-temurin:21-jdk-jammy as deps + +WORKDIR /build + +COPY --chmod=0755 mvnw mvnw +COPY .mvn/ .mvn/ + +RUN --mount=type=bind,source=pom.xml,target=pom.xml \ + --mount=type=cache,target=/root/.m2 ./mvnw dependency:go-offline -DskipTests + +FROM deps as package + +WORKDIR /build + +COPY ./src src/ +RUN --mount=type=bind,source=pom.xml,target=pom.xml \ + --mount=type=cache,target=/root/.m2 \ + ./mvnw package -DskipTests && \ + mv target/$(./mvnw help:evaluate -Dexpression=project.artifactId -q -DforceStdout)-$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout).jar target/app.jar + +FROM eclipse-temurin:21-jre-jammy AS final + +ARG UID=10001 +RUN adduser \ + --disabled-password \ + --gecos "" \ + --home "/nonexistent" \ + --shell "/sbin/nologin" \ + --no-create-home \ + --uid "${UID}" \ + appuser +USER appuser + +COPY --from=package build/target/app.jar app.jar + +EXPOSE 8081 + +ENTRYPOINT [ "java", "-jar", "app.jar" ] \ No newline at end of file diff --git a/spring-postgres-example/compose.yaml b/spring-postgres-example/compose.yaml new file mode 100644 index 0000000..fb365f1 --- /dev/null +++ b/spring-postgres-example/compose.yaml @@ -0,0 +1,27 @@ + +services: + + app-postgres: + container_name: app-postgres + build: + context: . + ports: + - "8081:8081" + environment: + SPRING_PROFILES_ACTIVE: prd + SPRING_DATASOURCE_URL: jdbc:postgresql://postgres-db:5432/myapp_db + SPRING_DATASOURCE_USERNAME: myapp_user + SPRING_DATASOURCE_PASSWORD: user123 + SPRING_DATASOURCE_DRIVER: org.postgresql.Driver + SPRING_JPA_HIBERNATE_DDL_AUTO: none + SPRING_JPA_SHOW_SQL: false + + postgres-db: + image: postgres:17 + container_name: postgres-db + ports: + - "5432:5432" + environment: + POSTGRES_DB: myapp_db + POSTGRES_USER: myapp_user + POSTGRES_PASSWORD: user123 diff --git a/spring-postgres-example/mvnw b/spring-postgres-example/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/spring-postgres-example/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/spring-postgres-example/mvnw.cmd b/spring-postgres-example/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/spring-postgres-example/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/spring-postgres-example/pom.xml b/spring-postgres-example/pom.xml new file mode 100644 index 0000000..311a83b --- /dev/null +++ b/spring-postgres-example/pom.xml @@ -0,0 +1,101 @@ + + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.5.7 + + + + com.io + spring-postgres-example + 1.0.0 + spring-postgres-example + Example project using Java + Postgres + + + 21 + 3.5.7 + 3.14.1 + 9.4.0 + 2.4.240 + 42.7.8 + + + + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring.boot.version} + + + + org.postgresql + postgresql + runtime + ${postgresql.version} + + + + org.springframework.boot + spring-boot-starter-test + test + ${spring.boot.version} + + + + com.h2database + h2 + test + ${h2database.version} + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + + + org.projectlombok + lombok + + + + + + + + + + + diff --git a/spring-postgres-example/src/main/java/com/io/example/SpringPostgresExampleApplication.java b/spring-postgres-example/src/main/java/com/io/example/SpringPostgresExampleApplication.java new file mode 100644 index 0000000..84dea98 --- /dev/null +++ b/spring-postgres-example/src/main/java/com/io/example/SpringPostgresExampleApplication.java @@ -0,0 +1,13 @@ +package com.io.example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringPostgresExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringPostgresExampleApplication.class, args); + } + +} diff --git a/spring-postgres-example/src/main/resources/application-default.yml b/spring-postgres-example/src/main/resources/application-default.yml new file mode 100644 index 0000000..63a2c7f --- /dev/null +++ b/spring-postgres-example/src/main/resources/application-default.yml @@ -0,0 +1,29 @@ +server: + port: 8081 + +spring: + application: + name: spring-mysql-example-dev + + datasource: + url: jdbc:postgresql://localhost:5432/myapp_db + username: myapp_user + password: user123 + driver-class-name: org.postgresql.Driver + + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: PostgresHikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: none + show-sql: true \ No newline at end of file diff --git a/spring-postgres-example/src/main/resources/application-prd.yml b/spring-postgres-example/src/main/resources/application-prd.yml new file mode 100644 index 0000000..b20afad --- /dev/null +++ b/spring-postgres-example/src/main/resources/application-prd.yml @@ -0,0 +1,26 @@ +spring: + application: + name: spring-mysql-example-prd + + datasource: + url: ${SPRING_DATASOURCE_URL} + username: ${SPRING_DATASOURCE_USERNAME} + password: ${SPRING_DATASOURCE_PASSWORD} + driver-class-name: ${SPRING_DATASOURCE_DRIVER} + + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: MySQLHikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: ${SPRING_JPA_HIBERNATE_DDL_AUTO} + show-sql: ${SPRING_JPA_SHOW_SQL} \ No newline at end of file diff --git a/spring-postgres-example/src/test/java/com/io/example/SpringPostgresExampleApplicationTest.java b/spring-postgres-example/src/test/java/com/io/example/SpringPostgresExampleApplicationTest.java new file mode 100644 index 0000000..bb149dc --- /dev/null +++ b/spring-postgres-example/src/test/java/com/io/example/SpringPostgresExampleApplicationTest.java @@ -0,0 +1,16 @@ +package com.io.example; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest +@ActiveProfiles("test") +public class SpringPostgresExampleApplicationTest { + + @Test + void contextLoads() { + } + + +} diff --git a/spring-postgres-example/src/test/resources/application-test.yml b/spring-postgres-example/src/test/resources/application-test.yml new file mode 100644 index 0000000..4ee0f74 --- /dev/null +++ b/spring-postgres-example/src/test/resources/application-test.yml @@ -0,0 +1,29 @@ +spring: + application: + name: spring-postgres-example-test + + datasource: + url: jdbc:h2:mem:mydb;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + driver-class-name: org.h2.Driver + username: sa + password: + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + pool-name: H2HikariPool + connection-test-query: SELECT 1 + initialization-fail-timeout: 0 + auto-commit: true + + jpa: + open-in-view: false + hibernate: + ddl-auto: update + show-sql: true + + h2: + console: + enabled: false