diff --git a/.github/workflows/boot-jpa-locks.yml b/.github/workflows/boot-jpa-locks.yml new file mode 100644 index 000000000..299f8fe48 --- /dev/null +++ b/.github/workflows/boot-jpa-locks.yml @@ -0,0 +1,35 @@ +name: boot-jpa-locks + +on: + push: + paths: + - "jpa/boot-jpa-locks/**" + branches: [main] + pull_request: + paths: + - "jpa/boot-jpa-locks/**" + types: + - opened + - synchronize + - reopened + +jobs: + build: + name: Run Unit & Integration Tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: "jpa/boot-jpa-locks" + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + - name: Set up JDK + uses: actions/setup-java@v3.13.0 + with: + java-version: 21 + distribution: "microsoft" + cache: "maven" + - name: Build and analyze + run: ./mvnw clean verify diff --git a/jpa/boot-jpa-locks/.github/workflows/maven.yml b/jpa/boot-jpa-locks/.github/workflows/maven.yml new file mode 100644 index 000000000..7a3b88388 --- /dev/null +++ b/jpa/boot-jpa-locks/.github/workflows/maven.yml @@ -0,0 +1,43 @@ +name: CI Build + +on: + push: + branches: + - "**" + +jobs: + build: + name: Build + runs-on: ubuntu-latest + strategy: + matrix: + distribution: [ 'temurin' ] + java: [ '17' ] + steps: + - uses: actions/checkout@v3 + + - name: Setup Java 17 + uses: actions/setup-java@v3 + 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 + + - if: ${{ github.ref == 'refs/heads/main' }} + name: SonarQube Scan + run: ./mvnw compile sonar:sonar -Dsonar.login=${{ secrets.SONAR_TOKEN }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - if: ${{ github.ref == 'refs/heads/main' }} + name: Build and Publish Docker Image + run: | + docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + ./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=${{ secrets.DOCKER_USERNAME }}/boot-jpa-locks + docker push ${{ secrets.DOCKER_USERNAME }}/boot-jpa-locks diff --git a/jpa/boot-jpa-locks/.gitignore b/jpa/boot-jpa-locks/.gitignore new file mode 100644 index 000000000..c456913cf --- /dev/null +++ b/jpa/boot-jpa-locks/.gitignore @@ -0,0 +1,37 @@ +HELP.md +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/ + +### Misc ### +*.log +.DS_Store \ No newline at end of file diff --git a/jpa/boot-jpa-locks/.mvn/wrapper/maven-wrapper.jar b/jpa/boot-jpa-locks/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..bf82ff01c Binary files /dev/null and b/jpa/boot-jpa-locks/.mvn/wrapper/maven-wrapper.jar differ diff --git a/jpa/boot-jpa-locks/.mvn/wrapper/maven-wrapper.properties b/jpa/boot-jpa-locks/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..eacdc9ed1 --- /dev/null +++ b/jpa/boot-jpa-locks/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# 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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/jpa/boot-jpa-locks/.yo-rc.json b/jpa/boot-jpa-locks/.yo-rc.json new file mode 100644 index 000000000..1b09bc435 --- /dev/null +++ b/jpa/boot-jpa-locks/.yo-rc.json @@ -0,0 +1,13 @@ +{ + "generator-springboot": { + "appName": "boot-jpa-locks", + "packageName": "com.example.locks", + "databaseType": "postgresql", + "dbMigrationTool": "liquibase", + "dbMigrationFormat": "xml", + "features": [], + "buildTool": "maven", + "packageFolder": "com/example/locks", + "liquibaseMigrationCounter": 3 + } +} diff --git a/jpa/boot-jpa-locks/Dockerfile b/jpa/boot-jpa-locks/Dockerfile new file mode 100644 index 000000000..3f088ee2f --- /dev/null +++ b/jpa/boot-jpa-locks/Dockerfile @@ -0,0 +1,14 @@ +FROM eclipse-temurin:17.0.9_9-jre-focal as builder +WORKDIR application +ARG JAR_FILE=target/boot-jpa-locks-0.0.1-SNAPSHOT.jar +COPY ${JAR_FILE} application.jar +RUN java -Djarmode=layertools -jar application.jar extract + +# the second stage of our build will copy the extracted layers +FROM eclipse-temurin:17.0.9_9-jre-focal +WORKDIR application +COPY --from=builder application/dependencies/ ./ +COPY --from=builder application/spring-boot-loader/ ./ +COPY --from=builder application/snapshot-dependencies/ ./ +COPY --from=builder application/application/ ./ +ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"] diff --git a/jpa/boot-jpa-locks/Jenkinsfile b/jpa/boot-jpa-locks/Jenkinsfile new file mode 100644 index 000000000..30bf9ffd1 --- /dev/null +++ b/jpa/boot-jpa-locks/Jenkinsfile @@ -0,0 +1,19 @@ +pipeline { + agent any + + triggers { + pollSCM('* * * * *') + } + + environment { + APPLICATION_NAME = 'boot-jpa-locks' + } + + stages { + stage('Build') { + steps { + sh './mvnw clean verify' + } + } + } +} diff --git a/jpa/boot-jpa-locks/README.md b/jpa/boot-jpa-locks/README.md new file mode 100644 index 000000000..63cd6e9c9 --- /dev/null +++ b/jpa/boot-jpa-locks/README.md @@ -0,0 +1,33 @@ +# boot-jpa-locks + +### Format code + +```shell +$ ./mvnw spotless:apply +``` + +### Run tests + +```shell +$ ./mvnw clean verify +``` + +### Run locally + +```shell +$ docker-compose -f docker/docker-compose.yml up -d +$ ./mvnw spring-boot:run -Dspring-boot.run.profiles=local +``` + +### Using Testcontainers at Development Time +You can run `TestApplication.java` from your IDE directly. +You can also run the application using Maven as follows: + +```shell +./mvnw spring-boot:test-run +``` + + +### Useful Links +* Swagger UI: http://localhost:8080/swagger-ui.html +* Actuator Endpoint: http://localhost:8080/actuator diff --git a/jpa/boot-jpa-locks/docker/docker-compose-app.yml b/jpa/boot-jpa-locks/docker/docker-compose-app.yml new file mode 100644 index 000000000..e9eebc76d --- /dev/null +++ b/jpa/boot-jpa-locks/docker/docker-compose-app.yml @@ -0,0 +1,17 @@ +version: '3.8' +services: + + boot-jpa-locks: + build: .. + ports: + - "18080:8080" + - "18787:8787" + restart: always + depends_on: + - postgresqldb + environment: + - SPRING_PROFILES_ACTIVE=docker + - SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver + - SPRING_DATASOURCE_URL=jdbc:postgresql://postgresqldb:5432/appdb + - SPRING_DATASOURCE_USERNAME=appuser + - SPRING_DATASOURCE_PASSWORD=secret diff --git a/jpa/boot-jpa-locks/docker/docker-compose.yml b/jpa/boot-jpa-locks/docker/docker-compose.yml new file mode 100644 index 000000000..7940a44b3 --- /dev/null +++ b/jpa/boot-jpa-locks/docker/docker-compose.yml @@ -0,0 +1,12 @@ +version: '3.8' +services: + + postgresqldb: + image: postgres:16.0-alpine + environment: + - POSTGRES_USER=appuser + - POSTGRES_PASSWORD=secret + - POSTGRES_DB=appdb + ports: + - "5432:5432" + diff --git a/jpa/boot-jpa-locks/lombok.config b/jpa/boot-jpa-locks/lombok.config new file mode 100644 index 000000000..7a21e8804 --- /dev/null +++ b/jpa/boot-jpa-locks/lombok.config @@ -0,0 +1 @@ +lombok.addLombokGeneratedAnnotation = true diff --git a/jpa/boot-jpa-locks/mvnw b/jpa/boot-jpa-locks/mvnw new file mode 100644 index 000000000..8a8fb2282 --- /dev/null +++ b/jpa/boot-jpa-locks/mvnw @@ -0,0 +1,316 @@ +#!/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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/jpa/boot-jpa-locks/mvnw.cmd b/jpa/boot-jpa-locks/mvnw.cmd new file mode 100644 index 000000000..1d8ab018e --- /dev/null +++ b/jpa/boot-jpa-locks/mvnw.cmd @@ -0,0 +1,188 @@ +@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 https://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 Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/jpa/boot-jpa-locks/pom.xml b/jpa/boot-jpa-locks/pom.xml new file mode 100644 index 000000000..3b9c32910 --- /dev/null +++ b/jpa/boot-jpa-locks/pom.xml @@ -0,0 +1,353 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.5 + + + com.example.locks + boot-jpa-locks + 0.0.1-SNAPSHOT + boot-jpa-locks + boot-jpa-locks + + + UTF-8 + UTF-8 + + 17 + 2022.0.4 + 2.2.0 + 2.15.0 + + ${project.build.directory}/test-results + 2.40.0 + 8.4.2 + 1.2.1 + 3.10.0.2594 + 0.8.11 + 0.80 + ${project.build.directory}/jacoco/test + ${jacoco.utReportFolder}/test.exec + ${project.build.directory}/jacoco/integrationTest + ${jacoco.itReportFolder}/integrationTest.exec + ${project.testresult.directory}/test + ${project.testresult.directory}/integrationTest + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + org.liquibase + liquibase-core + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc-openapi.version} + + + org.apache.commons + commons-lang3 + + + commons-io + commons-io + ${commons-io.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-testcontainers + test + + + org.awaitility + awaitility + test + + + org.testcontainers + junit-jupiter + test + + + org.testcontainers + postgresql + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + + io.github.git-commit-id + git-commit-id-maven-plugin + + + + revision + + + + + false + false + true + + ^git.branch$ + ^git.commit.id.abbrev$ + ^git.commit.user.name$ + ^git.commit.message.full$ + + + + + org.apache.maven.plugins + maven-surefire-plugin + + alphabetical + ${junit.utReportFolder} + + **/*IT* + **/*IntTest* + **/*IntegrationTest* + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + ${project.build.outputDirectory} + alphabetical + ${junit.itReportFolder} + + **/*IT* + **/*IntTest* + **/*IntegrationTest* + + + + + integration-test + + integration-test + + + + verify + + verify + + + + + + org.codehaus.mojo + properties-maven-plugin + ${properties-maven-plugin.version} + + + initialize + + read-project-properties + + + + sonar-project.properties + + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + 2.38.0 + + + + + + + + + compile + + check + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + ${project.build.directory}/jacoco/test/jacoco.exec + + + BUNDLE + + + COMPLEXITY + COVEREDRATIO + ${jacoco.minimum.coverage} + + + + + + **/*Application.* + **/config/** + **/models/* + **/dtos/* + **/exceptions/* + **/*Constants* + + + + + pre-unit-tests + + prepare-agent + + + + ${jacoco.utReportFile} + + + + + post-unit-test + test + + report + + + ${jacoco.utReportFile} + ${jacoco.utReportFolder} + + + + pre-integration-tests + + prepare-agent-integration + + + + ${jacoco.itReportFile} + + + + + post-integration-tests + post-integration-test + + report-integration + + + ${jacoco.itReportFile} + ${jacoco.itReportFolder} + + + + + + org.owasp + dependency-check-maven + ${dependency-check-maven.version} + + false + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} + + + + sonar + + + + + + + + diff --git a/jpa/boot-jpa-locks/sonar-project.properties b/jpa/boot-jpa-locks/sonar-project.properties new file mode 100644 index 000000000..922e58e66 --- /dev/null +++ b/jpa/boot-jpa-locks/sonar-project.properties @@ -0,0 +1,12 @@ +sonar.sourceEncoding=UTF-8 +sonar.projectKey=sonar_projectkey +sonar.organization=sonar_org +sonar.host.url=https://sonarcloud.io + +sonar.sources=src/main/java +sonar.tests=src/test/java +sonar.exclusions=src/main/java/**/config/*.*,src/main/java/**/entities/*.*,src/main/java/**/models/*.*,src/main/java/**/exceptions/*.*,src/main/java/**/utils/*.*,src/main/java/**/*Application.* +sonar.test.inclusions=**/*Test.java,**/*IntegrationTest.java,**/*IT.java +sonar.java.codeCoveragePlugin=jacoco +sonar.coverage.jacoco.xmlReportPaths=target/jacoco/test/jacoco.xml,target/jacoco/integrationTest/jacoco.xml +sonar.junit.reportPaths=target/test-results/test,target/test-results/integrationTest diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/Application.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/Application.java new file mode 100644 index 000000000..d4921cc9d --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/Application.java @@ -0,0 +1,15 @@ +package com.example.locks; + +import com.example.locks.config.ApplicationProperties; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +@SpringBootApplication +@EnableConfigurationProperties({ApplicationProperties.class}) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/ApplicationProperties.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/ApplicationProperties.java new file mode 100644 index 000000000..1b7d1fb69 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/ApplicationProperties.java @@ -0,0 +1,22 @@ +package com.example.locks.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + +@Data +@ConfigurationProperties("application") +public class ApplicationProperties { + + @NestedConfigurationProperty + private Cors cors = new Cors(); + + @Data + public static class Cors { + private String pathPattern = "/api/**"; + private String allowedMethods = "*"; + private String allowedHeaders = "*"; + private String allowedOriginPatterns = "*"; + private boolean allowCredentials = true; + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/GlobalExceptionHandler.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/GlobalExceptionHandler.java new file mode 100644 index 000000000..8f4dd4554 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/GlobalExceptionHandler.java @@ -0,0 +1,61 @@ +package com.example.locks.config; + +import com.example.locks.exception.ResourceNotFoundException; +import java.net.URI; +import java.time.Instant; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ProblemDetail; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ControllerAdvice +@Order(Ordered.HIGHEST_PRECEDENCE) +public class GlobalExceptionHandler { + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ProblemDetail onException(MethodArgumentNotValidException methodArgumentNotValidException) { + ProblemDetail problemDetail = + ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), "Invalid request content."); + problemDetail.setTitle("Constraint Violation"); + List validationErrorsList = methodArgumentNotValidException.getAllErrors().stream() + .map(objectError -> { + FieldError fieldError = (FieldError) objectError; + return new ApiValidationError( + fieldError.getObjectName(), + fieldError.getField(), + fieldError.getRejectedValue(), + Objects.requireNonNull(fieldError.getDefaultMessage(), "")); + }) + .sorted(Comparator.comparing(ApiValidationError::field)) + .toList(); + problemDetail.setProperty("violations", validationErrorsList); + return problemDetail; + } + + @ExceptionHandler(Exception.class) + ProblemDetail onException(Exception exception) { + if (exception instanceof ResourceNotFoundException resourceNotFoundException) { + ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail( + resourceNotFoundException.getHttpStatus(), resourceNotFoundException.getMessage()); + problemDetail.setTitle("Not Found"); + problemDetail.setType(URI.create("http://api.boot-jpa-locks.com/errors/not-found")); + problemDetail.setProperty("errorCategory", "Generic"); + problemDetail.setProperty("timestamp", Instant.now()); + return problemDetail; + } else { + return ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(500), exception.getMessage()); + } + } + + record ApiValidationError(String object, String field, Object rejectedValue, String message) {} +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/Initializer.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/Initializer.java new file mode 100644 index 000000000..28d5413e2 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/Initializer.java @@ -0,0 +1,19 @@ +package com.example.locks.config; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class Initializer implements CommandLineRunner { + + private final ApplicationProperties properties; + + @Override + public void run(String... args) { + log.info("Running Initializer....."); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/SwaggerConfig.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/SwaggerConfig.java new file mode 100644 index 000000000..76d77a26d --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/SwaggerConfig.java @@ -0,0 +1,10 @@ +package com.example.locks.config; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.servers.Server; +import org.springframework.context.annotation.Configuration; + +@Configuration(proxyBeanMethods = false) +@OpenAPIDefinition(info = @Info(title = "boot-jpa-locks", version = "v1"), servers = @Server(url = "/")) +public class SwaggerConfig {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/WebMvcConfig.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/WebMvcConfig.java new file mode 100644 index 000000000..446d28c07 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/WebMvcConfig.java @@ -0,0 +1,21 @@ +package com.example.locks.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@RequiredArgsConstructor +public class WebMvcConfig implements WebMvcConfigurer { + private final ApplicationProperties properties; + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping(properties.getCors().getPathPattern()) + .allowedMethods(properties.getCors().getAllowedMethods()) + .allowedHeaders(properties.getCors().getAllowedHeaders()) + .allowedOriginPatterns(properties.getCors().getAllowedOriginPatterns()) + .allowCredentials(properties.getCors().isAllowCredentials()); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/logging/Loggable.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/logging/Loggable.java new file mode 100644 index 000000000..b6d680a8c --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/logging/Loggable.java @@ -0,0 +1,14 @@ +package com.example.locks.config.logging; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Target({TYPE, METHOD}) +@Retention(RUNTIME) +@Inherited +public @interface Loggable {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/logging/LoggingAspect.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/logging/LoggingAspect.java new file mode 100644 index 000000000..182fb145e --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/config/logging/LoggingAspect.java @@ -0,0 +1,81 @@ +package com.example.locks.config.logging; + +import com.example.locks.utils.AppConstants; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class LoggingAspect { + + private final Logger log = LoggerFactory.getLogger(this.getClass()); + + private final Environment env; + + public LoggingAspect(Environment env) { + this.env = env; + } + + @Pointcut("within(@org.springframework.stereotype.Repository *)" + + " || within(@org.springframework.stereotype.Service *)" + + " || within(@org.springframework.web.bind.annotation.RestController *)") + public void springBeanPointcut() { + // pointcut definition + } + + @Pointcut("@within(com.example.locks.config.logging.Loggable) || " + + "@annotation(com.example.locks.config.logging.Loggable)") + public void applicationPackagePointcut() { + // pointcut definition + } + + @AfterThrowing(pointcut = "applicationPackagePointcut()", throwing = "e") + public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { + if (env.acceptsProfiles(Profiles.of(AppConstants.PROFILE_NOT_PROD))) { + log.error( + "Exception in {}.{}() with cause = '{}' and exception = '{}'", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + e.getCause() == null ? "NULL" : e.getCause(), + e.getMessage(), + e); + + } else { + log.error( + "Exception in {}.{}() with cause = {}", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + e.getCause() == null ? "NULL" : e.getCause()); + } + } + + @Around("applicationPackagePointcut()") + public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { + if (log.isTraceEnabled()) { + log.trace( + "Enter: {}.{}()", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName()); + } + long start = System.currentTimeMillis(); + Object result = joinPoint.proceed(); + long end = System.currentTimeMillis(); + if (log.isTraceEnabled()) { + log.trace( + "Exit: {}.{}(). Time taken: {} millis", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + end - start); + } + return result; + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/entities/Actor.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/entities/Actor.java new file mode 100644 index 000000000..418dacfe9 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/entities/Actor.java @@ -0,0 +1,43 @@ +package com.example.locks.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.util.Objects; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.Hibernate; + +@Entity +@Table(name = "actors") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class Actor { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(nullable = false) + private String text; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; + Actor actor = (Actor) o; + return id != null && Objects.equals(id, actor.id); + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/entities/Movie.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/entities/Movie.java new file mode 100644 index 000000000..e4939712a --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/entities/Movie.java @@ -0,0 +1,43 @@ +package com.example.locks.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.util.Objects; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.Hibernate; + +@Entity +@Table(name = "movies") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class Movie { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(nullable = false) + private String text; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; + Movie movie = (Movie) o; + return id != null && Objects.equals(id, movie.id); + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/ActorNotFoundException.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/ActorNotFoundException.java new file mode 100644 index 000000000..4c0275319 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/ActorNotFoundException.java @@ -0,0 +1,8 @@ +package com.example.locks.exception; + +public class ActorNotFoundException extends ResourceNotFoundException { + + public ActorNotFoundException(Long id) { + super("Actor with Id '%d' not found".formatted(id)); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/MovieNotFoundException.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/MovieNotFoundException.java new file mode 100644 index 000000000..01d207582 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/MovieNotFoundException.java @@ -0,0 +1,8 @@ +package com.example.locks.exception; + +public class MovieNotFoundException extends ResourceNotFoundException { + + public MovieNotFoundException(Long id) { + super("Movie with Id '%d' not found".formatted(id)); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/ResourceNotFoundException.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/ResourceNotFoundException.java new file mode 100644 index 000000000..f32ef4001 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/exception/ResourceNotFoundException.java @@ -0,0 +1,17 @@ +package com.example.locks.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; + +public class ResourceNotFoundException extends RuntimeException { + + private static final HttpStatus httpStatus = HttpStatus.NOT_FOUND; + + public ResourceNotFoundException(String errorMessage) { + super(errorMessage); + } + + public HttpStatusCode getHttpStatus() { + return httpStatus; + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/mapper/ActorMapper.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/mapper/ActorMapper.java new file mode 100644 index 000000000..5f32b16f0 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/mapper/ActorMapper.java @@ -0,0 +1,29 @@ +package com.example.locks.mapper; + +import com.example.locks.entities.Actor; +import com.example.locks.model.request.ActorRequest; +import com.example.locks.model.response.ActorResponse; +import java.util.List; +import org.springframework.stereotype.Service; + +@Service +public class ActorMapper { + + public Actor toEntity(ActorRequest actorRequest) { + Actor actor = new Actor(); + actor.setText(actorRequest.text()); + return actor; + } + + public void mapActorWithRequest(Actor actor, ActorRequest actorRequest) { + actor.setText(actorRequest.text()); + } + + public ActorResponse toResponse(Actor actor) { + return new ActorResponse(actor.getId(), actor.getText()); + } + + public List toResponseList(List actorList) { + return actorList.stream().map(this::toResponse).toList(); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/mapper/MovieMapper.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/mapper/MovieMapper.java new file mode 100644 index 000000000..27ee0dfc6 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/mapper/MovieMapper.java @@ -0,0 +1,29 @@ +package com.example.locks.mapper; + +import com.example.locks.entities.Movie; +import com.example.locks.model.request.MovieRequest; +import com.example.locks.model.response.MovieResponse; +import java.util.List; +import org.springframework.stereotype.Service; + +@Service +public class MovieMapper { + + public Movie toEntity(MovieRequest movieRequest) { + Movie movie = new Movie(); + movie.setText(movieRequest.text()); + return movie; + } + + public void mapMovieWithRequest(Movie movie, MovieRequest movieRequest) { + movie.setText(movieRequest.text()); + } + + public MovieResponse toResponse(Movie movie) { + return new MovieResponse(movie.getId(), movie.getText()); + } + + public List toResponseList(List movieList) { + return movieList.stream().map(this::toResponse).toList(); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/query/FindActorsQuery.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/query/FindActorsQuery.java new file mode 100644 index 000000000..3e1de4d6b --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/query/FindActorsQuery.java @@ -0,0 +1,3 @@ +package com.example.locks.model.query; + +public record FindActorsQuery(int pageNo, int pageSize, String sortBy, String sortDir) {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/query/FindMoviesQuery.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/query/FindMoviesQuery.java new file mode 100644 index 000000000..d8e55670c --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/query/FindMoviesQuery.java @@ -0,0 +1,3 @@ +package com.example.locks.model.query; + +public record FindMoviesQuery(int pageNo, int pageSize, String sortBy, String sortDir) {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/request/ActorRequest.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/request/ActorRequest.java new file mode 100644 index 000000000..ab970b456 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/request/ActorRequest.java @@ -0,0 +1,5 @@ +package com.example.locks.model.request; + +import jakarta.validation.constraints.NotEmpty; + +public record ActorRequest(@NotEmpty(message = "Text cannot be empty") String text) {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/request/MovieRequest.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/request/MovieRequest.java new file mode 100644 index 000000000..963151602 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/request/MovieRequest.java @@ -0,0 +1,5 @@ +package com.example.locks.model.request; + +import jakarta.validation.constraints.NotEmpty; + +public record MovieRequest(@NotEmpty(message = "Text cannot be empty") String text) {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/ActorResponse.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/ActorResponse.java new file mode 100644 index 000000000..d86cf0bf9 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/ActorResponse.java @@ -0,0 +1,3 @@ +package com.example.locks.model.response; + +public record ActorResponse(Long id, String text) {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/MovieResponse.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/MovieResponse.java new file mode 100644 index 000000000..ebfa818f0 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/MovieResponse.java @@ -0,0 +1,3 @@ +package com.example.locks.model.response; + +public record MovieResponse(Long id, String text) {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/PagedResult.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/PagedResult.java new file mode 100644 index 000000000..63f396d35 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/model/response/PagedResult.java @@ -0,0 +1,27 @@ +package com.example.locks.model.response; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import org.springframework.data.domain.Page; + +public record PagedResult( + List data, + long totalElements, + int pageNumber, + int totalPages, + @JsonProperty("isFirst") boolean isFirst, + @JsonProperty("isLast") boolean isLast, + @JsonProperty("hasNext") boolean hasNext, + @JsonProperty("hasPrevious") boolean hasPrevious) { + public PagedResult(Page page, List data) { + this( + data, + page.getTotalElements(), + page.getNumber() + 1, + page.getTotalPages(), + page.isFirst(), + page.isLast(), + page.hasNext(), + page.hasPrevious()); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/repositories/ActorRepository.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/repositories/ActorRepository.java new file mode 100644 index 000000000..685df6a73 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/repositories/ActorRepository.java @@ -0,0 +1,6 @@ +package com.example.locks.repositories; + +import com.example.locks.entities.Actor; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ActorRepository extends JpaRepository {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/repositories/MovieRepository.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/repositories/MovieRepository.java new file mode 100644 index 000000000..ee68131b4 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/repositories/MovieRepository.java @@ -0,0 +1,6 @@ +package com.example.locks.repositories; + +import com.example.locks.entities.Movie; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MovieRepository extends JpaRepository {} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/services/ActorService.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/services/ActorService.java new file mode 100644 index 000000000..27fe154dd --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/services/ActorService.java @@ -0,0 +1,78 @@ +package com.example.locks.services; + +import com.example.locks.entities.Actor; +import com.example.locks.exception.ActorNotFoundException; +import com.example.locks.mapper.ActorMapper; +import com.example.locks.model.query.FindActorsQuery; +import com.example.locks.model.request.ActorRequest; +import com.example.locks.model.response.ActorResponse; +import com.example.locks.model.response.PagedResult; +import com.example.locks.repositories.ActorRepository; +import java.util.List; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +@RequiredArgsConstructor +public class ActorService { + + private final ActorRepository actorRepository; + private final ActorMapper actorMapper; + + public PagedResult findAllActors(FindActorsQuery findActorsQuery) { + + // create Pageable instance + Pageable pageable = createPageable(findActorsQuery); + + Page actorsPage = actorRepository.findAll(pageable); + + List actorResponseList = actorMapper.toResponseList(actorsPage.getContent()); + + return new PagedResult<>(actorsPage, actorResponseList); + } + + private Pageable createPageable(FindActorsQuery findActorsQuery) { + int pageNo = Math.max(findActorsQuery.pageNo() - 1, 0); + Sort sort = Sort.by( + findActorsQuery.sortDir().equalsIgnoreCase(Sort.Direction.ASC.name()) + ? Sort.Order.asc(findActorsQuery.sortBy()) + : Sort.Order.desc(findActorsQuery.sortBy())); + return PageRequest.of(pageNo, findActorsQuery.pageSize(), sort); + } + + public Optional findActorById(Long id) { + return actorRepository.findById(id).map(actorMapper::toResponse); + } + + @Transactional + public ActorResponse saveActor(ActorRequest actorRequest) { + Actor actor = actorMapper.toEntity(actorRequest); + Actor savedActor = actorRepository.save(actor); + return actorMapper.toResponse(savedActor); + } + + @Transactional + public ActorResponse updateActor(Long id, ActorRequest actorRequest) { + Actor actor = actorRepository.findById(id).orElseThrow(() -> new ActorNotFoundException(id)); + + // Update the actor object with data from actorRequest + actorMapper.mapActorWithRequest(actor, actorRequest); + + // Save the updated actor object + Actor updatedActor = actorRepository.save(actor); + + return actorMapper.toResponse(updatedActor); + } + + @Transactional + public void deleteActorById(Long id) { + actorRepository.deleteById(id); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/services/MovieService.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/services/MovieService.java new file mode 100644 index 000000000..8f5a85361 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/services/MovieService.java @@ -0,0 +1,78 @@ +package com.example.locks.services; + +import com.example.locks.entities.Movie; +import com.example.locks.exception.MovieNotFoundException; +import com.example.locks.mapper.MovieMapper; +import com.example.locks.model.query.FindMoviesQuery; +import com.example.locks.model.request.MovieRequest; +import com.example.locks.model.response.MovieResponse; +import com.example.locks.model.response.PagedResult; +import com.example.locks.repositories.MovieRepository; +import java.util.List; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +@RequiredArgsConstructor +public class MovieService { + + private final MovieRepository movieRepository; + private final MovieMapper movieMapper; + + public PagedResult findAllMovies(FindMoviesQuery findMoviesQuery) { + + // create Pageable instance + Pageable pageable = createPageable(findMoviesQuery); + + Page moviesPage = movieRepository.findAll(pageable); + + List movieResponseList = movieMapper.toResponseList(moviesPage.getContent()); + + return new PagedResult<>(moviesPage, movieResponseList); + } + + private Pageable createPageable(FindMoviesQuery findMoviesQuery) { + int pageNo = Math.max(findMoviesQuery.pageNo() - 1, 0); + Sort sort = Sort.by( + findMoviesQuery.sortDir().equalsIgnoreCase(Sort.Direction.ASC.name()) + ? Sort.Order.asc(findMoviesQuery.sortBy()) + : Sort.Order.desc(findMoviesQuery.sortBy())); + return PageRequest.of(pageNo, findMoviesQuery.pageSize(), sort); + } + + public Optional findMovieById(Long id) { + return movieRepository.findById(id).map(movieMapper::toResponse); + } + + @Transactional + public MovieResponse saveMovie(MovieRequest movieRequest) { + Movie movie = movieMapper.toEntity(movieRequest); + Movie savedMovie = movieRepository.save(movie); + return movieMapper.toResponse(savedMovie); + } + + @Transactional + public MovieResponse updateMovie(Long id, MovieRequest movieRequest) { + Movie movie = movieRepository.findById(id).orElseThrow(() -> new MovieNotFoundException(id)); + + // Update the movie object with data from movieRequest + movieMapper.mapMovieWithRequest(movie, movieRequest); + + // Save the updated movie object + Movie updatedMovie = movieRepository.save(movie); + + return movieMapper.toResponse(updatedMovie); + } + + @Transactional + public void deleteMovieById(Long id) { + movieRepository.deleteById(id); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/utils/AppConstants.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/utils/AppConstants.java new file mode 100644 index 000000000..9f13170fa --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/utils/AppConstants.java @@ -0,0 +1,12 @@ +package com.example.locks.utils; + +public final class AppConstants { + public static final String PROFILE_PROD = "prod"; + public static final String PROFILE_NOT_PROD = "!" + PROFILE_PROD; + public static final String PROFILE_TEST = "test"; + public static final String PROFILE_NOT_TEST = "!" + PROFILE_TEST; + public static final String DEFAULT_PAGE_NUMBER = "0"; + public static final String DEFAULT_PAGE_SIZE = "10"; + public static final String DEFAULT_SORT_BY = "id"; + public static final String DEFAULT_SORT_DIRECTION = "asc"; +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/web/controllers/ActorController.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/web/controllers/ActorController.java new file mode 100644 index 000000000..9b7dfe5ba --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/web/controllers/ActorController.java @@ -0,0 +1,80 @@ +package com.example.locks.web.controllers; + +import com.example.locks.exception.ActorNotFoundException; +import com.example.locks.model.query.FindActorsQuery; +import com.example.locks.model.request.ActorRequest; +import com.example.locks.model.response.ActorResponse; +import com.example.locks.model.response.PagedResult; +import com.example.locks.services.ActorService; +import com.example.locks.utils.AppConstants; +import jakarta.validation.Valid; +import java.net.URI; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +@RestController +@RequestMapping("/api/actors") +@Slf4j +@RequiredArgsConstructor +public class ActorController { + + private final ActorService actorService; + + @GetMapping + public PagedResult getAllActors( + @RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) + int pageNo, + @RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) + int pageSize, + @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) + String sortBy, + @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) + String sortDir) { + FindActorsQuery findActorsQuery = new FindActorsQuery(pageNo, pageSize, sortBy, sortDir); + return actorService.findAllActors(findActorsQuery); + } + + @GetMapping("/{id}") + public ResponseEntity getActorById(@PathVariable Long id) { + return actorService.findActorById(id).map(ResponseEntity::ok).orElseThrow(() -> new ActorNotFoundException(id)); + } + + @PostMapping + public ResponseEntity createActor(@RequestBody @Validated ActorRequest actorRequest) { + ActorResponse response = actorService.saveActor(actorRequest); + URI location = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/api/actors/{id}") + .buildAndExpand(response.id()) + .toUri(); + return ResponseEntity.created(location).body(response); + } + + @PutMapping("/{id}") + public ResponseEntity updateActor( + @PathVariable Long id, @RequestBody @Valid ActorRequest actorRequest) { + return ResponseEntity.ok(actorService.updateActor(id, actorRequest)); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteActor(@PathVariable Long id) { + return actorService + .findActorById(id) + .map(actor -> { + actorService.deleteActorById(id); + return ResponseEntity.ok(actor); + }) + .orElseThrow(() -> new ActorNotFoundException(id)); + } +} diff --git a/jpa/boot-jpa-locks/src/main/java/com/example/locks/web/controllers/MovieController.java b/jpa/boot-jpa-locks/src/main/java/com/example/locks/web/controllers/MovieController.java new file mode 100644 index 000000000..24da93340 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/java/com/example/locks/web/controllers/MovieController.java @@ -0,0 +1,80 @@ +package com.example.locks.web.controllers; + +import com.example.locks.exception.MovieNotFoundException; +import com.example.locks.model.query.FindMoviesQuery; +import com.example.locks.model.request.MovieRequest; +import com.example.locks.model.response.MovieResponse; +import com.example.locks.model.response.PagedResult; +import com.example.locks.services.MovieService; +import com.example.locks.utils.AppConstants; +import jakarta.validation.Valid; +import java.net.URI; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +@RestController +@RequestMapping("/api/movies") +@Slf4j +@RequiredArgsConstructor +public class MovieController { + + private final MovieService movieService; + + @GetMapping + public PagedResult getAllMovies( + @RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) + int pageNo, + @RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) + int pageSize, + @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) + String sortBy, + @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) + String sortDir) { + FindMoviesQuery findMoviesQuery = new FindMoviesQuery(pageNo, pageSize, sortBy, sortDir); + return movieService.findAllMovies(findMoviesQuery); + } + + @GetMapping("/{id}") + public ResponseEntity getMovieById(@PathVariable Long id) { + return movieService.findMovieById(id).map(ResponseEntity::ok).orElseThrow(() -> new MovieNotFoundException(id)); + } + + @PostMapping + public ResponseEntity createMovie(@RequestBody @Validated MovieRequest movieRequest) { + MovieResponse response = movieService.saveMovie(movieRequest); + URI location = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/api/movies/{id}") + .buildAndExpand(response.id()) + .toUri(); + return ResponseEntity.created(location).body(response); + } + + @PutMapping("/{id}") + public ResponseEntity updateMovie( + @PathVariable Long id, @RequestBody @Valid MovieRequest movieRequest) { + return ResponseEntity.ok(movieService.updateMovie(id, movieRequest)); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteMovie(@PathVariable Long id) { + return movieService + .findMovieById(id) + .map(movie -> { + movieService.deleteMovieById(id); + return ResponseEntity.ok(movie); + }) + .orElseThrow(() -> new MovieNotFoundException(id)); + } +} diff --git a/jpa/boot-jpa-locks/src/main/resources/application-local.properties b/jpa/boot-jpa-locks/src/main/resources/application-local.properties new file mode 100644 index 000000000..62c4e116a --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/application-local.properties @@ -0,0 +1,5 @@ +spring.datasource.driver-class-name=org.postgresql.Driver +spring.datasource.url=jdbc:postgresql://localhost:5432/appdb +spring.datasource.username=appuser +spring.datasource.password=secret + diff --git a/jpa/boot-jpa-locks/src/main/resources/application.properties b/jpa/boot-jpa-locks/src/main/resources/application.properties new file mode 100644 index 000000000..f0252f0da --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/application.properties @@ -0,0 +1,28 @@ +spring.application.name=boot-jpa-locks +server.port=8080 +server.shutdown=graceful +spring.main.allow-bean-definition-overriding=true +spring.jmx.enabled=false +spring.mvc.problemdetails.enabled=true + +################ Actuator ##################### +management.endpoints.web.exposure.include=configprops,env,health,info,logfile,loggers,metrics,prometheus +management.endpoint.health.show-details=always + +################ Database ##################### +spring.jpa.show-sql=false +spring.jpa.open-in-view=false +spring.data.jpa.repositories.bootstrap-mode=deferred +spring.datasource.hikari.auto-commit=false +spring.jpa.hibernate.ddl-auto=none +#spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.jdbc.time_zone=UTC +spring.jpa.properties.hibernate.generate_statistics=false +spring.jpa.properties.hibernate.jdbc.batch_size=25 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true +spring.jpa.properties.hibernate.query.in_clause_parameter_padding=true +spring.jpa.properties.hibernate.query.plan_cache_max_size=4096 +spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true diff --git a/jpa/boot-jpa-locks/src/main/resources/db/changelog/db.changelog-master.yaml b/jpa/boot-jpa-locks/src/main/resources/db/changelog/db.changelog-master.yaml new file mode 100644 index 000000000..7e9e64aa4 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/db/changelog/db.changelog-master.yaml @@ -0,0 +1,5 @@ +databaseChangeLog: + - includeAll: + path: migration/ + errorIfMissingOrEmpty: true + relativeToChangelogFile: true \ No newline at end of file diff --git a/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/01-init.xml b/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/01-init.xml new file mode 100644 index 000000000..9d3b8b9b3 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/01-init.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/02-create_actors_table.xml b/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/02-create_actors_table.xml new file mode 100644 index 000000000..565644f94 --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/02-create_actors_table.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/03-create_movies_table.xml b/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/03-create_movies_table.xml new file mode 100644 index 000000000..b20b8df2e --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/db/changelog/migration/03-create_movies_table.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-locks/src/main/resources/logback-spring.xml b/jpa/boot-jpa-locks/src/main/resources/logback-spring.xml new file mode 100644 index 000000000..5fb09640f --- /dev/null +++ b/jpa/boot-jpa-locks/src/main/resources/logback-spring.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/ApplicationIntegrationTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/ApplicationIntegrationTest.java new file mode 100644 index 000000000..1654d5dde --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/ApplicationIntegrationTest.java @@ -0,0 +1,10 @@ +package com.example.locks; + +import com.example.locks.common.AbstractIntegrationTest; +import org.junit.jupiter.api.Test; + +class ApplicationIntegrationTest extends AbstractIntegrationTest { + + @Test + void contextLoads() {} +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/SchemaValidationTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/SchemaValidationTest.java new file mode 100644 index 000000000..a7b367fdd --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/SchemaValidationTest.java @@ -0,0 +1,16 @@ +package com.example.locks; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + +@DataJpaTest( + properties = { + "spring.jpa.hibernate.ddl-auto=validate", + "spring.test.database.replace=none", + "spring.datasource.url=jdbc:tc:postgresql:16.0-alpine:///db" + }) +class SchemaValidationTest { + + @Test + void validateJpaMappingsWithDbSchema() {} +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/TestApplication.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/TestApplication.java new file mode 100644 index 000000000..8f960b642 --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/TestApplication.java @@ -0,0 +1,12 @@ +package com.example.locks; + +import com.example.locks.common.ContainersConfig; +import org.springframework.boot.SpringApplication; + +public class TestApplication { + + public static void main(String[] args) { + System.setProperty("spring.profiles.active", "local"); + SpringApplication.from(Application::main).with(ContainersConfig.class).run(args); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/common/AbstractIntegrationTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/common/AbstractIntegrationTest.java new file mode 100644 index 000000000..59e273646 --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/common/AbstractIntegrationTest.java @@ -0,0 +1,25 @@ +package com.example.locks.common; + +import static com.example.locks.utils.AppConstants.PROFILE_TEST; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +@ActiveProfiles({PROFILE_TEST}) +@SpringBootTest( + webEnvironment = RANDOM_PORT, + classes = {ContainersConfig.class}) +@AutoConfigureMockMvc +public abstract class AbstractIntegrationTest { + + @Autowired + protected MockMvc mockMvc; + + @Autowired + protected ObjectMapper objectMapper; +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/common/ContainersConfig.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/common/ContainersConfig.java new file mode 100644 index 000000000..2e17a5ffb --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/common/ContainersConfig.java @@ -0,0 +1,17 @@ +package com.example.locks.common; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.utility.DockerImageName; + +@TestConfiguration(proxyBeanMethods = false) +public class ContainersConfig { + + @Bean + @ServiceConnection + PostgreSQLContainer postgreSQLContainer() { + return new PostgreSQLContainer<>(DockerImageName.parse("postgres:16.0-alpine")); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/services/ActorServiceTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/services/ActorServiceTest.java new file mode 100644 index 000000000..7597add1c --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/services/ActorServiceTest.java @@ -0,0 +1,67 @@ +package com.example.locks.services; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.times; +import static org.mockito.BDDMockito.verify; +import static org.mockito.BDDMockito.willDoNothing; + +import com.example.locks.entities.Actor; +import com.example.locks.mapper.ActorMapper; +import com.example.locks.model.response.ActorResponse; +import com.example.locks.repositories.ActorRepository; +import java.util.Optional; +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; + +@ExtendWith(MockitoExtension.class) +class ActorServiceTest { + + @Mock + private ActorRepository actorRepository; + + @Mock + private ActorMapper actorMapper; + + @InjectMocks + private ActorService actorService; + + @Test + void findActorById() { + // given + given(actorRepository.findById(1L)).willReturn(Optional.of(getActor())); + given(actorMapper.toResponse(any(Actor.class))).willReturn(getActorResponse()); + // when + Optional optionalActor = actorService.findActorById(1L); + // then + assertThat(optionalActor).isPresent(); + ActorResponse actor = optionalActor.get(); + assertThat(actor.id()).isEqualTo(1L); + assertThat(actor.text()).isEqualTo("junitTest"); + } + + @Test + void deleteActorById() { + // given + willDoNothing().given(actorRepository).deleteById(1L); + // when + actorService.deleteActorById(1L); + // then + verify(actorRepository, times(1)).deleteById(1L); + } + + private Actor getActor() { + Actor actor = new Actor(); + actor.setId(1L); + actor.setText("junitTest"); + return actor; + } + + private ActorResponse getActorResponse() { + return new ActorResponse(1L, "junitTest"); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/services/MovieServiceTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/services/MovieServiceTest.java new file mode 100644 index 000000000..395a95965 --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/services/MovieServiceTest.java @@ -0,0 +1,67 @@ +package com.example.locks.services; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.times; +import static org.mockito.BDDMockito.verify; +import static org.mockito.BDDMockito.willDoNothing; + +import com.example.locks.entities.Movie; +import com.example.locks.mapper.MovieMapper; +import com.example.locks.model.response.MovieResponse; +import com.example.locks.repositories.MovieRepository; +import java.util.Optional; +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; + +@ExtendWith(MockitoExtension.class) +class MovieServiceTest { + + @Mock + private MovieRepository movieRepository; + + @Mock + private MovieMapper movieMapper; + + @InjectMocks + private MovieService movieService; + + @Test + void findMovieById() { + // given + given(movieRepository.findById(1L)).willReturn(Optional.of(getMovie())); + given(movieMapper.toResponse(any(Movie.class))).willReturn(getMovieResponse()); + // when + Optional optionalMovie = movieService.findMovieById(1L); + // then + assertThat(optionalMovie).isPresent(); + MovieResponse movie = optionalMovie.get(); + assertThat(movie.id()).isEqualTo(1L); + assertThat(movie.text()).isEqualTo("junitTest"); + } + + @Test + void deleteMovieById() { + // given + willDoNothing().given(movieRepository).deleteById(1L); + // when + movieService.deleteMovieById(1L); + // then + verify(movieRepository, times(1)).deleteById(1L); + } + + private Movie getMovie() { + Movie movie = new Movie(); + movie.setId(1L); + movie.setText("junitTest"); + return movie; + } + + private MovieResponse getMovieResponse() { + return new MovieResponse(1L, "junitTest"); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/ActorControllerIT.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/ActorControllerIT.java new file mode 100644 index 000000000..36f1f050d --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/ActorControllerIT.java @@ -0,0 +1,129 @@ +package com.example.locks.web.controllers; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.locks.common.AbstractIntegrationTest; +import com.example.locks.entities.Actor; +import com.example.locks.model.request.ActorRequest; +import com.example.locks.repositories.ActorRepository; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +class ActorControllerIT extends AbstractIntegrationTest { + + @Autowired + private ActorRepository actorRepository; + + private List actorList = null; + + @BeforeEach + void setUp() { + actorRepository.deleteAllInBatch(); + + actorList = new ArrayList<>(); + actorList.add(new Actor(null, "First Actor")); + actorList.add(new Actor(null, "Second Actor")); + actorList.add(new Actor(null, "Third Actor")); + actorList = actorRepository.saveAll(actorList); + } + + @Test + void shouldFetchAllActors() throws Exception { + this.mockMvc + .perform(get("/api/actors")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()", is(actorList.size()))) + .andExpect(jsonPath("$.totalElements", is(3))) + .andExpect(jsonPath("$.pageNumber", is(1))) + .andExpect(jsonPath("$.totalPages", is(1))) + .andExpect(jsonPath("$.isFirst", is(true))) + .andExpect(jsonPath("$.isLast", is(true))) + .andExpect(jsonPath("$.hasNext", is(false))) + .andExpect(jsonPath("$.hasPrevious", is(false))); + } + + @Test + void shouldFindActorById() throws Exception { + Actor actor = actorList.get(0); + Long actorId = actor.getId(); + + this.mockMvc + .perform(get("/api/actors/{id}", actorId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(actor.getId()), Long.class)) + .andExpect(jsonPath("$.text", is(actor.getText()))); + } + + @Test + void shouldCreateNewActor() throws Exception { + ActorRequest actorRequest = new ActorRequest("New Actor"); + this.mockMvc + .perform(post("/api/actors") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isCreated()) + .andExpect(header().exists(HttpHeaders.LOCATION)) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.text", is(actorRequest.text()))); + } + + @Test + void shouldReturn400WhenCreateNewActorWithoutText() throws Exception { + ActorRequest actorRequest = new ActorRequest(null); + + this.mockMvc + .perform(post("/api/actors") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isBadRequest()) + .andExpect(header().string("Content-Type", is("application/problem+json"))) + .andExpect(jsonPath("$.type", is("about:blank"))) + .andExpect(jsonPath("$.title", is("Constraint Violation"))) + .andExpect(jsonPath("$.status", is(400))) + .andExpect(jsonPath("$.detail", is("Invalid request content."))) + .andExpect(jsonPath("$.instance", is("/api/actors"))) + .andExpect(jsonPath("$.violations", hasSize(1))) + .andExpect(jsonPath("$.violations[0].field", is("text"))) + .andExpect(jsonPath("$.violations[0].message", is("Text cannot be empty"))) + .andReturn(); + } + + @Test + void shouldUpdateActor() throws Exception { + Long actorId = actorList.get(0).getId(); + ActorRequest actorRequest = new ActorRequest("Updated Actor"); + + this.mockMvc + .perform(put("/api/actors/{id}", actorId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(actorId), Long.class)) + .andExpect(jsonPath("$.text", is(actorRequest.text()))); + } + + @Test + void shouldDeleteActor() throws Exception { + Actor actor = actorList.get(0); + + this.mockMvc + .perform(delete("/api/actors/{id}", actor.getId())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(actor.getId()), Long.class)) + .andExpect(jsonPath("$.text", is(actor.getText()))); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/ActorControllerTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/ActorControllerTest.java new file mode 100644 index 000000000..21fb2b42c --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/ActorControllerTest.java @@ -0,0 +1,218 @@ +package com.example.locks.web.controllers; + +import static com.example.locks.utils.AppConstants.PROFILE_TEST; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doNothing; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.locks.entities.Actor; +import com.example.locks.exception.ActorNotFoundException; +import com.example.locks.model.query.FindActorsQuery; +import com.example.locks.model.request.ActorRequest; +import com.example.locks.model.response.ActorResponse; +import com.example.locks.model.response.PagedResult; +import com.example.locks.services.ActorService; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(controllers = ActorController.class) +@ActiveProfiles(PROFILE_TEST) +class ActorControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ActorService actorService; + + @Autowired + private ObjectMapper objectMapper; + + private List actorList; + + @BeforeEach + void setUp() { + this.actorList = new ArrayList<>(); + this.actorList.add(new Actor(1L, "text 1")); + this.actorList.add(new Actor(2L, "text 2")); + this.actorList.add(new Actor(3L, "text 3")); + } + + @Test + void shouldFetchAllActors() throws Exception { + + Page page = new PageImpl<>(actorList); + PagedResult actorPagedResult = new PagedResult<>(page, getActorResponseList()); + FindActorsQuery findActorsQuery = new FindActorsQuery(0, 10, "id", "asc"); + given(actorService.findAllActors(findActorsQuery)).willReturn(actorPagedResult); + + this.mockMvc + .perform(get("/api/actors")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()", is(actorList.size()))) + .andExpect(jsonPath("$.totalElements", is(3))) + .andExpect(jsonPath("$.pageNumber", is(1))) + .andExpect(jsonPath("$.totalPages", is(1))) + .andExpect(jsonPath("$.isFirst", is(true))) + .andExpect(jsonPath("$.isLast", is(true))) + .andExpect(jsonPath("$.hasNext", is(false))) + .andExpect(jsonPath("$.hasPrevious", is(false))); + } + + @Test + void shouldFindActorById() throws Exception { + Long actorId = 1L; + ActorResponse actor = new ActorResponse(actorId, "text 1"); + given(actorService.findActorById(actorId)).willReturn(Optional.of(actor)); + + this.mockMvc + .perform(get("/api/actors/{id}", actorId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.text", is(actor.text()))); + } + + @Test + void shouldReturn404WhenFetchingNonExistingActor() throws Exception { + Long actorId = 1L; + given(actorService.findActorById(actorId)).willReturn(Optional.empty()); + + this.mockMvc + .perform(get("/api/actors/{id}", actorId)) + .andExpect(status().isNotFound()) + .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) + .andExpect(jsonPath("$.type", is("http://api.boot-jpa-locks.com/errors/not-found"))) + .andExpect(jsonPath("$.title", is("Not Found"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.detail").value("Actor with Id '%d' not found".formatted(actorId))); + } + + @Test + void shouldCreateNewActor() throws Exception { + + ActorResponse actor = new ActorResponse(1L, "some text"); + ActorRequest actorRequest = new ActorRequest("some text"); + given(actorService.saveActor(any(ActorRequest.class))).willReturn(actor); + + this.mockMvc + .perform(post("/api/actors") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isCreated()) + .andExpect(header().exists(HttpHeaders.LOCATION)) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.text", is(actor.text()))); + } + + @Test + void shouldReturn400WhenCreateNewActorWithoutText() throws Exception { + ActorRequest actorRequest = new ActorRequest(null); + + this.mockMvc + .perform(post("/api/actors") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isBadRequest()) + .andExpect(header().string("Content-Type", is("application/problem+json"))) + .andExpect(jsonPath("$.type", is("about:blank"))) + .andExpect(jsonPath("$.title", is("Constraint Violation"))) + .andExpect(jsonPath("$.status", is(400))) + .andExpect(jsonPath("$.detail", is("Invalid request content."))) + .andExpect(jsonPath("$.instance", is("/api/actors"))) + .andExpect(jsonPath("$.violations", hasSize(1))) + .andExpect(jsonPath("$.violations[0].field", is("text"))) + .andExpect(jsonPath("$.violations[0].message", is("Text cannot be empty"))) + .andReturn(); + } + + @Test + void shouldUpdateActor() throws Exception { + Long actorId = 1L; + ActorResponse actor = new ActorResponse(actorId, "Updated text"); + ActorRequest actorRequest = new ActorRequest("Updated text"); + given(actorService.updateActor(eq(actorId), any(ActorRequest.class))).willReturn(actor); + + this.mockMvc + .perform(put("/api/actors/{id}", actorId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(actorId), Long.class)) + .andExpect(jsonPath("$.text", is(actor.text()))); + } + + @Test + void shouldReturn404WhenUpdatingNonExistingActor() throws Exception { + Long actorId = 1L; + ActorRequest actorRequest = new ActorRequest("Updated text"); + given(actorService.updateActor(eq(actorId), any(ActorRequest.class))) + .willThrow(new ActorNotFoundException(actorId)); + + this.mockMvc + .perform(put("/api/actors/{id}", actorId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(actorRequest))) + .andExpect(status().isNotFound()) + .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) + .andExpect(jsonPath("$.type", is("http://api.boot-jpa-locks.com/errors/not-found"))) + .andExpect(jsonPath("$.title", is("Not Found"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.detail").value("Actor with Id '%d' not found".formatted(actorId))); + } + + @Test + void shouldDeleteActor() throws Exception { + Long actorId = 1L; + ActorResponse actor = new ActorResponse(actorId, "Some text"); + given(actorService.findActorById(actorId)).willReturn(Optional.of(actor)); + doNothing().when(actorService).deleteActorById(actorId); + + this.mockMvc + .perform(delete("/api/actors/{id}", actorId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.text", is(actor.text()))); + } + + @Test + void shouldReturn404WhenDeletingNonExistingActor() throws Exception { + Long actorId = 1L; + given(actorService.findActorById(actorId)).willReturn(Optional.empty()); + + this.mockMvc + .perform(delete("/api/actors/{id}", actorId)) + .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) + .andExpect(jsonPath("$.type", is("http://api.boot-jpa-locks.com/errors/not-found"))) + .andExpect(jsonPath("$.title", is("Not Found"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.detail").value("Actor with Id '%d' not found".formatted(actorId))); + } + + List getActorResponseList() { + return actorList.stream() + .map(actor -> new ActorResponse(actor.getId(), actor.getText())) + .toList(); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/MovieControllerIT.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/MovieControllerIT.java new file mode 100644 index 000000000..2812aee38 --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/MovieControllerIT.java @@ -0,0 +1,129 @@ +package com.example.locks.web.controllers; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.locks.common.AbstractIntegrationTest; +import com.example.locks.entities.Movie; +import com.example.locks.model.request.MovieRequest; +import com.example.locks.repositories.MovieRepository; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +class MovieControllerIT extends AbstractIntegrationTest { + + @Autowired + private MovieRepository movieRepository; + + private List movieList = null; + + @BeforeEach + void setUp() { + movieRepository.deleteAllInBatch(); + + movieList = new ArrayList<>(); + movieList.add(new Movie(null, "First Movie")); + movieList.add(new Movie(null, "Second Movie")); + movieList.add(new Movie(null, "Third Movie")); + movieList = movieRepository.saveAll(movieList); + } + + @Test + void shouldFetchAllMovies() throws Exception { + this.mockMvc + .perform(get("/api/movies")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()", is(movieList.size()))) + .andExpect(jsonPath("$.totalElements", is(3))) + .andExpect(jsonPath("$.pageNumber", is(1))) + .andExpect(jsonPath("$.totalPages", is(1))) + .andExpect(jsonPath("$.isFirst", is(true))) + .andExpect(jsonPath("$.isLast", is(true))) + .andExpect(jsonPath("$.hasNext", is(false))) + .andExpect(jsonPath("$.hasPrevious", is(false))); + } + + @Test + void shouldFindMovieById() throws Exception { + Movie movie = movieList.get(0); + Long movieId = movie.getId(); + + this.mockMvc + .perform(get("/api/movies/{id}", movieId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(movie.getId()), Long.class)) + .andExpect(jsonPath("$.text", is(movie.getText()))); + } + + @Test + void shouldCreateNewMovie() throws Exception { + MovieRequest movieRequest = new MovieRequest("New Movie"); + this.mockMvc + .perform(post("/api/movies") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isCreated()) + .andExpect(header().exists(HttpHeaders.LOCATION)) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.text", is(movieRequest.text()))); + } + + @Test + void shouldReturn400WhenCreateNewMovieWithoutText() throws Exception { + MovieRequest movieRequest = new MovieRequest(null); + + this.mockMvc + .perform(post("/api/movies") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isBadRequest()) + .andExpect(header().string("Content-Type", is("application/problem+json"))) + .andExpect(jsonPath("$.type", is("about:blank"))) + .andExpect(jsonPath("$.title", is("Constraint Violation"))) + .andExpect(jsonPath("$.status", is(400))) + .andExpect(jsonPath("$.detail", is("Invalid request content."))) + .andExpect(jsonPath("$.instance", is("/api/movies"))) + .andExpect(jsonPath("$.violations", hasSize(1))) + .andExpect(jsonPath("$.violations[0].field", is("text"))) + .andExpect(jsonPath("$.violations[0].message", is("Text cannot be empty"))) + .andReturn(); + } + + @Test + void shouldUpdateMovie() throws Exception { + Long movieId = movieList.get(0).getId(); + MovieRequest movieRequest = new MovieRequest("Updated Movie"); + + this.mockMvc + .perform(put("/api/movies/{id}", movieId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(movieId), Long.class)) + .andExpect(jsonPath("$.text", is(movieRequest.text()))); + } + + @Test + void shouldDeleteMovie() throws Exception { + Movie movie = movieList.get(0); + + this.mockMvc + .perform(delete("/api/movies/{id}", movie.getId())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(movie.getId()), Long.class)) + .andExpect(jsonPath("$.text", is(movie.getText()))); + } +} diff --git a/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/MovieControllerTest.java b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/MovieControllerTest.java new file mode 100644 index 000000000..025716a05 --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/java/com/example/locks/web/controllers/MovieControllerTest.java @@ -0,0 +1,218 @@ +package com.example.locks.web.controllers; + +import static com.example.locks.utils.AppConstants.PROFILE_TEST; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doNothing; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.locks.entities.Movie; +import com.example.locks.exception.MovieNotFoundException; +import com.example.locks.model.query.FindMoviesQuery; +import com.example.locks.model.request.MovieRequest; +import com.example.locks.model.response.MovieResponse; +import com.example.locks.model.response.PagedResult; +import com.example.locks.services.MovieService; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(controllers = MovieController.class) +@ActiveProfiles(PROFILE_TEST) +class MovieControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private MovieService movieService; + + @Autowired + private ObjectMapper objectMapper; + + private List movieList; + + @BeforeEach + void setUp() { + this.movieList = new ArrayList<>(); + this.movieList.add(new Movie(1L, "text 1")); + this.movieList.add(new Movie(2L, "text 2")); + this.movieList.add(new Movie(3L, "text 3")); + } + + @Test + void shouldFetchAllMovies() throws Exception { + + Page page = new PageImpl<>(movieList); + PagedResult moviePagedResult = new PagedResult<>(page, getMovieResponseList()); + FindMoviesQuery findMoviesQuery = new FindMoviesQuery(0, 10, "id", "asc"); + given(movieService.findAllMovies(findMoviesQuery)).willReturn(moviePagedResult); + + this.mockMvc + .perform(get("/api/movies")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()", is(movieList.size()))) + .andExpect(jsonPath("$.totalElements", is(3))) + .andExpect(jsonPath("$.pageNumber", is(1))) + .andExpect(jsonPath("$.totalPages", is(1))) + .andExpect(jsonPath("$.isFirst", is(true))) + .andExpect(jsonPath("$.isLast", is(true))) + .andExpect(jsonPath("$.hasNext", is(false))) + .andExpect(jsonPath("$.hasPrevious", is(false))); + } + + @Test + void shouldFindMovieById() throws Exception { + Long movieId = 1L; + MovieResponse movie = new MovieResponse(movieId, "text 1"); + given(movieService.findMovieById(movieId)).willReturn(Optional.of(movie)); + + this.mockMvc + .perform(get("/api/movies/{id}", movieId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.text", is(movie.text()))); + } + + @Test + void shouldReturn404WhenFetchingNonExistingMovie() throws Exception { + Long movieId = 1L; + given(movieService.findMovieById(movieId)).willReturn(Optional.empty()); + + this.mockMvc + .perform(get("/api/movies/{id}", movieId)) + .andExpect(status().isNotFound()) + .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) + .andExpect(jsonPath("$.type", is("http://api.boot-jpa-locks.com/errors/not-found"))) + .andExpect(jsonPath("$.title", is("Not Found"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.detail").value("Movie with Id '%d' not found".formatted(movieId))); + } + + @Test + void shouldCreateNewMovie() throws Exception { + + MovieResponse movie = new MovieResponse(1L, "some text"); + MovieRequest movieRequest = new MovieRequest("some text"); + given(movieService.saveMovie(any(MovieRequest.class))).willReturn(movie); + + this.mockMvc + .perform(post("/api/movies") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isCreated()) + .andExpect(header().exists(HttpHeaders.LOCATION)) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.text", is(movie.text()))); + } + + @Test + void shouldReturn400WhenCreateNewMovieWithoutText() throws Exception { + MovieRequest movieRequest = new MovieRequest(null); + + this.mockMvc + .perform(post("/api/movies") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isBadRequest()) + .andExpect(header().string("Content-Type", is("application/problem+json"))) + .andExpect(jsonPath("$.type", is("about:blank"))) + .andExpect(jsonPath("$.title", is("Constraint Violation"))) + .andExpect(jsonPath("$.status", is(400))) + .andExpect(jsonPath("$.detail", is("Invalid request content."))) + .andExpect(jsonPath("$.instance", is("/api/movies"))) + .andExpect(jsonPath("$.violations", hasSize(1))) + .andExpect(jsonPath("$.violations[0].field", is("text"))) + .andExpect(jsonPath("$.violations[0].message", is("Text cannot be empty"))) + .andReturn(); + } + + @Test + void shouldUpdateMovie() throws Exception { + Long movieId = 1L; + MovieResponse movie = new MovieResponse(movieId, "Updated text"); + MovieRequest movieRequest = new MovieRequest("Updated text"); + given(movieService.updateMovie(eq(movieId), any(MovieRequest.class))).willReturn(movie); + + this.mockMvc + .perform(put("/api/movies/{id}", movieId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(movieId), Long.class)) + .andExpect(jsonPath("$.text", is(movie.text()))); + } + + @Test + void shouldReturn404WhenUpdatingNonExistingMovie() throws Exception { + Long movieId = 1L; + MovieRequest movieRequest = new MovieRequest("Updated text"); + given(movieService.updateMovie(eq(movieId), any(MovieRequest.class))) + .willThrow(new MovieNotFoundException(movieId)); + + this.mockMvc + .perform(put("/api/movies/{id}", movieId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(movieRequest))) + .andExpect(status().isNotFound()) + .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) + .andExpect(jsonPath("$.type", is("http://api.boot-jpa-locks.com/errors/not-found"))) + .andExpect(jsonPath("$.title", is("Not Found"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.detail").value("Movie with Id '%d' not found".formatted(movieId))); + } + + @Test + void shouldDeleteMovie() throws Exception { + Long movieId = 1L; + MovieResponse movie = new MovieResponse(movieId, "Some text"); + given(movieService.findMovieById(movieId)).willReturn(Optional.of(movie)); + doNothing().when(movieService).deleteMovieById(movieId); + + this.mockMvc + .perform(delete("/api/movies/{id}", movieId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.text", is(movie.text()))); + } + + @Test + void shouldReturn404WhenDeletingNonExistingMovie() throws Exception { + Long movieId = 1L; + given(movieService.findMovieById(movieId)).willReturn(Optional.empty()); + + this.mockMvc + .perform(delete("/api/movies/{id}", movieId)) + .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) + .andExpect(jsonPath("$.type", is("http://api.boot-jpa-locks.com/errors/not-found"))) + .andExpect(jsonPath("$.title", is("Not Found"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.detail").value("Movie with Id '%d' not found".formatted(movieId))); + } + + List getMovieResponseList() { + return movieList.stream() + .map(movie -> new MovieResponse(movie.getId(), movie.getText())) + .toList(); + } +} diff --git a/jpa/boot-jpa-locks/src/test/resources/application-test.properties b/jpa/boot-jpa-locks/src/test/resources/application-test.properties new file mode 100644 index 000000000..e69de29bb diff --git a/jpa/boot-jpa-locks/src/test/resources/logback-test.xml b/jpa/boot-jpa-locks/src/test/resources/logback-test.xml new file mode 100644 index 000000000..1378a823a --- /dev/null +++ b/jpa/boot-jpa-locks/src/test/resources/logback-test.xml @@ -0,0 +1,14 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + + + + + + + + +