From 6c1da1626dbbbd197ea7f4e06e9512dfb81783b5 Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Fri, 6 Mar 2026 02:28:26 -0800 Subject: [PATCH 01/20] first commit --- .gitattributes | 2 + .gitignore | 33 ++ .mvn/wrapper/maven-wrapper.properties | 3 + mvnw | 295 ++++++++++++++++++ mvnw.cmd | 189 +++++++++++ pom.xml | 69 ++++ .../HomeworkJavaIronbattleApplication.java | 13 + src/main/resources/application.properties | 1 + ...omeworkJavaIronbattleApplicationTests.java | 13 + 9 files changed, 618 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java create mode 100644 src/main/resources/application.properties create mode 100644 src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java 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..8dea6c22 --- /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.12/apache-maven-3.9.12-bin.zip diff --git a/mvnw b/mvnw new file mode 100644 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..22b0455e --- /dev/null +++ b/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.3 + + + com.ironhack + homework-java-ironbattle + 0.0.1-SNAPSHOT + homework-java-ironbattle + homework-java-ironbattle + + + + + + + + + + + + + + + 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/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java b/src/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java new file mode 100644 index 00000000..ecf58566 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java @@ -0,0 +1,13 @@ +package com.ironhack.homeworkjavaironbattle; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HomeworkJavaIronbattleApplication { + + public static void main(String[] args) { + SpringApplication.run(HomeworkJavaIronbattleApplication.class, args); + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..3380a9b5 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=homework-java-ironbattle diff --git a/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java b/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java new file mode 100644 index 00000000..7404c551 --- /dev/null +++ b/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java @@ -0,0 +1,13 @@ +package com.ironhack.homeworkjavaironbattle; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class HomeworkJavaIronbattleApplicationTests { + + @Test + void contextLoads() { + } + +} From 3761129b7018c987e7e8de02728ef955e872b09a Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Fri, 6 Mar 2026 02:52:06 -0800 Subject: [PATCH 02/20] Add: Course class --- .../homeworkjavaironbattle/model/Course.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java new file mode 100644 index 00000000..65728b12 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java @@ -0,0 +1,59 @@ +package com.ironhack.homeworkjavaironbattle.model; +import jakarta.annotation.Nullable; + +import java.util.UUID; + +public class Course { + private UUID uuid = UUID.randomUUID(); + private String courseId = uuid.toString(); + private String name; + private double price; + private double money_earned; +// private @Nullable Teacher teacher; + + public Course(String name, double price) { + this.name = name; + this.price = price; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public String getCourseId() { + return courseId; + } + + public void setCourseId(String courseId) { + this.courseId = courseId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +// +// @Nullable +// public Teacher getTeacher() { +// return teacher; +// } +// +// public void setTeacher(@Nullable Teacher teacher) { +// this.teacher = teacher; +// } + + public double getMoney_earned() { + return money_earned; + } + + public void setMoney_earned(double money_earned) { + this.money_earned = money_earned; + } +} From b25d60c24abc6f0ebf9b3ee724928c202a94cfac Mon Sep 17 00:00:00 2001 From: ruzi Date: Fri, 6 Mar 2026 14:55:51 +0400 Subject: [PATCH 03/20] Teacher class created --- .../homeworkjavaironbattle/model/Teacher.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java new file mode 100644 index 00000000..72e5abae --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java @@ -0,0 +1,23 @@ +package com.ironhack.homeworkjavaironbattle.model; + +import java.util.UUID; + +public class Teacher { +private String teacherId; +private String name; +private double salary; + + + public Teacher(String name , double salary){ + this.teacherId=generateUniqueId(); + this.name=name; + this.salary=salary; +} + public String getTeacherId(){return teacherId;} + private String generateUniqueId() {return UUID.randomUUID().toString();} + public String getName() {return name;} + public void setName(String name) {this.name = name;} + public double getSalary(){return salary;} + public void setSalary(double salary){this.salary=salary;} + +} From 9dd8093e080eddb2b7cfaae7eb387da6d2970e3b Mon Sep 17 00:00:00 2001 From: ruzi Date: Fri, 6 Mar 2026 15:28:44 +0400 Subject: [PATCH 04/20] Student class created --- .../homeworkjavaironbattle/model/Student.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java new file mode 100644 index 00000000..cbf59c6d --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java @@ -0,0 +1,40 @@ +package com.ironhack.homeworkjavaironbattle.model; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.Null; + +import java.util.UUID; + +public class Student { + private String studentId; + private String name; + private String address; + private String email; + @Nullable private Course course; + +public Student(String name, String address ,String email){ + this.studentId=uniqueStudentId(); + this.name=name; + this.address=address; + this.email=email; + +} + public String uniqueStudentId(){return UUID.randomUUID().toString();} + //Getters + public String getStudentId(){return studentId;} + public String getName(){return name;} + public String getAddress(){return address;} + public String getEmail(){return email;} + @Nullable + public Course getCourse() { + return course; + } + + //Setters + public void setName(String name) {this.name = name;} + public void setAddress(String address){this.address=address;} + public void setEmail(String email){this.email=email;} + public void setCourse(@Nullable Course course) { + this.course = course; + } +} \ No newline at end of file From c15604ce99c42768782267c9a24cc8a8feab0044 Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Fri, 6 Mar 2026 03:44:04 -0800 Subject: [PATCH 05/20] Add: Course class --- .../service/TeacherService.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java b/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java new file mode 100644 index 00000000..04030ceb --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java @@ -0,0 +1,27 @@ +package com.ironhack.homeworkjavaironbattle.service; + +import com.ironhack.homeworkjavaironbattle.model.Teacher; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TeacherService { + private final Map teachers = new HashMap<>(); + + public TeacherService() { + Teacher teacher = new Teacher("Joao", 45.59); + teachers.put(teacher.getTeacherId(), teacher); + } + + public List findAll() { + return new ArrayList<>(teachers.values()); + } + + public Teacher create(String name, double price) { + Teacher teacher = new Teacher(name, price); + teachers.put(teacher.getTeacherId(), teacher); + return teacher; + } +} From 8037cdaaaad3994d7af8864481b9f4d616413341 Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Fri, 6 Mar 2026 04:55:34 -0800 Subject: [PATCH 06/20] Add: CourseService, Teacher, TeacherService classes --- .../homeworkjavaironbattle/model/Course.java | 20 ++++++------- .../homeworkjavaironbattle/model/Teacher.java | 9 +++--- .../service/CourseService.java | 28 +++++++++++++++++ .../service/TeacherService.java | 30 ++++++++++++++++++- 4 files changed, 71 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java index 65728b12..028afd2f 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java @@ -9,7 +9,7 @@ public class Course { private String name; private double price; private double money_earned; -// private @Nullable Teacher teacher; + private @Nullable Teacher teacher; public Course(String name, double price) { this.name = name; @@ -39,15 +39,15 @@ public String getName() { public void setName(String name) { this.name = name; } -// -// @Nullable -// public Teacher getTeacher() { -// return teacher; -// } -// -// public void setTeacher(@Nullable Teacher teacher) { -// this.teacher = teacher; -// } + + @Nullable + public Teacher getTeacher() { + return teacher; + } + + public void setTeacher(@Nullable Teacher teacher) { + this.teacher = teacher; + } public double getMoney_earned() { return money_earned; diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java index 72e5abae..09e384bc 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java @@ -2,11 +2,10 @@ import java.util.UUID; -public class Teacher { -private String teacherId; -private String name; -private double salary; - + public class Teacher { + private String teacherId; + private String name; + private double salary; public Teacher(String name , double salary){ this.teacherId=generateUniqueId(); diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java b/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java new file mode 100644 index 00000000..1a46a6b4 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java @@ -0,0 +1,28 @@ +package com.ironhack.homeworkjavaironbattle.service; + +import com.ironhack.homeworkjavaironbattle.model.Course; +import com.ironhack.homeworkjavaironbattle.model.Teacher; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class CourseService { + private final Map courses = new HashMap<>(); + + public CourseService() { + Course course = new Course("Ironhack", 44544.59); + courses.put(course.getCourseId(), course); + } + + public List findAll() { + return new ArrayList<>(courses.values()); + } + + public Course findById(String id) { + return courses.get(id); + } +} diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java b/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java index 04030ceb..e5e2fb39 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java @@ -1,16 +1,24 @@ package com.ironhack.homeworkjavaironbattle.service; +import com.ironhack.homeworkjavaironbattle.model.Course; import com.ironhack.homeworkjavaironbattle.model.Teacher; +import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +@Service public class TeacherService { + private final CourseService courseService; + private final Map teachers = new HashMap<>(); + private final Map assignedTeachers = new HashMap<>(); + + public TeacherService(CourseService courseService) { + this.courseService = courseService; - public TeacherService() { Teacher teacher = new Teacher("Joao", 45.59); teachers.put(teacher.getTeacherId(), teacher); } @@ -24,4 +32,24 @@ public Teacher create(String name, double price) { teachers.put(teacher.getTeacherId(), teacher); return teacher; } + + public Teacher findById(String id) { + return teachers.get(id); + } + + public List findByName(String name) { + return teachers.values().stream() + .filter(c -> c.getName().toLowerCase() + .contains(name.toLowerCase())).toList(); + } + + public void assign(String teacherId, String courseId) { + Teacher teacher = teachers.get(teacherId); + Course course = courseService.findById(courseId); + + course.setTeacher(teacher); + + assignedTeachers.put(teacher, course); + + } } From 8412fb3295146dee62727d84d02247c2a3a05f03 Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Fri, 6 Mar 2026 05:24:49 -0800 Subject: [PATCH 07/20] Add: showProfit method in CourseService class --- .../homeworkjavaironbattle/model/Student.java | 1 - .../service/CourseService.java | 18 +++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java index cbf59c6d..59609588 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java @@ -17,7 +17,6 @@ public Student(String name, String address ,String email){ this.name=name; this.address=address; this.email=email; - } public String uniqueStudentId(){return UUID.randomUUID().toString();} //Getters diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java b/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java index 1a46a6b4..2d8549bb 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java @@ -1,7 +1,6 @@ package com.ironhack.homeworkjavaironbattle.service; import com.ironhack.homeworkjavaironbattle.model.Course; -import com.ironhack.homeworkjavaironbattle.model.Teacher; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -25,4 +24,21 @@ public List findAll() { public Course findById(String id) { return courses.get(id); } + + public Course create(String name, double price) { + Course course = new Course(name, price); + courses.put(course.getCourseId(), course); + return course; + } + + public double showProfit() { + double sum = 0; + + for (Map.Entry courseEntry : courses.entrySet()) { + double price = courseEntry.getValue().getPrice(); + sum += price; + } + + return sum; + } } From c852f518a5f7d8b9674227a57e10d5104a990c38 Mon Sep 17 00:00:00 2001 From: ruzi Date: Fri, 6 Mar 2026 17:27:23 +0400 Subject: [PATCH 08/20] StudentService --- .../service/StudentService.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java new file mode 100644 index 00000000..f93d1f28 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java @@ -0,0 +1,49 @@ +package com.ironhack.homeworkjavaironbattle.service; + +import com.ironhack.homeworkjavaironbattle.model.Course; +import com.ironhack.homeworkjavaironbattle.model.Student; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StudentService { + private CourseService courseService; + private final Map students = new HashMap<>(); + public StudentService(){ + Student student1 = new Student("Ruzi" ,"Sumqgayit","ruzi@gmail.com"); + Student student2 = new Student("Shaiq", "Baku","shaiq@gmail.com"); + students.put(student1.getStudentId(), student1); + students.put(student2.getStudentId(),student2); + + } + public List findAll(){ + return new ArrayList<>(students.values()); + } + public Student findByID(String id){ + return students.get(id); + } + public Student create(String name, String address, String email ){ + Student student = new Student(name,address,email); + students.put(student.getStudentId(),student); + return student; + } + + public void enroll(String studentId, String courseId){ + Student student=students.get(studentId); + Course course = courseService.findById(courseId); + + if (student == null || course == null) { + System.out.println("Error: Student or Course not found."); + return; + } + + student.setCourse(course); + double budget= course.getMoney_earned(); + budget+=course.getPrice(); + course.setMoney_earned(budget); + System.out.println("Success: Student " + studentId + " enrolled in " + course.getName()); + } + +} From 3f8cfe98b6bc01659c679d0d65c99b6e9cd8c3f2 Mon Sep 17 00:00:00 2001 From: ruzi Date: Sun, 8 Mar 2026 15:56:47 +0400 Subject: [PATCH 09/20] TeacherController created --- .../controlller/TeacherController.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/controlller/TeacherController.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/controlller/TeacherController.java b/src/main/java/com/ironhack/homeworkjavaironbattle/controlller/TeacherController.java new file mode 100644 index 00000000..f2791fcd --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/controlller/TeacherController.java @@ -0,0 +1,51 @@ +package com.ironhack.homeworkjavaironbattle.controlller; + +import com.ironhack.homeworkjavaironbattle.model.Teacher; +import com.ironhack.homeworkjavaironbattle.service.TeacherService; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +@RestController +@RequestMapping("/api/teachers") +public class TeacherController { + private final TeacherService teacherService; + + public TeacherController(TeacherService teacherService) { + this.teacherService = teacherService; + } + + @GetMapping + @ResponseStatus(HttpStatus.OK) + public List getAllTeachers() { + return teacherService.findAll(); + } + + @GetMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Teacher getTeacherById(@PathVariable String id) { + Teacher teacher = teacherService.findById(id); + if (teacher == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher not found with ID: " + id); + } + return teacher; + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Teacher createTeacher(@RequestBody Teacher teacher) { + return teacherService.create(teacher.getName(), teacher.getSalary()); + } + + @PostMapping("/assign/{teacherId}/{courseId}") + @ResponseStatus(HttpStatus.OK) + public void assignTeacher(@PathVariable String teacherId, @PathVariable String courseId) { + try { + teacherService.assign(teacherId, courseId); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Assign denied"); + } + } +} \ No newline at end of file From be32aea90c6cfd106912b6a3ff242bcadcde674f Mon Sep 17 00:00:00 2001 From: ruzi Date: Mon, 9 Mar 2026 12:33:50 +0400 Subject: [PATCH 10/20] TeacherController created --- .../controller/TeacherController.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java b/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java new file mode 100644 index 00000000..4ac92691 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java @@ -0,0 +1,51 @@ +package com.ironhack.homeworkjavaironbattle.controller; + +import com.ironhack.homeworkjavaironbattle.model.Teacher; +import com.ironhack.homeworkjavaironbattle.service.TeacherService; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +@RestController +@RequestMapping("/api/teachers") +public class TeacherController { + private final TeacherService teacherService; + + public TeacherController(TeacherService teacherService) { + this.teacherService = teacherService; + } + + @GetMapping + @ResponseStatus(HttpStatus.OK) + public List getAllTeachers() { + return teacherService.findAll(); + } + + @GetMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Teacher getTeacherById(@PathVariable String id) { + Teacher teacher = teacherService.findById(id); + if (teacher == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher not found with ID: " + id); + } + return teacher; + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Teacher createTeacher(@RequestBody Teacher teacher) { + return teacherService.create(teacher.getName(), teacher.getSalary()); + } + + @PostMapping("/assign/{teacherId}/{courseId}") + @ResponseStatus(HttpStatus.OK) + public void assignTeacher(@PathVariable String teacherId, @PathVariable String courseId) { + try { + teacherService.assign(teacherId, courseId); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Assign denied"); + } + } +} From ee9d7d3e9d05762cd1c20519070a0cbb0ad69f10 Mon Sep 17 00:00:00 2001 From: dev-shaig Date: Mon, 9 Mar 2026 13:35:12 +0400 Subject: [PATCH 11/20] Add: CourseController class with valid endpoints --- .../HomeworkJavaIronSchoolApplication.java} | 6 +- .../controller/CourseController.java | 58 +++++++++++++++++++ .../model/Course.java | 2 +- .../model/Student.java | 3 +- .../model/Teacher.java | 2 +- .../service/CourseService.java | 12 +++- .../service/StudentService.java | 6 +- .../service/TeacherService.java | 6 +- ...meworkJavaIronSchoolApplicationTests.java} | 2 +- 9 files changed, 81 insertions(+), 16 deletions(-) rename src/main/java/com/ironhack/{homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java => homeworkjavaironschool/HomeworkJavaIronSchoolApplication.java} (57%) create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/model/Course.java (95%) rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/model/Student.java (91%) rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/model/Teacher.java (92%) rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/service/CourseService.java (73%) rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/service/StudentService.java (90%) rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/service/TeacherService.java (89%) rename src/test/java/com/ironhack/homeworkjavaironbattle/{HomeworkJavaIronbattleApplicationTests.java => HomeworkJavaIronSchoolApplicationTests.java} (81%) diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java b/src/main/java/com/ironhack/homeworkjavaironschool/HomeworkJavaIronSchoolApplication.java similarity index 57% rename from src/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java rename to src/main/java/com/ironhack/homeworkjavaironschool/HomeworkJavaIronSchoolApplication.java index ecf58566..b8a8db9a 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplication.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/HomeworkJavaIronSchoolApplication.java @@ -1,13 +1,13 @@ -package com.ironhack.homeworkjavaironbattle; +package com.ironhack.homeworkjavaironschool; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class HomeworkJavaIronbattleApplication { +public class HomeworkJavaIronSchoolApplication { public static void main(String[] args) { - SpringApplication.run(HomeworkJavaIronbattleApplication.class, args); + SpringApplication.run(HomeworkJavaIronSchoolApplication.class, args); } } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java b/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java new file mode 100644 index 00000000..fda93100 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java @@ -0,0 +1,58 @@ +package com.ironhack.homeworkjavaironschool.controller; + +import com.ironhack.homeworkjavaironschool.model.Course; +import com.ironhack.homeworkjavaironschool.service.CourseService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("api/courses") +public class CourseController { + + private final CourseService courseService; + + public record CourseCreateRequest(String name, double price) {} + + public CourseController(CourseService courseService) { + this.courseService = courseService; + } + + @GetMapping + public List getAllCourses() { + return courseService.findAll(); + } + + @GetMapping("/{id}") + public ResponseEntity getCourseById(@PathVariable String id) { + Course course = courseService.findById(id); + if (course != null) { + return ResponseEntity.ok(course); + } else { + return ResponseEntity.notFound().build(); + } + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Course createCourse(@RequestBody CourseCreateRequest request) { + return courseService.create(request.name(), request.price()); + } + + @GetMapping("/profit") + public double getProfit() { + return courseService.showProfit(); + } + + @GetMapping("/{id}/money-earned") + public ResponseEntity getMoneyEarned(@PathVariable String id) { + try { + double moneyEarned = courseService.showMoneyEarned(id); + return ResponseEntity.ok(moneyEarned); + } catch (IllegalArgumentException e) { + return ResponseEntity.notFound().build(); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java similarity index 95% rename from src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java rename to src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java index 028afd2f..133ec7ca 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Course.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java @@ -1,4 +1,4 @@ -package com.ironhack.homeworkjavaironbattle.model; +package com.ironhack.homeworkjavaironschool.model; import jakarta.annotation.Nullable; import java.util.UUID; diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java similarity index 91% rename from src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java rename to src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java index 59609588..18207893 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Student.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java @@ -1,7 +1,6 @@ -package com.ironhack.homeworkjavaironbattle.model; +package com.ironhack.homeworkjavaironschool.model; import jakarta.annotation.Nullable; -import jakarta.validation.constraints.Null; import java.util.UUID; diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java similarity index 92% rename from src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java rename to src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java index 09e384bc..8d8a805c 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/model/Teacher.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java @@ -1,4 +1,4 @@ -package com.ironhack.homeworkjavaironbattle.model; +package com.ironhack.homeworkjavaironschool.model; import java.util.UUID; diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java similarity index 73% rename from src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java rename to src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java index 2d8549bb..3871e8f0 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/service/CourseService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java @@ -1,6 +1,6 @@ -package com.ironhack.homeworkjavaironbattle.service; +package com.ironhack.homeworkjavaironschool.service; -import com.ironhack.homeworkjavaironbattle.model.Course; +import com.ironhack.homeworkjavaironschool.model.Course; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -41,4 +41,12 @@ public double showProfit() { return sum; } + + public double showMoneyEarned(String id) { + Course course = courses.get(id); + if (course != null) { + return course.getMoney_earned(); + } + throw new IllegalArgumentException("Kurs tapılmadı: " + id); + } } diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java similarity index 90% rename from src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java rename to src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java index f93d1f28..51d836f9 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java @@ -1,7 +1,7 @@ -package com.ironhack.homeworkjavaironbattle.service; +package com.ironhack.homeworkjavaironschool.service; -import com.ironhack.homeworkjavaironbattle.model.Course; -import com.ironhack.homeworkjavaironbattle.model.Student; +import com.ironhack.homeworkjavaironschool.model.Course; +import com.ironhack.homeworkjavaironschool.model.Student; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java similarity index 89% rename from src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java rename to src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java index e5e2fb39..872b30da 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/service/TeacherService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java @@ -1,7 +1,7 @@ -package com.ironhack.homeworkjavaironbattle.service; +package com.ironhack.homeworkjavaironschool.service; -import com.ironhack.homeworkjavaironbattle.model.Course; -import com.ironhack.homeworkjavaironbattle.model.Teacher; +import com.ironhack.homeworkjavaironschool.model.Course; +import com.ironhack.homeworkjavaironschool.model.Teacher; import org.springframework.stereotype.Service; import java.util.ArrayList; diff --git a/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java b/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronSchoolApplicationTests.java similarity index 81% rename from src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java rename to src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronSchoolApplicationTests.java index 7404c551..c7164c9c 100644 --- a/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronbattleApplicationTests.java +++ b/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronSchoolApplicationTests.java @@ -4,7 +4,7 @@ import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class HomeworkJavaIronbattleApplicationTests { +class HomeworkJavaIronSchoolApplicationTests { @Test void contextLoads() { From 78d9cc18a0e7a50df81451a513596b5d37c23896 Mon Sep 17 00:00:00 2001 From: Shaig Mahmudov Date: Mon, 9 Mar 2026 13:38:23 +0400 Subject: [PATCH 12/20] Update src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../controller/TeacherController.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java b/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java index 4ac92691..90200392 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java +++ b/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java @@ -44,8 +44,10 @@ public Teacher createTeacher(@RequestBody Teacher teacher) { public void assignTeacher(@PathVariable String teacherId, @PathVariable String courseId) { try { teacherService.assign(teacherId, courseId); - } catch (Exception e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Assign denied"); + } catch (IllegalArgumentException e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Assign denied: " + e.getMessage(), e); + } catch (NullPointerException e) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher or course not found for provided IDs", e); } } } From 90e15b0f86d3e548efaf369518fb0c9b28e4f2af Mon Sep 17 00:00:00 2001 From: dev-shaig Date: Mon, 9 Mar 2026 13:46:14 +0400 Subject: [PATCH 13/20] Resolve the naming problem --- .../service/StudentService.java | 49 ------------------- .../controller/TeacherController.java | 6 +-- .../service/StudentService.java | 3 +- ...omeworkJavaIronSchoolApplicationTests.java | 0 4 files changed, 5 insertions(+), 53 deletions(-) delete mode 100644 src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java rename src/main/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/controller/TeacherController.java (90%) rename src/test/java/com/ironhack/{homeworkjavaironbattle => homeworkjavaironschool}/HomeworkJavaIronSchoolApplicationTests.java (100%) diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java deleted file mode 100644 index f93d1f28..00000000 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/service/StudentService.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ironhack.homeworkjavaironbattle.service; - -import com.ironhack.homeworkjavaironbattle.model.Course; -import com.ironhack.homeworkjavaironbattle.model.Student; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class StudentService { - private CourseService courseService; - private final Map students = new HashMap<>(); - public StudentService(){ - Student student1 = new Student("Ruzi" ,"Sumqgayit","ruzi@gmail.com"); - Student student2 = new Student("Shaiq", "Baku","shaiq@gmail.com"); - students.put(student1.getStudentId(), student1); - students.put(student2.getStudentId(),student2); - - } - public List findAll(){ - return new ArrayList<>(students.values()); - } - public Student findByID(String id){ - return students.get(id); - } - public Student create(String name, String address, String email ){ - Student student = new Student(name,address,email); - students.put(student.getStudentId(),student); - return student; - } - - public void enroll(String studentId, String courseId){ - Student student=students.get(studentId); - Course course = courseService.findById(courseId); - - if (student == null || course == null) { - System.out.println("Error: Student or Course not found."); - return; - } - - student.setCourse(course); - double budget= course.getMoney_earned(); - budget+=course.getPrice(); - course.setMoney_earned(budget); - System.out.println("Success: Student " + studentId + " enrolled in " + course.getName()); - } - -} diff --git a/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java b/src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java similarity index 90% rename from src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java rename to src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java index 90200392..56b5bb08 100644 --- a/src/main/java/com/ironhack/homeworkjavaironbattle/controller/TeacherController.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java @@ -1,7 +1,7 @@ -package com.ironhack.homeworkjavaironbattle.controller; +package com.ironhack.homeworkjavaironschool.controller; -import com.ironhack.homeworkjavaironbattle.model.Teacher; -import com.ironhack.homeworkjavaironbattle.service.TeacherService; +import com.ironhack.homeworkjavaironschool.model.Teacher; +import com.ironhack.homeworkjavaironschool.service.TeacherService; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java index 51d836f9..a2eafe99 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java @@ -1,7 +1,8 @@ -package com.ironhack.homeworkjavaironschool.service; +package com.ironhack.homeworkjavaionschool.service; import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Student; +import com.ironhack.homeworkjavaironschool.service.CourseService; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronSchoolApplicationTests.java b/src/test/java/com/ironhack/homeworkjavaironschool/HomeworkJavaIronSchoolApplicationTests.java similarity index 100% rename from src/test/java/com/ironhack/homeworkjavaironbattle/HomeworkJavaIronSchoolApplicationTests.java rename to src/test/java/com/ironhack/homeworkjavaironschool/HomeworkJavaIronSchoolApplicationTests.java From 6d2b536c7fe7b4b01761659d17d3eea33a342652 Mon Sep 17 00:00:00 2001 From: dev-shaig Date: Mon, 9 Mar 2026 20:10:38 +0400 Subject: [PATCH 14/20] Add: StudentController class --- .../controller/StudentController.java | 48 +++++++++++++++++++ .../service/StudentService.java | 4 +- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java b/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java new file mode 100644 index 00000000..2fa0b316 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java @@ -0,0 +1,48 @@ +package com.ironhack.homeworkjavaironschool.controller; + + +import com.ironhack.homeworkjavaironschool.model.Student; +import com.ironhack.homeworkjavaironschool.service.StudentService; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +@RestController +@RequestMapping("/api/students") +public class StudentController { + private final StudentService studentService; + public StudentController(StudentService studentService){this.studentService=studentService;} + + @GetMapping + @ResponseStatus(HttpStatus.OK) + public List getAllStudents(){return studentService.findAll();} + + @GetMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Student getStudentById(@PathVariable String id){ + Student student= studentService.findByID(id); + if (student == null){ + throw new ResponseStatusException(HttpStatus.NOT_FOUND,"Studnet not found with ID: " + id); + } + return student; + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Student createStudent(@RequestBody Student student){ + return studentService.create(student.getName(),student.getAddress(),student.getEmail()); + } + @PostMapping("/enroll/{studentId}/{courseId}") + @ResponseStatus(HttpStatus.OK) + public void enrollCourse(@PathVariable String studentId, @PathVariable String courseId){ + try{ + studentService.enroll(studentId,courseId); + } + catch (Exception e){ + throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"Enroll denied"); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java index a2eafe99..b0663add 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java @@ -1,14 +1,16 @@ -package com.ironhack.homeworkjavaionschool.service; +package com.ironhack.homeworkjavaironschool.service; import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Student; import com.ironhack.homeworkjavaironschool.service.CourseService; +import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +@Service public class StudentService { private CourseService courseService; private final Map students = new HashMap<>(); From 1f413f607b1673d33186a5561a542ce890782c2d Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Tue, 10 Mar 2026 06:00:16 -0700 Subject: [PATCH 15/20] Add: patch and delete methods for all classes --- .../controller/CourseController.java | 11 +++++++ .../controller/StudentController.java | 13 +++++++++ .../controller/TeacherController.java | 13 +++++++++ .../service/CourseService.java | 27 ++++++++++++++++- .../service/StudentService.java | 29 ++++++++++++++++++- .../service/TeacherService.java | 20 +++++++++++++ 6 files changed, 111 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java b/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java index fda93100..bdeb894a 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/controller/CourseController.java @@ -55,4 +55,15 @@ public ResponseEntity getMoneyEarned(@PathVariable String id) { return ResponseEntity.notFound().build(); } } + + @PatchMapping("/{id}") + public Course partialUpdateCourse(@PathVariable String id, @RequestBody Course course) { + return courseService.partialUpdate(id, course.getName(), course.getPrice(), course.getMoney_earned(), course.getTeacher()); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteCourse(@PathVariable String id) { + courseService.delete(id); + return ResponseEntity.noContent().build(); + } } \ No newline at end of file diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java b/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java index 2fa0b316..90f339d6 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/controller/StudentController.java @@ -1,9 +1,11 @@ package com.ironhack.homeworkjavaironschool.controller; +import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Student; import com.ironhack.homeworkjavaironschool.service.StudentService; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @@ -45,4 +47,15 @@ public void enrollCourse(@PathVariable String studentId, @PathVariable String co } } + @PatchMapping("/{id}") + public Student partialUpdateCourse(@PathVariable String id, @RequestBody Student student) { + return studentService.partialUpdate(id, student.getName(), student.getAddress(), student.getEmail(), student.getCourse()); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteCourse(@PathVariable String id) { + studentService.delete(id); + return ResponseEntity.noContent().build(); + } + } \ No newline at end of file diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java b/src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java index 56b5bb08..a2a0cc58 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/controller/TeacherController.java @@ -1,8 +1,10 @@ package com.ironhack.homeworkjavaironschool.controller; +import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Teacher; import com.ironhack.homeworkjavaironschool.service.TeacherService; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @@ -50,4 +52,15 @@ public void assignTeacher(@PathVariable String teacherId, @PathVariable String c throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher or course not found for provided IDs", e); } } + + @PatchMapping("/{id}") + public Teacher partialUpdateCourse(@PathVariable String id, @RequestBody Teacher teacher) { + return teacherService.partialUpdate(id, teacher.getName(), teacher.getSalary()); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteCourse(@PathVariable String id) { + teacherService.delete(id); + return ResponseEntity.noContent().build(); + } } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java index 3871e8f0..c12bf792 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java @@ -1,6 +1,7 @@ package com.ironhack.homeworkjavaironschool.service; import com.ironhack.homeworkjavaironschool.model.Course; +import com.ironhack.homeworkjavaironschool.model.Teacher; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -47,6 +48,30 @@ public double showMoneyEarned(String id) { if (course != null) { return course.getMoney_earned(); } - throw new IllegalArgumentException("Kurs tapılmadı: " + id); + throw new IllegalArgumentException("Course Not Found with id: " + id); + } + + public Course partialUpdate(String id, String name, Double price, Double moneyEarned, Teacher teacher) { + Course existingCourse = findById(id); + + if (name != null) { + existingCourse.setName(name); + } + if (price != null) { + existingCourse.setPrice(price); + } + if (moneyEarned != null) { + existingCourse.setMoney_earned(moneyEarned); + } + if (teacher.getTeacherId() != null) { + existingCourse.setTeacher(teacher); + } + + return existingCourse; + } + + public void delete(String id) { + findById(id); + courses.remove(id); } } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java index b0663add..8591386a 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java @@ -2,6 +2,7 @@ import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Student; +import com.ironhack.homeworkjavaironschool.model.Teacher; import com.ironhack.homeworkjavaironschool.service.CourseService; import org.springframework.stereotype.Service; @@ -16,7 +17,7 @@ public class StudentService { private final Map students = new HashMap<>(); public StudentService(){ Student student1 = new Student("Ruzi" ,"Sumqgayit","ruzi@gmail.com"); - Student student2 = new Student("Shaiq", "Baku","shaiq@gmail.com"); + Student student2 = new Student("Shaig", "Baku","shaig@gmail.com"); students.put(student1.getStudentId(), student1); students.put(student2.getStudentId(),student2); @@ -24,9 +25,11 @@ public StudentService(){ public List findAll(){ return new ArrayList<>(students.values()); } + public Student findByID(String id){ return students.get(id); } + public Student create(String name, String address, String email ){ Student student = new Student(name,address,email); students.put(student.getStudentId(),student); @@ -49,4 +52,28 @@ public void enroll(String studentId, String courseId){ System.out.println("Success: Student " + studentId + " enrolled in " + course.getName()); } + public Student partialUpdate(String id, String name, String address, String email, Course course) { + Student existingStudent = findByID(id); + + if (name != null) { + existingStudent.setName(name); + } + if (address != null) { + existingStudent.setAddress(address); + } + if (email != null) { + existingStudent.setEmail(email); + } + if (course.getCourseId() != null) { + existingStudent.setCourse(course); + } + + return existingStudent; + } + + public void delete(String id) { + findByID(id); + students.remove(id); + } + } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java index 872b30da..917fa564 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java @@ -52,4 +52,24 @@ public void assign(String teacherId, String courseId) { assignedTeachers.put(teacher, course); } + + public Teacher partialUpdate(String id, String name, Double salary) { + Teacher existingTeacher = findById(id); + + if (name != null) { + existingTeacher.setName(name); + } + if (salary != null) { + existingTeacher.setSalary(salary); + } + + return existingTeacher; + } + + public void delete(String id) { + Teacher existingTeacher = findById(id); + + teachers.remove(id); + assignedTeachers.remove(existingTeacher); + } } From 39cb73523ff27d9ed1486b13aac889dcea841fe8 Mon Sep 17 00:00:00 2001 From: ruzi Date: Tue, 10 Mar 2026 17:52:08 +0400 Subject: [PATCH 16/20] CLI added --- .../cli/CliApplication.java | 20 ++ .../homeworkjavaironschool/cli/CliRunner.java | 300 ++++++++++++++++++ .../cli/SchoolCliFacade.java | 91 ++++++ 3 files changed, 411 insertions(+) create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/cli/CliApplication.java create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/cli/CliRunner.java create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/cli/SchoolCliFacade.java diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/cli/CliApplication.java b/src/main/java/com/ironhack/homeworkjavaironschool/cli/CliApplication.java new file mode 100644 index 00000000..6f360651 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/cli/CliApplication.java @@ -0,0 +1,20 @@ +package com.ironhack.homeworkjavaironschool.cli; + +import com.ironhack.homeworkjavaironschool.HomeworkJavaIronSchoolApplication; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; + +public class CliApplication { + public static void main(String[] args) { + ConfigurableApplicationContext context = new SpringApplicationBuilder(HomeworkJavaIronSchoolApplication.class) + .web(WebApplicationType.NONE) + .run(args); + + try { + context.getBean(CliRunner.class).run(); + } finally { + context.close(); + } + } +} diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/cli/CliRunner.java b/src/main/java/com/ironhack/homeworkjavaironschool/cli/CliRunner.java new file mode 100644 index 00000000..9f0a180a --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/cli/CliRunner.java @@ -0,0 +1,300 @@ +package com.ironhack.homeworkjavaironschool.cli; + +import com.ironhack.homeworkjavaironschool.model.Course; +import com.ironhack.homeworkjavaironschool.model.Student; +import com.ironhack.homeworkjavaironschool.model.Teacher; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Locale; +import java.util.Scanner; + +@Component +public class CliRunner { + private final SchoolCliFacade facade; + private Scanner scanner; + + public CliRunner(SchoolCliFacade facade) { + this.facade = facade; + } + + public void run() { + this.scanner = new Scanner(System.in); + + printBanner(); + printStartupMessage(); + printHelp(); + + while (true) { + System.out.print("\ncli> "); + if (!scanner.hasNextLine()) { + System.out.println("Exiting CLI."); + break; + } + + String line = scanner.nextLine().trim(); + if (line.isEmpty()) { + continue; + } + + if (isExitCommand(line)) { + System.out.println("Exiting CLI."); + break; + } + + try { + handle(line); + } catch (Exception e) { + System.out.println("Error: " + e.getMessage()); + } + } + } + + private void printBanner() { + System.out.println("===================================="); + System.out.println(" School Management CLI "); + System.out.println("===================================="); + } + + private void printStartupMessage() { + System.out.println("CLI is ready."); + System.out.println("Add teachers, courses, and students later with ADD commands."); + } + + private void handle(String line) { + String normalized = line.trim(); + String upper = normalized.toUpperCase(Locale.ROOT); + + if (upper.equals("SHOW COURSES")) { + printCourses(facade.showCourses()); + return; + } + if (upper.equals("SHOW STUDENTS")) { + printStudents(facade.showStudents()); + return; + } + if (upper.equals("SHOW TEACHERS")) { + printTeachers(facade.showTeachers()); + return; + } + if (upper.equals("SHOW PROFIT")) { + System.out.println("Profit: " + facade.showProfit()); + return; + } + if (upper.equals("ADD TEACHER")) { + createTeacherFlow("Add teacher"); + return; + } + if (upper.equals("ADD COURSE")) { + createCourseFlow("Add course"); + return; + } + if (upper.equals("ADD STUDENT")) { + createStudentFlow("Add student"); + return; + } + if (upper.equals("HELP")) { + printHelp(); + return; + } + + if (upper.startsWith("LOOKUP COURSE ")) { + String id = normalized.substring("LOOKUP COURSE ".length()).trim(); + printCourse(facade.lookupCourse(id)); + return; + } + if (upper.startsWith("LOOKUP STUDENT ")) { + String id = normalized.substring("LOOKUP STUDENT ".length()).trim(); + printStudent(facade.lookupStudent(id)); + return; + } + if (upper.startsWith("LOOKUP TEACHER ")) { + String id = normalized.substring("LOOKUP TEACHER ".length()).trim(); + printTeacher(facade.lookupTeacher(id)); + return; + } + if (upper.startsWith("ENROLL ")) { + String[] parts = normalized.split("\\s+"); + if (parts.length != 3) { + throw new IllegalArgumentException("Usage: ENROLL [STUDENT_ID] [COURSE_ID]"); + } + facade.enroll(parts[1], parts[2]); + System.out.println("Student enrolled successfully."); + return; + } + if (upper.startsWith("ASSIGN ")) { + String[] parts = normalized.split("\\s+"); + if (parts.length != 3) { + throw new IllegalArgumentException("Usage: ASSIGN [TEACHER_ID] [COURSE_ID]"); + } + facade.assign(parts[1], parts[2]); + System.out.println("Teacher assigned successfully."); + return; + } + if (upper.startsWith("SHOW MONEY EARNED ")) { + String id = normalized.substring("SHOW MONEY EARNED ".length()).trim(); + System.out.println("Money earned: " + facade.showMoneyEarned(id)); + return; + } + + throw new IllegalArgumentException("Unknown command. Type HELP to see supported commands."); + } + + private boolean isExitCommand(String line) { + String upper = line.trim().toUpperCase(Locale.ROOT); + return upper.equals("EXIT") || upper.equals("QUIT"); + } + + private String prompt(String label) { + while (true) { + System.out.print(label + ": "); + String value = scanner.nextLine().trim(); + if (!value.isEmpty()) { + return value; + } + System.out.println("Value cannot be empty."); + } + } + + private int promptInt(String label) { + while (true) { + System.out.print(label + ": "); + String raw = scanner.nextLine().trim(); + try { + int value = Integer.parseInt(raw); + if (value < 0) { + throw new NumberFormatException(); + } + return value; + } catch (NumberFormatException e) { + System.out.println("Please enter a valid non-negative integer."); + } + } + } + + private double promptDouble(String label) { + while (true) { + System.out.print(label + ": "); + String raw = scanner.nextLine().trim(); + try { + double value = Double.parseDouble(raw); + if (Double.isNaN(value) || Double.isInfinite(value) || value < 0) { + throw new NumberFormatException(); + } + return value; + } catch (NumberFormatException e) { + System.out.println("Please enter a valid non-negative number."); + } + } + } + + private void createTeacherFlow(String title) { + System.out.println(title); + String name = prompt(" Name"); + double salary = promptDouble(" Salary"); + Teacher teacher = facade.createTeacher(name, salary); + System.out.println(" Created teacher with ID: " + teacher.getTeacherId()); + } + + private void createCourseFlow(String title) { + System.out.println(title); + String name = prompt(" Name"); + double price = promptDouble(" Price"); + Course course = facade.createCourse(name, price); + System.out.println(" Created course with ID: " + course.getCourseId()); + } + + private void createStudentFlow(String title) { + System.out.println(title); + String name = prompt(" Name"); + String address = prompt(" Address"); + String email = promptEmail(" Email"); + Student student = facade.createStudent(name, address, email); + System.out.println(" Created student with ID: " + student.getStudentId()); + } + + private String promptEmail(String label) { + while (true) { + String email = prompt(label); + if (email.contains("@") && !email.startsWith("@") && !email.endsWith("@")) { + return email; + } + System.out.println("Please enter a valid email address."); + } + } + + private void printHelp() { + System.out.println("\nSupported commands:"); + System.out.println(" SHOW COURSES"); + System.out.println(" LOOKUP COURSE [COURSE_ID]"); + System.out.println(" SHOW STUDENTS"); + System.out.println(" LOOKUP STUDENT [STUDENT_ID]"); + System.out.println(" SHOW TEACHERS"); + System.out.println(" LOOKUP TEACHER [TEACHER_ID]"); + System.out.println(" ADD TEACHER"); + System.out.println(" ADD COURSE"); + System.out.println(" ADD STUDENT"); + System.out.println(" ENROLL [STUDENT_ID] [COURSE_ID]"); + System.out.println(" ASSIGN [TEACHER_ID] [COURSE_ID]"); + System.out.println(" SHOW PROFIT"); + System.out.println(" SHOW MONEY EARNED [COURSE_ID]"); + System.out.println(" HELP"); + System.out.println(" EXIT"); + } + + private void printCourses(List courses) { + if (courses.isEmpty()) { + System.out.println("No courses found."); + return; + } + for (Course course : courses) { + printCourse(course); + } + } + + private void printStudents(List students) { + if (students.isEmpty()) { + System.out.println("No students found."); + return; + } + for (Student student : students) { + printStudent(student); + } + } + + private void printTeachers(List teachers) { + if (teachers.isEmpty()) { + System.out.println("No teachers found."); + return; + } + for (Teacher teacher : teachers) { + printTeacher(teacher); + } + } + + private void printCourse(Course course) { + if (course == null) { + System.out.println("Course not found."); + return; + } + String teacherName = course.getTeacher() != null ? course.getTeacher().getName() : "Unassigned"; + System.out.println("Course{id='" + course.getCourseId() + "', name='" + course.getName() + "', price=" + course.getPrice() + ", moneyEarned=" + course.getMoney_earned() + ", teacher='" + teacherName + "'}"); + } + + private void printStudent(Student student) { + if (student == null) { + System.out.println("Student not found."); + return; + } + String courseName = student.getCourse() != null ? student.getCourse().getName() : "Not enrolled"; + System.out.println("Student{id='" + student.getStudentId() + "', name='" + student.getName() + "', address='" + student.getAddress() + "', email='" + student.getEmail() + "', course='" + courseName + "'}"); + } + + private void printTeacher(Teacher teacher) { + if (teacher == null) { + System.out.println("Teacher not found."); + return; + } + System.out.println("Teacher{id='" + teacher.getTeacherId() + "', name='" + teacher.getName() + "', salary=" + teacher.getSalary() + "'}"); + } +} \ No newline at end of file diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/cli/SchoolCliFacade.java b/src/main/java/com/ironhack/homeworkjavaironschool/cli/SchoolCliFacade.java new file mode 100644 index 00000000..25b9151f --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/cli/SchoolCliFacade.java @@ -0,0 +1,91 @@ +package com.ironhack.homeworkjavaironschool.cli; + +import com.ironhack.homeworkjavaironschool.model.Course; +import com.ironhack.homeworkjavaironschool.model.Student; +import com.ironhack.homeworkjavaironschool.model.Teacher; +import com.ironhack.homeworkjavaironschool.service.CourseService; +import com.ironhack.homeworkjavaironschool.service.StudentService; +import com.ironhack.homeworkjavaironschool.service.TeacherService; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class SchoolCliFacade { + private final TeacherService teacherService; + private final StudentService studentService; + private final CourseService courseService; + + public SchoolCliFacade(TeacherService teacherService, StudentService studentService, CourseService courseService) { + this.teacherService = teacherService; + this.studentService = studentService; + this.courseService = courseService; + } + + public Teacher createTeacher(String name, double salary) { + return teacherService.create(name, salary); + } + + public Course createCourse(String name, double price) { + return courseService.create(name, price); + } + + public Student createStudent(String name, String address, String email) { + return studentService.create(name, address, email); + } + + public List showTeachers() { + return teacherService.findAll(); + } + + public List showStudents() { + return studentService.findAll(); + } + + public List showCourses() { + return courseService.findAll(); + } + + public Teacher lookupTeacher(String teacherId) { + return teacherService.findById(teacherId); + } + + public Student lookupStudent(String studentId) { + return studentService.findByID(studentId); + } + + public Course lookupCourse(String courseId) { + return courseService.findById(courseId); + } + + public void assign(String teacherId, String courseId) { + Teacher teacher = teacherService.findById(teacherId); + Course course = courseService.findById(courseId); + + if (teacher == null || course == null) { + throw new IllegalArgumentException("Teacher or course not found."); + } + + teacherService.assign(teacherId, courseId); + } + + public void enroll(String studentId, String courseId) { + Student student = studentService.findByID(studentId); + Course course = courseService.findById(courseId); + + if (student == null || course == null) { + throw new IllegalArgumentException("Student or course not found."); + } + + student.setCourse(course); + course.setMoney_earned(course.getMoney_earned() + course.getPrice()); + } + + public double showProfit() { + return courseService.showProfit(); + } + + public double showMoneyEarned(String courseId) { + return courseService.showMoneyEarned(courseId); + } +} From a964f592d073b20a734361b319be300d877bcc7c Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Wed, 11 Mar 2026 06:46:22 -0700 Subject: [PATCH 17/20] Add: Global Exception handling --- .../exception/ErrorResponsee.java | 49 ++++++++++++++++++ .../exception/GlobalExceptionHandler.java | 51 +++++++++++++++++++ .../exception/ResourceNotFoundException.java | 11 ++++ .../exception/ValidationErrorResponse.java | 23 +++++++++ .../service/CourseService.java | 19 +++++-- .../service/StudentService.java | 20 ++++++-- .../service/TeacherService.java | 21 +++++++- 7 files changed, 187 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/exception/ErrorResponsee.java create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/exception/ResourceNotFoundException.java create mode 100644 src/main/java/com/ironhack/homeworkjavaironschool/exception/ValidationErrorResponse.java diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/exception/ErrorResponsee.java b/src/main/java/com/ironhack/homeworkjavaironschool/exception/ErrorResponsee.java new file mode 100644 index 00000000..6319c524 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/exception/ErrorResponsee.java @@ -0,0 +1,49 @@ +package com.ironhack.homeworkjavaironschool.exception; + +import java.time.LocalDateTime; + +public class ErrorResponsee { + private int status; + private String error; + private LocalDateTime timestamp; + private String message; + + public ErrorResponsee(int status, String message, String error) { + this.status = status; + this.message = message; + this.error = error; + this.timestamp = LocalDateTime.now(); + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } +} diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/exception/GlobalExceptionHandler.java b/src/main/java/com/ironhack/homeworkjavaironschool/exception/GlobalExceptionHandler.java new file mode 100644 index 00000000..b79f9972 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/exception/GlobalExceptionHandler.java @@ -0,0 +1,51 @@ +package com.ironhack.homeworkjavaironschool.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.List; + +@ControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity handleResourceNotFound(ResourceNotFoundException ex) { + ErrorResponsee error = new ErrorResponsee( + HttpStatus.NOT_FOUND.value(), + "not found", + ex.getMessage() + ); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidation(MethodArgumentNotValidException ex) { + List fieldErrors = new ArrayList<>(); + + for (var error : ex.getBindingResult().getFieldErrors()) { + fieldErrors.add(error.getField() + ": " + error.getDefaultMessage()); + } + + ValidationErrorResponse response = new ValidationErrorResponse( + HttpStatus.BAD_REQUEST.value(), "Validation Failed", fieldErrors + ); + + return ResponseEntity.badRequest().body(response); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGenreicException(Exception ex) { + ErrorResponsee error = new ErrorResponsee( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + "Internal Server Error", + "An unexpected error occurred" + ); + + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); + } +} diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/exception/ResourceNotFoundException.java b/src/main/java/com/ironhack/homeworkjavaironschool/exception/ResourceNotFoundException.java new file mode 100644 index 00000000..2014e064 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/exception/ResourceNotFoundException.java @@ -0,0 +1,11 @@ +package com.ironhack.homeworkjavaironschool.exception; + +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } + + public ResourceNotFoundException(String resourceName, Long id) { + super(resourceName + " not found with id: " + id); + } +} diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/exception/ValidationErrorResponse.java b/src/main/java/com/ironhack/homeworkjavaironschool/exception/ValidationErrorResponse.java new file mode 100644 index 00000000..06a0d792 --- /dev/null +++ b/src/main/java/com/ironhack/homeworkjavaironschool/exception/ValidationErrorResponse.java @@ -0,0 +1,23 @@ +package com.ironhack.homeworkjavaironschool.exception; + +import java.time.LocalDateTime; +import java.util.List; + +public class ValidationErrorResponse { + private int status; + private String error; + private List fieldErrors; + private LocalDateTime timestamp; + + public ValidationErrorResponse(int status, String error, List fieldErrors) { + this.status = status; + this.error = error; + this.fieldErrors = fieldErrors; + this.timestamp = LocalDateTime.now(); + } + + public int getStatus() { return status; } + public String getError() { return error; } + public List getFieldErrors() { return fieldErrors; } + public LocalDateTime getTimestamp() { return timestamp; } +} diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java index c12bf792..63b7e037 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java @@ -1,5 +1,6 @@ package com.ironhack.homeworkjavaironschool.service; +import com.ironhack.homeworkjavaironschool.exception.ResourceNotFoundException; import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Teacher; import org.springframework.stereotype.Service; @@ -23,7 +24,12 @@ public List findAll() { } public Course findById(String id) { - return courses.get(id); + Course course = courses.get(id); + if (course == null) { + return courses.get(id); + } + + throw new ResourceNotFoundException("Course not found with id: " + id); } public Course create(String name, double price) { @@ -45,10 +51,12 @@ public double showProfit() { public double showMoneyEarned(String id) { Course course = courses.get(id); + if (course != null) { return course.getMoney_earned(); } - throw new IllegalArgumentException("Course Not Found with id: " + id); + + throw new ResourceNotFoundException("Course Not Found with id: " + id); } public Course partialUpdate(String id, String name, Double price, Double moneyEarned, Teacher teacher) { @@ -71,7 +79,12 @@ public Course partialUpdate(String id, String name, Double price, Double moneyEa } public void delete(String id) { - findById(id); + Course deleteCourse = findById(id); + + if (deleteCourse == null) { + throw new ResourceNotFoundException("Course Not Found with id: " + id); + } + courses.remove(id); } } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java index 8591386a..90b5bd90 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java @@ -1,5 +1,6 @@ package com.ironhack.homeworkjavaironschool.service; +import com.ironhack.homeworkjavaironschool.exception.ResourceNotFoundException; import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Student; import com.ironhack.homeworkjavaironschool.model.Teacher; @@ -15,7 +16,9 @@ public class StudentService { private CourseService courseService; private final Map students = new HashMap<>(); - public StudentService(){ + public StudentService(CourseService courseService){ + this.courseService = courseService; + Student student1 = new Student("Ruzi" ,"Sumqgayit","ruzi@gmail.com"); Student student2 = new Student("Shaig", "Baku","shaig@gmail.com"); students.put(student1.getStudentId(), student1); @@ -27,7 +30,13 @@ public List findAll(){ } public Student findByID(String id){ - return students.get(id); + Student student = students.get(id); + + if (student == null) { + throw new ResourceNotFoundException("Student not found with id: " + id); + } + + return student; } public Student create(String name, String address, String email ){ @@ -72,7 +81,12 @@ public Student partialUpdate(String id, String name, String address, String emai } public void delete(String id) { - findByID(id); + Student existingStudent = findByID(id); + + if (existingStudent == null) { + throw new ResourceNotFoundException("Student not found with id: " + id); + } + students.remove(id); } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java index 917fa564..621f4901 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/TeacherService.java @@ -1,5 +1,6 @@ package com.ironhack.homeworkjavaironschool.service; +import com.ironhack.homeworkjavaironschool.exception.ResourceNotFoundException; import com.ironhack.homeworkjavaironschool.model.Course; import com.ironhack.homeworkjavaironschool.model.Teacher; import org.springframework.stereotype.Service; @@ -34,19 +35,33 @@ public Teacher create(String name, double price) { } public Teacher findById(String id) { - return teachers.get(id); + Teacher teacher = teachers.get(id); + + if (teacher == null) { + throw new ResourceNotFoundException("Teacher not found with id: " + id); + } + + return teacher; } public List findByName(String name) { return teachers.values().stream() .filter(c -> c.getName().toLowerCase() .contains(name.toLowerCase())).toList(); + } public void assign(String teacherId, String courseId) { Teacher teacher = teachers.get(teacherId); Course course = courseService.findById(courseId); + if (teacher == null) { + throw new ResourceNotFoundException("Teacher not found with:" + teacherId); + } + if (course == null) { + throw new ResourceNotFoundException("Course not found with:" + courseId); + } + course.setTeacher(teacher); assignedTeachers.put(teacher, course); @@ -69,6 +84,10 @@ public Teacher partialUpdate(String id, String name, Double salary) { public void delete(String id) { Teacher existingTeacher = findById(id); + if (existingTeacher == null) { + throw new ResourceNotFoundException("Teacher not found with id: " + id); + } + teachers.remove(id); assignedTeachers.remove(existingTeacher); } From 5cce7575cc80b9e4db97c7a233bed2e84da618eb Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Thu, 12 Mar 2026 05:32:08 -0700 Subject: [PATCH 18/20] Add: Global Exception Handling --- .../homeworkjavaironschool/model/Course.java | 8 ++++++++ .../homeworkjavaironschool/model/Student.java | 10 ++++++++-- .../homeworkjavaironschool/model/Teacher.java | 13 +++++++++++-- .../service/StudentService.java | 1 + 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java index 133ec7ca..372eb6e4 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Course.java @@ -1,16 +1,24 @@ package com.ironhack.homeworkjavaironschool.model; import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; import java.util.UUID; public class Course { private UUID uuid = UUID.randomUUID(); private String courseId = uuid.toString(); + @NotNull(message = "Name is required") + @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters") private String name; + @Positive(message = "Price must be positive number") private double price; private double money_earned; private @Nullable Teacher teacher; + public Course() {}; + public Course(String name, double price) { this.name = name; this.price = price; diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java index 18207893..99464eff 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Student.java @@ -1,22 +1,28 @@ package com.ironhack.homeworkjavaironschool.model; import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import java.util.UUID; public class Student { private String studentId; + @NotNull(message = "Name is required") + @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters") private String name; private String address; private String email; @Nullable private Course course; -public Student(String name, String address ,String email){ + public Student() {} + + public Student(String name, String address ,String email){ this.studentId=uniqueStudentId(); this.name=name; this.address=address; this.email=email; -} + } public String uniqueStudentId(){return UUID.randomUUID().toString();} //Getters public String getStudentId(){return studentId;} diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java index 8d8a805c..b7ae5e74 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java @@ -1,17 +1,26 @@ package com.ironhack.homeworkjavaironschool.model; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; + import java.util.UUID; public class Teacher { private String teacherId; + @NotNull(message = "Name is required") + @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters") private String name; + @Positive(message = "Salary must be positive") private double salary; + public Teacher(){} + public Teacher(String name , double salary){ this.teacherId=generateUniqueId(); this.name=name; this.salary=salary; -} + } public String getTeacherId(){return teacherId;} private String generateUniqueId() {return UUID.randomUUID().toString();} public String getName() {return name;} @@ -19,4 +28,4 @@ public Teacher(String name , double salary){ public double getSalary(){return salary;} public void setSalary(double salary){this.salary=salary;} -} + } diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java index 90b5bd90..3f1a9f83 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/StudentService.java @@ -15,6 +15,7 @@ @Service public class StudentService { private CourseService courseService; + private final Map students = new HashMap<>(); public StudentService(CourseService courseService){ this.courseService = courseService; From 4c698ebf8c45cde6abe0d46ab994b51a8aa3e302 Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Thu, 12 Mar 2026 05:39:08 -0700 Subject: [PATCH 19/20] Add: Validations to Tacher, Student and Course models --- .../java/com/ironhack/homeworkjavaironschool/model/Teacher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java b/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java index b7ae5e74..e6924b2c 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/model/Teacher.java @@ -11,7 +11,7 @@ public class Teacher { @NotNull(message = "Name is required") @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters") private String name; - @Positive(message = "Salary must be positive") + @Positive(message = "Salary must be positive number") private double salary; public Teacher(){} From efd048c7080e1dca9fa63d08aec41edd07f0d760 Mon Sep 17 00:00:00 2001 From: shaig-mahmudov Date: Fri, 13 Mar 2026 04:35:51 -0700 Subject: [PATCH 20/20] Fix: Validation logic in CourseService --- .../ironhack/homeworkjavaironschool/service/CourseService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java index 63b7e037..d1306a80 100644 --- a/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java +++ b/src/main/java/com/ironhack/homeworkjavaironschool/service/CourseService.java @@ -25,7 +25,7 @@ public List findAll() { public Course findById(String id) { Course course = courses.get(id); - if (course == null) { + if (course != null) { return courses.get(id); }