From 04753d4f6d7e6038da06c7af385ec5b86027e79a Mon Sep 17 00:00:00 2001 From: Hadi Gholipour Date: Tue, 21 Apr 2026 23:35:35 +0200 Subject: [PATCH 1/2] spring boot Rest API --- .DS_Store | Bin 0 -> 6148 bytes .gitattributes | 2 + .gitignore | 33 ++ .mvn/wrapper/maven-wrapper.properties | 3 + mvnw | 295 ++++++++++++++++++ mvnw.cmd | 189 +++++++++++ pom.xml | 69 ++++ src/.DS_Store | Bin 0 -> 8196 bytes src/main/.DS_Store | Bin 0 -> 6148 bytes src/main/java/.DS_Store | Bin 0 -> 6148 bytes src/main/java/com/.DS_Store | Bin 0 -> 8196 bytes .../week5springboot/LabApplication.java | 11 + .../controller/CustomerController.java | 89 ++++++ .../controller/ProductController.java | 117 +++++++ .../week5springboot/dto/CustomerDTO.java | 38 +++ .../week5springboot/dto/ProductDTO.java | 38 +++ .../exception/GlobalExceptionHandler.java | 41 +++ .../exception/ResourceNotFoundException.java | 7 + .../week5springboot/model/Customer.java | 25 ++ .../week5springboot/model/Product.java | 25 ++ .../service/CustomerService.java | 44 +++ .../service/ProductService.java | 57 ++++ src/main/resources/application.properties | 1 + src/test/.DS_Store | Bin 0 -> 6148 bytes ...JavaSpringbootRestApiApplicationTests.java | 13 + 25 files changed, 1097 insertions(+) create mode 100644 .DS_Store create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/.DS_Store create mode 100644 src/main/.DS_Store create mode 100644 src/main/java/.DS_Store create mode 100644 src/main/java/com/.DS_Store create mode 100644 src/main/java/com/example/week5springboot/LabApplication.java create mode 100644 src/main/java/com/example/week5springboot/controller/CustomerController.java create mode 100644 src/main/java/com/example/week5springboot/controller/ProductController.java create mode 100644 src/main/java/com/example/week5springboot/dto/CustomerDTO.java create mode 100644 src/main/java/com/example/week5springboot/dto/ProductDTO.java create mode 100644 src/main/java/com/example/week5springboot/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/example/week5springboot/exception/ResourceNotFoundException.java create mode 100644 src/main/java/com/example/week5springboot/model/Customer.java create mode 100644 src/main/java/com/example/week5springboot/model/Product.java create mode 100644 src/main/java/com/example/week5springboot/service/CustomerService.java create mode 100644 src/main/java/com/example/week5springboot/service/ProductService.java create mode 100644 src/main/resources/application.properties create mode 100644 src/test/.DS_Store create mode 100644 src/test/java/com/amazon/learn/lab_java_springboot_rest_api/LabJavaSpringbootRestApiApplicationTests.java diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..6a0a39ea7fb1362f1388ddc38e1d195d5a12d269 GIT binary patch literal 6148 zcmeHKPfrs;6n|6DZb5YUQ^csrhF(l)uo9FI50(N^q6rNpSOQpf+oi5-XX@^@1qn&d zdh_B3@B^55@~9s`k6u0a1-y91H-AZWy?Lmjs~I%L>2hoD!}({93H?tJc2wN*}u#} z3qKZe*v1cppoYf;?(rs2Xvuy4oA>@0PYZb%wS0IkgnTl3j30+OFyxKH4)$(mbn^Nb zy9<2qpxnud@e}FjS{2J``E|<`Gk>t^uHy%p%vTcY>OOZq9#6!3;~RyitW^lipyB6C zZ;d}KGv->MZdxmj-74urvy29&Lv2quI29Wy>yI5;VXYi%(26g73(}BCXo-?OvbQ%i zIhi&l?qv4U#@_TqCT&bkPwej}v}Ee$-KEmDTchkHt{jEnIVz-2VF<5KQQ0`na~D(bIdO@8TuBe_*hGs6UxZ4qqO*GH~@;NguS#@^;nZ>zrjS^Kx#(F6ozi z%yyy7Xx_7%m}N1rcY=cR0!;(Q9G2|Llf$9q-8yoH4hKZg`<`vnwW{Y-7Pq#1J18E} zSNUvZkGXE1`A*<4y1FiA5A50k-C{T+U%_IXoBS2q^AS(@6jx2pGilY%?QXcHWxIiVkMMS1zV3)XlO(tEqcGWDOIk>Iw;W@P74ZMYS@Cm-aclZehq>l`fQ8Gr-mJ}T-JHwzwh8Li?-$nGSc%99GM^`1(!C`eR+r~+rH0{nb1uyM>PY)ceJ2X_3z z<@RolTu|p94IB-HS%qzhXh9*;6;Zkp^@~BIJB}NQmsQx7DBXdGnK6!N zL(qX_B}RQzfv5tV73h+WI=}zt|Nj5q=@dOh6^JTurYb&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 0000000..92450f9 --- /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 0000000..2c95728 --- /dev/null +++ b/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.5 + + + com.example + week5springboot + 0.0.1-SNAPSHOT + week5springboot + week5springboot + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-webmvc + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-starter-validation-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..d85f13399b47e3c5a3ecfd3e66ec4f9917b803ac GIT binary patch literal 8196 zcmeHL%}x_h6h0TKZAD~&7Hia`u^SVJR(?ZVI24Q_E+7oS62LNThdMI7x6VwdNJzTY z2k-%W025a(^#OG0)`c(N#xWdm3IHTmFW&-40YD5V zN23pyUkq;NvupGy4L1^uheeN-iXJQCvC-wN6`BFffM!55pc&8%{0j`=JDZQ#3GaPr z)vIPeGw@$Bz@HCkoE%MsO^M>sfs1GX5F@A-17-2)kC^5PL{ni?B5H6D8Hy-FiE1&3 z>Kup+N4u%~n-XO>5V13!N9{~hheA~2LDIq{p6Y1%VoH-kf#-n}FE$b0$SfL%(gPiSe@S|16ykbkX zi)*gaC>V)(Mnl`BjxPe-vV$(04_sPijU21fav)+YX^6*T@q&>$IGCK67)wu1%p8uT z4`#=+D9?@`9>!zI%+1>?go*>jmHQI8Agm&fh(1xoFF+|r)PhkR(|^Vu*|MzQ$0 zzVrPT28_X>;ladUGMOB?n7TA{`AWeUF50EtiqEffo_WmAd3C2?3qThCA{rSgLVTu;%yyVpmLl-S&N(R-D}amS-0oZ;9qu7_w^K#Vq)h zi!H61U2n2}S=Tkre6xug= z&+@6qXa#lLKLQ~*5J1>b^l#AibI~imzg_gx(^FXJ+3DXddXLzy-J=V4! zngPW?uf!DZ|L>ms|G(x-GoTqb#SD`0$Lx+r~9K2V?h-vOGD$PEAh literal 0 HcmV?d00001 diff --git a/src/main/.DS_Store b/src/main/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..92222fcbc3142bd21e91a37446a74ec462daf4d9 GIT binary patch literal 6148 zcmeHKPfrs;6n_K7c0pu;7BOnl*oz575io>!a9J>hc!013O90DmJJf|`rtWTAk&yJP zAHWab2QcyEQ9pnly?XEqc=3#H{uBiCW{e^Gl9}I|dGF2a`|Zxm4ge6lUbzEc0zd|f zz*IL@zY$><<&1Rbo-RZp#+VOy*$cRbZ82aX2?GfO|2G3-?WSNGTxfuMYW>=1yLBi< zCUNBFHKUqd=kL8*;79S;*cZ~#nd-WbP8;c-^oH}4H=Wpx>yhn-YofKxdEm8m*IV&v zvt(vxIg4GN(NG5X6^btFk9}6*O`F$QC6cj@G8jh2D4E0i`;!wBqxs2+se{q{{`B}5 z>eJ%~2Sz4WxP5P_v=i(y{!-CSa9@(rtFaBQP&vxSFE?~P}_{zZ5YbA5gbIUu`P(0}@4|r$?by_m}BFuNb%-Lc{8<=M?rq5%? ze}SffQvpk~^5nQ{d9Q{(+2am5=);gwwpI=O%EH!GMC0Nw`l^_%9P%JoMXC3ndbvB(TrB5P!mxMW+!ceG#fbv>R25}|VRk{eFQ0?w+~ zC;SZvfkFfv>Zp~4e(LjohhD#a{@6TUqG`+YoUgQ!Y!U_%2L1vAVt>eE5ol>_DU@3W zRvp+B_LM*&sLNk}#Jp}>8e0m{f zL|;5eUb+LZ6ee}TK*GRD20B&K6zBf~T*H63|DOy>S_uOQ1LukXlA3eoY)na?t!I)G xXKfzKCKe&Wucc6iV5N^^sfeR^7>g9N<%NQ1X>2LP9+c!qK+=#@2?PI>fuBDe;Q{~v literal 0 HcmV?d00001 diff --git a/src/main/java/.DS_Store b/src/main/java/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..77ff62ebcf9e433911a2619a27602390f8e5e8d1 GIT binary patch literal 6148 zcmeHKPfrs;6rTsxwji=Vix@R&?8OA42pB>@J@^H@c*Zw>8m!3G7@3#M{NB7jGy8s<+1Vk4fYYqrCd49yWUvWL z^#5?P^B2M`8Z%z-g0=8Rb!d!Dn~Y($(F6LgM*pr>50P3^z7k8;b3lR67{*M z!^3PQU%Yj9wY(eF8Gofn2mB^U8PM2)*Qn@fg36w*20nGF`D$6Zo=mo{|H8n$MPC=IRU#gSD?AR8fV1^Yxq3qD zOKgYZisA{D8^RSoqEU=^BB!+OMUls9)Y;z(J)efl%;8DG>!kpz5Kk_bbQ@kJV721C z?~220(Y~QHixfMwW^x@(BNRV)+frX+oKZ|#QJ$jxP={p5IGHCd*(A?No4g@!$vg6q zd?w$>4{`(pFbdaU946on%z_Q`unHTn4IVsG`8}Oid`-`%0b*42E8cS>7IIcYODDQJ z_{@$p9hv?!%YZ4|Fkl!sjREm}C}0z4Yiui&pAPJLa47uZH$n>P^5-A1APk7M#k^7@+SCpwiKA>-e@pl}Y=540JQltA>_1 z|L>oE|L;yRBg24U;J;!3Qj6}QgC*&+^+a*vtSw;M#wJ9>wH3+~?DTOg6>$`gVUvQs Zf>01`jctW!K`}o9k_OWm2L37oKLH3&(8mA( literal 0 HcmV?d00001 diff --git a/src/main/java/com/.DS_Store b/src/main/java/com/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..424c4ac4f776f46673f81aaa4f14b2157944c234 GIT binary patch literal 8196 zcmeHLPfrs;6n_IqTM=2HMU0wk?8OA42pB>b9w02i62P+CE_G!)Q+KyiAS6BO z2k-;<0Zcr3)DNIXuO9pYUOeNQKNV>8XkzG0GV^;o@BMaWemnc;EdY>Qt#lV)6abP~ zIU0S~{Go6^uWhAE^>8OaJ^%x{7_g!nFt;sQcW4E)0$KsBfL1^&@INSk?`&R@e|hgq zuWq#hT7iyKfIlBhtQ;+c4T<8>fsIH35PPs&6tpo95FAsXrLZAUQ1P5HdmxHRREj|) z9sMQ`N3;|+BuY9ENe7}vCMrWAVszx0A{>Y%QMXzFtw6g1{I=-@2P#+(TJm>(E9J1> zJ{Cog&&0a*sH$@P4{kN^qj+NCE9vU)xzL+Pq!N9JE&Ca(+p!bZqMQ?M@S|160=H>9 z?waq_3r2dL(b(~+7Yc%3@-SrciBC(co?|syiUik|j#Mg{Dj1`OhtpG2uhBZQCcn6+)CU<^dK=EWkT%b~Z2 zYt6^r%h>i0&^6RTSn*0vPr6q3s~D3$=@2J<6nY-rD2IM&X=f+$;`}LlosU)wSr9C< z$d7$S*EhxJu~%87I}AtUGgzu}SG4AZ5n>xBzwU&gL(5)ne=BfYFIb{E7RRiT_i+_` z=3+>@>J)ui&OZ1drA%e5ThcNh+f+B1ZdwXS_M@{c>{ZIBhooic$y$$9ND{_i4s6(j z7tnw=@D|>|C-?&2;U^rEelkLCk})z)?vWW{kvXzLHpn({$aBf>YF_9Y>U;`FgvOZ* zy=R9sV6=?=oYM^f-U9Ba-&cJ5zsGud`>UvPvhmew^p-!rTV7q_md%d4T9=Mjpj#?1 z%Jct+fB*mA@j7V%v;yZ@0n)QzFYpij=C@PpVtKA@V%^5d3y*6^6clWD2=5o^IHF3& kMW3mBmcoWaK}C+BBFaqupZ^HxtWRG3{^y%bmo^1{0f9Ts1ONa4 literal 0 HcmV?d00001 diff --git a/src/main/java/com/example/week5springboot/LabApplication.java b/src/main/java/com/example/week5springboot/LabApplication.java new file mode 100644 index 0000000..e85a07b --- /dev/null +++ b/src/main/java/com/example/week5springboot/LabApplication.java @@ -0,0 +1,11 @@ +package com.example.week5springboot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LabApplication { + public static void main(String[] args) { + SpringApplication.run(LabApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/controller/CustomerController.java b/src/main/java/com/example/week5springboot/controller/CustomerController.java new file mode 100644 index 0000000..ea5979b --- /dev/null +++ b/src/main/java/com/example/week5springboot/controller/CustomerController.java @@ -0,0 +1,89 @@ +package com.example.week5springboot.controller; + +import com.example.week5springboot.dto.CustomerDTO; +import com.example.week5springboot.model.Customer; +import com.example.week5springboot.service.CustomerService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/customers") +public class CustomerController { + + private static final String VALID_API_KEY = "123456"; + + private final CustomerService customerService; + + public CustomerController(CustomerService customerService) { + this.customerService = customerService; + } + + private boolean isInvalidKey(String apiKey) { + return !VALID_API_KEY.equals(apiKey); + } + + @PostMapping + public ResponseEntity createCustomer( + @RequestHeader(value = "API-Key", required = false) String apiKey, + @Valid @RequestBody CustomerDTO customerDTO) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + Customer saved = customerService.addCustomer(customerDTO); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } + + @GetMapping + public ResponseEntity> getAllCustomers(@RequestHeader("API-Key") String apiKey) { + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + return ResponseEntity.ok(customerService.getAllCustomers()); + } + + @GetMapping("/{email}") + public ResponseEntity getCustomerByEmail( + @RequestHeader("API-Key") String apiKey, + @PathVariable String email) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + Customer customer = customerService.getCustomerByEmail(email); + return ResponseEntity.ok(customer); + } + + @PutMapping("/{email}") + public ResponseEntity updateCustomer( + @RequestHeader("API-Key") String apiKey, + @PathVariable String email, + @Valid @RequestBody CustomerDTO customerDTO) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + Customer updated = customerService.updateCustomer(email, customerDTO); + return ResponseEntity.ok(updated); + } + + @DeleteMapping("/{email}") + public ResponseEntity deleteCustomer( + @RequestHeader("API-Key") String apiKey, + @PathVariable String email) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + boolean deleted = customerService.deleteCustomer(email); + return deleted ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/controller/ProductController.java b/src/main/java/com/example/week5springboot/controller/ProductController.java new file mode 100644 index 0000000..9a8a3da --- /dev/null +++ b/src/main/java/com/example/week5springboot/controller/ProductController.java @@ -0,0 +1,117 @@ +package com.example.week5springboot.controller; + +import com.example.week5springboot.dto.ProductDTO; +import com.example.week5springboot.model.Product; +import com.example.week5springboot.service.ProductService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/products") +public class ProductController { + + private static final String VALID_API_KEY = "123456"; + + private final ProductService productService; + + public ProductController(ProductService productService) { + this.productService = productService; + } + + private boolean isInvalidKey(String apiKey) { + return !VALID_API_KEY.equals(apiKey); + } + + @PostMapping + public ResponseEntity createProduct( + @RequestHeader(value = "API-Key", required = false) String apiKey, + @Valid @RequestBody ProductDTO productDTO) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + Product saved = productService.addProduct(productDTO); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } + + @GetMapping + public ResponseEntity> getAllProducts(@RequestHeader("API-Key") String apiKey) { + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + return ResponseEntity.ok(productService.getAllProducts()); + } + + @GetMapping("/{name}") + public ResponseEntity getProductByName( + @RequestHeader("API-Key") String apiKey, + @PathVariable String name) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + Product product = productService.getProductByName(name); + return ResponseEntity.ok(product); + } + + @PutMapping("/{name}") + public ResponseEntity updateProduct( + @RequestHeader("API-Key") String apiKey, + @PathVariable String name, + @Valid @RequestBody ProductDTO productDTO) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + Product updated = productService.updateProduct(name, productDTO); + return ResponseEntity.ok(updated); + } + + @DeleteMapping("/{name}") + public ResponseEntity deleteProduct( + @RequestHeader("API-Key") String apiKey, + @PathVariable String name) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + boolean deleted = productService.deleteProduct(name); + return deleted ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); + } + + @GetMapping("/category/{category}") + public ResponseEntity> getProductsByCategory( + @RequestHeader("API-Key") String apiKey, + @PathVariable String category) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + return ResponseEntity.ok(productService.getProductsByCategory(category)); + } + + @GetMapping("/price") + public ResponseEntity> getProductsByPriceRange( + @RequestHeader("API-Key") String apiKey, + @RequestParam double min, + @RequestParam double max) { + + if (isInvalidKey(apiKey)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + if (min > max) { + return ResponseEntity.badRequest().build(); + } + + return ResponseEntity.ok(productService.getProductsByPriceRange(min, max)); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/dto/CustomerDTO.java b/src/main/java/com/example/week5springboot/dto/CustomerDTO.java new file mode 100644 index 0000000..a6a96dd --- /dev/null +++ b/src/main/java/com/example/week5springboot/dto/CustomerDTO.java @@ -0,0 +1,38 @@ +package com.example.week5springboot.dto; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; + +public class CustomerDTO { + + @NotBlank(message = "Name is required") + private String name; + + @Email(message = "Email should be valid") + @NotBlank(message = "Email is required") + private String email; + + @Min(value = 18, message = "Age must be at least 18") + private int age; + + @NotBlank(message = "Address is required") + private String address; + + public CustomerDTO() {} + public CustomerDTO(String name, String email, int age, String address) { + this.name = name; + this.email = email; + this.age = age; + this.address = address; + } + + 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 int getAge() { return age; } + public void setAge(int age) { this.age = age; } + public String getAddress() { return address; } + public void setAddress(String address) { this.address = address; } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/dto/ProductDTO.java b/src/main/java/com/example/week5springboot/dto/ProductDTO.java new file mode 100644 index 0000000..57b42a1 --- /dev/null +++ b/src/main/java/com/example/week5springboot/dto/ProductDTO.java @@ -0,0 +1,38 @@ +package com.example.week5springboot.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; + +public class ProductDTO { + + @NotBlank(message = "Name is required") + @Size(min = 3, message = "Name must be at least 3 characters") + private String name; + + @Positive(message = "Price must be positive") + private double price; + + @NotBlank(message = "Category is required") + private String category; + + @Positive(message = "Quantity must be positive") + private int quantity; + + public ProductDTO() {} + public ProductDTO(String name, double price, String category, int quantity) { + this.name = name; + this.price = price; + this.category = category; + this.quantity = quantity; + } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } + public String getCategory() { return category; } + public void setCategory(String category) { this.category = category; } + public int getQuantity() { return quantity; } + public void setQuantity(int quantity) { this.quantity = quantity; } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/exception/GlobalExceptionHandler.java b/src/main/java/com/example/week5springboot/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..91a798a --- /dev/null +++ b/src/main/java/com/example/week5springboot/exception/GlobalExceptionHandler.java @@ -0,0 +1,41 @@ +package com.example.week5springboot.exception; + +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.MissingRequestHeaderException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.HashMap; +import java.util.Map; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions(MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach(error -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ResponseEntity.badRequest().body(errors); + } + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity> handleResourceNotFoundException(ResourceNotFoundException ex) { + Map error = new HashMap<>(); + error.put("error", ex.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error); + } + + @ExceptionHandler(MissingRequestHeaderException.class) + public ResponseEntity> handleMissingHeader(MissingRequestHeaderException ex) { + Map error = new HashMap<>(); + error.put("error", "Missing header: " + ex.getHeaderName()); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/exception/ResourceNotFoundException.java b/src/main/java/com/example/week5springboot/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..3faf068 --- /dev/null +++ b/src/main/java/com/example/week5springboot/exception/ResourceNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.week5springboot.exception; + +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/model/Customer.java b/src/main/java/com/example/week5springboot/model/Customer.java new file mode 100644 index 0000000..aab1aa4 --- /dev/null +++ b/src/main/java/com/example/week5springboot/model/Customer.java @@ -0,0 +1,25 @@ +package com.example.week5springboot.model; + +public class Customer { + private String name; + private String email; + private int age; + private String address; + + public Customer() {} + public Customer(String name, String email, int age, String address) { + this.name = name; + this.email = email; + this.age = age; + this.address = address; + } + + 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 int getAge() { return age; } + public void setAge(int age) { this.age = age; } + public String getAddress() { return address; } + public void setAddress(String address) { this.address = address; } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/model/Product.java b/src/main/java/com/example/week5springboot/model/Product.java new file mode 100644 index 0000000..06d48cd --- /dev/null +++ b/src/main/java/com/example/week5springboot/model/Product.java @@ -0,0 +1,25 @@ +package com.example.week5springboot.model; + +public class Product { + private String name; + private double price; + private String category; + private int quantity; + + public Product() {} + public Product(String name, double price, String category, int quantity) { + this.name = name; + this.price = price; + this.category = category; + this.quantity = quantity; + } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } + public String getCategory() { return category; } + public void setCategory(String category) { this.category = category; } + public int getQuantity() { return quantity; } + public void setQuantity(int quantity) { this.quantity = quantity; } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/service/CustomerService.java b/src/main/java/com/example/week5springboot/service/CustomerService.java new file mode 100644 index 0000000..ead5634 --- /dev/null +++ b/src/main/java/com/example/week5springboot/service/CustomerService.java @@ -0,0 +1,44 @@ +package com.example.week5springboot.service; + +import com.example.week5springboot.dto.CustomerDTO; +import com.example.week5springboot.model.Customer; +import com.example.week5springboot.exception.ResourceNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class CustomerService { + + private final List customers = new ArrayList<>(); + + public Customer addCustomer(CustomerDTO dto) { + Customer customer = new Customer(dto.getName(), dto.getEmail(), dto.getAge(), dto.getAddress()); + customers.add(customer); + return customer; + } + + public List getAllCustomers() { + return new ArrayList<>(customers); + } + + public Customer getCustomerByEmail(String email) { + return customers.stream() + .filter(c -> c.getEmail().equalsIgnoreCase(email)) + .findFirst() + .orElseThrow(() -> new ResourceNotFoundException("Customer not found: " + email)); + } + + public Customer updateCustomer(String email, CustomerDTO dto) { + Customer existing = getCustomerByEmail(email); + existing.setName(dto.getName()); + existing.setAge(dto.getAge()); + existing.setAddress(dto.getAddress()); + return existing; + } + + public boolean deleteCustomer(String email) { + return customers.removeIf(c -> c.getEmail().equalsIgnoreCase(email)); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/week5springboot/service/ProductService.java b/src/main/java/com/example/week5springboot/service/ProductService.java new file mode 100644 index 0000000..8f27d1b --- /dev/null +++ b/src/main/java/com/example/week5springboot/service/ProductService.java @@ -0,0 +1,57 @@ +package com.example.week5springboot.service; + +import com.example.week5springboot.dto.ProductDTO; +import com.example.week5springboot.model.Product; +import com.example.week5springboot.exception.ResourceNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class ProductService { + + private final List products = new ArrayList<>(); + + public Product addProduct(ProductDTO dto) { + Product product = new Product(dto.getName(), dto.getPrice(), dto.getCategory(), dto.getQuantity()); + products.add(product); + return product; + } + + public List getAllProducts() { + return new ArrayList<>(products); + } + + public Product getProductByName(String name) { + return products.stream() + .filter(p -> p.getName().equalsIgnoreCase(name)) + .findFirst() + .orElseThrow(() -> new ResourceNotFoundException("Product not found: " + name)); + } + + public Product updateProduct(String name, ProductDTO dto) { + Product existing = getProductByName(name); + existing.setPrice(dto.getPrice()); + existing.setCategory(dto.getCategory()); + existing.setQuantity(dto.getQuantity()); + return existing; + } + + public boolean deleteProduct(String name) { + return products.removeIf(p -> p.getName().equalsIgnoreCase(name)); + } + + public List getProductsByCategory(String category) { + return products.stream() + .filter(p -> p.getCategory().equalsIgnoreCase(category)) + .collect(Collectors.toList()); + } + + public List getProductsByPriceRange(double minPrice, double maxPrice) { + return products.stream() + .filter(p -> p.getPrice() >= minPrice && p.getPrice() <= maxPrice) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..228eb9d --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=lab-java-springboot-rest-api diff --git a/src/test/.DS_Store b/src/test/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..70514554205a44eb7112b7c8cdff023907205c54 GIT binary patch literal 6148 zcmeHKPfrs;6rWeBZ9!y#7BOnl*oz57D-jIw;Id#0@le7NECDRL?NS$(nYz1eMMBcE zegHp!AHb_e{Q!FO>cKDI#WTM7QxMR2Ge+hmGru?Q&&24So$2kn(0_5j z7#tcN%ns&qxsgkwmxr!gtr)|uQ{AqI{7Gk7z(Ol%dKF_J!g}Ycj4p&;3+pV$-t*Y@ zU!ZH~M8cw1dvau2+HGJ=_Q)V6eHeNkU9E?Ht+crrd2#tCeTA=94OtK@u*i>nMpxFv z>an*oPd6E^$e*Cp;I3%d3nRo+Ipq~63>{kctljm%alN2KEf&XYr|e@D{K>_VcEhRq zv|hOXO|qCNm^Y+mkV2Q(bhfK0gu;7gL+DGCQ4fmfCF1HKhb^3*VKFpAVTHvCAaL528`Cx z){Q?Ne&$AshIHSVt6UeX8PE*;i2?q7$YbMZD(pxUpAPI2IOKl*8zBUB@#~M6=LSSm zVMiibP(Y?4%2ZHS3{W=*km=|*ReVRHOeY{##(C7rpl&FjE*_8<;RH;Hy4MV7297h( zBZme*{~zEU{>}aWc#sE Date: Tue, 21 Apr 2026 23:44:17 +0200 Subject: [PATCH 2/2] spring boot Rest API --- src/main/java/com/example/week5springboot/LabApplication.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/example/week5springboot/LabApplication.java b/src/main/java/com/example/week5springboot/LabApplication.java index e85a07b..19d31c8 100644 --- a/src/main/java/com/example/week5springboot/LabApplication.java +++ b/src/main/java/com/example/week5springboot/LabApplication.java @@ -8,4 +8,4 @@ public class LabApplication { public static void main(String[] args) { SpringApplication.run(LabApplication.class, args); } -} \ No newline at end of file +} \ No newline at end of file