diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..667aaef0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +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/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c595b009 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip diff --git a/mvnw b/mvnw new file mode 100755 index 00000000..bd8896bf --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..76990537 --- /dev/null +++ b/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.5 + + + com.ironhack + homework-java-ironlibrary + 0.0.1-SNAPSHOT + homework-java-ironlibrary + homework-java-ironlibrary + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-devtools + runtime + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/com/ironhack/Application.java b/src/main/java/com/ironhack/Application.java new file mode 100644 index 00000000..418d88af --- /dev/null +++ b/src/main/java/com/ironhack/Application.java @@ -0,0 +1,13 @@ +package com.ironhack; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/src/main/java/com/ironhack/controller/AuthorController.java b/src/main/java/com/ironhack/controller/AuthorController.java new file mode 100644 index 00000000..8f603066 --- /dev/null +++ b/src/main/java/com/ironhack/controller/AuthorController.java @@ -0,0 +1,40 @@ +package com.ironhack.controller; + +import com.ironhack.dto.response.AuthorResponse; +import com.ironhack.dto.request.CreateAuthorRequest; +import com.ironhack.service.AuthorService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.UUID; + +@RestController +@RequestMapping("/v1/authors") +public class AuthorController { + private final AuthorService authorService; + + public AuthorController(AuthorService authorService) { + this.authorService = authorService; + } + + @PostMapping + public ResponseEntity createAuthor( + @Valid @RequestBody CreateAuthorRequest request + ) { + return ResponseEntity.status(HttpStatus.CREATED).body(authorService.create(request)); + } + + @GetMapping("/{id}") + public ResponseEntity getAuthorById( + @PathVariable UUID id + ) { + return ResponseEntity.ok(authorService.getById(id)); + } +} diff --git a/src/main/java/com/ironhack/controller/BookController.java b/src/main/java/com/ironhack/controller/BookController.java new file mode 100644 index 00000000..20a44c68 --- /dev/null +++ b/src/main/java/com/ironhack/controller/BookController.java @@ -0,0 +1,52 @@ +package com.ironhack.controller; + +import com.ironhack.dto.request.CreateBookRequest; +import com.ironhack.dto.response.BookResponse; +import com.ironhack.model.BookCategory; +import com.ironhack.service.BookService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.UUID; + +@RestController +@RequestMapping("/v1/books") +public class BookController { + private final BookService bookService; + + public BookController(BookService bookService) { + this.bookService = bookService; + } + + @PostMapping + public ResponseEntity createBook( + @Valid @RequestBody CreateBookRequest request + ) { + return ResponseEntity.status(HttpStatus.CREATED).body(bookService.create(request)); + } + + @GetMapping + public ResponseEntity> getBooks( + @RequestParam(required = false) String title, + @RequestParam(required = false) BookCategory category, + @RequestParam(required = false) UUID authorId + ) { + return ResponseEntity.ok(bookService.getBooks(title, category, authorId)); + } + + @GetMapping("/{id}") + public ResponseEntity getBookById( + @PathVariable UUID id + ) { + return ResponseEntity.ok(bookService.getById(id)); + } +} diff --git a/src/main/java/com/ironhack/controller/IssueController.java b/src/main/java/com/ironhack/controller/IssueController.java new file mode 100644 index 00000000..b5df4a1f --- /dev/null +++ b/src/main/java/com/ironhack/controller/IssueController.java @@ -0,0 +1,41 @@ +package com.ironhack.controller; + +import com.ironhack.dto.response.BookResponse; +import com.ironhack.dto.request.IssueBookRequest; +import com.ironhack.dto.response.IssueResponse; +import com.ironhack.service.IssueService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/v1/issues") +public class IssueController { + private final IssueService issueService; + + public IssueController(IssueService issueService) { + this.issueService = issueService; + } + + @PostMapping + public ResponseEntity issueBookToStudent( + @Valid @RequestBody IssueBookRequest request + ) { + return ResponseEntity.status(HttpStatus.CREATED).body(issueService.issueBook(request)); + } + + @GetMapping("/usn/{usn}/books") + public ResponseEntity> listBooksByUsn( + @PathVariable String usn + ) { + return ResponseEntity.ok(issueService.listBooksByUsn(usn)); + } +} diff --git a/src/main/java/com/ironhack/controller/StudentController.java b/src/main/java/com/ironhack/controller/StudentController.java new file mode 100644 index 00000000..5154a5d2 --- /dev/null +++ b/src/main/java/com/ironhack/controller/StudentController.java @@ -0,0 +1,38 @@ +package com.ironhack.controller; + +import com.ironhack.dto.request.CreateStudentRequest; +import com.ironhack.dto.response.StudentResponse; +import com.ironhack.service.StudentService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.UUID; + +@RestController +@RequestMapping("/v1/students") +public class StudentController { + private final StudentService studentService; + + public StudentController(StudentService studentService) { + this.studentService = studentService; + } + + @PostMapping + public ResponseEntity createStudent( + @Valid @RequestBody CreateStudentRequest request + ) { + return ResponseEntity.status(HttpStatus.CREATED).body(studentService.create(request)); + } + + @GetMapping("/{id}") + public ResponseEntity getStudentById(@PathVariable UUID id) { + return ResponseEntity.ok(studentService.getById(id)); + } +} diff --git a/src/main/java/com/ironhack/controller/advice/GlobalExceptionHandler.java b/src/main/java/com/ironhack/controller/advice/GlobalExceptionHandler.java new file mode 100644 index 00000000..f6a605ed --- /dev/null +++ b/src/main/java/com/ironhack/controller/advice/GlobalExceptionHandler.java @@ -0,0 +1,85 @@ +package com.ironhack.controller.advice; + +import com.ironhack.dto.response.ErrorResponse; +import com.ironhack.dto.response.ValidationErrorResponse; +import com.ironhack.exception.BadRequestException; +import com.ironhack.exception.ConflictException; +import com.ironhack.exception.NotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.time.LocalDateTime; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidation(MethodArgumentNotValidException exception) { + Map fieldErrors = exception.getBindingResult() + .getFieldErrors() + .stream() + .collect(Collectors.toMap( + FieldError::getField, + error -> Optional.ofNullable(error.getDefaultMessage()).orElse("Validation error"), + (existing, replacement) -> existing + )); + + ValidationErrorResponse response = new ValidationErrorResponse( + HttpStatus.BAD_REQUEST.value(), + "VALIDATION_ERROR", + fieldErrors, + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity handleNotFound(NotFoundException exception) { + ErrorResponse response = new ErrorResponse( + HttpStatus.NOT_FOUND.value(), + "NOT_FOUND", + exception.getMessage(), + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity handleConflict(ConflictException exception) { + ErrorResponse response = new ErrorResponse( + HttpStatus.CONFLICT.value(), + "CONFLICT", + exception.getMessage(), + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.CONFLICT).body(response); + } + + @ExceptionHandler(BadRequestException.class) + public ResponseEntity handleBadRequest(BadRequestException exception) { + ErrorResponse response = new ErrorResponse( + HttpStatus.BAD_REQUEST.value(), + "BAD_REQUEST", + exception.getMessage(), + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleUnexpected(Exception exception) { + ErrorResponse response = new ErrorResponse( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + "INTERNAL_SERVER_ERROR", + "An unexpected error occurred", + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } +} diff --git a/src/main/java/com/ironhack/dto/request/CreateAuthorRequest.java b/src/main/java/com/ironhack/dto/request/CreateAuthorRequest.java new file mode 100644 index 00000000..d6d3ad66 --- /dev/null +++ b/src/main/java/com/ironhack/dto/request/CreateAuthorRequest.java @@ -0,0 +1,12 @@ +package com.ironhack.dto.request; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; + +public record CreateAuthorRequest( + @NotBlank(message = "Author name is required") + String name, + @NotBlank(message = "Author email is required") + @Email(message = "Author email must be valid") + String email +) {} diff --git a/src/main/java/com/ironhack/dto/request/CreateBookRequest.java b/src/main/java/com/ironhack/dto/request/CreateBookRequest.java new file mode 100644 index 00000000..37230f8d --- /dev/null +++ b/src/main/java/com/ironhack/dto/request/CreateBookRequest.java @@ -0,0 +1,21 @@ +package com.ironhack.dto.request; + +import com.ironhack.model.BookCategory; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.util.UUID; + +public record CreateBookRequest( + @NotBlank(message = "ISBN is required") + String isbn, + @NotBlank(message = "Title is required") + String title, + @NotNull(message = "Category is required") + BookCategory category, + @NotNull @Min(value = 1, message = "Quantity must be at least 1") + Integer quantity, + @NotNull(message = "Author ID is required") + UUID authorId +) {} diff --git a/src/main/java/com/ironhack/dto/request/CreateStudentRequest.java b/src/main/java/com/ironhack/dto/request/CreateStudentRequest.java new file mode 100644 index 00000000..07f0ad82 --- /dev/null +++ b/src/main/java/com/ironhack/dto/request/CreateStudentRequest.java @@ -0,0 +1,11 @@ +package com.ironhack.dto.request; + +import jakarta.validation.constraints.NotBlank; + +public record CreateStudentRequest( + @NotBlank(message = "Student usn is required") + String usn, + @NotBlank(message = "Student name is required") + String name +) { +} diff --git a/src/main/java/com/ironhack/dto/request/IssueBookRequest.java b/src/main/java/com/ironhack/dto/request/IssueBookRequest.java new file mode 100644 index 00000000..f331f339 --- /dev/null +++ b/src/main/java/com/ironhack/dto/request/IssueBookRequest.java @@ -0,0 +1,17 @@ +package com.ironhack.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.util.UUID; + +public record IssueBookRequest( + @NotNull(message = "Student ID is required") + UUID studentId, + @NotNull(message = "Book ID is required") + UUID bookId, + @NotBlank(message = "Issue date is required") + String issueDate, + @NotBlank(message = "Return date is required") + String returnDate +) {} diff --git a/src/main/java/com/ironhack/dto/response/AuthorResponse.java b/src/main/java/com/ironhack/dto/response/AuthorResponse.java new file mode 100644 index 00000000..0b3a4d43 --- /dev/null +++ b/src/main/java/com/ironhack/dto/response/AuthorResponse.java @@ -0,0 +1,9 @@ +package com.ironhack.dto.response; + +import java.util.UUID; + +public record AuthorResponse( + UUID id, + String name, + String email +) {} diff --git a/src/main/java/com/ironhack/dto/response/BookResponse.java b/src/main/java/com/ironhack/dto/response/BookResponse.java new file mode 100644 index 00000000..6927963a --- /dev/null +++ b/src/main/java/com/ironhack/dto/response/BookResponse.java @@ -0,0 +1,14 @@ +package com.ironhack.dto.response; + +import com.ironhack.model.BookCategory; + +import java.util.UUID; + +public record BookResponse( + UUID id, + String isbn, + String title, + BookCategory category, + Integer quantity, + AuthorResponse author +) {} diff --git a/src/main/java/com/ironhack/dto/response/ErrorResponse.java b/src/main/java/com/ironhack/dto/response/ErrorResponse.java new file mode 100644 index 00000000..2de753d5 --- /dev/null +++ b/src/main/java/com/ironhack/dto/response/ErrorResponse.java @@ -0,0 +1,10 @@ +package com.ironhack.dto.response; + +import java.time.LocalDateTime; + +public record ErrorResponse( + Integer status, + String error, + String message, + LocalDateTime timestamp +) {} diff --git a/src/main/java/com/ironhack/dto/response/IssueResponse.java b/src/main/java/com/ironhack/dto/response/IssueResponse.java new file mode 100644 index 00000000..58f50b45 --- /dev/null +++ b/src/main/java/com/ironhack/dto/response/IssueResponse.java @@ -0,0 +1,11 @@ +package com.ironhack.dto.response; + +import java.util.UUID; + +public record IssueResponse( + UUID id, + String issueDate, + String returnDate, + BookResponse book, + StudentResponse student +) {} diff --git a/src/main/java/com/ironhack/dto/response/StudentResponse.java b/src/main/java/com/ironhack/dto/response/StudentResponse.java new file mode 100644 index 00000000..979ace7e --- /dev/null +++ b/src/main/java/com/ironhack/dto/response/StudentResponse.java @@ -0,0 +1,9 @@ +package com.ironhack.dto.response; + +import java.util.UUID; + +public record StudentResponse( + UUID id, + String usn, + String name +) {} diff --git a/src/main/java/com/ironhack/dto/response/ValidationErrorResponse.java b/src/main/java/com/ironhack/dto/response/ValidationErrorResponse.java new file mode 100644 index 00000000..5ba67fb9 --- /dev/null +++ b/src/main/java/com/ironhack/dto/response/ValidationErrorResponse.java @@ -0,0 +1,11 @@ +package com.ironhack.dto.response; + +import java.time.LocalDateTime; +import java.util.Map; + +public record ValidationErrorResponse( + Integer status, + String error, + Map errors, + LocalDateTime timestamp +) {} diff --git a/src/main/java/com/ironhack/entity/Author.java b/src/main/java/com/ironhack/entity/Author.java new file mode 100644 index 00000000..f747cb7d --- /dev/null +++ b/src/main/java/com/ironhack/entity/Author.java @@ -0,0 +1,63 @@ +package com.ironhack.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; + +import java.util.UUID; + +@Entity +@Table(name = "authors") +public class Author { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(nullable = false) + private String name; + + @Column(unique = true, nullable = false) + private String email; + + @OneToOne(mappedBy = "author", cascade = CascadeType.ALL) + @JsonIgnore + private Book book; + + public Author() {} + public Author(String name, String email, Book book) { + this.name = name; + this.email = email; + this.book = book; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Book getBook() { + return book; + } + + public void setBook(Book authorBook) { + this.book = authorBook; + } +} \ No newline at end of file diff --git a/src/main/java/com/ironhack/entity/Book.java b/src/main/java/com/ironhack/entity/Book.java new file mode 100644 index 00000000..c7f616e5 --- /dev/null +++ b/src/main/java/com/ironhack/entity/Book.java @@ -0,0 +1,92 @@ +package com.ironhack.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.ironhack.model.BookCategory; +import jakarta.persistence.*; + +import java.util.UUID; + +@Entity +@Table(name = "books") +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(unique = true, nullable = false) + private String isbn; + + @Column(nullable = false) + private String title; + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private BookCategory category; + + @Column(nullable = false) + private Integer quantity; + + @OneToOne + @JoinColumn(name = "author_id", nullable = false) + private Author author; + + @OneToOne(mappedBy = "book", cascade = CascadeType.REMOVE) + @JsonIgnore + private Issue issue; + + public Book() {} + public Book(String isbn, String title, BookCategory category, Integer quantity) { + this.isbn = isbn; + this.title = title; + this.category = category; + this.quantity = quantity; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public BookCategory getCategory() { + return category; + } + + public void setCategory(BookCategory category) { + this.category = category; + } + + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } +} diff --git a/src/main/java/com/ironhack/entity/Issue.java b/src/main/java/com/ironhack/entity/Issue.java new file mode 100644 index 00000000..59580988 --- /dev/null +++ b/src/main/java/com/ironhack/entity/Issue.java @@ -0,0 +1,75 @@ +package com.ironhack.entity; + +import jakarta.persistence.*; + +import java.util.UUID; + +@Entity +@Table(name = "issues") +public class Issue { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(nullable = false) + private String issueDate; + + @Column(nullable = false) + private String returnDate; + + @OneToOne + @JoinColumn(name = "student_id", nullable = false) + private Student student; + + @OneToOne + @JoinColumn(name = "book_id", nullable = false) + private Book book; + + public Issue() {} + public Issue(String issueDate, String returnDate, Student student, Book book) { + this.issueDate = issueDate; + this.returnDate = returnDate; + this.student = student; + this.book = book; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getIssueDate() { + return issueDate; + } + + public void setIssueDate(String issueDate) { + this.issueDate = issueDate; + } + + public String getReturnDate() { + return returnDate; + } + + public void setReturnDate(String returnDate) { + this.returnDate = returnDate; + } + + public Student getStudent() { + return student; + } + + public void setStudent(Student student) { + this.student = student; + } + + public Book getBook() { + return book; + } + + public void setBook(Book book) { + this.book = book; + } +} \ No newline at end of file diff --git a/src/main/java/com/ironhack/entity/Student.java b/src/main/java/com/ironhack/entity/Student.java new file mode 100644 index 00000000..d2adb135 --- /dev/null +++ b/src/main/java/com/ironhack/entity/Student.java @@ -0,0 +1,54 @@ +package com.ironhack.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; + +import java.util.UUID; + +@Entity +@Table(name = "students") +public class Student { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(unique = true, nullable = false) + private String usn; + + @Column(nullable = false) + private String name; + + @OneToOne(mappedBy = "student", cascade = CascadeType.REMOVE) + @JsonIgnore + private Issue issue; + + public Student() {} + public Student(String usn, String name) { + this.usn = usn; + this.name = name; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getUsn() { + return usn; + } + + public void setUsn(String usn) { + this.usn = usn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/com/ironhack/exception/BadRequestException.java b/src/main/java/com/ironhack/exception/BadRequestException.java new file mode 100644 index 00000000..5351c467 --- /dev/null +++ b/src/main/java/com/ironhack/exception/BadRequestException.java @@ -0,0 +1,7 @@ +package com.ironhack.exception; + +public class BadRequestException extends RuntimeException { + public BadRequestException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ironhack/exception/ConflictException.java b/src/main/java/com/ironhack/exception/ConflictException.java new file mode 100644 index 00000000..fcaa3c49 --- /dev/null +++ b/src/main/java/com/ironhack/exception/ConflictException.java @@ -0,0 +1,7 @@ +package com.ironhack.exception; + +public class ConflictException extends RuntimeException { + public ConflictException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ironhack/exception/NotFoundException.java b/src/main/java/com/ironhack/exception/NotFoundException.java new file mode 100644 index 00000000..ec6c322a --- /dev/null +++ b/src/main/java/com/ironhack/exception/NotFoundException.java @@ -0,0 +1,7 @@ +package com.ironhack.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ironhack/mapper/AuthorMapper.java b/src/main/java/com/ironhack/mapper/AuthorMapper.java new file mode 100644 index 00000000..65eeb4b8 --- /dev/null +++ b/src/main/java/com/ironhack/mapper/AuthorMapper.java @@ -0,0 +1,16 @@ +package com.ironhack.mapper; + +import com.ironhack.dto.response.AuthorResponse; +import com.ironhack.entity.Author; +import org.springframework.stereotype.Component; + +@Component +public class AuthorMapper { + public AuthorResponse toDto(Author author) { + return new AuthorResponse( + author.getId(), + author.getName(), + author.getEmail() + ); + } +} diff --git a/src/main/java/com/ironhack/mapper/BookMapper.java b/src/main/java/com/ironhack/mapper/BookMapper.java new file mode 100644 index 00000000..b50b1625 --- /dev/null +++ b/src/main/java/com/ironhack/mapper/BookMapper.java @@ -0,0 +1,25 @@ +package com.ironhack.mapper; + +import com.ironhack.dto.response.BookResponse; +import com.ironhack.entity.Book; +import org.springframework.stereotype.Component; + +@Component +public class BookMapper { + private final AuthorMapper authorMapper; + + public BookMapper(AuthorMapper authorMapper) { + this.authorMapper = authorMapper; + } + + public BookResponse toDto(Book book) { + return new BookResponse( + book.getId(), + book.getIsbn(), + book.getTitle(), + book.getCategory(), + book.getQuantity(), + authorMapper.toDto(book.getAuthor()) + ); + } +} diff --git a/src/main/java/com/ironhack/mapper/IssueMapper.java b/src/main/java/com/ironhack/mapper/IssueMapper.java new file mode 100644 index 00000000..9f3f7335 --- /dev/null +++ b/src/main/java/com/ironhack/mapper/IssueMapper.java @@ -0,0 +1,26 @@ +package com.ironhack.mapper; + +import com.ironhack.dto.response.IssueResponse; +import com.ironhack.entity.Issue; +import org.springframework.stereotype.Component; + +@Component +public class IssueMapper { + private final BookMapper bookMapper; + private final StudentMapper studentMapper; + + public IssueMapper(BookMapper bookMapper, StudentMapper studentMapper) { + this.bookMapper = bookMapper; + this.studentMapper = studentMapper; + } + + public IssueResponse toDto(Issue issue) { + return new IssueResponse( + issue.getId(), + issue.getIssueDate(), + issue.getReturnDate(), + bookMapper.toDto(issue.getBook()), + studentMapper.toDto(issue.getStudent()) + ); + } +} diff --git a/src/main/java/com/ironhack/mapper/StudentMapper.java b/src/main/java/com/ironhack/mapper/StudentMapper.java new file mode 100644 index 00000000..a36ea96e --- /dev/null +++ b/src/main/java/com/ironhack/mapper/StudentMapper.java @@ -0,0 +1,16 @@ +package com.ironhack.mapper; + +import com.ironhack.dto.response.StudentResponse; +import com.ironhack.entity.Student; +import org.springframework.stereotype.Component; + +@Component +public class StudentMapper { + public StudentResponse toDto(Student student) { + return new StudentResponse( + student.getId(), + student.getUsn(), + student.getName() + ); + } +} diff --git a/src/main/java/com/ironhack/model/BookCategory.java b/src/main/java/com/ironhack/model/BookCategory.java new file mode 100644 index 00000000..954c1595 --- /dev/null +++ b/src/main/java/com/ironhack/model/BookCategory.java @@ -0,0 +1,8 @@ +package com.ironhack.model; + +public enum BookCategory { + ROMANCE, + FANTASY, + HORROR, + DETECTIVE +} diff --git a/src/main/java/com/ironhack/repository/AuthorRepository.java b/src/main/java/com/ironhack/repository/AuthorRepository.java new file mode 100644 index 00000000..c8f1e91e --- /dev/null +++ b/src/main/java/com/ironhack/repository/AuthorRepository.java @@ -0,0 +1,10 @@ +package com.ironhack.repository; + +import com.ironhack.entity.Author; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.UUID; + +public interface AuthorRepository extends JpaRepository { + boolean existsByEmail(String email); +} diff --git a/src/main/java/com/ironhack/repository/BookRepository.java b/src/main/java/com/ironhack/repository/BookRepository.java new file mode 100644 index 00000000..364fa3a3 --- /dev/null +++ b/src/main/java/com/ironhack/repository/BookRepository.java @@ -0,0 +1,11 @@ +package com.ironhack.repository; + +import com.ironhack.entity.Book; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; +import java.util.UUID; + +public interface BookRepository extends JpaRepository { + Optional findByIsbn(String isbn); +} diff --git a/src/main/java/com/ironhack/repository/IssueRepository.java b/src/main/java/com/ironhack/repository/IssueRepository.java new file mode 100644 index 00000000..97ee6e44 --- /dev/null +++ b/src/main/java/com/ironhack/repository/IssueRepository.java @@ -0,0 +1,15 @@ +package com.ironhack.repository; + +import com.ironhack.entity.Issue; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.UUID; + +public interface IssueRepository extends JpaRepository { + boolean existsByStudent_Id(UUID studentId); + + boolean existsByBook_Id(UUID bookId); + + List findByStudent_Usn(String usn); +} diff --git a/src/main/java/com/ironhack/repository/StudentRepository.java b/src/main/java/com/ironhack/repository/StudentRepository.java new file mode 100644 index 00000000..5a23428e --- /dev/null +++ b/src/main/java/com/ironhack/repository/StudentRepository.java @@ -0,0 +1,10 @@ +package com.ironhack.repository; + +import com.ironhack.entity.Student; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.UUID; + +public interface StudentRepository extends JpaRepository { + boolean existsByUsn(String usn); +} diff --git a/src/main/java/com/ironhack/service/AuthorService.java b/src/main/java/com/ironhack/service/AuthorService.java new file mode 100644 index 00000000..539d91a4 --- /dev/null +++ b/src/main/java/com/ironhack/service/AuthorService.java @@ -0,0 +1,53 @@ +package com.ironhack.service; + +import com.ironhack.dto.response.AuthorResponse; +import com.ironhack.dto.request.CreateAuthorRequest; +import com.ironhack.entity.Author; +import com.ironhack.exception.ConflictException; +import com.ironhack.exception.NotFoundException; +import com.ironhack.mapper.AuthorMapper; +import com.ironhack.repository.AuthorRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.UUID; + +@Service +public class AuthorService { + private final AuthorRepository authorRepository; + private final AuthorMapper authorMapper; + + public AuthorService(AuthorRepository authorRepository, AuthorMapper authorMapper) { + this.authorRepository = authorRepository; + this.authorMapper = authorMapper; + } + + @Transactional + public AuthorResponse create(CreateAuthorRequest request) { + checkForDuplicate(request.email()); + + Author author = new Author(); + author.setName(request.name()); + author.setEmail(request.email()); + + Author savedAuthor = authorRepository.save(author); + return authorMapper.toDto(savedAuthor); + } + + @Transactional(readOnly = true) + public AuthorResponse getById(UUID id) { + Author author = findByIdOrThrow(id); + return authorMapper.toDto(author); + } + + public Author findByIdOrThrow(UUID id) { + return authorRepository.findById(id) + .orElseThrow(() -> new NotFoundException("Author not found with ID: " + id)); + } + + private void checkForDuplicate(String email) { + if (authorRepository.existsByEmail(email)) { + throw new ConflictException("Author with this email already exists"); + } + } +} diff --git a/src/main/java/com/ironhack/service/BookService.java b/src/main/java/com/ironhack/service/BookService.java new file mode 100644 index 00000000..14113dae --- /dev/null +++ b/src/main/java/com/ironhack/service/BookService.java @@ -0,0 +1,89 @@ +package com.ironhack.service; + +import com.ironhack.dto.request.CreateBookRequest; +import com.ironhack.dto.response.BookResponse; +import com.ironhack.entity.Author; +import com.ironhack.entity.Book; +import com.ironhack.exception.BadRequestException; +import com.ironhack.exception.ConflictException; +import com.ironhack.exception.NotFoundException; +import com.ironhack.mapper.BookMapper; +import com.ironhack.model.BookCategory; +import com.ironhack.repository.BookRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.UUID; + +@Service +public class BookService { + private final BookRepository bookRepository; + private final AuthorService authorService; + private final BookMapper bookMapper; + + public BookService(BookRepository bookRepository, AuthorService authorService, BookMapper bookMapper) { + this.bookRepository = bookRepository; + this.authorService = authorService; + this.bookMapper = bookMapper; + } + + @Transactional + public BookResponse create(CreateBookRequest request) { + checkForDuplicate(request.isbn()); + + Author author = authorService.findByIdOrThrow(request.authorId()); + + Book book = new Book(); + book.setIsbn(request.isbn()); + book.setTitle(request.title()); + book.setCategory(request.category()); + book.setQuantity(request.quantity()); + book.setAuthor(author); + + author.setBook(book); + + Book savedBook = bookRepository.save(book); + return bookMapper.toDto(savedBook); + } + + private void checkForDuplicate(String isbn) { + if (bookRepository.findByIsbn(isbn).isPresent()) { + throw new ConflictException("Book with this ISBN already exists"); + } + } + + @Transactional(readOnly = true) + public BookResponse getById(UUID id) { + Book book = bookRepository.findById(id) + .orElseThrow(() -> new NotFoundException("Book not found with ID: " + id)); + return bookMapper.toDto(book); + } + + public Book findByIdOrThrow(UUID id) { + return bookRepository.findById(id) + .orElseThrow(() -> new NotFoundException("Book not found with ID: " + id)); + } + + @Transactional(readOnly = true) + public List getBooks(String title, BookCategory category, UUID authorId) { + return bookRepository.findAll() + .stream() + .filter(book -> title == null || book.getTitle().contains(title)) + .filter(book -> category == null || book.getCategory() == category) + .filter(book -> authorId == null || book.getAuthor().getId().equals(authorId)) + .map(bookMapper::toDto) + .toList(); + } + + @Transactional + public void decreaseQuantity(UUID id, Integer quantity) { + Book book = findByIdOrThrow(id); + + if (book.getQuantity() < quantity) { + throw new BadRequestException("Book quantity exceeded"); + } + book.setQuantity(book.getQuantity() - quantity); + bookRepository.save(book); + } +} diff --git a/src/main/java/com/ironhack/service/IssueService.java b/src/main/java/com/ironhack/service/IssueService.java new file mode 100644 index 00000000..303a02f0 --- /dev/null +++ b/src/main/java/com/ironhack/service/IssueService.java @@ -0,0 +1,76 @@ +package com.ironhack.service; + +import com.ironhack.dto.response.BookResponse; +import com.ironhack.dto.request.IssueBookRequest; +import com.ironhack.dto.response.IssueResponse; +import com.ironhack.entity.Book; +import com.ironhack.entity.Issue; +import com.ironhack.entity.Student; +import com.ironhack.exception.ConflictException; +import com.ironhack.mapper.BookMapper; +import com.ironhack.mapper.IssueMapper; +import com.ironhack.repository.IssueRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +public class IssueService { + private final IssueRepository issueRepository; + private final BookService bookService; + private final StudentService studentService; + private final IssueMapper issueMapper; + private final BookMapper bookMapper; + + public IssueService( + IssueRepository issueRepository, + BookService bookService, + StudentService studentService, + IssueMapper issueMapper, + BookMapper bookMapper + ) { + this.issueRepository = issueRepository; + this.bookService = bookService; + this.studentService = studentService; + this.issueMapper = issueMapper; + this.bookMapper = bookMapper; + } + + @Transactional + public IssueResponse issueBook(IssueBookRequest request) { + Book book = bookService.findByIdOrThrow(request.bookId()); + Student student = studentService.findByIdOrThrow(request.studentId()); + + checkForDuplicate(student, book); + + bookService.decreaseQuantity(book.getId(), 1); + + Issue issue = new Issue(); + issue.setIssueDate(request.issueDate()); + issue.setReturnDate(request.returnDate()); + issue.setBook(book); + issue.setStudent(student); + + Issue savedIssue = issueRepository.save(issue); + return issueMapper.toDto(savedIssue); + } + + private void checkForDuplicate(Student student, Book book) { + if (issueRepository.existsByStudent_Id(student.getId())) { + throw new ConflictException("Student already has an issued book"); + } + if (issueRepository.existsByBook_Id(book.getId())) { + throw new ConflictException("Book is already issued"); + } + } + + @Transactional(readOnly = true) + public List listBooksByUsn(String usn) { + return issueRepository.findByStudent_Usn(usn) + .stream() + .map(Issue::getBook) + .map(bookMapper::toDto) + .toList(); + } +} diff --git a/src/main/java/com/ironhack/service/StudentService.java b/src/main/java/com/ironhack/service/StudentService.java new file mode 100644 index 00000000..5979216c --- /dev/null +++ b/src/main/java/com/ironhack/service/StudentService.java @@ -0,0 +1,53 @@ +package com.ironhack.service; + +import com.ironhack.dto.request.CreateStudentRequest; +import com.ironhack.dto.response.StudentResponse; +import com.ironhack.entity.Student; +import com.ironhack.exception.ConflictException; +import com.ironhack.exception.NotFoundException; +import com.ironhack.mapper.StudentMapper; +import com.ironhack.repository.StudentRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.UUID; + +@Service +public class StudentService { + private final StudentRepository studentRepository; + private final StudentMapper studentMapper; + + public StudentService(StudentRepository studentRepository, StudentMapper studentMapper) { + this.studentRepository = studentRepository; + this.studentMapper = studentMapper; + } + + @Transactional + public StudentResponse create(CreateStudentRequest request) { + checkForDuplicate(request.usn()); + + Student student = new Student(); + student.setUsn(request.usn()); + student.setName(request.name()); + + Student savedStudent = studentRepository.save(student); + return studentMapper.toDto(savedStudent); + } + + @Transactional(readOnly = true) + public StudentResponse getById(UUID id) { + Student student = findByIdOrThrow(id); + return studentMapper.toDto(student); + } + + public Student findByIdOrThrow(UUID id) { + return studentRepository.findById(id) + .orElseThrow(() -> new NotFoundException("Student not found with ID: " + id)); + } + + private void checkForDuplicate(String usn) { + if (studentRepository.existsByUsn(usn)) { + throw new ConflictException("Student with this usn already exists"); + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..11b9421a --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/ironboard +spring.datasource.username=user +spring.datasource.password=password +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.format_sql=true