From b8c1e2075b2b8868c2df24c4da4f2f71051832a7 Mon Sep 17 00:00:00 2001 From: kenanqafarov Date: Wed, 8 Apr 2026 12:54:28 +0400 Subject: [PATCH 1/2] Predeploy --- .idea/.gitignore | 10 + .idea/compiler.xml | 18 ++ .idea/encodings.xml | 6 + .idea/homework-java-ironlibrary.iml | 9 + .idea/jarRepositories.xml | 20 ++ .idea/misc.xml | 14 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + ironLibraryApp/.gitattributes | 2 + ironLibraryApp/.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + ironLibraryApp/mvnw | 295 ++++++++++++++++++ ironLibraryApp/mvnw.cmd | 189 +++++++++++ ironLibraryApp/pom.xml | 61 ++++ .../IronLibraryAppApplication.java | 183 +++++++++++ .../ironLibraryApp/dao/AuthorDAO.java | 95 ++++++ .../ironLibraryApp/dao/BookDAO.java | 154 +++++++++ .../ironLibraryApp/dao/IssueDAO.java | 80 +++++ .../ironLibraryApp/dao/StudentDAO.java | 46 +++ .../ironLibraryApp/model/Author.java | 45 +++ .../ironLibraryApp/model/Book.java | 42 +++ .../ironLibraryApp/model/Issue.java | 59 ++++ .../ironLibraryApp/model/Student.java | 25 ++ .../service/LibraryService.java | 109 +++++++ .../util/DatabaseConnection.java | 17 + .../src/main/resources/application.properties | 1 + .../IronLibraryAppApplicationTests.java | 13 + 27 files changed, 1543 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/compiler.xml create mode 100644 .idea/encodings.xml create mode 100644 .idea/homework-java-ironlibrary.iml create mode 100644 .idea/jarRepositories.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 ironLibraryApp/.gitattributes create mode 100644 ironLibraryApp/.gitignore create mode 100644 ironLibraryApp/.mvn/wrapper/maven-wrapper.properties create mode 100644 ironLibraryApp/mvnw create mode 100644 ironLibraryApp/mvnw.cmd create mode 100644 ironLibraryApp/pom.xml create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplication.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/BookDAO.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/IssueDAO.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/StudentDAO.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java create mode 100644 ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/util/DatabaseConnection.java create mode 100644 ironLibraryApp/src/main/resources/application.properties create mode 100644 ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..ab1f4164 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 00000000..f65f00bb --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 00000000..8871c7b3 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/homework-java-ironlibrary.iml b/.idea/homework-java-ironlibrary.iml new file mode 100644 index 00000000..d6ebd480 --- /dev/null +++ b/.idea/homework-java-ironlibrary.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 00000000..712ab9d9 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..a24e3755 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 00000000..821fdf28 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..35eb1ddf --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ironLibraryApp/.gitattributes b/ironLibraryApp/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/ironLibraryApp/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/ironLibraryApp/.gitignore b/ironLibraryApp/.gitignore new file mode 100644 index 00000000..667aaef0 --- /dev/null +++ b/ironLibraryApp/.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/ironLibraryApp/.mvn/wrapper/maven-wrapper.properties b/ironLibraryApp/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c595b009 --- /dev/null +++ b/ironLibraryApp/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip diff --git a/ironLibraryApp/mvnw b/ironLibraryApp/mvnw new file mode 100644 index 00000000..bd8896bf --- /dev/null +++ b/ironLibraryApp/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/ironLibraryApp/mvnw.cmd b/ironLibraryApp/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/ironLibraryApp/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/ironLibraryApp/pom.xml b/ironLibraryApp/pom.xml new file mode 100644 index 00000000..9cf72114 --- /dev/null +++ b/ironLibraryApp/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.5 + + + com.ironlibrary + ironLibraryApp + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.mysql + mysql-connector-j + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplication.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplication.java new file mode 100644 index 00000000..bf539d0a --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplication.java @@ -0,0 +1,183 @@ +package com.ironlibrary.ironLibraryApp; + +import com.ironlibrary.ironLibraryApp.model.Author; +import com.ironlibrary.ironLibraryApp.model.Book; +import com.ironlibrary.ironLibraryApp.model.Issue; +import com.ironlibrary.ironLibraryApp.service.LibraryService; + +import java.util.List; +import java.util.Scanner; + +public class IronLibraryAppApplication { + public static void main(String[] args) { + LibraryService service = new LibraryService(); + Scanner scanner = new Scanner(System.in); + + while (true) { + printMenu(); + try { + int choice = Integer.parseInt(scanner.nextLine().trim()); + + switch (choice) { + case 1: + addBook(service, scanner); + break; + case 2: + searchBookByTitle(service, scanner); + break; + case 3: + searchBooksByCategory(service, scanner); + break; + case 4: + searchBooksByAuthor(service, scanner); + break; + case 5: + getAllBooks(service, scanner); + break; + case 6: + issueBook(service, scanner); + break; + case 7: + listBooksByUsn(service, scanner); + break; + case 8: + System.out.println("Exiting the system. Goodbye!"); + scanner.close(); + return; + default: + System.out.println("Invalid choice. Please try again."); + } + } catch (NumberFormatException e) { + System.out.println("Please enter a valid number."); + } catch (Exception e) { + System.out.println("An unexpected error occurred: " + e.getMessage()); + } + } + } + + private static void printMenu() { + System.out.println("\n=== Library Management System ==="); + System.out.println("1. Add a book"); + System.out.println("2. Search book by title"); + System.out.println("3. Search book by category"); + System.out.println("4. Search book by Author"); + System.out.println("5. List all books along with author"); + System.out.println("6. Issue book to student"); + System.out.println("7. List books by usn"); + System.out.println("8. Exit"); + System.out.print("Enter your choice: "); + } + + private static void addBook(LibraryService service, Scanner sc) { + System.out.print("Enter isbn: "); + String isbn = sc.nextLine(); + System.out.print("Enter title: "); + String title = sc.nextLine(); + System.out.print("Enter category: "); + String category = sc.nextLine(); + System.out.print("Enter Author name: "); + String authorName = sc.nextLine(); + System.out.print("Enter Author mail: "); + String email = sc.nextLine(); + System.out.print("Enter number of books: "); + int qty = Integer.parseInt(sc.nextLine()); + + service.addBookWithAuthor(isbn, title, category, qty, authorName, email); + } + + private static void issueBook(LibraryService service, Scanner sc) { + System.out.print("Enter usn: "); + String usn = sc.nextLine(); + System.out.print("Enter student name: "); + String studentName = sc.nextLine(); + System.out.print("Enter isbn: "); + String isbn = sc.nextLine(); + service.issueBook(usn, studentName, isbn); + } + + private static void searchBookByTitle(LibraryService service, Scanner sc) { + System.out.print("Enter title of the book: "); + String title = sc.nextLine(); + Book book = service.searchBookByTitle(title); + if (book != null) { + System.out.println("------------------------------------------------------------"); + System.out.printf("%-15s %-30s %-15s %-5s%n", "ISBN", "Title", "Category", "Qty"); + System.out.println("------------------------------------------------------------"); + System.out.printf("%-15s %-30s %-15s %-5d%n", + book.getIsbn(), book.getTitle(), book.getCategory(), book.getQuantity()); + System.out.println("------------------------------------------------------------"); + } + } + + private static void getAllBooks(LibraryService service, Scanner sc) { + System.out.println("Here is the list!"); + List books = service.getAllBooks(); + + if (books.isEmpty()) { + System.out.println("No books found."); + return; + } + + System.out.println("------------------------------------------------------------"); + System.out.printf("%-15s %-30s %-15s %-5s%n", "ISBN", "Title", "Category", "Qty"); + System.out.println("------------------------------------------------------------"); + for (Book book : books) { + System.out.printf("%-15s %-30s %-15s %-5d%n", + book.getIsbn(), book.getTitle(), book.getCategory(), book.getQuantity()); + } + System.out.println("------------------------------------------------------------"); + } + + private static void searchBooksByCategory(LibraryService service, Scanner sc) { + System.out.print("Enter the category to search: "); + String category = sc.nextLine(); + List books = service.searchBooksByCategory(category); + printBookList(books); + } + + private static void searchBooksByAuthor(LibraryService service, Scanner sc) { + System.out.print("Enter the author name to search: "); + String author = sc.nextLine(); + List books = service.searchBooksByAuthor(author); + printBookList(books); + } + + private static void listBooksByUsn(LibraryService service, Scanner sc) { + System.out.print("Enter student USN: "); + String usn = sc.nextLine(); + List issues = service.getIssuesByStudent(usn); + + if (issues.isEmpty()) { + return; + } + + System.out.println("------------------------------------------------------------"); + System.out.printf("%-5s %-15s %-30s %-12s %-12s%n", + "ID", "USN", "Book Title", "Issue Date", "Return Date"); + System.out.println("------------------------------------------------------------"); + for (Issue issue : issues) { + System.out.printf("%-5d %-15s %-30s %-12s %-12s%n", + issue.getIssueId(), + issue.getIssueStudent().getUsn(), + issue.getIssueBook().getTitle(), + issue.getIssueDate(), + issue.getReturnDate()); + } + System.out.println("------------------------------------------------------------"); + } + + private static void printBookList(List books) { + if (books == null || books.isEmpty()) { + System.out.println("No books found."); + return; + } + System.out.println("------------------------------------------------------------"); + System.out.printf("%-15s %-30s %-15s %-5s%n", "ISBN", "Title", "Category", "Qty"); + System.out.println("------------------------------------------------------------"); + for (Book book : books) { + System.out.printf("%-15s %-30s %-15s %-5d%n", + book.getIsbn(), book.getTitle(), book.getCategory(), book.getQuantity()); + } + System.out.println("------------------------------------------------------------"); + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java new file mode 100644 index 00000000..c4ba1054 --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java @@ -0,0 +1,95 @@ +package com.ironlibrary.ironLibraryApp.dao; + +import com.ironlibrary.ironLibraryApp.model.Author; +import com.ironlibrary.ironLibraryApp.model.Book; +import com.ironlibrary.ironLibraryApp.util.DatabaseConnection; +import java.sql.*; + + +//Author DAO +public class AuthorDAO { + +// Adding new author + public void addAuthor(Author author) { + String sql = "INSERT INTO author (name, email, book_isbn) VALUES (?, ?, ?)"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + + pstmt.setString(1, author.getName()); + pstmt.setString(2, author.getEmail()); + pstmt.setString(3, author.getAuthorBook().getIsbn()); + + pstmt.executeUpdate(); + + // Get generated author_id + try (ResultSet rs = pstmt.getGeneratedKeys()) { + if (rs.next()) { + author.setAuthorId(rs.getInt(1)); + } + } + System.out.println("Author added successfully."); + } catch (SQLException e) { + System.err.println("Error adding author: " + e.getMessage()); + } + } + + +// Finding Author by 'isbn' + public Author findByBookIsbn(String isbn) { + String sql = "SELECT a.*, b.* FROM author a JOIN book b ON a.book_isbn = b.isbn WHERE a.book_isbn = ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, isbn); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + Book book = new Book( + rs.getString("b.isbn"), + rs.getString("b.title"), + rs.getString("b.category"), + rs.getInt("b.quantity") + ); + + Author author = new Author( + rs.getString("a.name"), + rs.getString("a.email"), + book + ); + author.setAuthorId(rs.getInt("a.author_id")); + return author; + } + } catch (SQLException e) { + System.err.println("Error finding author by book: " + e.getMessage()); + } + return null; + } + + +// Finding author by their name + public Author findByName(String name) { + String sql = "SELECT a.*, b.* FROM author a JOIN book b ON a.book_isbn = b.isbn WHERE a.name LIKE ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, "%" + name + "%"); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + Book book = new Book( + rs.getString("b.isbn"), + rs.getString("b.title"), + rs.getString("b.category"), + rs.getInt("b.quantity") + ); + + Author author = new Author(rs.getString("a.name"), rs.getString("a.email"), book); + author.setAuthorId(rs.getInt("a.author_id")); + return author; + } + } catch (SQLException e) { + System.err.println("Error finding author by name: " + e.getMessage()); + } + return null; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/BookDAO.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/BookDAO.java new file mode 100644 index 00000000..48f8f47f --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/BookDAO.java @@ -0,0 +1,154 @@ +package com.ironlibrary.ironLibraryApp.dao; + +import com.ironlibrary.ironLibraryApp.model.Book; +import com.ironlibrary.ironLibraryApp.util.DatabaseConnection; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +public class BookDAO { + + public void addBook(Book book) { + String sql = "INSERT INTO book (isbn, title, category, quantity) VALUES (?, ?, ?, ?)"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, book.getIsbn()); + pstmt.setString(2, book.getTitle()); + pstmt.setString(3, book.getCategory()); + pstmt.setInt(4, book.getQuantity()); + + pstmt.executeUpdate(); + System.out.println("Book added successfully."); + } catch (SQLException e) { + System.err.println("Error adding book: " + e.getMessage()); + } + } + + public Book searchByTitle(String title) { + String sql = "SELECT * FROM book WHERE title LIKE ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, "%" + title + "%"); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + return new Book( + rs.getString("isbn"), + rs.getString("title"), + rs.getString("category"), + rs.getInt("quantity") + ); + } + } catch (SQLException e) { + System.err.println("Error searching book by title: " + e.getMessage()); + } + return null; + } + + public List searchByCategory(String category) { + List books = new ArrayList<>(); + String sql = "SELECT * FROM book WHERE category LIKE ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, "%" + category + "%"); + ResultSet rs = pstmt.executeQuery(); + + while (rs.next()) { + books.add(new Book( + rs.getString("isbn"), + rs.getString("title"), + rs.getString("category"), + rs.getInt("quantity") + )); + } + } catch (SQLException e) { + System.err.println("Error searching books by category: " + e.getMessage()); + } + return books; + } + + public List searchByAuthor(String author) { + List books = new ArrayList<>(); + String sql = "SELECT b.* FROM book b JOIN author a ON b.isbn = a.book_isbn WHERE a.name LIKE ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, "%" + author + "%"); + ResultSet rs = pstmt.executeQuery(); + + while (rs.next()) { + books.add(new Book( + rs.getString("isbn"), + rs.getString("title"), + rs.getString("category"), + rs.getInt("quantity") + )); + } + } catch (SQLException e) { + System.err.println("Error searching books by author: " + e.getMessage()); + } + return books; + } + + public Book findByIsbn(String isbn) { + String sql = "SELECT * FROM book WHERE isbn = ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, isbn); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + return new Book( + rs.getString("isbn"), + rs.getString("title"), + rs.getString("category"), + rs.getInt("quantity") + ); + } + } catch (SQLException e) { + System.err.println("Error finding book by ISBN: " + e.getMessage()); + } + return null; + } + + public void updateBook(Book book) { + String sql = "UPDATE book SET title = ?, category = ?, quantity = ? WHERE isbn = ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, book.getTitle()); + pstmt.setString(2, book.getCategory()); + pstmt.setInt(3, book.getQuantity()); + pstmt.setString(4, book.getIsbn()); + + pstmt.executeUpdate(); + } catch (SQLException e) { + System.err.println("Error updating book: " + e.getMessage()); + } + } + + public List getAllBooks() { + List books = new ArrayList<>(); + String sql = "SELECT * FROM book"; + try (Connection conn = DatabaseConnection.getConnection(); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(sql)) { + + while (rs.next()) { + books.add(new Book( + rs.getString("isbn"), + rs.getString("title"), + rs.getString("category"), + rs.getInt("quantity") + )); + } + } catch (SQLException e) { + System.err.println("Error retrieving all books: " + e.getMessage()); + } + return books; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/IssueDAO.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/IssueDAO.java new file mode 100644 index 00000000..fdf4be5f --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/IssueDAO.java @@ -0,0 +1,80 @@ +package com.ironlibrary.ironLibraryApp.dao; + +import com.ironlibrary.ironLibraryApp.model.Issue; +import com.ironlibrary.ironLibraryApp.model.Student; +import com.ironlibrary.ironLibraryApp.model.Book; +import com.ironlibrary.ironLibraryApp.util.DatabaseConnection; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + + +//Issue DAO +public class IssueDAO { + + +// Adding issue to db + public void addIssue(Issue issue) { + String sql = "INSERT INTO issue (issue_date, return_date, student_usn, book_isbn) " + + "VALUES (?, ?, ?, ?)"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + + pstmt.setString(1, issue.getIssueDate()); + pstmt.setString(2, issue.getReturnDate()); + pstmt.setString(3, issue.getIssueStudent().getUsn()); + pstmt.setString(4, issue.getIssueBook().getIsbn()); + + pstmt.executeUpdate(); + + try (ResultSet rs = pstmt.getGeneratedKeys()) { + if (rs.next()) { + issue.setIssueId(rs.getInt(1)); + } + } + System.out.println("Issue record created."); + } catch (SQLException e) { + System.err.println("Error issuing book: " + e.getMessage()); + } + } + +// Searching all data due to their 'usn data' + public List getIssuesByStudentUsn(String usn) { + List issues = new ArrayList<>(); + String sql = "SELECT i.*, s.name as student_name, b.title as book_title " + + "FROM issue i " + + "JOIN student s ON i.student_usn = s.usn " + + "JOIN book b ON i.book_isbn = b.isbn " + + "WHERE i.student_usn = ?"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, usn); + ResultSet rs = pstmt.executeQuery(); + + while (rs.next()) { + Student student = new Student(rs.getString("student_usn"), rs.getString("student_name")); + Book book = new Book(rs.getString("book_isbn"), rs.getString("book_title"), "", 0); + + Issue issue = new Issue( + rs.getString("issue_date"), + rs.getString("return_date"), + student, + book + ); + issue.setIssueId(rs.getInt("issue_id")); + issues.add(issue); + } + } catch (SQLException e) { + System.err.println("Error retrieving issues by student: " + e.getMessage()); + } + return issues; + } + + // Bonus: Books to be returned today (optional) + public List getBooksToReturnToday() { + // Implement similarly using CURRENT_DATE comparison if needed + return new ArrayList<>(); + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/StudentDAO.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/StudentDAO.java new file mode 100644 index 00000000..b1fac80d --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/StudentDAO.java @@ -0,0 +1,46 @@ +package com.ironlibrary.ironLibraryApp.dao; + +import com.ironlibrary.ironLibraryApp.model.Student; +import com.ironlibrary.ironLibraryApp.util.DatabaseConnection; +import java.sql.*; + + +// Student DAO +public class StudentDAO { + +// Add Student or update data + public void addOrUpdateStudent(Student student) { + String sql = "INSERT INTO student (usn, name) VALUES (?, ?) " + + "ON DUPLICATE KEY UPDATE name = ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, student.getUsn()); + pstmt.setString(2, student.getName()); + pstmt.setString(3, student.getName()); + + pstmt.executeUpdate(); + } catch (SQLException e) { + System.err.println("Error adding/updating student: " + e.getMessage()); + } + } + + +// Finding student by their 'usn' + public Student findByUsn(String usn) { + String sql = "SELECT * FROM student WHERE usn = ?"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + + pstmt.setString(1, usn); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + return new Student(rs.getString("usn"), rs.getString("name")); + } + } catch (SQLException e) { + System.err.println("Error finding student: " + e.getMessage()); + } + return null; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java new file mode 100644 index 00000000..d6b528c2 --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java @@ -0,0 +1,45 @@ +package com.ironlibrary.ironLibraryApp.model; + +public class Author{ + private int authorId; + private String name; + private String email; + private Book authorBook; + + public Author (String name,String email,Book authorBook){ + this.name = name; + this.email = email; + this.authorBook = authorBook; + } + +// Getters + public int getAuthorId(){ + return authorId; + } + public String getName(){ + return name; + } + public String getEmail(){ + return email; + } + public Book getAuthorBook(){ + return authorBook; + } +// Setters + public void setAuthorId(int authorId){ + this.authorId = authorId; + } + public void setName(String name){ + this.name = name; + } + public void setEmail(String email){ + this.email = email; + } + public void setAuthorBook(Book authorBook){ + this.authorBook = authorBook; + } + + +} + + diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java new file mode 100644 index 00000000..9171ab0d --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java @@ -0,0 +1,42 @@ +package com.ironlibrary.ironLibraryApp.model; + +public class Book{ + private String isbn; + private String title; + private String category; + private int quantity; + public Book(String isbn,String title,String category,int quantity){ + this.isbn = isbn; + this.title = title; + this.category = category; + this.quantity = quantity; + } + +// Getters + public String getIsbn(){ + return isbn; + } + public String getTitle(){ + return title; + } + public String getCategory(){ + return category; + } + public int getQuantity(){ + return quantity; + } + +// Setters + public void setIsbn(String isbn){ + this.isbn = isbn; + } + public void setTitle(String title){ + this.title = title; + } + public void setCategory(String category){ + this.category = category; + } + public void setQuantity(int quantity){ + this.quantity = quantity; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java new file mode 100644 index 00000000..24af58c0 --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java @@ -0,0 +1,59 @@ +package com.ironlibrary.ironLibraryApp.model; + +public class Issue{ + private int issueId; + private String issueDate; + private String returnDate; + private Student issueStudent; + private Book issueBook; + + public Issue(int issueId,String issueDate, String returnDate,Student issueStudent,Book issueBook ){ + this.issueId = issueId; + this.issueDate = issueDate; + this.returnDate = returnDate; + this.issueStudent = issueStudent; + this.issueBook = issueBook; + } + + public Issue(String issueDate, String returnDate, Student issueStudent, Book issueBook) { + this.issueDate = issueDate; + this.returnDate = returnDate; + this.issueStudent = issueStudent; + this.issueBook = issueBook; + } + + // Getters + public int getIssueId(){ + return issueId; + } + public String getIssueDate(){ + return issueDate; + } + public String getReturnDate(){ + return returnDate; + } + public Student getIssueStudent(){ + return issueStudent; + } + public Book getIssueBook(){ + return issueBook; + } +// Setters + public void setIssueId(int issueId){ + this.issueId = issueId; + } + public void setIssueDate(String issueDate){ + this.issueDate = issueDate; + } + public void setReturnDate(String returnDate){ + this.returnDate = returnDate; + } + public void setIssueStudent(Student issueStudent){ + this.issueStudent = issueStudent; + } + public void setIssueBook(Book issueBook){ + this.issueBook = issueBook; + } + + +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java new file mode 100644 index 00000000..158bde5a --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java @@ -0,0 +1,25 @@ +package com.ironlibrary.ironLibraryApp.model; + +public class Student{ + private String usn; + private String name; + + public Student (String usn,String name){ + this.usn = usn; + this.name = name; + } +// Getters + public String getUsn(){ + return usn; + } + public String getName(){ + return name; + } +// Setters + public void setUsn(String usn){ + this.usn = usn; + } + public void setName(String name){ + this.name = name; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java new file mode 100644 index 00000000..7e5df729 --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java @@ -0,0 +1,109 @@ +package com.ironlibrary.ironLibraryApp.service; + +import com.ironlibrary.ironLibraryApp.dao.*; +import com.ironlibrary.ironLibraryApp.model.*; +import java.time.LocalDate; +import java.util.List; + +public class LibraryService { + + private final BookDAO bookDAO = new BookDAO(); + private final AuthorDAO authorDAO = new AuthorDAO(); + private final StudentDAO studentDAO = new StudentDAO(); + private final IssueDAO issueDAO = new IssueDAO(); + + public void addBookWithAuthor(String isbn, String title, String category, int quantity, + String authorName, String authorEmail) { + Book book = new Book(isbn, title, category, quantity); + bookDAO.addBook(book); + + Author author = new Author(authorName, authorEmail, book); + authorDAO.addAuthor(author); + } + + public void issueBook(String usn, String studentName, String isbn) { + Book book = bookDAO.findByIsbn(isbn); + if (book == null) { + System.out.println("Book not found: " + isbn); + return; + } + if (book.getQuantity() <= 0) { + System.out.println("Book is not available."); + return; + } + + Student student = new Student(usn, studentName); + studentDAO.addOrUpdateStudent(student); + + String issueDate = LocalDate.now().toString(); + String returnDate = LocalDate.now().plusDays(7).toString(); + + Issue issue = new Issue(issueDate, returnDate, student, book); + issueDAO.addIssue(issue); + + book.setQuantity(book.getQuantity() - 1); + bookDAO.updateBook(book); + + System.out.println("Book issued. Return date: " + returnDate); + } + + public Book searchBookByTitle(String title) { + Book book = bookDAO.searchByTitle(title); + if (book == null) { + System.out.println("Book not found: " + title); + } + return book; + } + + public List searchBooksByCategory(String category) { + List books = bookDAO.searchByCategory(category); + if (books.isEmpty()) { + System.out.println("No books found in category: " + category); + } + return books; + } + + public List searchBooksByAuthor(String author) { + List books = bookDAO.searchByAuthor(author); + if (books.isEmpty()) { + System.out.println("No books found for author: " + author); + } + return books; + } + + public List getAllBooks() { + return bookDAO.getAllBooks(); + } + + public Author findAuthorByIsbn(String isbn) { + Author author = authorDAO.findByBookIsbn(isbn); + if (author == null) { + System.out.println("Author not found for ISBN: " + isbn); + } + return author; + } + + public Author findAuthorByName(String name) { + Author author = authorDAO.findByName(name); + if (author == null) { + System.out.println("Author not found: " + name); + } + return author; + } + + public List getIssuesByStudent(String usn) { + List issues = issueDAO.getIssuesByStudentUsn(usn); + if (issues.isEmpty()) { + System.out.println("No active issues for student: " + usn); + } + return issues; + } + + public Student findStudent(String usn) { + Student student = studentDAO.findByUsn(usn); + if (student == null) { + System.out.println("Student not found: " + usn); + } + return student; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/util/DatabaseConnection.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/util/DatabaseConnection.java new file mode 100644 index 00000000..2ccc4773 --- /dev/null +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/util/DatabaseConnection.java @@ -0,0 +1,17 @@ +package com.ironlibrary.ironLibraryApp.util; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DatabaseConnection { + private static final String URL = "jdbc:mysql://localhost:3306/ironLibraryDB?useSSL=false&allowPublicKeyRetrieval=true"; + private static final String USER = "root"; + private static final String PASSWORD = "admin"; + + public static Connection getConnection() throws SQLException { + Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); + conn.setAutoCommit(true); + return conn; + } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/resources/application.properties b/ironLibraryApp/src/main/resources/application.properties new file mode 100644 index 00000000..7e5d827f --- /dev/null +++ b/ironLibraryApp/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=ironLibraryApp diff --git a/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java b/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java new file mode 100644 index 00000000..cc40e97c --- /dev/null +++ b/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java @@ -0,0 +1,13 @@ +package com.ironlibrary.ironLibraryApp; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class IronLibraryAppApplicationTests { + + @Test + void contextLoads() { + } + +} From 9014329654c7591c11eeb7a08ab31102cfe5e819 Mon Sep 17 00:00:00 2001 From: kenanqafarov Date: Wed, 8 Apr 2026 13:24:10 +0400 Subject: [PATCH 2/2] Sometest added preruning --- .../ironLibraryApp/dao/AuthorDAO.java | 7 +- .../ironLibraryApp/model/Author.java | 44 +- .../ironLibraryApp/model/Book.java | 80 ++- .../ironLibraryApp/model/Issue.java | 48 +- .../ironLibraryApp/model/Student.java | 25 +- .../service/LibraryService.java | 133 +++- .../IronLibraryAppApplicationTests.java | 673 ++++++++++++++++++ 7 files changed, 892 insertions(+), 118 deletions(-) diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java index c4ba1054..74232fec 100644 --- a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/dao/AuthorDAO.java @@ -34,7 +34,7 @@ public void addAuthor(Author author) { } -// Finding Author by 'isbn' +// public Author findByBookIsbn(String isbn) { String sql = "SELECT a.*, b.* FROM author a JOIN book b ON a.book_isbn = b.isbn WHERE a.book_isbn = ?"; try (Connection conn = DatabaseConnection.getConnection(); @@ -65,8 +65,9 @@ public Author findByBookIsbn(String isbn) { return null; } - -// Finding author by their name + /** + * Finds author by name (for search by author). + */ public Author findByName(String name) { String sql = "SELECT a.*, b.* FROM author a JOIN book b ON a.book_isbn = b.isbn WHERE a.name LIKE ?"; try (Connection conn = DatabaseConnection.getConnection(); diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java index d6b528c2..d6db2205 100644 --- a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Author.java @@ -1,45 +1,25 @@ package com.ironlibrary.ironLibraryApp.model; -public class Author{ +public class Author { + private int authorId; private String name; private String email; private Book authorBook; - public Author (String name,String email,Book authorBook){ + public Author(String name, String email, Book authorBook) { this.name = name; this.email = email; this.authorBook = authorBook; } -// Getters - public int getAuthorId(){ - return authorId; - } - public String getName(){ - return name; - } - public String getEmail(){ - return email; - } - public Book getAuthorBook(){ - return authorBook; - } -// Setters - public void setAuthorId(int authorId){ - this.authorId = authorId; - } - public void setName(String name){ - this.name = name; - } - public void setEmail(String email){ - this.email = email; - } - public void setAuthorBook(Book authorBook){ - this.authorBook = authorBook; - } - - -} - + public int getAuthorId() { return authorId; } + public String getName() { return name; } + public String getEmail() { return email; } + public Book getAuthorBook() { return authorBook; } + public void setAuthorId(int authorId) { this.authorId = authorId; } + public void setName(String name) { this.name = name; } + public void setEmail(String email) { this.email = email; } + public void setAuthorBook(Book authorBook) { this.authorBook = authorBook; } +} \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java index 9171ab0d..f720210a 100644 --- a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Book.java @@ -1,42 +1,84 @@ package com.ironlibrary.ironLibraryApp.model; -public class Book{ +public class Book { + private String isbn; private String title; private String category; private int quantity; - public Book(String isbn,String title,String category,int quantity){ + private Author author; + + public Book(String isbn, String title, String category, int quantity, Author author) { + if (isbn == null || isbn.trim().isEmpty()) + throw new IllegalArgumentException("ERROR: ISBN cannot be null or empty."); + if (title == null || title.trim().isEmpty()) + throw new IllegalArgumentException("ERROR: Book title cannot be null or empty."); + if (category == null || category.trim().isEmpty()) + throw new IllegalArgumentException("ERROR: Book category cannot be null or empty."); + if (quantity < 0) + throw new IllegalArgumentException("ERROR: Quantity cannot be negative. Provided: " + quantity); + this.isbn = isbn; this.title = title; this.category = category; this.quantity = quantity; + this.author = author; } -// Getters - public String getIsbn(){ - return isbn; - } - public String getTitle(){ - return title; - } - public String getCategory(){ - return category; - } - public int getQuantity(){ - return quantity; + // Constructor without Author (used by DAOs before author is linked) + public Book(String isbn, String title, String category, int quantity) { + this(isbn, title, category, quantity, null); } -// Setters - public void setIsbn(String isbn){ + public String getIsbn() { return isbn; } + public String getTitle() { return title; } + public String getCategory() { return category; } + public int getQuantity() { return quantity; } + public Author getAuthor() { return author; } + + public void setIsbn(String isbn) { + if (isbn == null || isbn.trim().isEmpty()) + throw new IllegalArgumentException("ERROR: ISBN cannot be null or empty."); this.isbn = isbn; } - public void setTitle(String title){ + + public void setTitle(String title) { + if (title == null || title.trim().isEmpty()) + throw new IllegalArgumentException("ERROR: Book title cannot be null or empty."); this.title = title; } - public void setCategory(String category){ + + public void setCategory(String category) { + if (category == null || category.trim().isEmpty()) + throw new IllegalArgumentException("ERROR: Book category cannot be null or empty."); this.category = category; } - public void setQuantity(int quantity){ + + public void setQuantity(int quantity) { + if (quantity < 0) + throw new IllegalArgumentException("ERROR: Quantity cannot be negative. Provided: " + quantity); this.quantity = quantity; } + + public void setAuthor(Author author) { this.author = author; } + + public void addQuantity(int count) { + if (count < 0) + throw new IllegalArgumentException("ERROR: Cannot add negative quantity. Provided: " + count); + this.quantity += count; + } + + public void reduceQuantity(int count) { + if (count < 0) + throw new IllegalArgumentException("ERROR: Cannot reduce by negative quantity. Provided: " + count); + if (count > this.quantity) + throw new IllegalArgumentException("ERROR: Insufficient copies. Available: " + this.quantity + ", Requested: " + count); + this.quantity -= count; + } + + @Override + public String toString() { + return "Book{isbn='" + isbn + "', title='" + title + "', category='" + category + + "', quantity=" + quantity + ", author=" + (author != null ? author.getName() : "Unknown") + '}'; + } } \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java index 24af58c0..c2830f7b 100644 --- a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Issue.java @@ -1,13 +1,14 @@ package com.ironlibrary.ironLibraryApp.model; -public class Issue{ +public class Issue { + private int issueId; private String issueDate; private String returnDate; private Student issueStudent; private Book issueBook; - public Issue(int issueId,String issueDate, String returnDate,Student issueStudent,Book issueBook ){ + public Issue(int issueId, String issueDate, String returnDate, Student issueStudent, Book issueBook) { this.issueId = issueId; this.issueDate = issueDate; this.returnDate = returnDate; @@ -22,38 +23,15 @@ public Issue(String issueDate, String returnDate, Student issueStudent, Book iss this.issueBook = issueBook; } - // Getters - public int getIssueId(){ - return issueId; - } - public String getIssueDate(){ - return issueDate; - } - public String getReturnDate(){ - return returnDate; - } - public Student getIssueStudent(){ - return issueStudent; - } - public Book getIssueBook(){ - return issueBook; - } -// Setters - public void setIssueId(int issueId){ - this.issueId = issueId; - } - public void setIssueDate(String issueDate){ - this.issueDate = issueDate; - } - public void setReturnDate(String returnDate){ - this.returnDate = returnDate; - } - public void setIssueStudent(Student issueStudent){ - this.issueStudent = issueStudent; - } - public void setIssueBook(Book issueBook){ - this.issueBook = issueBook; - } - + public int getIssueId() { return issueId; } + public String getIssueDate() { return issueDate; } + public String getReturnDate() { return returnDate; } + public Student getIssueStudent() { return issueStudent; } + public Book getIssueBook() { return issueBook; } + public void setIssueId(int issueId) { this.issueId = issueId; } + public void setIssueDate(String issueDate) { this.issueDate = issueDate; } + public void setReturnDate(String returnDate) { this.returnDate = returnDate; } + public void setIssueStudent(Student issueStudent) { this.issueStudent = issueStudent; } + public void setIssueBook(Book issueBook) { this.issueBook = issueBook; } } \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java index 158bde5a..6d025a39 100644 --- a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/model/Student.java @@ -1,25 +1,18 @@ package com.ironlibrary.ironLibraryApp.model; -public class Student{ +public class Student { + private String usn; private String name; - public Student (String usn,String name){ + public Student(String usn, String name) { this.usn = usn; this.name = name; } -// Getters - public String getUsn(){ - return usn; - } - public String getName(){ - return name; - } -// Setters - public void setUsn(String usn){ - this.usn = usn; - } - public void setName(String name){ - this.name = name; - } + + public String getUsn() { return usn; } + public String getName() { return name; } + + public void setUsn(String usn) { this.usn = usn; } + public void setName(String name) { this.name = name; } } \ No newline at end of file diff --git a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java index 7e5df729..b4a9c448 100644 --- a/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java +++ b/ironLibraryApp/src/main/java/com/ironlibrary/ironLibraryApp/service/LibraryService.java @@ -5,6 +5,13 @@ import java.time.LocalDate; import java.util.List; +/** + * LibraryService: Core business logic layer for library operations. + * Handles book management, student records, author information, and book issue tracking. + * + * @author Library Management System + * @version 2.0 + */ public class LibraryService { private final BookDAO bookDAO = new BookDAO(); @@ -12,24 +19,79 @@ public class LibraryService { private final StudentDAO studentDAO = new StudentDAO(); private final IssueDAO issueDAO = new IssueDAO(); + // ============================= BOOK MANAGEMENT ============================= + + /** + * Adds a new book to the library with associated author information. + * Book is created first (with null author), then Author is created and linked back. + * + * @param isbn Unique identifier for the book + * @param title Book title + * @param category Book category/genre + * @param quantity Available quantity (must be > 0) + * @param authorName Name of the author + * @param authorEmail Email of the author (must be valid format) + */ public void addBookWithAuthor(String isbn, String title, String category, int quantity, String authorName, String authorEmail) { - Book book = new Book(isbn, title, category, quantity); + if (isbn == null || isbn.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: ISBN cannot be null or empty. Please provide a valid ISBN."); + } + if (title == null || title.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Book title cannot be null or empty. Please enter a valid book title."); + } + if (category == null || category.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Category cannot be null or empty. Please specify a valid category."); + } + if (quantity <= 0) { + throw new IllegalArgumentException("ERROR: Book quantity must be greater than 0. Please enter a positive number."); + } + if (authorName == null || authorName.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Author name cannot be null or empty. Please provide a valid author name."); + } + if (authorEmail == null || !isValidEmail(authorEmail)) { + throw new IllegalArgumentException("ERROR: Invalid email format. Please provide a valid email address (e.g., author@example.com)."); + } + + // Step 1: Create book with null author (Author object does not exist yet) + Book book = new Book(isbn, title, category, quantity, null); bookDAO.addBook(book); + // Step 2: Create author with the book reference Author author = new Author(authorName, authorEmail, book); authorDAO.addAuthor(author); + + // Step 3: Link author back to the book and persist + book.setAuthor(author); + bookDAO.updateBook(book); + + System.out.println("SUCCESS: Book '" + title + "' with ISBN " + isbn + " and author '" + authorName + "' added successfully."); } + /** + * Issues a book to a student for a 7-day loan period. + * + * @param usn Student Unique Serial Number + * @param studentName Name of the student + * @param isbn ISBN of the book to issue + */ public void issueBook(String usn, String studentName, String isbn) { + if (usn == null || usn.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Student USN cannot be null or empty. Please provide a valid student ID."); + } + if (studentName == null || studentName.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Student name cannot be null or empty. Please enter the student's name."); + } + if (isbn == null || isbn.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: ISBN cannot be null or empty. Please provide a valid book ISBN."); + } + Book book = bookDAO.findByIsbn(isbn); if (book == null) { - System.out.println("Book not found: " + isbn); - return; + throw new IllegalArgumentException("ERROR: Book with ISBN '" + isbn + "' not found in the library. Please verify the ISBN and try again."); } if (book.getQuantity() <= 0) { - System.out.println("Book is not available."); - return; + throw new IllegalArgumentException("ERROR: Book '" + book.getTitle() + "' is currently unavailable. All copies are already issued."); } Student student = new Student(usn, studentName); @@ -44,57 +106,95 @@ public void issueBook(String usn, String studentName, String isbn) { book.setQuantity(book.getQuantity() - 1); bookDAO.updateBook(book); - System.out.println("Book issued. Return date: " + returnDate); + System.out.println("SUCCESS: Book '" + book.getTitle() + "' issued to " + studentName + ". Return date: " + returnDate); } + // ============================= BOOK SEARCH ============================= + public Book searchBookByTitle(String title) { + if (title == null || title.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Search title cannot be null or empty. Please enter a valid book title."); + } Book book = bookDAO.searchByTitle(title); if (book == null) { - System.out.println("Book not found: " + title); + System.out.println("INFO: Book with title '" + title + "' not found."); + } else { + System.out.println("SUCCESS: Book found - '" + title + "' (ISBN: " + book.getIsbn() + ")"); } return book; } public List searchBooksByCategory(String category) { + if (category == null || category.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Category cannot be null or empty. Please specify a valid category."); + } List books = bookDAO.searchByCategory(category); if (books.isEmpty()) { - System.out.println("No books found in category: " + category); + System.out.println("INFO: No books found in category '" + category + "'."); + } else { + System.out.println("SUCCESS: Found " + books.size() + " book(s) in category '" + category + "'."); } return books; } public List searchBooksByAuthor(String author) { + if (author == null || author.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Author name cannot be null or empty. Please enter a valid author name."); + } List books = bookDAO.searchByAuthor(author); if (books.isEmpty()) { - System.out.println("No books found for author: " + author); + System.out.println("INFO: No books found for author '" + author + "'."); + } else { + System.out.println("SUCCESS: Found " + books.size() + " book(s) by author '" + author + "'."); } return books; } public List getAllBooks() { - return bookDAO.getAllBooks(); + List allBooks = bookDAO.getAllBooks(); + System.out.println("INFO: Retrieved " + allBooks.size() + " total book(s) from library."); + return allBooks; } + // ============================= AUTHOR SEARCH ============================= + public Author findAuthorByIsbn(String isbn) { + if (isbn == null || isbn.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: ISBN cannot be null or empty. Please provide a valid ISBN."); + } Author author = authorDAO.findByBookIsbn(isbn); if (author == null) { - System.out.println("Author not found for ISBN: " + isbn); + System.out.println("INFO: Author not found for ISBN '" + isbn + "'."); + } else { + System.out.println("SUCCESS: Author '" + author.getName() + "' found for ISBN '" + isbn + "'."); } return author; } public Author findAuthorByName(String name) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Author name cannot be null or empty. Please enter a valid author name."); + } Author author = authorDAO.findByName(name); if (author == null) { - System.out.println("Author not found: " + name); + System.out.println("INFO: Author '" + name + "' not found."); + } else { + System.out.println("SUCCESS: Author '" + author.getName() + "' found with email: " + author.getEmail()); } return author; } + // ============================= ISSUE MANAGEMENT ============================= + public List getIssuesByStudent(String usn) { + if (usn == null || usn.trim().isEmpty()) { + throw new IllegalArgumentException("ERROR: Student USN cannot be null or empty. Please provide a valid student ID."); + } List issues = issueDAO.getIssuesByStudentUsn(usn); if (issues.isEmpty()) { - System.out.println("No active issues for student: " + usn); + System.out.println("INFO: No active book issues found for student '" + usn + "'."); + } else { + System.out.println("SUCCESS: Found " + issues.size() + " active issue(s) for student '" + usn + "'."); } return issues; } @@ -106,4 +206,11 @@ public Student findStudent(String usn) { } return student; } + + // ============================= UTILITY ============================= + + private boolean isValidEmail(String email) { + String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$"; + return email != null && email.matches(emailRegex) && email.contains("."); + } } \ No newline at end of file diff --git a/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java b/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java index cc40e97c..af314373 100644 --- a/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java +++ b/ironLibraryApp/src/test/java/com/ironlibrary/ironLibraryApp/IronLibraryAppApplicationTests.java @@ -1,13 +1,686 @@ package com.ironlibrary.ironLibraryApp; +import com.ironlibrary.ironLibraryApp.model.*; +import com.ironlibrary.ironLibraryApp.service.LibraryService; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.DisplayName; import org.springframework.boot.test.context.SpringBootTest; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Comprehensive Unit Test Suite for IronLibrary Application + * + * Test Coverage: + * ✓ Book Management (Add, Search, Get All) + * ✓ Author Management (Find by ISBN, Find by Name) + * ✓ Book Issue/Loan Management + * ✓ Exception Handling with detailed user feedback + * ✓ Edge cases and invalid inputs + * ✓ Boundary conditions + * + * @author QA Team + * @version 2.0 - Comprehensive Test Coverage + */ @SpringBootTest +@DisplayName("Iron Library Application - Complete Test Suite") class IronLibraryAppApplicationTests { + // LibraryService instance used for all tests + private LibraryService libraryService; + + /** + * Setup method - initializes LibraryService before each test + * Ensures clean state for every test execution + */ + @BeforeEach + void setUp() { + libraryService = new LibraryService(); + } + + // ============================= BOOT CONTEXT TESTS ============================= + + /** + * Test 1: Verify Spring context loads successfully + * Purpose: Basic sanity check that application starts correctly + */ @Test + @DisplayName("Test 1: Spring Boot Context Loading") void contextLoads() { + // If this test passes, Spring context loaded successfully + assertNotNull(libraryService, "LibraryService should be initialized"); + } + + // ============================= ADD BOOK WITH AUTHOR TESTS ============================= + + /** + * Test 2: Successfully add a valid book with author information + * Purpose: Verify successful book and author addition with valid inputs + */ + @Test + @DisplayName("Test 2: Add Valid Book with Author - Success Case") + void testAddBookWithAuthorSuccess() { + // Arrange: Prepare valid test data + String isbn = "978-0-13-110362-7"; + String title = "The Clean Code"; + String category = "Programming"; + int quantity = 5; + String authorName = "Robert C. Martin"; + String authorEmail = "robert@example.com"; + + // Act: Add book with author + assertDoesNotThrow(() -> libraryService.addBookWithAuthor(isbn, title, category, quantity, authorName, authorEmail), + "Adding valid book with author should not throw exception"); + + // Assert: Verify no exception was thrown + } + + /** + * Test 3: Exception when ISBN is null + * Purpose: Verify detailed error message for missing ISBN + */ + @Test + @DisplayName("Test 3: Add Book with Null ISBN - Exception") + void testAddBookWithNullIsbn() { + // Arrange & Act & Assert: Verify exception with detailed message + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor(null, "Java Basics", "Programming", 3, "Author", "author@example.com"), + "Should throw exception for null ISBN"); + + assertTrue(exception.getMessage().contains("ISBN cannot be null"), + "Exception message should explain ISBN is required"); + assertTrue(exception.getMessage().contains("ERROR:"), + "Exception message should start with ERROR prefix"); + } + + /** + * Test 4: Exception when ISBN is empty string + * Purpose: Verify validation rejects empty ISBN + */ + @Test + @DisplayName("Test 4: Add Book with Empty ISBN - Exception") + void testAddBookWithEmptyIsbn() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("", "Java Basics", "Programming", 3, "Author", "author@example.com")); + + assertTrue(exception.getMessage().contains("ISBN cannot be null or empty"), + "Error message should clarify ISBN is empty"); + } + + /** + * Test 5: Exception when title is null + * Purpose: Verify detailed error message for missing title + */ + @Test + @DisplayName("Test 5: Add Book with Null Title - Exception") + void testAddBookWithNullTitle() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", null, "Programming", 3, "Author", "author@example.com")); + + assertTrue(exception.getMessage().contains("title cannot be null"), + "Exception message should mention title"); + } + + /** + * Test 6: Exception when category is null + * Purpose: Verify category validation + */ + @Test + @DisplayName("Test 6: Add Book with Null Category - Exception") + void testAddBookWithNullCategory() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", "Java Book", null, 3, "Author", "author@example.com")); + + assertTrue(exception.getMessage().contains("Category cannot be null"), + "Exception should mention category requirement"); + } + + /** + * Test 7: Exception when quantity is zero + * Purpose: Verify quantity must be positive + */ + @Test + @DisplayName("Test 7: Add Book with Zero Quantity - Exception") + void testAddBookWithZeroQuantity() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", "Java Book", "Programming", 0, "Author", "author@example.com")); + + assertTrue(exception.getMessage().contains("must be greater than 0"), + "Exception should specify quantity must be positive"); + } + + /** + * Test 8: Exception when quantity is negative + * Purpose: Verify negative quantities are rejected + */ + @Test + @DisplayName("Test 8: Add Book with Negative Quantity - Exception") + void testAddBookWithNegativeQuantity() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", "Java Book", "Programming", -5, "Author", "author@example.com")); + + assertTrue(exception.getMessage().contains("must be greater than 0"), + "Negative quantities should be rejected"); + } + + /** + * Test 9: Exception when author name is null + * Purpose: Verify author name validation + */ + @Test + @DisplayName("Test 9: Add Book with Null Author Name - Exception") + void testAddBookWithNullAuthorName() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", "Java Book", "Programming", 3, null, "author@example.com")); + + assertTrue(exception.getMessage().contains("Author name cannot be null"), + "Should validate author name"); + } + + /** + * Test 10: Exception when email is invalid format + * Purpose: Verify email format validation with detailed feedback + */ + @Test + @DisplayName("Test 10: Add Book with Invalid Email Format - Exception") + void testAddBookWithInvalidEmail() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", "Java Book", "Programming", 3, "Author", "invalid-email")); + + assertTrue(exception.getMessage().contains("Invalid email format"), + "Should reject invalid email format"); + assertTrue(exception.getMessage().contains("example.com"), + "Should provide email format example"); + } + + /** + * Test 11: Exception when email is null + * Purpose: Verify null email rejection + */ + @Test + @DisplayName("Test 11: Add Book with Null Email - Exception") + void testAddBookWithNullEmail() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.addBookWithAuthor("978-123", "Java Book", "Programming", 3, "Author", null)); + + assertTrue(exception.getMessage().contains("Invalid email format"), + "Null email should be caught by email validation"); + } + + // ============================= ISSUE BOOK TESTS ============================= + + /** + * Test 12: Successfully issue a book to a student + * Purpose: Verify book issuance with valid inputs + */ + @Test + @DisplayName("Test 12: Issue Book with Valid Inputs - Success") + void testIssueBookSuccess() { + // First add a book to the library + libraryService.addBookWithAuthor("978-456", "Spring Guide", "Web Development", 3, "Mark", "mark@example.com"); + + // Act: Issue the book to a student + assertDoesNotThrow(() -> libraryService.issueBook("USN001", "John Student", "978-456"), + "Issuing valid book to student should succeed"); + } + + /** + * Test 13: Exception when student USN is null + * Purpose: Verify USN validation with clear error message + */ + @Test + @DisplayName("Test 13: Issue Book with Null Student USN - Exception") + void testIssueBookNullUsn() { + // Add book first + libraryService.addBookWithAuthor("978-456", "Spring Guide", "Web Development", 3, "Mark", "mark@example.com"); + + // Act & Assert: Verify exception + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.issueBook(null, "John", "978-456")); + + assertTrue(exception.getMessage().contains("Student USN cannot be null"), + "Error message should specify USN requirement"); + } + + /** + * Test 14: Exception when student name is empty + * Purpose: Verify student name validation + */ + @Test + @DisplayName("Test 14: Issue Book with Empty Student Name - Exception") + void testIssueBookEmptyStudentName() { + libraryService.addBookWithAuthor("978-456", "Spring Guide", "Web Development", 3, "Mark", "mark@example.com"); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.issueBook("USN001", " ", "978-456")); + + assertTrue(exception.getMessage().contains("Student name cannot be null"), + "Should reject empty/whitespace-only names"); + } + + /** + * Test 15: Exception when ISBN is null during issue + * Purpose: Verify ISBN validation for book lookup + */ + @Test + @DisplayName("Test 15: Issue Book with Null ISBN - Exception") + void testIssueBookNullIsbn() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.issueBook("USN001", "John", null)); + + assertTrue(exception.getMessage().contains("ISBN cannot be null"), + "Should validate ISBN for book lookup"); + } + + /** + * Test 16: Exception when book is not found + * Purpose: Verify helpful error message when book ISBN doesn't exist + */ + @Test + @DisplayName("Test 16: Issue Non-Existent Book - Exception") + void testIssueNonExistentBook() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.issueBook("USN001", "John", "999-INVALID")); + + assertTrue(exception.getMessage().contains("not found in the library"), + "Should indicate book not in library"); + assertTrue(exception.getMessage().contains("verify the ISBN"), + "Should suggest verification step"); + } + + /** + * Test 17: Exception when book quantity is zero (unavailable) + * Purpose: Verify helpful message when no copies available + */ + @Test + @DisplayName("Test 17: Issue Unavailable Book (Zero Quantity) - Exception") + void testIssueUnavailableBook() { + // Add book with zero quantity + libraryService.addBookWithAuthor("978-789", "Advanced Java", "Programming", 0, "Josh", "josh@example.com"); + + // Act & Assert: Verify exception with helpful message + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.issueBook("USN001", "John", "978-789")); + + assertTrue(exception.getMessage().contains("currently unavailable"), + "Error message should indicate book unavailable"); + assertTrue(exception.getMessage().contains("All copies are already issued"), + "Should explain why unavailable"); + } + + // ============================= SEARCH BOOK BY TITLE TESTS ============================= + + /** + * Test 18: Successfully search book by title + * Purpose: Verify book search returns correct results + */ + @Test + @DisplayName("Test 18: Search Book by Valid Title - Success") + void testSearchBookByTitleSuccess() { + // Add a book + libraryService.addBookWithAuthor("978-111", "Database Design", "Databases", 2, "Philip", "philip@example.com"); + + // Act: Search for the book + Book foundBook = libraryService.searchBookByTitle("Database Design"); + + // Assert: Verify book was found + assertNotNull(foundBook, "Book should be found by title"); + assertEquals("Database Design", foundBook.getTitle(), "Title should match"); + } + + /** + * Test 19: Search with null title should throw exception + * Purpose: Verify null title rejection with clear error + */ + @Test + @DisplayName("Test 19: Search Book with Null Title - Exception") + void testSearchBookNullTitle() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.searchBookByTitle(null)); + + assertTrue(exception.getMessage().contains("cannot be null or empty"), + "Should reject null search titles"); + } + + /** + * Test 20: Search for non-existent book + * Purpose: Verify graceful handling when book not found + */ + @Test + @DisplayName("Test 20: Search for Non-Existent Book Title") + void testSearchNonExistentBookTitle() { + // Act: Search for non-existent book + Book foundBook = libraryService.searchBookByTitle("Non Existent Book 12345"); + + // Assert: Verify null returned (without exception) + assertNull(foundBook, "Should return null for non-existent book, not throw exception"); } + // ============================= SEARCH BOOKS BY CATEGORY TESTS ============================= + + /** + * Test 21: Successfully search books by category + * Purpose: Verify category search functionality + */ + @Test + @DisplayName("Test 21: Search Books by Valid Category - Success") + void testSearchBooksByCategorySuccess() { + // Add books in specific category + libraryService.addBookWithAuthor("978-222", "OOP Principles", "Programming", 2, "Steven", "steven@example.com"); + libraryService.addBookWithAuthor("978-333", "Design Patterns", "Programming", 1, "Steven", "steven@example.com"); + + // Act: Search for books in category + List books = libraryService.searchBooksByCategory("Programming"); + + // Assert: Verify results + assertNotNull(books, "Search results should not be null"); + assertFalse(books.isEmpty(), "Should find books in category"); + } + + /** + * Test 22: Category search with null input + * Purpose: Verify null category rejection + */ + @Test + @DisplayName("Test 22: Search Books with Null Category - Exception") + void testSearchBooksCategoryNull() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.searchBooksByCategory(null)); + + assertTrue(exception.getMessage().contains("Category cannot be null"), + "Should require valid category"); + } + + /** + * Test 23: Search for non-existent category + * Purpose: Verify empty list returned for unknown categories + */ + @Test + @DisplayName("Test 23: Search Books by Non-Existent Category") + void testSearchNonExistentCategory() { + // Act: Search for non-existent category + List books = libraryService.searchBooksByCategory("Science Fiction 999"); + + // Assert: Verify empty list returned + assertNotNull(books, "Should return empty list, not null"); + assertTrue(books.isEmpty(), "Should return empty list for non-existent category"); + } + + // ============================= SEARCH BOOKS BY AUTHOR TESTS ============================= + + /** + * Test 24: Successfully search books by author + * Purpose: Verify author search functionality + */ + @Test + @DisplayName("Test 24: Search Books by Valid Author - Success") + void testSearchBooksByAuthorSuccess() { + // Add books by same author + libraryService.addBookWithAuthor("978-444", "Book One", "Fiction", 1, "Jane Doe", "jane@example.com"); + libraryService.addBookWithAuthor("978-555", "Book Two", "Mystery", 2, "Jane Doe", "jane@example.com"); + + // Act: Search for books by author + List books = libraryService.searchBooksByAuthor("Jane Doe"); + + // Assert: Verify results + assertNotNull(books, "Search results should not be null"); + assertFalse(books.isEmpty(), "Should find books by author"); + } + + /** + * Test 25: Author search with null input + * Purpose: Verify null author name rejection + */ + @Test + @DisplayName("Test 25: Search Books with Null Author - Exception") + void testSearchBooksAuthorNull() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.searchBooksByAuthor(null)); + + assertTrue(exception.getMessage().contains("Author name cannot be null"), + "Should require valid author name"); + } + + /** + * Test 26: Search for non-existent author + * Purpose: Verify empty list returned for unknown authors + */ + @Test + @DisplayName("Test 26: Search Books by Non-Existent Author") + void testSearchNonExistentAuthor() { + // Act: Search for non-existent author + List books = libraryService.searchBooksByAuthor("Unknown Author XYZ"); + + // Assert: Verify empty list returned + assertTrue(books.isEmpty(), "Should return empty list for unknown author"); + } + + // ============================= GET ALL BOOKS TESTS ============================= + + /** + * Test 27: Get all books from library + * Purpose: Verify retrieving complete book inventory + */ + @Test + @DisplayName("Test 27: Get All Books - Returns List") + void testGetAllBooks() { + // Add multiple books + libraryService.addBookWithAuthor("978-666", "Science Today", "Science", 3, "Dr. Smith", "smith@example.com"); + libraryService.addBookWithAuthor("978-777", "History Lessons", "History", 2, "Prof. Jones", "jones@example.com"); + + // Act: Get all books + List allBooks = libraryService.getAllBooks(); + + // Assert: Verify list is not null and contains books + assertNotNull(allBooks, "Book list should not be null"); + assertTrue(allBooks.size() >= 2, "Should contain at least 2 books"); + } + + // ============================= FIND AUTHOR BY ISBN TESTS ============================= + + /** + * Test 28: Successfully find author by book ISBN + * Purpose: Verify author lookup by ISBN works correctly + */ + @Test + @DisplayName("Test 28: Find Author by Valid ISBN - Success") + void testFindAuthorByIsbnSuccess() { + // Add book with author + libraryService.addBookWithAuthor("978-888", "Web Development", "Technology", 1, "Ryan Cooper", "ryan@example.com"); + + // Act: Find author by ISBN + Author foundAuthor = libraryService.findAuthorByIsbn("978-888"); + + // Assert: Verify author found + assertNotNull(foundAuthor, "Author should be found by ISBN"); + assertEquals("Ryan Cooper", foundAuthor.getName(), "Author name should match"); + } + + /** + * Test 29: Find author with null ISBN + * Purpose: Verify null ISBN rejection + */ + @Test + @DisplayName("Test 29: Find Author with Null ISBN - Exception") + void testFindAuthorByNullIsbn() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.findAuthorByIsbn(null)); + + assertTrue(exception.getMessage().contains("ISBN cannot be null"), + "Should require valid ISBN"); + } + + /** + * Test 30: Find author for non-existent ISBN + * Purpose: Verify graceful handling when author not found + */ + @Test + @DisplayName("Test 30: Find Author by Non-Existent ISBN") + void testFindAuthorNonExistentIsbn() { + // Act: Search for author by non-existent ISBN + Author foundAuthor = libraryService.findAuthorByIsbn("999-NOBOOK"); + + // Assert: Verify null returned + assertNull(foundAuthor, "Should return null for non-existent ISBN"); + } + + // ============================= FIND AUTHOR BY NAME TESTS ============================= + + /** + * Test 31: Successfully find author by name + * Purpose: Verify author name search functionality + */ + @Test + @DisplayName("Test 31: Find Author by Valid Name - Success") + void testFindAuthorByNameSuccess() { + // Add book to create author record + libraryService.addBookWithAuthor("978-999", "Machine Learning", "AI", 2, "Dr. Anne Smith", "anne@example.com"); + + // Act: Find author by name + Author foundAuthor = libraryService.findAuthorByName("Dr. Anne Smith"); + + // Assert: Verify author found + assertNotNull(foundAuthor, "Author should be found by name"); + assertEquals("Dr. Anne Smith", foundAuthor.getName(), "Author name should match"); + } + + /** + * Test 32: Find author with null name + * Purpose: Verify null name rejection + */ + @Test + @DisplayName("Test 32: Find Author with Null Name - Exception") + void testFindAuthorByNullName() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.findAuthorByName(null)); + + assertTrue(exception.getMessage().contains("Author name cannot be null"), + "Should require valid author name"); + } + + /** + * Test 33: Find author with non-existent name + * Purpose: Verify graceful handling when name not found + */ + @Test + @DisplayName("Test 33: Find Author by Non-Existent Name") + void testFindAuthorNonExistentName() { + // Act: Search for non-existent author + Author foundAuthor = libraryService.findAuthorByName("Author Not In System"); + + // Assert: Verify null returned + assertNull(foundAuthor, "Should return null for non-existent author"); + } + + // ============================= GET ISSUES BY STUDENT TESTS ============================= + + /** + * Test 34: Successfully get student's book issues + * Purpose: Verify retrieval of student's borrowed books + */ + @Test + @DisplayName("Test 34: Get Issues by Valid Student USN - Success") + void testGetIssuesByStudentSuccess() { + // Setup: Add book and issue it to student + libraryService.addBookWithAuthor("978-1000", "Test Book", "Testing", 5, "Test Author", "test@example.com"); + libraryService.issueBook("STU001", "Alice Brown", "978-1000"); + + // Act: Get issues for student + List studentIssues = libraryService.getIssuesByStudent("STU001"); + + // Assert: Verify issues found + assertNotNull(studentIssues, "Issues list should not be null"); + } + + /** + * Test 35: Get issues with null student USN + * Purpose: Verify null USN rejection + */ + @Test + @DisplayName("Test 35: Get Issues with Null Student USN - Exception") + void testGetIssuesByNullUsn() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.getIssuesByStudent(null)); + + assertTrue(exception.getMessage().contains("Student USN cannot be null"), + "Should require valid student USN"); + } + + /** + * Test 36: Get issues for student with no borrowed books + * Purpose: Verify empty list returned for students with no issues + */ + @Test + @DisplayName("Test 36: Get Issues for Student with No Borrowed Books") + void testGetIssuesNoBooks() { + // Act: Get issues for student who hasn't borrowed anything + List studentIssues = libraryService.getIssuesByStudent("STU999"); + + // Assert: Verify empty list + assertNotNull(studentIssues, "Should return empty list, not null"); + assertTrue(studentIssues.isEmpty(), "Should return empty list when no issues"); + } + + // ============================= BOUNDARY AND EDGE CASE TESTS ============================= + + /** + * Test 37: Add book with maximum quantity + * Purpose: Verify system handles large quantities appropriately + */ + @Test + @DisplayName("Test 37: Add Book with Large Quantity - Boundary Test") + void testAddBookLargeQuantity() { + // Act & Assert: Should handle large quantities + assertDoesNotThrow(() -> + libraryService.addBookWithAuthor("978-2000", "Popular Book", "General", 10000, "Popular Author", "pop@example.com"), + "Should handle large quantities without issue"); + } + + /** + * Test 38: Add book with quantity of 1 + * Purpose: Verify minimum valid quantity accepted + */ + @Test + @DisplayName("Test 38: Add Book with Minimum Quantity (1) - Boundary Test") + void testAddBookMinimumQuantity() { + // Act & Assert: Should accept quantity of 1 + assertDoesNotThrow(() -> + libraryService.addBookWithAuthor("978-2001", "Rare Book", "Collectible", 1, "Rare Author", "rare@example.com"), + "Should accept quantity of 1"); + } + + /** + * Test 39: Search with whitespace-only strings + * Purpose: Verify whitespace-only inputs are rejected + */ + @Test + @DisplayName("Test 39: Search with Whitespace-Only Input - Exception") + void testSearchWhitespaceOnly() { + // Act & Assert: Whitespace-only should be treated as empty + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + libraryService.searchBookByTitle(" ")); + + assertTrue(exception.getMessage().contains("cannot be null or empty"), + "Whitespace-only input should be rejected"); + } + + /** + * Test 40: Email validation with various formats + * Purpose: Verify email validation accepts valid formats + */ + @Test + @DisplayName("Test 40: Email Validation - Valid Format Acceptance") + void testValidEmailFormats() { + // Test various valid email formats + assertDoesNotThrow(() -> + libraryService.addBookWithAuthor("978-3001", "Email Test 1", "Tech", 1, "Author1", "user@domain.com")); + + assertDoesNotThrow(() -> + libraryService.addBookWithAuthor("978-3002", "Email Test 2", "Tech", 1, "Author2", "user.name@domain.co.uk")); + + assertDoesNotThrow(() -> + libraryService.addBookWithAuthor("978-3003", "Email Test 3", "Tech", 1, "Author3", "user+tag@domain.org")); + } }