From e1cbca31e556ffc48c0ccd66ef2a7ed46e5f81c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 15:31:22 +0200 Subject: [PATCH 01/21] Commit inicial --- .gitattributes | 2 + .gitignore | 34 +++ .mvn/wrapper/maven-wrapper.properties | 19 ++ mvnw | 259 ++++++++++++++++++ mvnw.cmd | 149 ++++++++++ pom.xml | 63 +++++ .../HomeworkLibratyApplication.java | 13 + src/main/resources/application.properties | 5 + .../HomeworkLibratyApplicationTests.java | 13 + 9 files changed, 557 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java create mode 100644 src/main/resources/application.properties create mode 100644 src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b6a95e78 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/mvnw b/mvnw new file mode 100644 index 00000000..19529ddf --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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.2 +# +# 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:]' +} + +# 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 <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.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${0##*/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 +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..249bdf38 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : 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.2 +@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) { "/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_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::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 +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..97a955f9 --- /dev/null +++ b/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.4 + + + com.example + homework_libraty + 0.0.1-SNAPSHOT + homework_libraty + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java new file mode 100644 index 00000000..d625b469 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -0,0 +1,13 @@ +package com.example.homework_libraty; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HomeworkLibratyApplication { + + public static void main(String[] args) { + SpringApplication.run(HomeworkLibratyApplication.class, args); + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..d84b6b97 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.application.name=homework_libraty +spring.datasource.url=jdbc:mysql://localhost:3306/lab_library?serverTimezone=UTC +spring.datasource.username=root +spring.datasource.password=admin +spring.jpa.hibernate.ddl-auto=update diff --git a/src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java b/src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java new file mode 100644 index 00000000..e358d86e --- /dev/null +++ b/src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.homework_libraty; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class HomeworkLibratyApplicationTests { + + @Test + void contextLoads() { + } + +} From c39f9f45b44ec72f99b5ec37738bcfa0e8141be0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 16:43:55 +0200 Subject: [PATCH 02/21] Modelos y repositorios definidos --- .../homework_libraty/models/Author.java | 73 ++++++++++++++++ .../example/homework_libraty/models/Book.java | 72 ++++++++++++++++ .../homework_libraty/models/Issue.java | 86 +++++++++++++++++++ .../homework_libraty/models/Student.java | 47 ++++++++++ .../repositories/AuthorRepository.java | 7 ++ .../repositories/BookRepository.java | 8 ++ .../repositories/IssuesRepository.java | 7 ++ .../repositories/StudentRepository.java | 7 ++ .../homework_libraty/models/StudentTest.java | 25 ++++++ 9 files changed, 332 insertions(+) create mode 100644 src/main/java/com/example/homework_libraty/models/Author.java create mode 100644 src/main/java/com/example/homework_libraty/models/Book.java create mode 100644 src/main/java/com/example/homework_libraty/models/Issue.java create mode 100644 src/main/java/com/example/homework_libraty/models/Student.java create mode 100644 src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java create mode 100644 src/main/java/com/example/homework_libraty/repositories/BookRepository.java create mode 100644 src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java create mode 100644 src/main/java/com/example/homework_libraty/repositories/StudentRepository.java create mode 100644 src/test/java/com/example/homework_libraty/models/StudentTest.java diff --git a/src/main/java/com/example/homework_libraty/models/Author.java b/src/main/java/com/example/homework_libraty/models/Author.java new file mode 100644 index 00000000..336a7b33 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/models/Author.java @@ -0,0 +1,73 @@ +package com.example.homework_libraty.models; + +import jakarta.persistence.*; + +import java.awt.print.Book; + +@Entity +@Table(name = "author") +public class Author { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "author_id") + private int id; + + private String name; + + private String email; + + @Column(name = "author_book") + private Book authorBook; + + public Author() { + } + + public Author(String name, String email, Book authorBook) { + this.name = name; + this.email = email; + this.authorBook = authorBook; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Book getAuthorBook() { + return authorBook; + } + + public void setAuthorBook(Book authorBook) { + this.authorBook = authorBook; + } + + @Override + public String toString() { + return "Author{" + + "id=" + id + + ", name='" + name + '\'' + + ", email='" + email + '\'' + + ", authorBook=" + authorBook + + '}'; + } +} diff --git a/src/main/java/com/example/homework_libraty/models/Book.java b/src/main/java/com/example/homework_libraty/models/Book.java new file mode 100644 index 00000000..416d0488 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/models/Book.java @@ -0,0 +1,72 @@ +package com.example.homework_libraty.models; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(name = "books") +public class Book { + + @Id + private String isbn; + + private String tittle; + + private String category; + + private int quantity; + + public Book() { + } + + public Book(String isbn, String tittle, String category, int quantity) { + this.isbn = isbn; + this.tittle = tittle; + this.category = category; + this.quantity = quantity; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getTittle() { + return tittle; + } + + public void setTittle(String tittle) { + this.tittle = tittle; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + @Override + public String toString() { + return "Book{" + + "isbn='" + isbn + '\'' + + ", tittle='" + tittle + '\'' + + ", category='" + category + '\'' + + ", quantity=" + quantity + + '}'; + } +} diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_libraty/models/Issue.java new file mode 100644 index 00000000..ada8df77 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/models/Issue.java @@ -0,0 +1,86 @@ +package com.example.homework_libraty.models; + +import jakarta.persistence.*; + +@Entity +@Table(name = "issues") +public class Issue { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "issue_id") + private int issueId; + + @Column(name = "issue_date") + private String issueDate; + + @Column(name = "return_date") + private String returnDate; + + @Column(name = "issue_book") + private Book issueBook; + + @Column(name = "issue_student") + private Student issueStudent; + + public Issue() { + } + + public Issue(String issueDate, String returnDate, Book issueBook, Student issueStudent) { + this.issueDate = issueDate; + this.returnDate = returnDate; + this.issueBook = issueBook; + this.issueStudent = issueStudent; + } + + public int getIssueId() { + return issueId; + } + + public void setIssueId(int issueId) { + this.issueId = issueId; + } + + public String getIssueDate() { + return issueDate; + } + + public void setIssueDate(String issueDate) { + this.issueDate = issueDate; + } + + public String getReturnDate() { + return returnDate; + } + + public void setReturnDate(String returnDate) { + this.returnDate = returnDate; + } + + public Book getIssueBook() { + return issueBook; + } + + public void setIssueBook(Book issueBook) { + this.issueBook = issueBook; + } + + public Student getIssueStudent() { + return issueStudent; + } + + public void setIssueStudent(Student issueStudent) { + this.issueStudent = issueStudent; + } + + @Override + public String toString() { + return "Issue{" + + "issueId=" + issueId + + ", issueDate='" + issueDate + '\'' + + ", returnDate='" + returnDate + '\'' + + ", issueBook=" + issueBook + + ", issueStudent=" + issueStudent + + '}'; + } +} diff --git a/src/main/java/com/example/homework_libraty/models/Student.java b/src/main/java/com/example/homework_libraty/models/Student.java new file mode 100644 index 00000000..af78eb21 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/models/Student.java @@ -0,0 +1,47 @@ +package com.example.homework_libraty.models; + +import jakarta.persistence.*; + +@Entity +@Table(name = "students") +public class Student { + + @Id + private String usn; + + private String name; + + public Student() { + } + + public Student(String usn, String name) { + this.usn = usn; + this.name = name; + } + + public String getUsn() { + return usn; + } + + public void setUsn(String usn) { + this.usn = usn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Student{" + + "usn='" + usn + '\'' + + ", name='" + name + '\'' + + '}'; + } + + +} diff --git a/src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java b/src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java new file mode 100644 index 00000000..17007b63 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java @@ -0,0 +1,7 @@ +package com.example.homework_libraty.repositories; + +import com.example.homework_libraty.models.Author; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface AuthorRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java new file mode 100644 index 00000000..e1846a95 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -0,0 +1,8 @@ +package com.example.homework_libraty.repositories; + +import com.example.homework_libraty.models.Author; +import com.example.homework_libraty.models.Book; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface BookRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java b/src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java new file mode 100644 index 00000000..f75d0dba --- /dev/null +++ b/src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java @@ -0,0 +1,7 @@ +package com.example.homework_libraty.repositories; + +import com.example.homework_libraty.models.Issue; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface IssuesRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java b/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java new file mode 100644 index 00000000..5912af42 --- /dev/null +++ b/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java @@ -0,0 +1,7 @@ +package com.example.homework_libraty.repositories; + +import com.example.homework_libraty.models.Student; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StudentRepository extends JpaRepository { +} diff --git a/src/test/java/com/example/homework_libraty/models/StudentTest.java b/src/test/java/com/example/homework_libraty/models/StudentTest.java new file mode 100644 index 00000000..e95e434e --- /dev/null +++ b/src/test/java/com/example/homework_libraty/models/StudentTest.java @@ -0,0 +1,25 @@ +package com.example.homework_libraty.models; + +import com.example.homework_libraty.repositories.StudentRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +class StudentTest { + + @Autowired + StudentRepository studentRepository; + + @Test + @DisplayName("Guardo un estudiante en la base de datos") + void saveStudent(){ + Student student = new Student("32e2r4frf", "Victor Sanz"); + + studentRepository.save(student); + } + +} \ No newline at end of file From 06f5f101ad7f02a1133758bc25bb01884aa3a484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 16:49:38 +0200 Subject: [PATCH 03/21] Relaciones establecidas --- .../java/com/example/homework_libraty/models/Author.java | 3 ++- .../java/com/example/homework_libraty/models/Issue.java | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/example/homework_libraty/models/Author.java b/src/main/java/com/example/homework_libraty/models/Author.java index 336a7b33..05152de3 100644 --- a/src/main/java/com/example/homework_libraty/models/Author.java +++ b/src/main/java/com/example/homework_libraty/models/Author.java @@ -17,7 +17,8 @@ public class Author { private String email; - @Column(name = "author_book") + @OneToOne + @JoinColumn(name = "author_book", referencedColumnName = "isbn") private Book authorBook; public Author() { diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_libraty/models/Issue.java index ada8df77..5da02c80 100644 --- a/src/main/java/com/example/homework_libraty/models/Issue.java +++ b/src/main/java/com/example/homework_libraty/models/Issue.java @@ -17,10 +17,12 @@ public class Issue { @Column(name = "return_date") private String returnDate; - @Column(name = "issue_book") + @OneToOne + @JoinColumn(name = "issue_book", referencedColumnName = "isbm") private Book issueBook; - @Column(name = "issue_student") + @OneToOne + @JoinColumn(name = "issue_student", referencedColumnName = "usn") private Student issueStudent; public Issue() { From 65e42f522e24fd8e19f1c766a70565b982f75aec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 16:50:16 +0200 Subject: [PATCH 04/21] Errata corregida --- src/main/java/com/example/homework_libraty/models/Issue.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_libraty/models/Issue.java index 5da02c80..e0311f34 100644 --- a/src/main/java/com/example/homework_libraty/models/Issue.java +++ b/src/main/java/com/example/homework_libraty/models/Issue.java @@ -18,7 +18,7 @@ public class Issue { private String returnDate; @OneToOne - @JoinColumn(name = "issue_book", referencedColumnName = "isbm") + @JoinColumn(name = "issue_book", referencedColumnName = "isbn") private Book issueBook; @OneToOne From c10c8de1dea7ef53d1f82e5097cd0b5d801b9878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 17:25:54 +0200 Subject: [PATCH 05/21] Fallo tecnico ejemplo --- .../homework_libraty/models/Author.java | 10 ++++---- .../models/{Book.java => BookExample.java} | 7 +++--- .../homework_libraty/models/Issue.java | 8 +++--- .../repositories/BookRepository.java | 5 ++-- src/main/resources/application.properties | 6 +++-- .../homework_libraty/models/BookTest.java | 25 +++++++++++++++++++ .../homework_libraty/models/StudentTest.java | 2 +- 7 files changed, 44 insertions(+), 19 deletions(-) rename src/main/java/com/example/homework_libraty/models/{Book.java => BookExample.java} (89%) create mode 100644 src/test/java/com/example/homework_libraty/models/BookTest.java diff --git a/src/main/java/com/example/homework_libraty/models/Author.java b/src/main/java/com/example/homework_libraty/models/Author.java index 05152de3..e748d6d3 100644 --- a/src/main/java/com/example/homework_libraty/models/Author.java +++ b/src/main/java/com/example/homework_libraty/models/Author.java @@ -2,7 +2,7 @@ import jakarta.persistence.*; -import java.awt.print.Book; +//import java.awt.print.Book; @Entity @Table(name = "author") @@ -19,12 +19,12 @@ public class Author { @OneToOne @JoinColumn(name = "author_book", referencedColumnName = "isbn") - private Book authorBook; + private BookExample authorBook; public Author() { } - public Author(String name, String email, Book authorBook) { + public Author(String name, String email, BookExample authorBook) { this.name = name; this.email = email; this.authorBook = authorBook; @@ -54,11 +54,11 @@ public void setEmail(String email) { this.email = email; } - public Book getAuthorBook() { + public BookExample getAuthorBook() { return authorBook; } - public void setAuthorBook(Book authorBook) { + public void setAuthorBook(BookExample authorBook) { this.authorBook = authorBook; } diff --git a/src/main/java/com/example/homework_libraty/models/Book.java b/src/main/java/com/example/homework_libraty/models/BookExample.java similarity index 89% rename from src/main/java/com/example/homework_libraty/models/Book.java rename to src/main/java/com/example/homework_libraty/models/BookExample.java index 416d0488..214c1165 100644 --- a/src/main/java/com/example/homework_libraty/models/Book.java +++ b/src/main/java/com/example/homework_libraty/models/BookExample.java @@ -1,13 +1,12 @@ package com.example.homework_libraty.models; -import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table(name = "books") -public class Book { +public class BookExample { @Id private String isbn; @@ -18,10 +17,10 @@ public class Book { private int quantity; - public Book() { + public BookExample() { } - public Book(String isbn, String tittle, String category, int quantity) { + public BookExample(String isbn, String tittle, String category, int quantity) { this.isbn = isbn; this.tittle = tittle; this.category = category; diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_libraty/models/Issue.java index e0311f34..5be25165 100644 --- a/src/main/java/com/example/homework_libraty/models/Issue.java +++ b/src/main/java/com/example/homework_libraty/models/Issue.java @@ -19,7 +19,7 @@ public class Issue { @OneToOne @JoinColumn(name = "issue_book", referencedColumnName = "isbn") - private Book issueBook; + private BookExample issueBook; @OneToOne @JoinColumn(name = "issue_student", referencedColumnName = "usn") @@ -28,7 +28,7 @@ public class Issue { public Issue() { } - public Issue(String issueDate, String returnDate, Book issueBook, Student issueStudent) { + public Issue(String issueDate, String returnDate, BookExample issueBook, Student issueStudent) { this.issueDate = issueDate; this.returnDate = returnDate; this.issueBook = issueBook; @@ -59,11 +59,11 @@ public void setReturnDate(String returnDate) { this.returnDate = returnDate; } - public Book getIssueBook() { + public BookExample getIssueBook() { return issueBook; } - public void setIssueBook(Book issueBook) { + public void setIssueBook(BookExample issueBook) { this.issueBook = issueBook; } diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index e1846a95..3d39111f 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -1,8 +1,7 @@ package com.example.homework_libraty.repositories; -import com.example.homework_libraty.models.Author; -import com.example.homework_libraty.models.Book; +import com.example.homework_libraty.models.BookExample; import org.springframework.data.jpa.repository.JpaRepository; -public interface BookRepository extends JpaRepository { +public interface BookRepository extends JpaRepository { } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index d84b6b97..d9691582 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,5 +1,7 @@ spring.application.name=homework_libraty -spring.datasource.url=jdbc:mysql://localhost:3306/lab_library?serverTimezone=UTC +spring.datasource.url=jdbc:mysql://localhost:3306/lab_library spring.datasource.username=root spring.datasource.password=admin -spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.ddl-auto=none +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect + diff --git a/src/test/java/com/example/homework_libraty/models/BookTest.java b/src/test/java/com/example/homework_libraty/models/BookTest.java new file mode 100644 index 00000000..e302d0d2 --- /dev/null +++ b/src/test/java/com/example/homework_libraty/models/BookTest.java @@ -0,0 +1,25 @@ +package com.example.homework_libraty.models; + +import com.example.homework_libraty.repositories.BookRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +class BookTest { + + /*@Autowired + BookRepository bookRepository; + + @Test + @DisplayName("Save book") + void saveBook(){ + Book book = new Book("32fs4r", "El señor de los anillos", "accion", 42); + bookRepository.save(book); + + }*/ + +} \ No newline at end of file diff --git a/src/test/java/com/example/homework_libraty/models/StudentTest.java b/src/test/java/com/example/homework_libraty/models/StudentTest.java index e95e434e..caec7664 100644 --- a/src/test/java/com/example/homework_libraty/models/StudentTest.java +++ b/src/test/java/com/example/homework_libraty/models/StudentTest.java @@ -17,7 +17,7 @@ class StudentTest { @Test @DisplayName("Guardo un estudiante en la base de datos") void saveStudent(){ - Student student = new Student("32e2r4frf", "Victor Sanz"); + Student student = new Student("843t", "Daniel"); studentRepository.save(student); } From adcb47db293a36f402b551ac3718c1725e127ba1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 17:28:59 +0200 Subject: [PATCH 06/21] Fallo tecnico resuelto --- .../com/example/homework_libraty/models/Author.java | 10 ++++------ .../models/{BookExample.java => Book.java} | 6 +++--- .../com/example/homework_libraty/models/Issue.java | 8 ++++---- .../homework_libraty/repositories/BookRepository.java | 4 ++-- .../com/example/homework_libraty/models/BookTest.java | 4 ++-- 5 files changed, 15 insertions(+), 17 deletions(-) rename src/main/java/com/example/homework_libraty/models/{BookExample.java => Book.java} (90%) diff --git a/src/main/java/com/example/homework_libraty/models/Author.java b/src/main/java/com/example/homework_libraty/models/Author.java index e748d6d3..cfe8abba 100644 --- a/src/main/java/com/example/homework_libraty/models/Author.java +++ b/src/main/java/com/example/homework_libraty/models/Author.java @@ -2,8 +2,6 @@ import jakarta.persistence.*; -//import java.awt.print.Book; - @Entity @Table(name = "author") public class Author { @@ -19,12 +17,12 @@ public class Author { @OneToOne @JoinColumn(name = "author_book", referencedColumnName = "isbn") - private BookExample authorBook; + private Book authorBook; public Author() { } - public Author(String name, String email, BookExample authorBook) { + public Author(String name, String email, Book authorBook) { this.name = name; this.email = email; this.authorBook = authorBook; @@ -54,11 +52,11 @@ public void setEmail(String email) { this.email = email; } - public BookExample getAuthorBook() { + public Book getAuthorBook() { return authorBook; } - public void setAuthorBook(BookExample authorBook) { + public void setAuthorBook(Book authorBook) { this.authorBook = authorBook; } diff --git a/src/main/java/com/example/homework_libraty/models/BookExample.java b/src/main/java/com/example/homework_libraty/models/Book.java similarity index 90% rename from src/main/java/com/example/homework_libraty/models/BookExample.java rename to src/main/java/com/example/homework_libraty/models/Book.java index 214c1165..a2abcf69 100644 --- a/src/main/java/com/example/homework_libraty/models/BookExample.java +++ b/src/main/java/com/example/homework_libraty/models/Book.java @@ -6,7 +6,7 @@ @Entity @Table(name = "books") -public class BookExample { +public class Book { @Id private String isbn; @@ -17,10 +17,10 @@ public class BookExample { private int quantity; - public BookExample() { + public Book() { } - public BookExample(String isbn, String tittle, String category, int quantity) { + public Book(String isbn, String tittle, String category, int quantity) { this.isbn = isbn; this.tittle = tittle; this.category = category; diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_libraty/models/Issue.java index 5be25165..e0311f34 100644 --- a/src/main/java/com/example/homework_libraty/models/Issue.java +++ b/src/main/java/com/example/homework_libraty/models/Issue.java @@ -19,7 +19,7 @@ public class Issue { @OneToOne @JoinColumn(name = "issue_book", referencedColumnName = "isbn") - private BookExample issueBook; + private Book issueBook; @OneToOne @JoinColumn(name = "issue_student", referencedColumnName = "usn") @@ -28,7 +28,7 @@ public class Issue { public Issue() { } - public Issue(String issueDate, String returnDate, BookExample issueBook, Student issueStudent) { + public Issue(String issueDate, String returnDate, Book issueBook, Student issueStudent) { this.issueDate = issueDate; this.returnDate = returnDate; this.issueBook = issueBook; @@ -59,11 +59,11 @@ public void setReturnDate(String returnDate) { this.returnDate = returnDate; } - public BookExample getIssueBook() { + public Book getIssueBook() { return issueBook; } - public void setIssueBook(BookExample issueBook) { + public void setIssueBook(Book issueBook) { this.issueBook = issueBook; } diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index 3d39111f..28aa2a3d 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -1,7 +1,7 @@ package com.example.homework_libraty.repositories; -import com.example.homework_libraty.models.BookExample; +import com.example.homework_libraty.models.Book; import org.springframework.data.jpa.repository.JpaRepository; -public interface BookRepository extends JpaRepository { +public interface BookRepository extends JpaRepository { } diff --git a/src/test/java/com/example/homework_libraty/models/BookTest.java b/src/test/java/com/example/homework_libraty/models/BookTest.java index e302d0d2..b9c2ee28 100644 --- a/src/test/java/com/example/homework_libraty/models/BookTest.java +++ b/src/test/java/com/example/homework_libraty/models/BookTest.java @@ -11,7 +11,7 @@ @SpringBootTest class BookTest { - /*@Autowired + @Autowired BookRepository bookRepository; @Test @@ -20,6 +20,6 @@ void saveBook(){ Book book = new Book("32fs4r", "El señor de los anillos", "accion", 42); bookRepository.save(book); - }*/ + } } \ No newline at end of file From 41b75b7e98ffe8ec27a920e8b0ab507c79881ce0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 17:37:17 +0200 Subject: [PATCH 07/21] todo message --- .../example/homework_libraty/HomeworkLibratyApplication.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index d625b469..717f8b40 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -6,6 +6,8 @@ @SpringBootApplication public class HomeworkLibratyApplication { + //TODO: implementaciones 3 y 4 de git hub + public static void main(String[] args) { SpringApplication.run(HomeworkLibratyApplication.class, args); } From 007ab79da5ce820e4acb1a9a067d1fb9339d7c68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Tue, 22 Apr 2025 17:56:33 +0200 Subject: [PATCH 08/21] Aplicacion prueba --- .../HomeworkLibratyApplication.java | 160 +++++++++++++++++- .../repositories/BookRepository.java | 4 + src/main/resources/application.properties | 2 +- 3 files changed, 164 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index 717f8b40..80438ad0 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -1,15 +1,173 @@ package com.example.homework_libraty; +import com.example.homework_libraty.models.Author; +import com.example.homework_libraty.models.Book; +import com.example.homework_libraty.repositories.AuthorRepository; +import com.example.homework_libraty.repositories.BookRepository; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +import java.util.NoSuchElementException; +import java.util.Scanner; @SpringBootApplication public class HomeworkLibratyApplication { + @Autowired + private BookRepository bookRepository; + + @Autowired + private AuthorRepository authorRepository; + + // ANSI CODES for colors + public static final String RESET = "\u001B[0m"; + public static final String GREEN = "\u001B[32m"; + public static final String CYAN = "\u001B[36m"; + public static final String YELLOW = "\u001B[33m"; + public static final String RED = "\u001B[31m"; + + private final Scanner scanner = new Scanner(System.in); + + public void addBook() { + System.out.print("Enter the isbn: "); + String isbn = scanner.nextLine().trim(); + if (isbn.isEmpty()) { + throw new IllegalArgumentException("ISBN cannot be empty."); + } + + System.out.print("Enter the title of the book: "); + String title = scanner.nextLine().trim(); + if (title.isEmpty()) { + throw new IllegalArgumentException("Book title cannot be empty."); + } + + System.out.print("Enter the category of the book: "); + String category = scanner.nextLine().trim(); + if (category.isEmpty()) { + throw new IllegalArgumentException("Book category cannot be empty."); + } + + System.out.print("Enter the author of the book: "); + String authorName = scanner.nextLine().trim(); + if (authorName.isEmpty()) { + throw new IllegalArgumentException("Author cannot be empty."); + } + + System.out.print("Enter the mail of the author: "); + String mail = scanner.nextLine().trim(); + if (mail.isEmpty()) { + throw new IllegalArgumentException("Author mail cannot be empty."); + } + + System.out.print("Enter the number of books: "); + int booksNumber = Integer.parseInt(scanner.nextLine().trim()); + if (booksNumber <= 0) { + throw new IllegalArgumentException("Book number cannot be 0 or less."); + } + + Book book = new Book(isbn, title, category, booksNumber); + Author author = new Author(authorName, mail, book); + + bookRepository.save(book); + authorRepository.save(author); + + System.out.println("Record created successfully!"); + } + + public void searchBook() { + System.out.print("Enter the title of the book: "); + String title = scanner.nextLine().trim(); + if (title.isEmpty()) { + throw new IllegalArgumentException("Book title cannot be empty."); + } + + Book book = bookRepository.findByTitle(title); + if (book != null) { + System.out.println("Book found: " + book); + } else { + System.out.println("Book not found."); + } + } + + public void menuDisplay() { + System.out.println(GREEN + "\n======== 📖 Iron Library ========" + RESET); + System.out.println(CYAN + "1. 📕 Add a book" + RESET); + System.out.println(CYAN + "2. 🔎 Search book by title" + RESET); + System.out.println(CYAN + "3. 🗂️ Search book by category" + RESET); + System.out.println(CYAN + "4. 🖋️ Search book by author" + RESET); + System.out.println(CYAN + "5. 📚 List all books along with author" + RESET); + System.out.println(CYAN + "6. 🎓 Issue book to student" + RESET); + System.out.println(CYAN + "7. 🆔 List books by USN" + RESET); + System.out.println(GREEN + "---------------------------------" + RESET); + System.out.println(RED + "8. 🚪 Exit" + RESET); + System.out.println(GREEN + "=================================" + RESET); + System.out.print("Choose an option: "); + } + + public void runMenu() { + boolean running = true; + + while (running) { + try { + menuDisplay(); + String option = scanner.nextLine(); + + switch (option) { + case "1": + addBook(); + break; + case "2": + searchBook(); + break; + case "3": + // TODO + break; + case "4": + // TODO + break; + case "5": + // TODO + break; + case "6": + // TODO + break; + case "7": + // TODO + break; + case "8", "exit": + running = false; + break; + default: + System.out.println("Invalid option. Please try again."); + } + } catch (IllegalArgumentException e) { + System.out.println("Incorrect argument: " + e.getMessage()); + } catch (NoSuchElementException e) { + System.out.println("Element not found: " + e.getMessage()); + } catch (Exception e) { + System.out.println("An unexpected error occurred: " + e.getMessage()); + } + } + + scanner.close(); + } + //TODO: implementaciones 3 y 4 de git hub public static void main(String[] args) { - SpringApplication.run(HomeworkLibratyApplication.class, args); + + // Run the Spring Boot application + ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibratyApplication.class, args); + + // Get the IronlibraryApplication bean from the context + HomeworkLibratyApplication app = context.getBean(HomeworkLibratyApplication.class); + + app.runMenu(); + + // Close the application context + SpringApplication.exit(context); } } diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index 28aa2a3d..360a9c9c 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -2,6 +2,10 @@ import com.example.homework_libraty.models.Book; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +@Repository public interface BookRepository extends JpaRepository { + + Book findByTitle(String tittle); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index d9691582..02e7fc6a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,6 +2,6 @@ spring.application.name=homework_libraty spring.datasource.url=jdbc:mysql://localhost:3306/lab_library spring.datasource.username=root spring.datasource.password=admin -spring.jpa.hibernate.ddl-auto=none +spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect From 073c29c7c5fa81f44ce3c2f6f616ab4d37e67965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 12:16:50 +0200 Subject: [PATCH 09/21] =?UTF-8?q?git=20example=20a=C3=B1adido?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 ++ src/main/resources/application.properties.example | 6 ++++++ 2 files changed, 8 insertions(+) create mode 100644 src/main/resources/application.properties.example diff --git a/.gitignore b/.gitignore index b6a95e78..1d249e99 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,5 @@ build/ ### VS Code ### .vscode/ +application.properties + diff --git a/src/main/resources/application.properties.example b/src/main/resources/application.properties.example new file mode 100644 index 00000000..64ae825d --- /dev/null +++ b/src/main/resources/application.properties.example @@ -0,0 +1,6 @@ +spring.application.name=myNameExample +spring.datasource.url=jdbc:mysql://localhost:3306/myDatabaseExample +spring.datasource.username=myUser +spring.datasource.password=myPassword +spring.jpa.hibernate.ddl-auto=validate +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect \ No newline at end of file From 4eb20de6f0ce155e8573fc194ac84b600fc0c199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 12:28:20 +0200 Subject: [PATCH 10/21] Prueba bases de datos remota --- pom.xml | 16 ++++-- .../homework_libraty/models/Author.java | 35 ++++++------ .../example/homework_libraty/models/Book.java | 41 +++++++------ .../homework_libraty/models/Issue.java | 57 ++++++++++--------- .../homework_libraty/models/Student.java | 30 +++++----- src/main/resources/application.properties | 11 ++-- 6 files changed, 103 insertions(+), 87 deletions(-) diff --git a/pom.xml b/pom.xml index 97a955f9..d184802e 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.springframework.boot @@ -9,10 +9,10 @@ com.example - homework_libraty + ironlibrary 0.0.1-SNAPSHOT - homework_libraty - Demo project for Spring Boot + ironlibrary + Library Management System @@ -49,6 +49,12 @@ spring-boot-starter-test test + + org.mariadb.jdbc + mariadb-java-client + 3.3.1 + + @@ -60,4 +66,4 @@ - + \ No newline at end of file diff --git a/src/main/java/com/example/homework_libraty/models/Author.java b/src/main/java/com/example/homework_libraty/models/Author.java index cfe8abba..1cc38146 100644 --- a/src/main/java/com/example/homework_libraty/models/Author.java +++ b/src/main/java/com/example/homework_libraty/models/Author.java @@ -7,12 +7,13 @@ public class Author { @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "author_id") - private int id; + @GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY) + private int authorId; + @Column(name = "name") private String name; + @Column(name = "email") private String email; @OneToOne @@ -23,17 +24,17 @@ public Author() { } public Author(String name, String email, Book authorBook) { - this.name = name; - this.email = email; - this.authorBook = authorBook; + setName(name); + setEmail(email); + setAuthorBook(authorBook); } - public int getId() { - return id; + public int getAuthorId() { + return authorId; } - public void setId(int id) { - this.id = id; + public void setAuthorId(int authorId) { + this.authorId = authorId; } public String getName() { @@ -62,11 +63,11 @@ public void setAuthorBook(Book authorBook) { @Override public String toString() { - return "Author{" + - "id=" + id + - ", name='" + name + '\'' + - ", email='" + email + '\'' + - ", authorBook=" + authorBook + - '}'; + return "Author {\n" + + " authorId=" + authorId + ",\n" + + " name='" + name + "',\n" + + " email='" + email + "',\n" + + " authorBook=" + authorBook + "\n" + + "}"; } -} +} \ No newline at end of file diff --git a/src/main/java/com/example/homework_libraty/models/Book.java b/src/main/java/com/example/homework_libraty/models/Book.java index a2abcf69..a80fccf4 100644 --- a/src/main/java/com/example/homework_libraty/models/Book.java +++ b/src/main/java/com/example/homework_libraty/models/Book.java @@ -1,30 +1,35 @@ package com.example.homework_libraty.models; +import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity -@Table(name = "books") +@Table(name = "book") public class Book { @Id private String isbn; - private String tittle; + @Column(name = "title") + private String title; + @Column(name = "category") private String category; + @Column(name = "quantity") private int quantity; public Book() { + } - public Book(String isbn, String tittle, String category, int quantity) { - this.isbn = isbn; - this.tittle = tittle; - this.category = category; - this.quantity = quantity; + public Book(String isbn, String title, String category, int quantity) { + setIsbn(isbn); + setTitle(title); + setCategory(category); + setQuantity(quantity); } public String getIsbn() { @@ -35,12 +40,12 @@ public void setIsbn(String isbn) { this.isbn = isbn; } - public String getTittle() { - return tittle; + public String getTitle() { + return title; } - public void setTittle(String tittle) { - this.tittle = tittle; + public void setTitle(String title) { + this.title = title; } public String getCategory() { @@ -61,11 +66,11 @@ public void setQuantity(int quantity) { @Override public String toString() { - return "Book{" + - "isbn='" + isbn + '\'' + - ", tittle='" + tittle + '\'' + - ", category='" + category + '\'' + - ", quantity=" + quantity + - '}'; + return "Book {\n" + + " isbn='" + isbn + "',\n" + + " title='" + title + "',\n" + + " category='" + category + "',\n" + + " quantity=" + quantity + "\n" + + "}"; } -} +} \ No newline at end of file diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_libraty/models/Issue.java index e0311f34..09c16fdc 100644 --- a/src/main/java/com/example/homework_libraty/models/Issue.java +++ b/src/main/java/com/example/homework_libraty/models/Issue.java @@ -2,13 +2,14 @@ import jakarta.persistence.*; +import jakarta.persistence.*; + @Entity -@Table(name = "issues") +@Table(name = "issue") public class Issue { @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "issue_id") + @GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY) private int issueId; @Column(name = "issue_date") @@ -17,22 +18,22 @@ public class Issue { @Column(name = "return_date") private String returnDate; - @OneToOne - @JoinColumn(name = "issue_book", referencedColumnName = "isbn") - private Book issueBook; - @OneToOne @JoinColumn(name = "issue_student", referencedColumnName = "usn") private Student issueStudent; + @OneToOne + @JoinColumn(name = "issue_book", referencedColumnName = "isbn") + private Book issueBook; + public Issue() { } - public Issue(String issueDate, String returnDate, Book issueBook, Student issueStudent) { - this.issueDate = issueDate; - this.returnDate = returnDate; - this.issueBook = issueBook; - this.issueStudent = issueStudent; + public Issue(String issueDate, String returnDate, Student issueStudent, Book issueBook) { + setIssueDate(issueDate); + setReturnDate(returnDate); + setIssueStudent(issueStudent); + setIssueBook(issueBook); } public int getIssueId() { @@ -59,14 +60,6 @@ public void setReturnDate(String returnDate) { this.returnDate = returnDate; } - public Book getIssueBook() { - return issueBook; - } - - public void setIssueBook(Book issueBook) { - this.issueBook = issueBook; - } - public Student getIssueStudent() { return issueStudent; } @@ -75,14 +68,22 @@ public void setIssueStudent(Student issueStudent) { this.issueStudent = issueStudent; } + public Book getIssueBook() { + return issueBook; + } + + public void setIssueBook(Book issueBook) { + this.issueBook = issueBook; + } + @Override public String toString() { - return "Issue{" + - "issueId=" + issueId + - ", issueDate='" + issueDate + '\'' + - ", returnDate='" + returnDate + '\'' + - ", issueBook=" + issueBook + - ", issueStudent=" + issueStudent + - '}'; + return "Issue {\n" + + " issueId=" + issueId + ",\n" + + " issueDate='" + issueDate + "',\n" + + " returnDate='" + returnDate + "',\n" + + " issueStudent=" + issueStudent + ",\n" + + " issueBook=" + issueBook + "\n" + + "}"; } -} +} \ No newline at end of file diff --git a/src/main/java/com/example/homework_libraty/models/Student.java b/src/main/java/com/example/homework_libraty/models/Student.java index af78eb21..d2b4b197 100644 --- a/src/main/java/com/example/homework_libraty/models/Student.java +++ b/src/main/java/com/example/homework_libraty/models/Student.java @@ -1,28 +1,32 @@ package com.example.homework_libraty.models; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity -@Table(name = "students") +@Table(name = "student") public class Student { @Id private String usn; + @Column(name = "name") private String name; public Student() { } - public Student(String usn, String name) { - this.usn = usn; - this.name = name; - } - public String getUsn() { return usn; } + public Student(String usn, String name) { + setUsn(usn); + setName(name); + } + public void setUsn(String usn) { this.usn = usn; } @@ -37,11 +41,9 @@ public void setName(String name) { @Override public String toString() { - return "Student{" + - "usn='" + usn + '\'' + - ", name='" + name + '\'' + - '}'; + return "Student {\n" + + " usn='" + usn + "',\n" + + " name='" + name + "'\n" + + "}"; } - - -} +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 02e7fc6a..755d30cd 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,7 +1,8 @@ -spring.application.name=homework_libraty -spring.datasource.url=jdbc:mysql://localhost:3306/lab_library -spring.datasource.username=root -spring.datasource.password=admin +spring.application.name=ironlibrary spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect +spring.datasource.url=jdbc:mariadb://tommy.heliohost.org:3306/dsuarezg_ironhack +spring.datasource.username=dsuarezg_ironhack +spring.datasource.password=ironlibrary From a4e91046787ec9016d489015f93b5bab4ac5a56d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 12:48:30 +0200 Subject: [PATCH 11/21] =?UTF-8?q?Funcionalidades=20Daniel=20Suarez=20a?= =?UTF-8?q?=C3=B1adidas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../HomeworkLibratyApplication.java | 26 +++++++++++++++++-- .../repositories/BookRepository.java | 4 +++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index 80438ad0..6783582c 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -9,6 +9,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; +import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; @@ -122,7 +123,7 @@ public void runMenu() { searchBook(); break; case "3": - // TODO + searchBookByCategory(); break; case "4": // TODO @@ -154,7 +155,28 @@ public void runMenu() { scanner.close(); } - //TODO: implementaciones 3 y 4 de git hub + public void searchBookByCategory() { + List books; + System.out.print("Enter the category of the book: "); + String category = scanner.nextLine().trim(); + if (category.isEmpty()) { + throw new IllegalArgumentException("Book category cannot be empty."); + } + + books = bookRepository.findByCategory(category); + if (!books.isEmpty()) { + System.out.println("Books found in category " + category + ":"); + for (Book book : books) { + System.out.println(book); + } + } else { + System.out.println("Book category not found."); + } + } + + + + //TODO: hacer el 5 (List all books along with author) y la 7 (List all books along with author) public static void main(String[] args) { diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index 360a9c9c..c8b8a6c7 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -4,8 +4,12 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.util.List; + @Repository public interface BookRepository extends JpaRepository { Book findByTitle(String tittle); + + List findByCategory(String category); } From 60f9caf853897b0d96a5bd7d08f7fc73864ab8a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 12:54:50 +0200 Subject: [PATCH 12/21] Errata corregida en el parametro title de BookRepository --- .../example/homework_libraty/HomeworkLibratyApplication.java | 2 ++ .../example/homework_libraty/repositories/BookRepository.java | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index 6783582c..1ade21f8 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -176,6 +176,8 @@ public void searchBookByCategory() { + + //TODO: hacer el 5 (List all books along with author) y la 7 (List all books along with author) public static void main(String[] args) { diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index c8b8a6c7..de393836 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -9,7 +9,8 @@ @Repository public interface BookRepository extends JpaRepository { - Book findByTitle(String tittle); + Book findByTitle(String title); List findByCategory(String category); + } From 2b24d845afd09d34e4e49434adc424ee502c4959 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 15:46:07 +0200 Subject: [PATCH 13/21] busqueda libros realizada --- .../HomeworkLibratyApplication.java | 411 ++++++++++-------- .../repositories/BookRepository.java | 4 + .../repositories/StudentRepository.java | 2 + .../homework_libraty/models/BookTest.java | 13 + 4 files changed, 249 insertions(+), 181 deletions(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index 1ade21f8..513ee1fe 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -1,9 +1,7 @@ package com.example.homework_libraty; -import com.example.homework_libraty.models.Author; -import com.example.homework_libraty.models.Book; -import com.example.homework_libraty.repositories.AuthorRepository; -import com.example.homework_libraty.repositories.BookRepository; +import com.example.homework_libraty.models.*; +import com.example.homework_libraty.repositories.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -16,182 +14,233 @@ @SpringBootApplication public class HomeworkLibratyApplication { - @Autowired - private BookRepository bookRepository; - - @Autowired - private AuthorRepository authorRepository; - - // ANSI CODES for colors - public static final String RESET = "\u001B[0m"; - public static final String GREEN = "\u001B[32m"; - public static final String CYAN = "\u001B[36m"; - public static final String YELLOW = "\u001B[33m"; - public static final String RED = "\u001B[31m"; - - private final Scanner scanner = new Scanner(System.in); - - public void addBook() { - System.out.print("Enter the isbn: "); - String isbn = scanner.nextLine().trim(); - if (isbn.isEmpty()) { - throw new IllegalArgumentException("ISBN cannot be empty."); - } - - System.out.print("Enter the title of the book: "); - String title = scanner.nextLine().trim(); - if (title.isEmpty()) { - throw new IllegalArgumentException("Book title cannot be empty."); - } - - System.out.print("Enter the category of the book: "); - String category = scanner.nextLine().trim(); - if (category.isEmpty()) { - throw new IllegalArgumentException("Book category cannot be empty."); - } - - System.out.print("Enter the author of the book: "); - String authorName = scanner.nextLine().trim(); - if (authorName.isEmpty()) { - throw new IllegalArgumentException("Author cannot be empty."); - } - - System.out.print("Enter the mail of the author: "); - String mail = scanner.nextLine().trim(); - if (mail.isEmpty()) { - throw new IllegalArgumentException("Author mail cannot be empty."); - } - - System.out.print("Enter the number of books: "); - int booksNumber = Integer.parseInt(scanner.nextLine().trim()); - if (booksNumber <= 0) { - throw new IllegalArgumentException("Book number cannot be 0 or less."); - } - - Book book = new Book(isbn, title, category, booksNumber); - Author author = new Author(authorName, mail, book); - - bookRepository.save(book); - authorRepository.save(author); - - System.out.println("Record created successfully!"); - } - - public void searchBook() { - System.out.print("Enter the title of the book: "); - String title = scanner.nextLine().trim(); - if (title.isEmpty()) { - throw new IllegalArgumentException("Book title cannot be empty."); - } - - Book book = bookRepository.findByTitle(title); - if (book != null) { - System.out.println("Book found: " + book); - } else { - System.out.println("Book not found."); - } - } - - public void menuDisplay() { - System.out.println(GREEN + "\n======== 📖 Iron Library ========" + RESET); - System.out.println(CYAN + "1. 📕 Add a book" + RESET); - System.out.println(CYAN + "2. 🔎 Search book by title" + RESET); - System.out.println(CYAN + "3. 🗂️ Search book by category" + RESET); - System.out.println(CYAN + "4. 🖋️ Search book by author" + RESET); - System.out.println(CYAN + "5. 📚 List all books along with author" + RESET); - System.out.println(CYAN + "6. 🎓 Issue book to student" + RESET); - System.out.println(CYAN + "7. 🆔 List books by USN" + RESET); - System.out.println(GREEN + "---------------------------------" + RESET); - System.out.println(RED + "8. 🚪 Exit" + RESET); - System.out.println(GREEN + "=================================" + RESET); - System.out.print("Choose an option: "); - } - - public void runMenu() { - boolean running = true; - - while (running) { - try { - menuDisplay(); - String option = scanner.nextLine(); - - switch (option) { - case "1": - addBook(); - break; - case "2": - searchBook(); - break; - case "3": - searchBookByCategory(); - break; - case "4": - // TODO - break; - case "5": - // TODO - break; - case "6": - // TODO - break; - case "7": - // TODO - break; - case "8", "exit": - running = false; - break; - default: - System.out.println("Invalid option. Please try again."); - } - } catch (IllegalArgumentException e) { - System.out.println("Incorrect argument: " + e.getMessage()); - } catch (NoSuchElementException e) { - System.out.println("Element not found: " + e.getMessage()); - } catch (Exception e) { - System.out.println("An unexpected error occurred: " + e.getMessage()); - } - } - - scanner.close(); - } - - public void searchBookByCategory() { - List books; - System.out.print("Enter the category of the book: "); - String category = scanner.nextLine().trim(); - if (category.isEmpty()) { - throw new IllegalArgumentException("Book category cannot be empty."); - } - - books = bookRepository.findByCategory(category); - if (!books.isEmpty()) { - System.out.println("Books found in category " + category + ":"); - for (Book book : books) { - System.out.println(book); - } - } else { - System.out.println("Book category not found."); - } - } - - - - - - //TODO: hacer el 5 (List all books along with author) y la 7 (List all books along with author) - - public static void main(String[] args) { - - // Run the Spring Boot application - ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibratyApplication.class, args); - - // Get the IronlibraryApplication bean from the context - HomeworkLibratyApplication app = context.getBean(HomeworkLibratyApplication.class); - - app.runMenu(); - - // Close the application context - SpringApplication.exit(context); - } + @Autowired + private BookRepository bookRepository; + + @Autowired + private AuthorRepository authorRepository; + + @Autowired + private StudentRepository studentRepository; + + @Autowired + private IssuesRepository issuesRepository; + + // ANSI CODES for colors + public static final String RESET = "\u001B[0m"; + public static final String GREEN = "\u001B[32m"; + public static final String CYAN = "\u001B[36m"; + public static final String YELLOW = "\u001B[33m"; + public static final String RED = "\u001B[31m"; + + private final Scanner scanner = new Scanner(System.in); + + public void addBook() { + System.out.print("Enter the isbn: "); + String isbn = scanner.nextLine().trim(); + if (isbn.isEmpty()) { + throw new IllegalArgumentException("ISBN cannot be empty."); + } + + System.out.print("Enter the title of the book: "); + String title = scanner.nextLine().trim(); + if (title.isEmpty()) { + throw new IllegalArgumentException("Book title cannot be empty."); + } + + System.out.print("Enter the category of the book: "); + String category = scanner.nextLine().trim(); + if (category.isEmpty()) { + throw new IllegalArgumentException("Book category cannot be empty."); + } + + System.out.print("Enter the author of the book: "); + String authorName = scanner.nextLine().trim(); + if (authorName.isEmpty()) { + throw new IllegalArgumentException("Author cannot be empty."); + } + + System.out.print("Enter the mail of the author: "); + String mail = scanner.nextLine().trim(); + if (mail.isEmpty()) { + throw new IllegalArgumentException("Author mail cannot be empty."); + } + + System.out.print("Enter the number of books: "); + int booksNumber = Integer.parseInt(scanner.nextLine().trim()); + if (booksNumber <= 0) { + throw new IllegalArgumentException("Book number cannot be 0 or less."); + } + + Book book = new Book(isbn, title, category, booksNumber); + Author author = new Author(authorName, mail, book); + + bookRepository.save(book); + authorRepository.save(author); + + System.out.println("Record created successfully!"); + } + + public void searchBook() { + System.out.print("Enter the title of the book: "); + String title = scanner.nextLine().trim(); + if (title.isEmpty()) { + throw new IllegalArgumentException("Book title cannot be empty."); + } + + Book book = bookRepository.findByTitle(title); + if (book != null) { + System.out.println("Book found: " + book); + } else { + System.out.println("Book not found."); + } + } + + public void issueBook() { + System.out.print("Enter the title of the book: "); + String title = scanner.nextLine().trim(); + if (title.isEmpty()) { + throw new IllegalArgumentException("Book title cannot be empty."); + } + + Book book = bookRepository.findByTitle(title); + if (book != null) { + System.out.println("Book found: " + book); + } else { + System.out.println("Book not found."); + } + System.out.print("Enter student name: "); + String studentName = scanner.nextLine().trim(); + if (studentName.isEmpty()) { + throw new IllegalArgumentException("Book title cannot be empty."); + } + Student student = studentRepository.findByName(studentName); + Issue issue = new Issue("23-05-2025", "15-05-2025", student, book); + //String issueDate, String returnDate, Student issueStudent, Book issueBook + issuesRepository.save(issue); + + } + + + public void listAllBooks() { + + + List allBooks = bookRepository.findAllBooksAndAuthors(); // Devuelve una lista de objetos Book + + System.out.println("==========================================================="); + System.out.printf("%-20s %-20s %-15s %-15s%n", + "Book ISBN", "Book Title", "Category", "Quantity"); + System.out.println("==========================================================="); + + for (Book book : allBooks) { + System.out.printf("%-20s %-20s %-15s %-15d%n", + book.getIsbn(), book.getTitle(), book.getCategory(), book.getQuantity()); + } + + System.out.println("==========================================================="); + + + } + + + + public void menuDisplay() { + System.out.println(GREEN + "\n======== 📖 Iron Library ========" + RESET); + System.out.println(CYAN + "1. 📕 Add a book" + RESET); + System.out.println(CYAN + "2. 🔎 Search book by title" + RESET); + System.out.println(CYAN + "3. 🗂️ Search book by category" + RESET); + System.out.println(CYAN + "4. 🖋️ Search book by author" + RESET); + System.out.println(CYAN + "5. 📚 List all books along with author" + RESET); + System.out.println(CYAN + "6. 🎓 Issue book to student" + RESET); + System.out.println(CYAN + "7. 🆔 List books by USN" + RESET); + System.out.println(GREEN + "---------------------------------" + RESET); + System.out.println(RED + "8. 🚪 Exit" + RESET); + System.out.println(GREEN + "=================================" + RESET); + System.out.print("Choose an option: "); + } + + public void runMenu() { + boolean running = true; + + while (running) { + try { + menuDisplay(); + String option = scanner.nextLine(); + + switch (option) { + case "1": + addBook(); + break; + case "2": + searchBook(); + break; + case "3": + searchBookByCategory(); + break; + case "4": + // TODO + break; + case "5": + listAllBooks(); + break; + case "6": + issueBook(); + break; + case "7": + // TODO + break; + case "8", "exit": + running = false; + break; + default: + System.out.println("Invalid option. Please try again."); + } + } catch (IllegalArgumentException e) { + System.out.println("Incorrect argument: " + e.getMessage()); + } catch (NoSuchElementException e) { + System.out.println("Element not found: " + e.getMessage()); + } catch (Exception e) { + System.out.println("An unexpected error occurred: " + e.getMessage()); + } + } + + scanner.close(); + } + + public void searchBookByCategory() { + List books; + System.out.print("Enter the category of the book: "); + String category = scanner.nextLine().trim(); + if (category.isEmpty()) { + throw new IllegalArgumentException("Book category cannot be empty."); + } + + books = bookRepository.findByCategory(category); + if (!books.isEmpty()) { + System.out.println("Books found in category " + category + ":"); + for (Book book : books) { + System.out.println(book); + } + } else { + System.out.println("Book category not found."); + } + } + + + //TODO: hacer el 5 (List all books along with author) y la 7 (List all books along with author) + + public static void main(String[] args) { + + // Run the Spring Boot application + ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibratyApplication.class, args); + + // Get the IronlibraryApplication bean from the context + HomeworkLibratyApplication app = context.getBean(HomeworkLibratyApplication.class); + + app.runMenu(); + + // Close the application context + SpringApplication.exit(context); + } } diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index de393836..b2c2c149 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -2,6 +2,7 @@ import com.example.homework_libraty.models.Book; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @@ -13,4 +14,7 @@ public interface BookRepository extends JpaRepository { List findByCategory(String category); + @Query("SELECT b FROM Book b") + List findAllBooksAndAuthors(); + } diff --git a/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java b/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java index 5912af42..153fedcd 100644 --- a/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java @@ -4,4 +4,6 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository { + + Student findByName(String studentName); } diff --git a/src/test/java/com/example/homework_libraty/models/BookTest.java b/src/test/java/com/example/homework_libraty/models/BookTest.java index b9c2ee28..e19d38a0 100644 --- a/src/test/java/com/example/homework_libraty/models/BookTest.java +++ b/src/test/java/com/example/homework_libraty/models/BookTest.java @@ -6,6 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import java.util.List; + import static org.junit.jupiter.api.Assertions.*; @SpringBootTest @@ -22,4 +24,15 @@ void saveBook(){ } + @Test + @DisplayName("Buscar todos los libros") + void listAllBooks(){ + List allBooks = bookRepository.findAllBooksAndAuthors(); + + System.out.println("============================"); + System.out.println("Los libros que hemos encontrado son: "); + System.out.println(allBooks); + System.out.println("==================="); + } + } \ No newline at end of file From 93ba2fca1f6138a6635a923f30276ad24830e143 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 16:02:50 +0200 Subject: [PATCH 14/21] metodos auxiliares para formatear realizados --- .../HomeworkLibratyApplication.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index 513ee1fe..fd064c20 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -7,6 +7,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; @@ -96,6 +98,7 @@ public void searchBook() { } } + //daniM entregar libro public void issueBook() { System.out.print("Enter the title of the book: "); String title = scanner.nextLine().trim(); @@ -115,11 +118,24 @@ public void issueBook() { throw new IllegalArgumentException("Book title cannot be empty."); } Student student = studentRepository.findByName(studentName); - Issue issue = new Issue("23-05-2025", "15-05-2025", student, book); + + Issue issue = new Issue(getDate(), getExpiredDate(), student, book); //String issueDate, String returnDate, Student issueStudent, Book issueBook issuesRepository.save(issue); } + public String getDate(){ + LocalDate actualDate = LocalDate.now(); + DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-mm-aa"); + String dateString = actualDate.format(formatter); + return dateString; + } + public String getExpiredDate(){ + LocalDate actualDate = LocalDate.now(); + LocalDate datePlusWeek=actualDate.plusWeeks(1); + DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-mm-dd"); + return datePlusWeek.format(formatter); + } public void listAllBooks() { From 2d27e9e516377e6cc963a2f7e7c464a619c5762f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 17:02:10 +0200 Subject: [PATCH 15/21] Funcionalidades mejoradas --- .../HomeworkLibratyApplication.java | 39 ++++++++++++------- .../repositories/BookRepository.java | 4 ++ 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index fd064c20..be39fe09 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -100,28 +100,36 @@ public void searchBook() { //daniM entregar libro public void issueBook() { - System.out.print("Enter the title of the book: "); - String title = scanner.nextLine().trim(); - if (title.isEmpty()) { - throw new IllegalArgumentException("Book title cannot be empty."); + System.out.print("Enter usn: "); + String usn = scanner.nextLine().trim(); + if (usn.isEmpty()) { + throw new IllegalArgumentException("usn cannot be empty."); } + //Student student = studentRepository.findByName(usn); - Book book = bookRepository.findByTitle(title); - if (book != null) { - System.out.println("Book found: " + book); + System.out.print("Enter name: "); + String name = scanner.nextLine().trim(); + if (name.isEmpty()) { + throw new IllegalArgumentException("name cannot be empty."); + } + Student student = studentRepository.findByName(name); + + + + System.out.print("Enter ISBN: "); + String isbn = scanner.nextLine().trim(); + if (isbn.isEmpty()) { + System.out.println("Book found: " + isbn); } else { System.out.println("Book not found."); } - System.out.print("Enter student name: "); - String studentName = scanner.nextLine().trim(); - if (studentName.isEmpty()) { - throw new IllegalArgumentException("Book title cannot be empty."); - } - Student student = studentRepository.findByName(studentName); + Book book = bookRepository.findByIsbn(isbn); Issue issue = new Issue(getDate(), getExpiredDate(), student, book); //String issueDate, String returnDate, Student issueStudent, Book issueBook + issuesRepository.save(issue); + System.out.println("Book issued. Return date" + getExpiredDate()); } public String getDate(){ @@ -133,8 +141,9 @@ public String getDate(){ public String getExpiredDate(){ LocalDate actualDate = LocalDate.now(); LocalDate datePlusWeek=actualDate.plusWeeks(1); - DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-mm-dd"); - return datePlusWeek.format(formatter); + //DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-mm-dd"); + //return datePlusWeek.format(formatter); + return datePlusWeek.toString(); } diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java index b2c2c149..5338742d 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_libraty/repositories/BookRepository.java @@ -17,4 +17,8 @@ public interface BookRepository extends JpaRepository { @Query("SELECT b FROM Book b") List findAllBooksAndAuthors(); + Book findByIsbn(String isbn); + + + } From fd264bc129f0a215172b576a175fbeeafce48823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Sanz?= Date: Wed, 23 Apr 2025 17:06:08 +0200 Subject: [PATCH 16/21] Salida formateada --- .../example/homework_libraty/HomeworkLibratyApplication.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java index be39fe09..fd6c3fa0 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java @@ -153,12 +153,12 @@ public void listAllBooks() { List allBooks = bookRepository.findAllBooksAndAuthors(); // Devuelve una lista de objetos Book System.out.println("==========================================================="); - System.out.printf("%-20s %-20s %-15s %-15s%n", + System.out.printf("%-25s %-30s %-20s %-10s%n", "Book ISBN", "Book Title", "Category", "Quantity"); System.out.println("==========================================================="); for (Book book : allBooks) { - System.out.printf("%-20s %-20s %-15s %-15d%n", + System.out.printf("%-25s %-30s %-20s %-10d%n", book.getIsbn(), book.getTitle(), book.getCategory(), book.getQuantity()); } From b06b90ef8e1a62db2108f00c60424e87efb8b547 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Su=C3=A1rez=20Garc=C3=ADa?= Date: Wed, 23 Apr 2025 17:40:46 +0200 Subject: [PATCH 17/21] Refactor Name --- .../HomeworkLibraryApplication.java} | 12 ++++++------ .../models/Author.java | 2 +- .../models/Book.java | 2 +- .../models/Issue.java | 4 +--- .../models/Student.java | 2 +- .../repositories/AuthorRepository.java | 4 ++-- .../repositories/BookRepository.java | 4 ++-- .../repositories/IssuesRepository.java | 4 ++-- .../repositories/StudentRepository.java | 4 ++-- .../HomeworkLibraryApplicationTests.java} | 4 ++-- .../models/BookTest.java | 6 ++---- .../models/StudentTest.java | 6 ++---- 12 files changed, 24 insertions(+), 30 deletions(-) rename src/main/java/com/example/{homework_libraty/HomeworkLibratyApplication.java => homework_library/HomeworkLibraryApplication.java} (96%) rename src/main/java/com/example/{homework_libraty => homework_library}/models/Author.java (97%) rename src/main/java/com/example/{homework_libraty => homework_library}/models/Book.java (97%) rename src/main/java/com/example/{homework_libraty => homework_library}/models/Issue.java (96%) rename src/main/java/com/example/{homework_libraty => homework_library}/models/Student.java (95%) rename src/main/java/com/example/{homework_libraty => homework_library}/repositories/AuthorRepository.java (58%) rename src/main/java/com/example/{homework_libraty => homework_library}/repositories/BookRepository.java (82%) rename src/main/java/com/example/{homework_libraty => homework_library}/repositories/IssuesRepository.java (58%) rename src/main/java/com/example/{homework_libraty => homework_library}/repositories/StudentRepository.java (64%) rename src/test/java/com/example/{homework_libraty/HomeworkLibratyApplicationTests.java => homework_library/HomeworkLibraryApplicationTests.java} (65%) rename src/test/java/com/example/{homework_libraty => homework_library}/models/BookTest.java (84%) rename src/test/java/com/example/{homework_libraty => homework_library}/models/StudentTest.java (75%) diff --git a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java similarity index 96% rename from src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java rename to src/main/java/com/example/homework_library/HomeworkLibraryApplication.java index fd6c3fa0..575596c4 100644 --- a/src/main/java/com/example/homework_libraty/HomeworkLibratyApplication.java +++ b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java @@ -1,7 +1,7 @@ -package com.example.homework_libraty; +package com.example.homework_library; -import com.example.homework_libraty.models.*; -import com.example.homework_libraty.repositories.*; +import com.example.homework_library.models.*; +import com.example.homework_library.repositories.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -14,7 +14,7 @@ import java.util.Scanner; @SpringBootApplication -public class HomeworkLibratyApplication { +public class HomeworkLibraryApplication { @Autowired private BookRepository bookRepository; @@ -257,10 +257,10 @@ public void searchBookByCategory() { public static void main(String[] args) { // Run the Spring Boot application - ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibratyApplication.class, args); + ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibraryApplication.class, args); // Get the IronlibraryApplication bean from the context - HomeworkLibratyApplication app = context.getBean(HomeworkLibratyApplication.class); + HomeworkLibraryApplication app = context.getBean(HomeworkLibraryApplication.class); app.runMenu(); diff --git a/src/main/java/com/example/homework_libraty/models/Author.java b/src/main/java/com/example/homework_library/models/Author.java similarity index 97% rename from src/main/java/com/example/homework_libraty/models/Author.java rename to src/main/java/com/example/homework_library/models/Author.java index 1cc38146..2a8d50a5 100644 --- a/src/main/java/com/example/homework_libraty/models/Author.java +++ b/src/main/java/com/example/homework_library/models/Author.java @@ -1,4 +1,4 @@ -package com.example.homework_libraty.models; +package com.example.homework_library.models; import jakarta.persistence.*; diff --git a/src/main/java/com/example/homework_libraty/models/Book.java b/src/main/java/com/example/homework_library/models/Book.java similarity index 97% rename from src/main/java/com/example/homework_libraty/models/Book.java rename to src/main/java/com/example/homework_library/models/Book.java index a80fccf4..8d3b4a46 100644 --- a/src/main/java/com/example/homework_libraty/models/Book.java +++ b/src/main/java/com/example/homework_library/models/Book.java @@ -1,4 +1,4 @@ -package com.example.homework_libraty.models; +package com.example.homework_library.models; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/src/main/java/com/example/homework_libraty/models/Issue.java b/src/main/java/com/example/homework_library/models/Issue.java similarity index 96% rename from src/main/java/com/example/homework_libraty/models/Issue.java rename to src/main/java/com/example/homework_library/models/Issue.java index 09c16fdc..a67b14c5 100644 --- a/src/main/java/com/example/homework_libraty/models/Issue.java +++ b/src/main/java/com/example/homework_library/models/Issue.java @@ -1,6 +1,4 @@ -package com.example.homework_libraty.models; - -import jakarta.persistence.*; +package com.example.homework_library.models; import jakarta.persistence.*; diff --git a/src/main/java/com/example/homework_libraty/models/Student.java b/src/main/java/com/example/homework_library/models/Student.java similarity index 95% rename from src/main/java/com/example/homework_libraty/models/Student.java rename to src/main/java/com/example/homework_library/models/Student.java index d2b4b197..0d5229ea 100644 --- a/src/main/java/com/example/homework_libraty/models/Student.java +++ b/src/main/java/com/example/homework_library/models/Student.java @@ -1,4 +1,4 @@ -package com.example.homework_libraty.models; +package com.example.homework_library.models; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java b/src/main/java/com/example/homework_library/repositories/AuthorRepository.java similarity index 58% rename from src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java rename to src/main/java/com/example/homework_library/repositories/AuthorRepository.java index 17007b63..ea2ef93a 100644 --- a/src/main/java/com/example/homework_libraty/repositories/AuthorRepository.java +++ b/src/main/java/com/example/homework_library/repositories/AuthorRepository.java @@ -1,6 +1,6 @@ -package com.example.homework_libraty.repositories; +package com.example.homework_library.repositories; -import com.example.homework_libraty.models.Author; +import com.example.homework_library.models.Author; import org.springframework.data.jpa.repository.JpaRepository; public interface AuthorRepository extends JpaRepository { diff --git a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java b/src/main/java/com/example/homework_library/repositories/BookRepository.java similarity index 82% rename from src/main/java/com/example/homework_libraty/repositories/BookRepository.java rename to src/main/java/com/example/homework_library/repositories/BookRepository.java index 5338742d..cbb27682 100644 --- a/src/main/java/com/example/homework_libraty/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_library/repositories/BookRepository.java @@ -1,6 +1,6 @@ -package com.example.homework_libraty.repositories; +package com.example.homework_library.repositories; -import com.example.homework_libraty.models.Book; +import com.example.homework_library.models.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java b/src/main/java/com/example/homework_library/repositories/IssuesRepository.java similarity index 58% rename from src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java rename to src/main/java/com/example/homework_library/repositories/IssuesRepository.java index f75d0dba..37158c4e 100644 --- a/src/main/java/com/example/homework_libraty/repositories/IssuesRepository.java +++ b/src/main/java/com/example/homework_library/repositories/IssuesRepository.java @@ -1,6 +1,6 @@ -package com.example.homework_libraty.repositories; +package com.example.homework_library.repositories; -import com.example.homework_libraty.models.Issue; +import com.example.homework_library.models.Issue; import org.springframework.data.jpa.repository.JpaRepository; public interface IssuesRepository extends JpaRepository { diff --git a/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java b/src/main/java/com/example/homework_library/repositories/StudentRepository.java similarity index 64% rename from src/main/java/com/example/homework_libraty/repositories/StudentRepository.java rename to src/main/java/com/example/homework_library/repositories/StudentRepository.java index 153fedcd..db3e1255 100644 --- a/src/main/java/com/example/homework_libraty/repositories/StudentRepository.java +++ b/src/main/java/com/example/homework_library/repositories/StudentRepository.java @@ -1,6 +1,6 @@ -package com.example.homework_libraty.repositories; +package com.example.homework_library.repositories; -import com.example.homework_libraty.models.Student; +import com.example.homework_library.models.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository { diff --git a/src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java b/src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java similarity index 65% rename from src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java rename to src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java index e358d86e..e889a16b 100644 --- a/src/test/java/com/example/homework_libraty/HomeworkLibratyApplicationTests.java +++ b/src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java @@ -1,10 +1,10 @@ -package com.example.homework_libraty; +package com.example.homework_library; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class HomeworkLibratyApplicationTests { +class HomeworkLibraryApplicationTests { @Test void contextLoads() { diff --git a/src/test/java/com/example/homework_libraty/models/BookTest.java b/src/test/java/com/example/homework_library/models/BookTest.java similarity index 84% rename from src/test/java/com/example/homework_libraty/models/BookTest.java rename to src/test/java/com/example/homework_library/models/BookTest.java index e19d38a0..55bfb5ea 100644 --- a/src/test/java/com/example/homework_libraty/models/BookTest.java +++ b/src/test/java/com/example/homework_library/models/BookTest.java @@ -1,6 +1,6 @@ -package com.example.homework_libraty.models; +package com.example.homework_library.models; -import com.example.homework_libraty.repositories.BookRepository; +import com.example.homework_library.repositories.BookRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -8,8 +8,6 @@ import java.util.List; -import static org.junit.jupiter.api.Assertions.*; - @SpringBootTest class BookTest { diff --git a/src/test/java/com/example/homework_libraty/models/StudentTest.java b/src/test/java/com/example/homework_library/models/StudentTest.java similarity index 75% rename from src/test/java/com/example/homework_libraty/models/StudentTest.java rename to src/test/java/com/example/homework_library/models/StudentTest.java index caec7664..6ac66349 100644 --- a/src/test/java/com/example/homework_libraty/models/StudentTest.java +++ b/src/test/java/com/example/homework_library/models/StudentTest.java @@ -1,13 +1,11 @@ -package com.example.homework_libraty.models; +package com.example.homework_library.models; -import com.example.homework_libraty.repositories.StudentRepository; +import com.example.homework_library.repositories.StudentRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import static org.junit.jupiter.api.Assertions.*; - @SpringBootTest class StudentTest { From 171483cf4cab50eb9715229e1f00ed7a25c0ec93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Su=C3=A1rez=20Garc=C3=ADa?= Date: Tue, 29 Apr 2025 11:49:39 +0200 Subject: [PATCH 18/21] Improved Main Functions --- .../HomeworkLibraryApplication.java | 87 ++++++++++++------- .../repositories/AuthorRepository.java | 15 ++++ .../repositories/BookRepository.java | 5 ++ .../repositories/IssuesRepository.java | 10 +++ .../repositories/StudentRepository.java | 4 + .../homework_library/models/StudentTest.java | 15 +++- 6 files changed, 104 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java index 575596c4..c4f92554 100644 --- a/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java +++ b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java @@ -28,7 +28,6 @@ public class HomeworkLibraryApplication { @Autowired private IssuesRepository issuesRepository; - // ANSI CODES for colors public static final String RESET = "\u001B[0m"; public static final String GREEN = "\u001B[32m"; public static final String CYAN = "\u001B[36m"; @@ -98,51 +97,54 @@ public void searchBook() { } } - //daniM entregar libro public void issueBook() { System.out.print("Enter usn: "); String usn = scanner.nextLine().trim(); - if (usn.isEmpty()) { + if (usn.isEmpty() || findIssueWithUSN(usn) != null) { throw new IllegalArgumentException("usn cannot be empty."); } - //Student student = studentRepository.findByName(usn); - - System.out.print("Enter name: "); - String name = scanner.nextLine().trim(); - if (name.isEmpty()) { - throw new IllegalArgumentException("name cannot be empty."); - } - Student student = studentRepository.findByName(name); + Student student = studentRepository.findStudentByUsn(usn); System.out.print("Enter ISBN: "); String isbn = scanner.nextLine().trim(); - if (isbn.isEmpty()) { - System.out.println("Book found: " + isbn); - } else { - System.out.println("Book not found."); + if (isbn.isEmpty() || findIssueWithISBN(isbn) != null) { + throw new IllegalArgumentException("isbn cannot be empty."); } + Book book = bookRepository.findByIsbn(isbn); - Issue issue = new Issue(getDate(), getExpiredDate(), student, book); - //String issueDate, String returnDate, Student issueStudent, Book issueBook + issuesRepository.save(new Issue(getDate(), getExpiredDate(), student, book)); + System.out.println("Book issued. Return date: " + getExpiredDate()); + } + + public Student findIssueWithUSN(String usn) { + if (usn.isEmpty()) { + throw new IllegalArgumentException("usn cannot be empty."); + } + return issuesRepository.findIssuesByIssueStudent_Usn(usn).getIssueStudent(); + + } + - issuesRepository.save(issue); - System.out.println("Book issued. Return date" + getExpiredDate()); + public Book findIssueWithISBN(String isbn) { + if (isbn.isEmpty()) { + throw new IllegalArgumentException("isbn cannot be empty."); + } + return issuesRepository.findIssuesByIssueBook_Isbn(isbn).getIssueBook(); } - public String getDate(){ + + public String getDate() { LocalDate actualDate = LocalDate.now(); - DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-mm-aa"); - String dateString = actualDate.format(formatter); - return dateString; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + return actualDate.format(formatter); } - public String getExpiredDate(){ + + public String getExpiredDate() { LocalDate actualDate = LocalDate.now(); - LocalDate datePlusWeek=actualDate.plusWeeks(1); - //DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-mm-dd"); - //return datePlusWeek.format(formatter); + LocalDate datePlusWeek = actualDate.plusWeeks(1); return datePlusWeek.toString(); } @@ -167,7 +169,32 @@ public void listAllBooks() { } + public void listAllBooksByUSN() { + System.out.print("Enter usn: "); + String usn = scanner.nextLine().trim(); + Issue issue = issuesRepository.findIssuesByIssueStudent_Usn(usn); + if (issue != null) { + System.out.println("Book found: " + issue.getIssueBook()); + } else { + System.out.println("Book not found."); + } + } + public void findBookByAuthor() { + System.out.print("Enter the author of the book: "); + String authorName = scanner.nextLine().trim(); + if (authorName.isEmpty()) { + throw new IllegalArgumentException("Author cannot be empty."); + } + + Book book = authorRepository.findByName(authorName).getAuthorBook(); + if (book != null) { + System.out.println("Book found: " + book); + } else { + System.out.println("Book not found."); + } + + } public void menuDisplay() { System.out.println(GREEN + "\n======== 📖 Iron Library ========" + RESET); @@ -203,7 +230,7 @@ public void runMenu() { searchBookByCategory(); break; case "4": - // TODO + findBookByAuthor(); break; case "5": listAllBooks(); @@ -212,7 +239,7 @@ public void runMenu() { issueBook(); break; case "7": - // TODO + listAllBooksByUSN(); break; case "8", "exit": running = false; @@ -252,8 +279,6 @@ public void searchBookByCategory() { } - //TODO: hacer el 5 (List all books along with author) y la 7 (List all books along with author) - public static void main(String[] args) { // Run the Spring Boot application diff --git a/src/main/java/com/example/homework_library/repositories/AuthorRepository.java b/src/main/java/com/example/homework_library/repositories/AuthorRepository.java index ea2ef93a..b94646b3 100644 --- a/src/main/java/com/example/homework_library/repositories/AuthorRepository.java +++ b/src/main/java/com/example/homework_library/repositories/AuthorRepository.java @@ -1,7 +1,22 @@ package com.example.homework_library.repositories; import com.example.homework_library.models.Author; +import com.example.homework_library.models.Book; + import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +@Repository public interface AuthorRepository extends JpaRepository { + + // Book findByIsbn(String isbn); + Author findByName(String authorName); + + + + + } + diff --git a/src/main/java/com/example/homework_library/repositories/BookRepository.java b/src/main/java/com/example/homework_library/repositories/BookRepository.java index cbb27682..d6daf452 100644 --- a/src/main/java/com/example/homework_library/repositories/BookRepository.java +++ b/src/main/java/com/example/homework_library/repositories/BookRepository.java @@ -1,5 +1,6 @@ package com.example.homework_library.repositories; +import com.example.homework_library.models.Author; import com.example.homework_library.models.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -21,4 +22,8 @@ public interface BookRepository extends JpaRepository { + + + + } diff --git a/src/main/java/com/example/homework_library/repositories/IssuesRepository.java b/src/main/java/com/example/homework_library/repositories/IssuesRepository.java index 37158c4e..ca64efbe 100644 --- a/src/main/java/com/example/homework_library/repositories/IssuesRepository.java +++ b/src/main/java/com/example/homework_library/repositories/IssuesRepository.java @@ -1,7 +1,17 @@ package com.example.homework_library.repositories; import com.example.homework_library.models.Issue; +import com.example.homework_library.models.Student; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import java.util.List; + +@Repository public interface IssuesRepository extends JpaRepository { + + //List findIssuesByIssueStudent_Usn(String issueStudentUsn); + Issue findIssuesByIssueStudent_Usn(String issueStudentUsn); + Issue findIssuesByIssueBook_Isbn(String issueBookIsbn); + } diff --git a/src/main/java/com/example/homework_library/repositories/StudentRepository.java b/src/main/java/com/example/homework_library/repositories/StudentRepository.java index db3e1255..a65f3d74 100644 --- a/src/main/java/com/example/homework_library/repositories/StudentRepository.java +++ b/src/main/java/com/example/homework_library/repositories/StudentRepository.java @@ -1,9 +1,13 @@ package com.example.homework_library.repositories; import com.example.homework_library.models.Student; +import jdk.jfr.Registered; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +@Repository public interface StudentRepository extends JpaRepository { Student findByName(String studentName); + Student findStudentByUsn(String usn); } diff --git a/src/test/java/com/example/homework_library/models/StudentTest.java b/src/test/java/com/example/homework_library/models/StudentTest.java index 6ac66349..f8aeeb7b 100644 --- a/src/test/java/com/example/homework_library/models/StudentTest.java +++ b/src/test/java/com/example/homework_library/models/StudentTest.java @@ -1,10 +1,12 @@ package com.example.homework_library.models; import com.example.homework_library.repositories.StudentRepository; +import jakarta.transaction.Transactional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; @SpringBootTest class StudentTest { @@ -14,10 +16,21 @@ class StudentTest { @Test @DisplayName("Guardo un estudiante en la base de datos") + @Transactional + @Rollback(false) void saveStudent(){ - Student student = new Student("843t", "Daniel"); + Student student = new Student("123a", "Daniel"); studentRepository.save(student); } + @Test + @DisplayName("Listar todos los estudiantes") + void findAll(){ + System.out.println("============================"); + System.out.println("Los estudiantes que hemos encontrado son: "); + System.out.println(studentRepository.findAll()); + System.out.println("==================="); + } + } \ No newline at end of file From 1e878a2c0f90b2e66fe65e8709de0f06b3020110 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Su=C3=A1rez=20Garc=C3=ADa?= Date: Wed, 30 Apr 2025 13:33:24 +0200 Subject: [PATCH 19/21] Final Version --- Instructions.md | 188 ++++++++++ README.md | 194 +++-------- pom.xml | 19 +- .../HomeworkLibraryApplication.java | 323 ++++++------------ .../repositories/IssuesRepository.java | 2 + .../services/AuthorService.java | 25 ++ .../services/BookService.java | 53 +++ .../services/IssueService.java | 70 ++++ .../services/StudentService.java | 25 ++ .../HomeworkLibraryApplicationTests.java | 13 - .../homework_library/models/BookTest.java | 36 -- .../homework_library/models/StudentTest.java | 36 -- .../services/BookServiceTest.java | 99 ++++++ .../services/IssueServiceTest.java | 61 ++++ .../services/StudentServiceTest.java | 49 +++ 15 files changed, 742 insertions(+), 451 deletions(-) create mode 100644 Instructions.md create mode 100644 src/main/java/com/example/homework_library/services/AuthorService.java create mode 100644 src/main/java/com/example/homework_library/services/BookService.java create mode 100644 src/main/java/com/example/homework_library/services/IssueService.java create mode 100644 src/main/java/com/example/homework_library/services/StudentService.java delete mode 100644 src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java delete mode 100644 src/test/java/com/example/homework_library/models/BookTest.java delete mode 100644 src/test/java/com/example/homework_library/models/StudentTest.java create mode 100644 src/test/java/com/example/homework_library/services/BookServiceTest.java create mode 100644 src/test/java/com/example/homework_library/services/IssueServiceTest.java create mode 100644 src/test/java/com/example/homework_library/services/StudentServiceTest.java diff --git a/Instructions.md b/Instructions.md new file mode 100644 index 00000000..df676c12 --- /dev/null +++ b/Instructions.md @@ -0,0 +1,188 @@ +![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) + +# HW | Java IronLibrary (Unit 3 homework) + +## Introduction + +For this homework, you will be building a Library Management System, that will help managing and acquiring data about the books that are being used by students. + +## Instructions + +Let's walk through the details of the homework: + +### Classes + +Four main classes are necessary to complete this homework. + +These classes will be called **Author**, **Book**, **Student** and **Issue**. + +
+ +**Book class** + +This class will have: + +- Variable called `isbn` of data type `string`, representing the **International Standard Book Number** and acting as the unique identifier for the table book (Private member) +- Variable called `title` of data type `string` (Private member) +- Variable called `category` of data type `string` (Private member) +- Variable called `quantity` of data type `integer` (Private member) +- A parameterized constructor that takes `isbn`, `title`, `category` and a `quantity` +- Public Getter functions to access these variables +- Public Setter functions to change these variables +- Optional attributes are accepted if needed based on the code structure + +
+ +**Author class** + +This class will have: + +- Variable called `authorId` of data type `integer`, auto-incremented (Private member) +- Variable called `name` of data type `string` (Private member) +- Variable called `email` of data type `string` (Private member) +- Variable called `authorBook` of data type `Book`, representing a One-to-One relationship with `Book` (Private member) +- A parameterized constructor that takes `name`, `email` and `authorBook` +- Public Getter functions to access these variables +- Public Setter functions to change these variables +- Optional attributes are accepted if needed based on the code structure + +
+ +**Issue class** + +This class will have: + +- Variable called `issueId` of data type `integer`, auto-incremented (Private member) +- Variable called `issueDate` of data type `string` (Private member) +- Variable called `returnDate` of data type `string` (Private member) +- Variable called `issueStudent` of data type `Student`, representing a One-to-One relationship with `Student`(Private member) +- Variable called `issueBook` of data type `Book`, representing a One-to-One relationship with `Book` (Private member) +- A parameterized constructor that takes `issueDate`, `returnDate`, `issueStudent` and `issueBook` +- Public Getter functions to access these variables +- Public Setter functions to change these variables +- Optional attributes are accepted if needed based on the code structure + +
+ +**Student class** + +This class will have: + +- Variable called `usn` of data type `string`, representing the **Universal Student Number** and acting as the unique identifier for the table student (Private member) +- Variable called `name` of data type `string` (Private member) +- A parameterized constructor that takes `usn` and `name` +- Public Getter functions to access these variables +- Public Setter functions to change these variables +- Optional attributes are accepted if needed based on the code structure + +## How the application works + +After starting this application, a list of options will pop up for the user. The user will be asked to input a number based on the list of options displayed, such as adding a book, searching for a book, issuing a book for a student, etc. +After a certain action is executed, the menu is re-displayed for the user automatically. + +The menu should have the following options: + +1. Add a book +2. Search book by title +3. Search book by category +4. Search book by Author +5. List all books along with author +6. Issue book to student +7. List books by usn +8. Exit + +## Actions + +1. **Add a book**: This action is responsible of adding a book and its author in the system. The user will be prompted to enter the details of both the book and the author in the following format: + +``` +Enter your choice: 1 +Enter isbn : 978-3-16-148410-0 +Enter title : The Notebook +Enter category : Romance +Enter Author name : Nicholas Sparks +Enter Author mail : nicholassparks@gmail.com +Enter number of books : 4 +``` + +2. **Search book by title**: This action is responsible for searching a book by title. + +``` +Enter your choice: 2 +Enter title : The Notebook + +Book ISBN Book Title Category No of Books +978-3-16-148410-0 The Notebook Romance 4 +``` + +3. **Search book by category**: This action is responsible for searching a book by category. + +``` +Enter your choice: 3 +Enter category : Romance + +Book ISBN Book Title Category No of Books +978-3-16-148410-0 The Notebook Romance 4 +``` + +4. **Search book by author**: This action is responsible for searching a book by author name. + +``` +Enter your choice: 4 +Enter name : Nicholas Sparks + +Book ISBN Book Title Category No of Books +978-3-16-148410-0 The Notebook Romance 4 +``` + +5. **List all books along with author**: This action is responsible for listing all the books available and there corresponding authors. + +``` +Enter your choice: 5 + +Book ISBN Book Title Category No of Books Author name Author mail +978-3-16-148410-0 The Notebook Romance 4 Nicholas Sparks nicholassparks@gmail.com +978-3-17-148410-0 Da Vinci Code Mystery 5 Dan Brown danbrown@gmail.com +``` + +6. **Issue book to student**: This action is responsible for creating a student and issuing him/her the specified book. The date issued represent the current date and the return date should be after 7 days. + +``` +Enter your choice: 6 +Enter usn : 09003688800 +Enter name : John Doe +Enter book ISBN : 978-3-17-148410-0 + +Book issued. Return date : Mon Aug 01 19:45:40 EEST 2022 +``` + +7. **List books by usn**: This action is responsible for listing all books rented by the specified student. + +``` +Enter your choice: 7 +Enter usn : 09003688800 + +Book Title Student Name Return date +Da Vinci Code John Doe 2022-08-01 16:45:40.636000 +``` + +## Requirements + +For this project, you must accomplish all of the following: + +1. Navigate through a text-based menu using Standard Input and Output. +2. Create unit tests for every method other than basic getters, setters and constructors (getters and setters with logic do require unit tests). +3. Handle all exceptions gracefully (incorrect input should not crash the program). +4. All data should be stored in a normalized SQL database. + +### Bonus + +1. Add more options that can help display more information such as **List books to be returned today**, etc. + +## Important Notes + +- Everyone in the squad should contribute equally to the project in time and lines of code written. +- All code must be reviewed before it is merged into the `master` branch. +- All squad members must participate in code review. +- Every repository should have a README file with clear instructions, demo files, or any documentation needed so other teams don't have problems with the review. +- This is intended to be a challenging assignment. You will have to rely heavily on your teammates and independent research. Learning independently is a hallmark of a good developer and our job is to turn you into good developers. This process may be frustrating but you will learn a ton! diff --git a/README.md b/README.md index df676c12..6dba3d52 100644 --- a/README.md +++ b/README.md @@ -1,101 +1,61 @@ -![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) +# IronLibrary -# HW | Java IronLibrary (Unit 3 homework) +## Introducción -## Introduction +Este proyecto consiste en un sistema de gestión de biblioteca que permite administrar y obtener datos sobre los libros utilizados por los estudiantes. A continuación, se detallan las instrucciones para ejecutar y probar la aplicación. -For this homework, you will be building a Library Management System, that will help managing and acquiring data about the books that are being used by students. +--- -## Instructions +## Requisitos previos -Let's walk through the details of the homework: +1. **Java**: Java 21. +2. **Maven**: correctamente configurado. +3. **Base de datos**: MySQL o MariaDB (ajustando las credenciales en el archivo `application.properties`). -### Classes +--- -Four main classes are necessary to complete this homework. +## Instalación -These classes will be called **Author**, **Book**, **Student** and **Issue**. +1. Clona el repositorio: + ```bash + git clone https://github.com/VAlexS/homework-java-ironlibrary + cd homework-java-ironlibrary + ``` -
+2. Compila el proyecto: + ```bash + mvn clean install + ``` -**Book class** +3. Ejecuta la aplicación: + ```bash + mvn spring-boot:run + ``` -This class will have: +--- -- Variable called `isbn` of data type `string`, representing the **International Standard Book Number** and acting as the unique identifier for the table book (Private member) -- Variable called `title` of data type `string` (Private member) -- Variable called `category` of data type `string` (Private member) -- Variable called `quantity` of data type `integer` (Private member) -- A parameterized constructor that takes `isbn`, `title`, `category` and a `quantity` -- Public Getter functions to access these variables -- Public Setter functions to change these variables -- Optional attributes are accepted if needed based on the code structure +## Uso -
+Al iniciar la aplicación, se mostrará un menú interactivo en la consola. A continuación, se presentan capturas de pantalla y ejemplos de uso. -**Author class** +### Menú principal -This class will have: - -- Variable called `authorId` of data type `integer`, auto-incremented (Private member) -- Variable called `name` of data type `string` (Private member) -- Variable called `email` of data type `string` (Private member) -- Variable called `authorBook` of data type `Book`, representing a One-to-One relationship with `Book` (Private member) -- A parameterized constructor that takes `name`, `email` and `authorBook` -- Public Getter functions to access these variables -- Public Setter functions to change these variables -- Optional attributes are accepted if needed based on the code structure - -
- -**Issue class** - -This class will have: - -- Variable called `issueId` of data type `integer`, auto-incremented (Private member) -- Variable called `issueDate` of data type `string` (Private member) -- Variable called `returnDate` of data type `string` (Private member) -- Variable called `issueStudent` of data type `Student`, representing a One-to-One relationship with `Student`(Private member) -- Variable called `issueBook` of data type `Book`, representing a One-to-One relationship with `Book` (Private member) -- A parameterized constructor that takes `issueDate`, `returnDate`, `issueStudent` and `issueBook` -- Public Getter functions to access these variables -- Public Setter functions to change these variables -- Optional attributes are accepted if needed based on the code structure - -
- -**Student class** - -This class will have: - -- Variable called `usn` of data type `string`, representing the **Universal Student Number** and acting as the unique identifier for the table student (Private member) -- Variable called `name` of data type `string` (Private member) -- A parameterized constructor that takes `usn` and `name` -- Public Getter functions to access these variables -- Public Setter functions to change these variables -- Optional attributes are accepted if needed based on the code structure - -## How the application works - -After starting this application, a list of options will pop up for the user. The user will be asked to input a number based on the list of options displayed, such as adding a book, searching for a book, issuing a book for a student, etc. -After a certain action is executed, the menu is re-displayed for the user automatically. - -The menu should have the following options: - -1. Add a book -2. Search book by title -3. Search book by category -4. Search book by Author -5. List all books along with author -6. Issue book to student -7. List books by usn -8. Exit - -## Actions +```plaintext +=========== 📖 Iron Library =========== +1. 📕 Add a book +2. 🔎 Search book by title +3. 🗂️ Search book by category +4. 🖋️ Search book by author +5. 📚 List all books along with author +6. 🎓 Issue book to student +7. 🆔 List books by USN +8. 🚪 Exit +Choose an option: +``` -1. **Add a book**: This action is responsible of adding a book and its author in the system. The user will be prompted to enter the details of both the book and the author in the following format: +### Ejemplo: Agregar un libro -``` +```plaintext Enter your choice: 1 Enter isbn : 978-3-16-148410-0 Enter title : The Notebook @@ -103,11 +63,12 @@ Enter category : Romance Enter Author name : Nicholas Sparks Enter Author mail : nicholassparks@gmail.com Enter number of books : 4 +Record created successfully! ``` -2. **Search book by title**: This action is responsible for searching a book by title. +### Ejemplo: Buscar un libro por título -``` +```plaintext Enter your choice: 2 Enter title : The Notebook @@ -115,74 +76,25 @@ Book ISBN Book Title Category No of Books 978-3-16-148410-0 The Notebook Romance 4 ``` -3. **Search book by category**: This action is responsible for searching a book by category. - -``` -Enter your choice: 3 -Enter category : Romance - -Book ISBN Book Title Category No of Books -978-3-16-148410-0 The Notebook Romance 4 -``` - -4. **Search book by author**: This action is responsible for searching a book by author name. - -``` -Enter your choice: 4 -Enter name : Nicholas Sparks - -Book ISBN Book Title Category No of Books -978-3-16-148410-0 The Notebook Romance 4 -``` - -5. **List all books along with author**: This action is responsible for listing all the books available and there corresponding authors. +### Ejemplo: Emitir un libro a un estudiante -``` -Enter your choice: 5 - -Book ISBN Book Title Category No of Books Author name Author mail -978-3-16-148410-0 The Notebook Romance 4 Nicholas Sparks nicholassparks@gmail.com -978-3-17-148410-0 Da Vinci Code Mystery 5 Dan Brown danbrown@gmail.com -``` - -6. **Issue book to student**: This action is responsible for creating a student and issuing him/her the specified book. The date issued represent the current date and the return date should be after 7 days. - -``` +```plaintext Enter your choice: 6 Enter usn : 09003688800 Enter name : John Doe Enter book ISBN : 978-3-17-148410-0 -Book issued. Return date : Mon Aug 01 19:45:40 EEST 2022 +Book issued. Return date : 2023-10-15 ``` -7. **List books by usn**: This action is responsible for listing all books rented by the specified student. +--- -``` -Enter your choice: 7 -Enter usn : 09003688800 +## Pruebas -Book Title Student Name Return date -Da Vinci Code John Doe 2022-08-01 16:45:40.636000 -``` +El proyecto incluye pruebas unitarias para todos los servicios principales. Para ejecutarlas, utiliza el siguiente comando: -## Requirements - -For this project, you must accomplish all of the following: - -1. Navigate through a text-based menu using Standard Input and Output. -2. Create unit tests for every method other than basic getters, setters and constructors (getters and setters with logic do require unit tests). -3. Handle all exceptions gracefully (incorrect input should not crash the program). -4. All data should be stored in a normalized SQL database. - -### Bonus - -1. Add more options that can help display more information such as **List books to be returned today**, etc. +```bash +mvn test +``` -## Important Notes -- Everyone in the squad should contribute equally to the project in time and lines of code written. -- All code must be reviewed before it is merged into the `master` branch. -- All squad members must participate in code review. -- Every repository should have a README file with clear instructions, demo files, or any documentation needed so other teams don't have problems with the review. -- This is intended to be a challenging assignment. You will have to rely heavily on your teammates and independent research. Learning independently is a hallmark of a good developer and our job is to turn you into good developers. This process may be frustrating but you will learn a ton! diff --git a/pom.xml b/pom.xml index d184802e..4e3c38af 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,24 @@ mariadb-java-client 3.3.1 - + + org.junit.jupiter + junit-jupiter + 5.11.4 + test + + + org.junit.platform + junit-platform-launcher + 1.11.4 + test + + + org.mockito + mockito-junit-jupiter + 5.5.0 + test + diff --git a/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java index c4f92554..4efb79fb 100644 --- a/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java +++ b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java @@ -1,14 +1,14 @@ package com.example.homework_library; -import com.example.homework_library.models.*; -import com.example.homework_library.repositories.*; +import com.example.homework_library.models.Book; +import com.example.homework_library.models.Issue; +import com.example.homework_library.services.BookService; +import com.example.homework_library.services.IssueService; +import com.example.homework_library.services.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; @@ -17,79 +17,84 @@ public class HomeworkLibraryApplication { @Autowired - private BookRepository bookRepository; + private BookService bookService; @Autowired - private AuthorRepository authorRepository; + private StudentService studentService; @Autowired - private StudentRepository studentRepository; - - @Autowired - private IssuesRepository issuesRepository; + private IssueService issueService; public static final String RESET = "\u001B[0m"; public static final String GREEN = "\u001B[32m"; public static final String CYAN = "\u001B[36m"; - public static final String YELLOW = "\u001B[33m"; public static final String RED = "\u001B[31m"; private final Scanner scanner = new Scanner(System.in); - public void addBook() { - System.out.print("Enter the isbn: "); - String isbn = scanner.nextLine().trim(); - if (isbn.isEmpty()) { - throw new IllegalArgumentException("ISBN cannot be empty."); - } - - System.out.print("Enter the title of the book: "); - String title = scanner.nextLine().trim(); - if (title.isEmpty()) { - throw new IllegalArgumentException("Book title cannot be empty."); - } + public static void main(String[] args) { + SpringApplication.run(HomeworkLibraryApplication.class, args).getBean(HomeworkLibraryApplication.class).runMenu(); + } - System.out.print("Enter the category of the book: "); - String category = scanner.nextLine().trim(); - if (category.isEmpty()) { - throw new IllegalArgumentException("Book category cannot be empty."); - } + public void runMenu() { + boolean running = true; - System.out.print("Enter the author of the book: "); - String authorName = scanner.nextLine().trim(); - if (authorName.isEmpty()) { - throw new IllegalArgumentException("Author cannot be empty."); - } + while (running) { + try { + menuDisplay(); + String option = scanner.nextLine().trim(); - System.out.print("Enter the mail of the author: "); - String mail = scanner.nextLine().trim(); - if (mail.isEmpty()) { - throw new IllegalArgumentException("Author mail cannot be empty."); + switch (option) { + case "1" -> addBook(); + case "2" -> searchBook(); + case "3" -> searchBookByCategory(); + case "4" -> findBookByAuthor(); + case "5" -> listAllBooks(); + case "6" -> issueBook(); + case "7" -> listAllBooksByUSN(); + case "8", "exit" -> running = false; + default -> System.out.println("Invalid option. Please try again."); + } + } catch (IllegalArgumentException e) { + System.out.println("Incorrect argument: " + e.getMessage()); + } catch (NoSuchElementException e) { + System.out.println("Element not found: " + e.getMessage()); + } catch (Exception e) { + System.out.println("An unexpected error occurred: " + e.getMessage()); + } } - System.out.print("Enter the number of books: "); - int booksNumber = Integer.parseInt(scanner.nextLine().trim()); - if (booksNumber <= 0) { - throw new IllegalArgumentException("Book number cannot be 0 or less."); - } + scanner.close(); + } - Book book = new Book(isbn, title, category, booksNumber); - Author author = new Author(authorName, mail, book); + private void menuDisplay() { + System.out.println(GREEN + "\n=========== 📖 Iron Library ===========" + RESET); + System.out.println(CYAN + "1. 📕 Add a book" + RESET); + System.out.println(CYAN + "2. 🔎 Search book by title" + RESET); + System.out.println(CYAN + "3. 🗂️ Search book by category" + RESET); + System.out.println(CYAN + "4. 🖋️ Search book by author" + RESET); + System.out.println(CYAN + "5. 📚 List all books along with author" + RESET); + System.out.println(CYAN + "6. 🎓 Issue book to student" + RESET); + System.out.println(CYAN + "7. 🆔 List books by USN" + RESET); + System.out.println(RED + "8. 🚪 Exit" + RESET); + System.out.print("Choose an option: "); + } - bookRepository.save(book); - authorRepository.save(author); + private void addBook() { + String isbn = prompt("Enter the ISBN: "); + String title = prompt("Enter the title of the book: "); + String category = prompt("Enter the category of the book: "); + String authorName = prompt("Enter the author of the book: "); + String mail = prompt("Enter the mail of the author: "); + int booksNumber = Integer.parseInt(prompt("Enter the number of books: ")); + bookService.addBook(isbn, title, category, authorName, mail, booksNumber); System.out.println("Record created successfully!"); } - public void searchBook() { - System.out.print("Enter the title of the book: "); - String title = scanner.nextLine().trim(); - if (title.isEmpty()) { - throw new IllegalArgumentException("Book title cannot be empty."); - } - - Book book = bookRepository.findByTitle(title); + private void searchBook() { + String title = prompt("Enter the title of the book: "); + Book book = bookService.searchBookByTitle(title); if (book != null) { System.out.println("Book found: " + book); } else { @@ -97,200 +102,70 @@ public void searchBook() { } } - public void issueBook() { - System.out.print("Enter usn: "); - String usn = scanner.nextLine().trim(); - if (usn.isEmpty() || findIssueWithUSN(usn) != null) { - throw new IllegalArgumentException("usn cannot be empty."); - } - - Student student = studentRepository.findStudentByUsn(usn); - - - System.out.print("Enter ISBN: "); - String isbn = scanner.nextLine().trim(); - if (isbn.isEmpty() || findIssueWithISBN(isbn) != null) { - throw new IllegalArgumentException("isbn cannot be empty."); - } - - Book book = bookRepository.findByIsbn(isbn); - - issuesRepository.save(new Issue(getDate(), getExpiredDate(), student, book)); - System.out.println("Book issued. Return date: " + getExpiredDate()); - } - - public Student findIssueWithUSN(String usn) { - if (usn.isEmpty()) { - throw new IllegalArgumentException("usn cannot be empty."); + private void searchBookByCategory() { + String category = prompt("Enter the category of the book: "); + List books = bookService.searchBooksByCategory(category); + if (!books.isEmpty()) { + System.out.println("Books found in category " + category + ":"); + books.forEach(System.out::println); + } else { + System.out.println("Book category not found."); } - return issuesRepository.findIssuesByIssueStudent_Usn(usn).getIssueStudent(); - } - - public Book findIssueWithISBN(String isbn) { - if (isbn.isEmpty()) { - throw new IllegalArgumentException("isbn cannot be empty."); + private void findBookByAuthor() { + String authorName = prompt("Enter the author of the book: "); + Book book = bookService.findBookByAuthor(authorName); + if (book != null) { + System.out.println("Book found: " + book); + } else { + System.out.println("Book not found."); } - return issuesRepository.findIssuesByIssueBook_Isbn(isbn).getIssueBook(); - - } - - public String getDate() { - LocalDate actualDate = LocalDate.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - return actualDate.format(formatter); } - public String getExpiredDate() { - LocalDate actualDate = LocalDate.now(); - LocalDate datePlusWeek = actualDate.plusWeeks(1); - return datePlusWeek.toString(); - } - - - public void listAllBooks() { + private void listAllBooks() { + List books = bookService.listAllBooks(); + String separator = String.format("%-90s", "").replace(' ', '='); - List allBooks = bookRepository.findAllBooksAndAuthors(); // Devuelve una lista de objetos Book - - System.out.println("==========================================================="); + System.out.println(separator); System.out.printf("%-25s %-30s %-20s %-10s%n", "Book ISBN", "Book Title", "Category", "Quantity"); - System.out.println("==========================================================="); + System.out.println(separator); - for (Book book : allBooks) { + for (Book book : books) { System.out.printf("%-25s %-30s %-20s %-10d%n", book.getIsbn(), book.getTitle(), book.getCategory(), book.getQuantity()); } - System.out.println("==========================================================="); - - - } - - public void listAllBooksByUSN() { - System.out.print("Enter usn: "); - String usn = scanner.nextLine().trim(); - Issue issue = issuesRepository.findIssuesByIssueStudent_Usn(usn); - if (issue != null) { - System.out.println("Book found: " + issue.getIssueBook()); - } else { - System.out.println("Book not found."); - } - } - - public void findBookByAuthor() { - System.out.print("Enter the author of the book: "); - String authorName = scanner.nextLine().trim(); - if (authorName.isEmpty()) { - throw new IllegalArgumentException("Author cannot be empty."); - } - - Book book = authorRepository.findByName(authorName).getAuthorBook(); - if (book != null) { - System.out.println("Book found: " + book); - } else { - System.out.println("Book not found."); - } - - } - - public void menuDisplay() { - System.out.println(GREEN + "\n======== 📖 Iron Library ========" + RESET); - System.out.println(CYAN + "1. 📕 Add a book" + RESET); - System.out.println(CYAN + "2. 🔎 Search book by title" + RESET); - System.out.println(CYAN + "3. 🗂️ Search book by category" + RESET); - System.out.println(CYAN + "4. 🖋️ Search book by author" + RESET); - System.out.println(CYAN + "5. 📚 List all books along with author" + RESET); - System.out.println(CYAN + "6. 🎓 Issue book to student" + RESET); - System.out.println(CYAN + "7. 🆔 List books by USN" + RESET); - System.out.println(GREEN + "---------------------------------" + RESET); - System.out.println(RED + "8. 🚪 Exit" + RESET); - System.out.println(GREEN + "=================================" + RESET); - System.out.print("Choose an option: "); + System.out.println(separator); } - public void runMenu() { - boolean running = true; - while (running) { - try { - menuDisplay(); - String option = scanner.nextLine(); + private void issueBook() { + String usn = prompt("Enter USN: "); + String isbn = prompt("Enter ISBN: "); - switch (option) { - case "1": - addBook(); - break; - case "2": - searchBook(); - break; - case "3": - searchBookByCategory(); - break; - case "4": - findBookByAuthor(); - break; - case "5": - listAllBooks(); - break; - case "6": - issueBook(); - break; - case "7": - listAllBooksByUSN(); - break; - case "8", "exit": - running = false; - break; - default: - System.out.println("Invalid option. Please try again."); - } - } catch (IllegalArgumentException e) { - System.out.println("Incorrect argument: " + e.getMessage()); - } catch (NoSuchElementException e) { - System.out.println("Element not found: " + e.getMessage()); - } catch (Exception e) { - System.out.println("An unexpected error occurred: " + e.getMessage()); - } + try { + issueService.issueBook(usn, isbn); + System.out.println("Book issued successfully!"); + } catch (IllegalArgumentException | IllegalStateException e) { + System.out.println("Error: " + e.getMessage()); } - - scanner.close(); } - public void searchBookByCategory() { - List books; - System.out.print("Enter the category of the book: "); - String category = scanner.nextLine().trim(); - if (category.isEmpty()) { - throw new IllegalArgumentException("Book category cannot be empty."); - } - - books = bookRepository.findByCategory(category); - if (!books.isEmpty()) { - System.out.println("Books found in category " + category + ":"); - for (Book book : books) { - System.out.println(book); - } + private void listAllBooksByUSN() { + String usn = prompt("Enter USN: "); + Issue issue = issueService.findIssueByStudentUsn(usn); + if (issue != null) { + System.out.println("Book found: " + issue.getIssueBook()); } else { - System.out.println("Book category not found."); + System.out.println("No books found for this USN."); } } - - public static void main(String[] args) { - - // Run the Spring Boot application - ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibraryApplication.class, args); - - // Get the IronlibraryApplication bean from the context - HomeworkLibraryApplication app = context.getBean(HomeworkLibraryApplication.class); - - app.runMenu(); - - // Close the application context - SpringApplication.exit(context); + private String prompt(String message) { + System.out.print(message); + return scanner.nextLine().trim(); } - } diff --git a/src/main/java/com/example/homework_library/repositories/IssuesRepository.java b/src/main/java/com/example/homework_library/repositories/IssuesRepository.java index ca64efbe..eb321d3c 100644 --- a/src/main/java/com/example/homework_library/repositories/IssuesRepository.java +++ b/src/main/java/com/example/homework_library/repositories/IssuesRepository.java @@ -13,5 +13,7 @@ public interface IssuesRepository extends JpaRepository { //List findIssuesByIssueStudent_Usn(String issueStudentUsn); Issue findIssuesByIssueStudent_Usn(String issueStudentUsn); Issue findIssuesByIssueBook_Isbn(String issueBookIsbn); + boolean existsByIssueStudent_Usn(String usn); + boolean existsByIssueBook_Isbn(String isbn); } diff --git a/src/main/java/com/example/homework_library/services/AuthorService.java b/src/main/java/com/example/homework_library/services/AuthorService.java new file mode 100644 index 00000000..e95b81ba --- /dev/null +++ b/src/main/java/com/example/homework_library/services/AuthorService.java @@ -0,0 +1,25 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Author; +import com.example.homework_library.models.Book; +import com.example.homework_library.repositories.AuthorRepository; +import org.springframework.stereotype.Service; + +@Service +public class AuthorService { + + private final AuthorRepository authorRepository; + + public AuthorService(AuthorRepository authorRepository) { + this.authorRepository = authorRepository; + } + + public Author addAuthor(String name, String email, Book book) { + Author author = new Author(name, email, book); + return authorRepository.save(author); + } + + public Author findAuthorByName(String name) { + return authorRepository.findByName(name); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/homework_library/services/BookService.java b/src/main/java/com/example/homework_library/services/BookService.java new file mode 100644 index 00000000..b24beccb --- /dev/null +++ b/src/main/java/com/example/homework_library/services/BookService.java @@ -0,0 +1,53 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Author; +import com.example.homework_library.models.Book; +import com.example.homework_library.repositories.AuthorRepository; +import com.example.homework_library.repositories.BookRepository; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class BookService { + + private final BookRepository bookRepository; + private final AuthorRepository authorRepository; + + public BookService(BookRepository bookRepository, AuthorRepository authorRepository) { + this.bookRepository = bookRepository; + this.authorRepository = authorRepository; + } + + public void addBook(String isbn, String title, String category, String authorName, String mail, int booksNumber) { + Book book = new Book(isbn, title, category, booksNumber); + Author author = new Author(authorName, mail, book); + + bookRepository.save(book); + authorRepository.save(author); + } + + public Book searchBookByTitle(String title) { + return bookRepository.findByTitle(title); + } + + public List listAllBooks() { + return bookRepository.findAllBooksAndAuthors(); + } + + public List searchBooksByCategory(String category) { + return bookRepository.findByCategory(category); + } + + public Book findBookByAuthor(String authorName) { + Author author = authorRepository.findByName(authorName); + if (author != null) { + return author.getAuthorBook(); + } + return null; + } + + public Book searchBookByIsbn(String isbn) { + return bookRepository.findByIsbn(isbn); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/homework_library/services/IssueService.java b/src/main/java/com/example/homework_library/services/IssueService.java new file mode 100644 index 00000000..a434761c --- /dev/null +++ b/src/main/java/com/example/homework_library/services/IssueService.java @@ -0,0 +1,70 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Book; +import com.example.homework_library.models.Issue; +import com.example.homework_library.models.Student; +import com.example.homework_library.repositories.BookRepository; +import com.example.homework_library.repositories.IssuesRepository; +import com.example.homework_library.repositories.StudentRepository; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +@Service +public class IssueService { + + private final IssuesRepository issuesRepository; + private final StudentRepository studentRepository; + private final BookRepository bookRepository; + + public IssueService(IssuesRepository issuesRepository,StudentRepository studentRepository, BookRepository bookRepository) { + this.issuesRepository = issuesRepository; + this.studentRepository = studentRepository; + this.bookRepository = bookRepository; + } + + public void issueBook(String usn, String isbn) { + // Buscar el estudiante por USN + Student student = studentRepository.findStudentByUsn(usn); + if (student == null) { + throw new IllegalArgumentException("Student not found with USN: " + usn); + } + + // Buscar el libro por ISBN + Book book = bookRepository.findByIsbn(isbn); + if (book == null) { + throw new IllegalArgumentException("Book not found with ISBN: " + isbn); + } + + // Validar si ya existe un préstamo asociado al estudiante o al libro + if (issuesRepository.existsByIssueStudent_Usn(usn)) { + throw new IllegalStateException("There is already an issue associated with this USN."); + } + + if (issuesRepository.existsByIssueBook_Isbn(isbn)) { + throw new IllegalStateException("There is already an issue associated with this ISBN."); + } + + // Crear y guardar el préstamo + Issue issue = new Issue(getDate(), getExpiredDate(), student, book); + issuesRepository.save(issue); + } + + + public Issue findIssueByStudentUsn(String usn) { + return issuesRepository.findIssuesByIssueStudent_Usn(usn); + } + + private String getDate() { + LocalDate actualDate = LocalDate.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + return actualDate.format(formatter); + } + + private String getExpiredDate() { + LocalDate actualDate = LocalDate.now(); + LocalDate datePlusWeek = actualDate.plusWeeks(1); + return datePlusWeek.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/homework_library/services/StudentService.java b/src/main/java/com/example/homework_library/services/StudentService.java new file mode 100644 index 00000000..a0a0e22a --- /dev/null +++ b/src/main/java/com/example/homework_library/services/StudentService.java @@ -0,0 +1,25 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Student; +import com.example.homework_library.repositories.StudentRepository; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class StudentService { + + private final StudentRepository studentRepository; + + public StudentService(StudentRepository studentRepository) { + this.studentRepository = studentRepository; + } + + public Student findStudentByUsn(String usn) { + return studentRepository.findStudentByUsn(usn); + } + + public List listAllStudents() { + return studentRepository.findAll(); + } +} \ No newline at end of file diff --git a/src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java b/src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java deleted file mode 100644 index e889a16b..00000000 --- a/src/test/java/com/example/homework_library/HomeworkLibraryApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.example.homework_library; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class HomeworkLibraryApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/src/test/java/com/example/homework_library/models/BookTest.java b/src/test/java/com/example/homework_library/models/BookTest.java deleted file mode 100644 index 55bfb5ea..00000000 --- a/src/test/java/com/example/homework_library/models/BookTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.example.homework_library.models; - -import com.example.homework_library.repositories.BookRepository; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; - -import java.util.List; - -@SpringBootTest -class BookTest { - - @Autowired - BookRepository bookRepository; - - @Test - @DisplayName("Save book") - void saveBook(){ - Book book = new Book("32fs4r", "El señor de los anillos", "accion", 42); - bookRepository.save(book); - - } - - @Test - @DisplayName("Buscar todos los libros") - void listAllBooks(){ - List allBooks = bookRepository.findAllBooksAndAuthors(); - - System.out.println("============================"); - System.out.println("Los libros que hemos encontrado son: "); - System.out.println(allBooks); - System.out.println("==================="); - } - -} \ No newline at end of file diff --git a/src/test/java/com/example/homework_library/models/StudentTest.java b/src/test/java/com/example/homework_library/models/StudentTest.java deleted file mode 100644 index f8aeeb7b..00000000 --- a/src/test/java/com/example/homework_library/models/StudentTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.example.homework_library.models; - -import com.example.homework_library.repositories.StudentRepository; -import jakarta.transaction.Transactional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.Rollback; - -@SpringBootTest -class StudentTest { - - @Autowired - StudentRepository studentRepository; - - @Test - @DisplayName("Guardo un estudiante en la base de datos") - @Transactional - @Rollback(false) - void saveStudent(){ - Student student = new Student("123a", "Daniel"); - - studentRepository.save(student); - } - - @Test - @DisplayName("Listar todos los estudiantes") - void findAll(){ - System.out.println("============================"); - System.out.println("Los estudiantes que hemos encontrado son: "); - System.out.println(studentRepository.findAll()); - System.out.println("==================="); - } - -} \ No newline at end of file diff --git a/src/test/java/com/example/homework_library/services/BookServiceTest.java b/src/test/java/com/example/homework_library/services/BookServiceTest.java new file mode 100644 index 00000000..eff308f8 --- /dev/null +++ b/src/test/java/com/example/homework_library/services/BookServiceTest.java @@ -0,0 +1,99 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Author; +import com.example.homework_library.models.Book; +import com.example.homework_library.repositories.AuthorRepository; +import com.example.homework_library.repositories.BookRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class BookServiceTest { + + @Mock + private BookRepository bookRepository; + + @Mock + private AuthorRepository authorRepository; + + @InjectMocks + private BookService bookService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testAddBook() { + // Arrange + String isbn = "123"; + String title = "Test Book"; + String category = "Fiction"; + String authorName = "John Doe"; + String mail = "john@example.com"; + int booksNumber = 10; + + // Act + bookService.addBook(isbn, title, category, authorName, mail, booksNumber); + + // Assert + ArgumentCaptor bookCaptor = ArgumentCaptor.forClass(Book.class); + ArgumentCaptor authorCaptor = ArgumentCaptor.forClass(Author.class); + + verify(bookRepository, times(1)).save(bookCaptor.capture()); + verify(authorRepository, times(1)).save(authorCaptor.capture()); + + Book capturedBook = bookCaptor.getValue(); + Author capturedAuthor = authorCaptor.getValue(); + + assertEquals(isbn, capturedBook.getIsbn()); + assertEquals(title, capturedBook.getTitle()); + assertEquals(category, capturedBook.getCategory()); + assertEquals(booksNumber, capturedBook.getQuantity()); + + assertEquals(authorName, capturedAuthor.getName()); + assertEquals(mail, capturedAuthor.getEmail()); + assertEquals(capturedBook, capturedAuthor.getAuthorBook()); + } + + @Test + void testSearchBookByTitle() { + Book book = new Book("123", "Test Book", "Fiction", 10); + when(bookRepository.findByTitle("Test Book")).thenReturn(book); + + Book result = bookService.searchBookByTitle("Test Book"); + + assertNotNull(result); + assertEquals("Test Book", result.getTitle()); + } + + @Test + void testListAllBooks() { + when(bookRepository.findAllBooksAndAuthors()).thenReturn(List.of(new Book("123", "Test Book", "Fiction", 10))); + + List books = bookService.listAllBooks(); + + assertFalse(books.isEmpty()); + assertEquals(1, books.size()); + } + + @Test + void testSearchBookByIsbn() { + Book book = new Book("123", "Test Book", "Fiction", 10); + when(bookRepository.findByIsbn("123")).thenReturn(book); + + Book result = bookService.searchBookByIsbn("123"); + + assertNotNull(result); + assertEquals("123", result.getIsbn()); + } +} \ No newline at end of file diff --git a/src/test/java/com/example/homework_library/services/IssueServiceTest.java b/src/test/java/com/example/homework_library/services/IssueServiceTest.java new file mode 100644 index 00000000..b126969b --- /dev/null +++ b/src/test/java/com/example/homework_library/services/IssueServiceTest.java @@ -0,0 +1,61 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Book; +import com.example.homework_library.models.Issue; +import com.example.homework_library.models.Student; +import com.example.homework_library.repositories.BookRepository; +import com.example.homework_library.repositories.IssuesRepository; +import com.example.homework_library.repositories.StudentRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class IssueServiceTest { + + @Mock + private IssuesRepository issuesRepository; + + @Mock + private StudentRepository studentRepository; + + @Mock + private BookRepository bookRepository; + + @InjectMocks + private IssueService issueService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testIssueBook() { + Student student = new Student("USN123", "John Doe"); + Book book = new Book("123", "Test Book", "Fiction", 10); + + when(studentRepository.findStudentByUsn("USN123")).thenReturn(student); + when(bookRepository.findByIsbn("123")).thenReturn(book); + when(issuesRepository.existsByIssueStudent_Usn("USN123")).thenReturn(false); + when(issuesRepository.existsByIssueBook_Isbn("123")).thenReturn(false); + + issueService.issueBook("USN123", "123"); + + verify(issuesRepository, times(1)).save(any(Issue.class)); + } + + @Test + void testFindIssueByStudentUsn() { + Issue issue = new Issue("2023-10-01", "2023-10-08", new Student(), new Book()); + when(issuesRepository.findIssuesByIssueStudent_Usn("USN123")).thenReturn(issue); + + Issue result = issueService.findIssueByStudentUsn("USN123"); + + assertNotNull(result); + } +} \ No newline at end of file diff --git a/src/test/java/com/example/homework_library/services/StudentServiceTest.java b/src/test/java/com/example/homework_library/services/StudentServiceTest.java new file mode 100644 index 00000000..d018dfe8 --- /dev/null +++ b/src/test/java/com/example/homework_library/services/StudentServiceTest.java @@ -0,0 +1,49 @@ +package com.example.homework_library.services; + +import com.example.homework_library.models.Student; +import com.example.homework_library.repositories.StudentRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class StudentServiceTest { + + @Mock + private StudentRepository studentRepository; + + @InjectMocks + private StudentService studentService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testFindStudentByUsn() { + Student student = new Student("USN123", "John Doe"); + when(studentRepository.findStudentByUsn("USN123")).thenReturn(student); + + Student result = studentService.findStudentByUsn("USN123"); + + assertNotNull(result); + assertEquals("USN123", result.getUsn()); + } + + @Test + void testListAllStudents() { + when(studentRepository.findAll()).thenReturn(List.of(new Student("USN123", "John Doe"))); + + List students = studentService.listAllStudents(); + + assertFalse(students.isEmpty()); + assertEquals(1, students.size()); + } +} \ No newline at end of file From a28a4d179226186b4d97a99ad1592793577c65e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Su=C3=A1rez=20Garc=C3=ADa?= Date: Wed, 30 Apr 2025 14:19:54 +0200 Subject: [PATCH 20/21] Minor Corrections --- .../HomeworkLibraryApplication.java | 64 +++++++++++++++++-- .../repositories/AuthorRepository.java | 2 + .../services/AuthorService.java | 6 ++ 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java index 4efb79fb..d7659b88 100644 --- a/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java +++ b/src/main/java/com/example/homework_library/HomeworkLibraryApplication.java @@ -1,13 +1,17 @@ package com.example.homework_library; +import com.example.homework_library.models.Author; import com.example.homework_library.models.Book; import com.example.homework_library.models.Issue; +import com.example.homework_library.models.Student; +import com.example.homework_library.services.AuthorService; import com.example.homework_library.services.BookService; import com.example.homework_library.services.IssueService; import com.example.homework_library.services.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; import java.util.List; import java.util.NoSuchElementException; @@ -25,6 +29,9 @@ public class HomeworkLibraryApplication { @Autowired private IssueService issueService; + @Autowired + private AuthorService authorService; + public static final String RESET = "\u001B[0m"; public static final String GREEN = "\u001B[32m"; public static final String CYAN = "\u001B[36m"; @@ -32,10 +39,6 @@ public class HomeworkLibraryApplication { private final Scanner scanner = new Scanner(System.in); - public static void main(String[] args) { - SpringApplication.run(HomeworkLibraryApplication.class, args).getBean(HomeworkLibraryApplication.class).runMenu(); - } - public void runMenu() { boolean running = true; @@ -52,7 +55,9 @@ public void runMenu() { case "5" -> listAllBooks(); case "6" -> issueBook(); case "7" -> listAllBooksByUSN(); - case "8", "exit" -> running = false; + case "8" -> listAllStudents(); + case "9" -> listAllAuthors(); + case "0", "exit" -> running = false; default -> System.out.println("Invalid option. Please try again."); } } catch (IllegalArgumentException e) { @@ -76,7 +81,11 @@ private void menuDisplay() { System.out.println(CYAN + "5. 📚 List all books along with author" + RESET); System.out.println(CYAN + "6. 🎓 Issue book to student" + RESET); System.out.println(CYAN + "7. 🆔 List books by USN" + RESET); - System.out.println(RED + "8. 🚪 Exit" + RESET); + System.out.println(CYAN + "8. 👩‍🎓 List all students" + RESET); + System.out.println(CYAN + "9. ✍️ List all authors" + RESET); + System.out.println(GREEN + "-----------------------------------------" + RESET); + System.out.println(RED + "0. 🚪 Exit" + RESET); + System.out.println(GREEN + "=========================================" + RESET); System.out.print("Choose an option: "); } @@ -141,6 +150,38 @@ private void listAllBooks() { System.out.println(separator); } + private void listAllStudents() { + List students = studentService.listAllStudents(); + + String separator = String.format("%-50s", "").replace(' ', '='); + + System.out.println(separator); + System.out.printf("%-20s %-30s%n", "USN", "Student Name"); + System.out.println(separator); + + for (Student student : students) { + System.out.printf("%-20s %-30s%n", student.getUsn(), student.getName()); + } + + System.out.println(separator); + } + + private void listAllAuthors() { + List authors = authorService.findAll(); + + String separator = String.format("%-60s", "").replace(' ', '='); + + System.out.println(separator); + System.out.printf("%-30s %-30s%n", "Author Name", "Email"); + System.out.println(separator); + + for (Author author : authors) { + System.out.printf("%-30s %-30s%n", author.getName(), author.getEmail()); + } + + System.out.println(separator); + } + private void issueBook() { String usn = prompt("Enter USN: "); @@ -168,4 +209,15 @@ private String prompt(String message) { System.out.print(message); return scanner.nextLine().trim(); } + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(HomeworkLibraryApplication.class, args); + + HomeworkLibraryApplication app = context.getBean(HomeworkLibraryApplication.class); + + app.runMenu(); + + SpringApplication.exit(context); + + } + } diff --git a/src/main/java/com/example/homework_library/repositories/AuthorRepository.java b/src/main/java/com/example/homework_library/repositories/AuthorRepository.java index b94646b3..7891bc73 100644 --- a/src/main/java/com/example/homework_library/repositories/AuthorRepository.java +++ b/src/main/java/com/example/homework_library/repositories/AuthorRepository.java @@ -14,6 +14,8 @@ public interface AuthorRepository extends JpaRepository { // Book findByIsbn(String isbn); Author findByName(String authorName); + List findAll(); + diff --git a/src/main/java/com/example/homework_library/services/AuthorService.java b/src/main/java/com/example/homework_library/services/AuthorService.java index e95b81ba..572bbd4d 100644 --- a/src/main/java/com/example/homework_library/services/AuthorService.java +++ b/src/main/java/com/example/homework_library/services/AuthorService.java @@ -5,6 +5,8 @@ import com.example.homework_library.repositories.AuthorRepository; import org.springframework.stereotype.Service; +import java.util.List; + @Service public class AuthorService { @@ -19,6 +21,10 @@ public Author addAuthor(String name, String email, Book book) { return authorRepository.save(author); } + public List findAll() { + return authorRepository.findAll(); + } + public Author findAuthorByName(String name) { return authorRepository.findByName(name); } From e01d420e6de5dc0cb70918328418d6f0bc9dffc4 Mon Sep 17 00:00:00 2001 From: dsuarezg <45487729+dsuarezg@users.noreply.github.com> Date: Wed, 30 Apr 2025 14:24:31 +0200 Subject: [PATCH 21/21] Delete src/main/resources directory --- src/main/resources/application.properties | 8 -------- src/main/resources/application.properties.example | 6 ------ 2 files changed, 14 deletions(-) delete mode 100644 src/main/resources/application.properties delete mode 100644 src/main/resources/application.properties.example diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index 755d30cd..00000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -spring.application.name=ironlibrary -spring.jpa.hibernate.ddl-auto=update -spring.jpa.show-sql=true -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect -spring.datasource.url=jdbc:mariadb://tommy.heliohost.org:3306/dsuarezg_ironhack -spring.datasource.username=dsuarezg_ironhack -spring.datasource.password=ironlibrary - diff --git a/src/main/resources/application.properties.example b/src/main/resources/application.properties.example deleted file mode 100644 index 64ae825d..00000000 --- a/src/main/resources/application.properties.example +++ /dev/null @@ -1,6 +0,0 @@ -spring.application.name=myNameExample -spring.datasource.url=jdbc:mysql://localhost:3306/myDatabaseExample -spring.datasource.username=myUser -spring.datasource.password=myPassword -spring.jpa.hibernate.ddl-auto=validate -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect \ No newline at end of file