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..3e63272c --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +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/ + +src/main/resources/application.properties 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/README.md b/README.md index df676c12..637c99f3 100644 --- a/README.md +++ b/README.md @@ -1,188 +1,78 @@ -![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) +# 📚 IronLibrary – Sistema de Gestión de Biblioteca en Java -# HW | Java IronLibrary (Unit 3 homework) +Este proyecto es una aplicación de consola desarrollada en Java que permite gestionar una biblioteca académica. A través de un menú interactivo, los usuarios pueden registrar libros y autores, emitir préstamos a estudiantes, buscar libros por distintos criterios y consultar información sobre préstamos activos. -## Introduction +## 🧩 Estructura del Proyecto -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. +El sistema se basa en cuatro clases principales: -## Instructions +- **Book**: Representa un libro con atributos como `isbn`, `title`, `category` y `quantity`. +- **Author**: Representa un autor con atributos como `authorId`, `name`, `email` y una relación uno a uno con un `Book`. +- **Student**: Representa a un estudiante con atributos como `usn` (número único de estudiante) y `name`. +- **Issue**: Representa un préstamo de libro con atributos como `issueId`, `issueDate`, `returnDate` y relaciones uno a uno con un `Student` y un `Book`. -Let's walk through the details of the homework: +## 🖥️ Funcionalidades -### Classes +- Agregar libros con sus autores. +- Buscar libros por título, categoría o autor. +- Listar todos los libros junto a su autor. +- Emitir libros a estudiantes (gestión de préstamos). +- Consultar los libros prestados a un estudiante por su USN. +- Validación de entradas y control de errores. +- Persistencia de datos con base de datos SQL. -Four main classes are necessary to complete this homework. +## ⚙️ Requisitos Previos -These classes will be called **Author**, **Book**, **Student** and **Issue**. +- **Java** +- **Maven** +- **MySQL** (u otro sistema de gestión de base de datos SQL compatible) +- **IDE recomendado**: IntelliJ IDEA -
+## 🧪 Configuración de Base de Datos -**Book class** +**1**. Crea una base de datos en MySQL llamada `ironlibrary`. -This class will have: + ```sql + CREATE DATABASE ironlibrary; + ``` -- 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 -
+**2.Configura tu conexión en el archivo src/main/resources/application.properties (si usas Spring) o directamente en el +código JDBC:** -**Author class** -This class will have: +``` properties -- 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 +jdbc.url=jdbc:mysql://localhost:3306/ironlibrary +jdbc.user=tu_usuario +jdbc.password=tu_contraseña ``` +**🚀 Ejecución del Proyecto** +Clonar el repositorio: -3. **Search book by category**: This action is responsible for searching a book by category. +```bash +git clone https://github.com/franciscofarrando/homework-java-ironlibrary.git +cd homework-java-ironlibrary +Compilar y ejecutar (usando Maven): ``` -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 +```bash +mvn clean install +mvn exec:java +Asegúrate de tener en el pom.xml configurado el plugin exec-maven-plugin con el mainClass correcto. ``` +## ✅ Pruebas +**Este proyecto contiene pruebas unitarias para métodos relevantes. Para ejecutarlas:** -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 +```bash + mvn test ``` -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! +## 👨🏻‍💻 Autores +- **Francisco Farrando** - [franciscofarrando] +- **Javier Moneo** - [AsterixKo] +- **Juan Jose Franco** - [DevJerryX] \ No newline at end of file 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..8bdd6046 --- /dev/null +++ b/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.4 + + + com.example + ironlibrary + 0.0.1-SNAPSHOT + ironlibrary + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + 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/ironlibrary/AppHandler.java b/src/main/java/com/example/ironlibrary/AppHandler.java new file mode 100644 index 00000000..ea4178b0 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/AppHandler.java @@ -0,0 +1,97 @@ +package com.example.ironlibrary; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Scanner; + +@Component +public class AppHandler { + @Autowired + private BookHandler bookHandler; + + Scanner scanner = new Scanner(System.in); + + public void menu() { + + String[] optionMenu = {"Add Book", + "Search book by title", + "Search book by category", + "Search book by Author", + "List all books along with Author", + "Issue book to Student", + "List books by usbn", + "Exit"}; + int option = 0; + while (option!=8) { + for (int i = 0; i < optionMenu.length; i++) { + System.out.println((i + 1) + ". " + optionMenu[i]); + } + + System.out.println("Please select an option: "); + try { + option = scanner.nextInt(); + switch (option) { + case 1: + System.out.println("Add Book"); + bookHandler.addBook(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 2: + System.out.println("Search book by title"); + bookHandler.findByTitle(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 3: + System.out.println("Search book by category"); + bookHandler.findByCategory(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 4: + System.out.println("Search book by Author"); + bookHandler.findByAuthor(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 5: + System.out.println("List all books along with Author"); + bookHandler.findByAlongAuthor(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 6: + System.out.println("Issue book to Student"); + bookHandler.issueBookToStudent(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 7: + System.out.println("List books by usbn"); + bookHandler.findBooksByUsbn(); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + break; + case 8: + System.out.println("Exit"); + break; + default: + System.out.println("Invalid option. Please try again."); + System.out.println("Please press enter to continue"); + scanner.nextLine(); + } + } catch (Exception e) { + System.out.println("Invalid input. Please enter a number."); + } finally { + scanner.nextLine(); // Clear the buffer + } + + } + + + } + + +} \ No newline at end of file diff --git a/src/main/java/com/example/ironlibrary/BookHandler.java b/src/main/java/com/example/ironlibrary/BookHandler.java new file mode 100644 index 00000000..8bc58fae --- /dev/null +++ b/src/main/java/com/example/ironlibrary/BookHandler.java @@ -0,0 +1,162 @@ +package com.example.ironlibrary; + + +import com.example.ironlibrary.exceptions.BookExceptions; +import com.example.ironlibrary.exceptions.ErrorsMessages; +import com.example.ironlibrary.models.Author; +import com.example.ironlibrary.models.Book; +import com.example.ironlibrary.models.Issue; +import com.example.ironlibrary.models.Student; +import com.example.ironlibrary.repository.AuthorRepository; +import com.example.ironlibrary.repository.BookRepository; +import com.example.ironlibrary.repository.IssueRepository; +import com.example.ironlibrary.repository.StudentRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; + +@Component +public class BookHandler { + + @Autowired + private BookRepository bookRepository; + + @Autowired + private AuthorRepository authorRepository; + + @Autowired + private IssueRepository issueRepository; + + @Autowired + private StudentRepository studentRepository; + + @Autowired + private DataTransferToBBDD dataTransferToBBDD; + + + static Scanner scanner = new Scanner(System.in); + + public void addBook() throws BookExceptions { + System.out.print("Enter ISBN: "); + String isbn = scanner.nextLine(); + // Check ISBN + String IsbnOk = checkISBN(isbn); + System.out.print("Enter Title: "); + String title = scanner.nextLine(); + checkEmpty(title, 1); + System.out.print("Enter Category: "); + String category = scanner.nextLine(); + checkEmpty(category, 2); + System.out.print("Enter Quantity: "); + String quantityInput = scanner.nextLine(); + int quantity; + try { + quantity = Integer.parseInt(quantityInput); + } catch (NumberFormatException e) { + throw new BookExceptions(ErrorsMessages.INVALID_QUANTITY); + } + + // Author + System.out.print("Enter Author Name: "); + String authorName = scanner.nextLine(); + System.out.print("Enter Author Email: "); + String authorEmail = scanner.nextLine(); + + dataTransferToBBDD.dataAddBook(authorName, authorEmail, IsbnOk, title, category, quantity); + // Show the book + System.out.println("Book added successfully!"); + + + } + + public void findByCategory() throws BookExceptions { + System.out.print("Enter the category of the book: "); + String category = scanner.nextLine(); + checkEmpty(category, 2); + // Find books by category + dataTransferToBBDD.findByCategory(category); + + } + + public void findByTitle() throws BookExceptions { + System.out.print("Enter the title of the book: "); + String title = scanner.nextLine(); + checkEmpty(title, 1); + dataTransferToBBDD.findByTitle(title); + + } + + public void findByAuthor() throws BookExceptions { + System.out.print("Enter the author name: "); + String authorName = scanner.nextLine(); + checkEmpty(authorName, 3); + dataTransferToBBDD.findByAuthor(authorName); + + } + + public void findByAlongAuthor() throws BookExceptions { + System.out.println("Enter the author name: "); + String authorName = scanner.nextLine(); + checkEmpty(authorName, 3); + dataTransferToBBDD.findByAlongAuthor(authorName); + + } + + public void issueBookToStudent() { + System.out.println("Enter a usn of Student: "); + String usn = scanner.nextLine(); + System.out.println("Enter a name of Student: "); + String name = scanner.nextLine(); + System.out.println("Enter a book ISBN: "); + String isbn = scanner.nextLine(); + dataTransferToBBDD.issueBookToStudent(usn,name,isbn); + + } + + public void findBooksByUsbn() throws BookExceptions { + System.out.println("Enter a usn of Student: "); + String usn = scanner.nextLine(); + checkEmpty(usn, 4); + dataTransferToBBDD.findBooksByUsbn(usn); + } + + // VALIDATES ADD BOOKS + private void checkEmpty(String input, int num) throws BookExceptions { + if (num == 1 && input.isEmpty()) { + throw new BookExceptions(ErrorsMessages.TITLE_EMPTY); + } + if (num == 2 && input.isEmpty()) { + throw new BookExceptions(ErrorsMessages.CATEGORY_EMPTY); + } + if (num == 3 && input.isEmpty()) { + throw new BookExceptions(ErrorsMessages.AUTHOR_EMPTY); + } + if (num == 4 && input.isEmpty()) { + throw new BookExceptions(ErrorsMessages.USN_EMPTY); + } + } + + private String checkISBN(String isbn) throws BookExceptions { + String isbnTrim = isbn.trim(); + if (isbnTrim.length() != 13) { + throw new BookExceptions(ErrorsMessages.ISBN_INVALID); + } else if (isbn.isEmpty()) { + throw new BookExceptions(ErrorsMessages.ISBN_EMPTY); + } else { + for (int i = 0; i < isbnTrim.length(); i++) { + if (!Character.isDigit(isbnTrim.charAt(i))) { + throw new BookExceptions(ErrorsMessages.ISBN_NOT_CHAR); + } + } + } + // format the ISBN + return isbn.substring(0, 3) + "-" + isbn.substring(3, 4) + "-" + isbn.substring(4, 7) + "-" + isbn.substring(7, + 12) + "-" + isbn.charAt(12); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/example/ironlibrary/DataTransferToBBDD.java b/src/main/java/com/example/ironlibrary/DataTransferToBBDD.java new file mode 100644 index 00000000..675b4d55 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/DataTransferToBBDD.java @@ -0,0 +1,174 @@ +package com.example.ironlibrary; + +import com.example.ironlibrary.models.Author; +import com.example.ironlibrary.models.Book; +import com.example.ironlibrary.models.Issue; +import com.example.ironlibrary.models.Student; +import com.example.ironlibrary.repository.AuthorRepository; +import com.example.ironlibrary.repository.BookRepository; +import com.example.ironlibrary.repository.IssueRepository; +import com.example.ironlibrary.repository.StudentRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +@Component +public class DataTransferToBBDD { + + @Autowired + private BookRepository bookRepository; + @Autowired + private AuthorRepository authorRepository; + @Autowired + private StudentRepository studentRepository; + @Autowired + private IssueRepository issueRepository; + + + + public void dataAddBook(String name, String email, String IsbnOk, String title, String category, int quantity) { + Author author = new Author(); + author.setName(name); + author.setEmail(email); + + // Save the author to the database + authorRepository.save(author); + // Create a new Book object + Book book = new Book(); + book.setIsbn(IsbnOk); + book.setTitle(title); + book.setCategory(category); + book.setQuantity(quantity); + book.setAuthor(author); + // Save the book to the database + bookRepository.save(book); + + } + + public void findByCategory(String category) { + // repository + List books = bookRepository.findBookByCategory(category); + if (books != null) { + System.out.printf("%-20s %-50s %-30s %-12s%n", + "Book ISBN", "Book Title", "Category", "No of Books"); + for (Book book : books) { + System.out.printf("%-20s %-50s %-30s %-12d%n", + book.getIsbn(), + book.getTitle(), + book.getCategory(), + book.getQuantity()); + } + } else { + System.out.println("No books found."); + } + } + + public void findByTitle(String title) { + Book book = bookRepository.findByTitleContaining(title); + if (book != null) { + System.out.printf("%-20s %-50s %-30s %-12s%n", + "Book ISBN", "Book Title", "Category", "No of Books"); + System.out.printf("%-20s %-50s %-30s %-12d%n", + book.getIsbn(), + book.getTitle(), + book.getCategory(), + book.getQuantity()); + } else { + System.out.println("No books found."); + } + } + + + public void findByAuthor(String name) { + List books = bookRepository.findBookByAuthorName(name); + if (books != null) { + System.out.printf("%-20s %-50s %-30s %-12s%n", + "Book ISBN", "Book Title", "Category", "No of Books"); + for (Book book : books) { + System.out.printf("%-20s %-50s %-30s %-12s%n", + book.getIsbn(), + book.getTitle(), + book.getCategory(), + book.getQuantity()); + } + } else { + System.out.println("No books found."); + } + + } + + public void findByAlongAuthor(String name){ + List books = bookRepository.findBookByAuthorName(name); + if (books != null) { + Book book = books.getFirst(); + System.out.printf("%-20s %-50s %-30s %-12s%n", + "Book ISBN", "Book Title", "Category", "No of Books"); + + System.out.printf("%-20s %-50s %-30s %-12s%n", + book.getIsbn(), + book.getTitle(), + book.getCategory(), + book.getQuantity()); + + } else { + System.out.println("No books found."); + } + } + + public void issueBookToStudent(String usn,String name, String isbn){ + // Find Student By USN and Name + + Optional student = studentRepository.findStudentByUsnAndName(usn, name); + //Find Book By ISBN + Optional book = bookRepository.findBookByIsbn(isbn); + + if (student.isPresent() && book.isPresent()) { + // ISSUE BOOK + Issue issue = new Issue(); + //TODO: mirar el dia del prestamo y el retorno del mismo + issue.setIssueDate(new Date().toString()); + issue.setReturnDate(new Date().toString() + 15); + issue.setStudent(student.get()); + issue.setBook(book.get()); + // update quantity of book + book.get().setQuantity(book.get().getQuantity() - 1); + // save book + bookRepository.save(book.get()); + // save issue + issueRepository.save(issue); + System.out.println("Issue Book"); + } else { + System.out.println("Student or Book not found"); + } + + } + + + public void findBooksByUsbn(String usn){ + + // Find id of Student by Student USN + Optional student = studentRepository.findStudentByUsn(usn); + if (student.isPresent()) { + // find iisued by student + List issues = issueRepository.findIssueByStudent(student.get()); + if (issues != null) { + System.out.printf("%-50s %-30s %-12s%n", + "Book Title", "Student Name", "Return Date"); + for (Issue issue : issues) { + Book book = issue.getBook(); + System.out.printf("%-50s %-30s %-12s%n", + issue.getBook().getTitle(), + issue.getStudent().getName(), + issue.getReturnDate()); + } + } else { + System.out.println("No books found."); + } + } + + } + +} diff --git a/src/main/java/com/example/ironlibrary/LibraryApplication.java b/src/main/java/com/example/ironlibrary/LibraryApplication.java new file mode 100644 index 00000000..510f1622 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/LibraryApplication.java @@ -0,0 +1,25 @@ +package com.example.ironlibrary; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import java.util.Scanner; + +@SpringBootApplication +@EnableJpaRepositories(basePackages = "com.example.ironlibrary") +public class LibraryApplication implements CommandLineRunner { + + @Autowired + private AppHandler appHandler; + + public static void main(String[] args) { + SpringApplication.run(LibraryApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + appHandler.menu(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/ironlibrary/exceptions/BookExceptions.java b/src/main/java/com/example/ironlibrary/exceptions/BookExceptions.java new file mode 100644 index 00000000..6c2da733 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/exceptions/BookExceptions.java @@ -0,0 +1,8 @@ +package com.example.ironlibrary.exceptions; + +public class BookExceptions extends Exception { + public BookExceptions(String message) { + super(); + } +} + diff --git a/src/main/java/com/example/ironlibrary/exceptions/ErrorsMessages.java b/src/main/java/com/example/ironlibrary/exceptions/ErrorsMessages.java new file mode 100644 index 00000000..de2686ac --- /dev/null +++ b/src/main/java/com/example/ironlibrary/exceptions/ErrorsMessages.java @@ -0,0 +1,26 @@ +package com.example.ironlibrary.exceptions; + +public class ErrorsMessages { + + // Error messages BOOK + //ISBN + public static final String ISBN_EMPTY = "ISBN cannot be empty"; + public static final String ISBN_INVALID = "The ISBN must have a length of 13 numbers"; + public static final String ISBN_NOT_CHAR = "The ISBN must contain only numbers"; + //TITLE + public static final String TITLE_EMPTY = "Title cannot be empty"; + //CATEGORY + public static final String CATEGORY_EMPTY = "Category cannot be empty"; + //QUANTITY + public static final String INVALID_QUANTITY = "Quantity must be a number"; + //AUTHOR BOOK + public static final String AUTHOR_EMPTY = "Author cannot be empty"; + //Student USN + public static final String USN_EMPTY = "USN cannot be empty"; + + // Constructor + public ErrorsMessages() { + } + } + + diff --git a/src/main/java/com/example/ironlibrary/models/Author.java b/src/main/java/com/example/ironlibrary/models/Author.java new file mode 100644 index 00000000..e0729889 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/models/Author.java @@ -0,0 +1,54 @@ +package com.example.ironlibrary.models; + +import jakarta.persistence.*; + +import java.util.List; + +@Entity +@Table(name = "author") +public class Author { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + + private Integer id; + @Column(name = "author_name") + private String name; + @Column(name = "author_email") + private String email; + @OneToMany(mappedBy = "author",cascade = CascadeType.ALL,orphanRemoval = true) + List books; + + public Author() { + } + + public Author(String name, String email, List books) { + this.name = name; + this.email = email; + this.books = books; + } + + + public Integer getId() { + return id; + } + + public void setId(Integer 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; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/ironlibrary/models/Book.java b/src/main/java/com/example/ironlibrary/models/Book.java new file mode 100644 index 00000000..a52be748 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/models/Book.java @@ -0,0 +1,95 @@ +package com.example.ironlibrary.models; + +import jakarta.persistence.*; + +@Entity +@Table(name = "books") + +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(unique = true) + private String isbn; + private String title; + private String category; + private int quantity; + @ManyToOne + @JoinColumn(name = "author_id") + private Author author; + @OneToOne(mappedBy = "book") + private Issue issue; + + public Book() { + + } + + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } + + public Issue getIssue() { + return issue; + } + + public void setIssue(Issue issue) { + this.issue = issue; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public 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{" + + "id=" + id + + ", isbn='" + isbn + '\'' + + ", title='" + title + '\'' + + ", category='" + category + '\'' + + ", quantity=" + quantity + + + '}'; + } +} diff --git a/src/main/java/com/example/ironlibrary/models/Issue.java b/src/main/java/com/example/ironlibrary/models/Issue.java new file mode 100644 index 00000000..a0386fa5 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/models/Issue.java @@ -0,0 +1,62 @@ +package com.example.ironlibrary.models; + +import jakarta.persistence.*; + +@Entity +@Table(name = "issue") +public class Issue { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + private String issueDate; + private String returnDate; + @ManyToOne + @JoinColumn(name = "student_id") + private Student student; + @OneToOne + @JoinColumn(name = "book_id") + private Book book; + + public Issue() { + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getIssueDate() { + return issueDate; + } + + public void setIssueDate(String issueDate) { + this.issueDate = issueDate; + } + + public String getReturnDate() { + return returnDate; + } + + public void setReturnDate(String returnDate) { + this.returnDate = returnDate; + } + + public Student getStudent() { + return student; + } + + public void setStudent(Student student) { + this.student = student; + } + + public Book getBook() { + return book; + } + + public void setBook(Book book) { + this.book = book; + } +} diff --git a/src/main/java/com/example/ironlibrary/models/Student.java b/src/main/java/com/example/ironlibrary/models/Student.java new file mode 100644 index 00000000..8447816c --- /dev/null +++ b/src/main/java/com/example/ironlibrary/models/Student.java @@ -0,0 +1,57 @@ +package com.example.ironlibrary.models; + +import jakarta.persistence.*; + +import java.util.List; + +@Entity +@Table(name = "student") +public class Student { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(unique = true) + private String usn; + private String name; + @OneToMany(mappedBy = "student", cascade = CascadeType.ALL,orphanRemoval = true) + List issues; + public Student() { + } + + public List getIssues() { + return issues; + } + + public void setIssues(List issues) { + this.issues = issues; + } + + public Student(String usn, String name) { + this.usn = usn; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsn() { + return usn; + } + + public void setUsn(String usn) { + this.usn = usn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/com/example/ironlibrary/repository/AuthorRepository.java b/src/main/java/com/example/ironlibrary/repository/AuthorRepository.java new file mode 100644 index 00000000..7421f73a --- /dev/null +++ b/src/main/java/com/example/ironlibrary/repository/AuthorRepository.java @@ -0,0 +1,13 @@ +package com.example.ironlibrary.repository; + +import com.example.ironlibrary.models.Author; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + + +@Repository +public interface AuthorRepository extends JpaRepository { + Author findByName(String nameAuthor); +} diff --git a/src/main/java/com/example/ironlibrary/repository/BookRepository.java b/src/main/java/com/example/ironlibrary/repository/BookRepository.java new file mode 100644 index 00000000..5bc45174 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/repository/BookRepository.java @@ -0,0 +1,22 @@ +package com.example.ironlibrary.repository; + +import com.example.ironlibrary.models.Book; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface BookRepository extends JpaRepository { + Book findByTitleContaining(String title); + List findBookByCategory(String category); + List findBookByAuthorName(String authorName); + + Optional findBookByIsbn(String isbn); + List findAllByIsbn(String isbn); + + Book findByIsbn(String isbn); + + Book findByTitle(String titleBook); +} diff --git a/src/main/java/com/example/ironlibrary/repository/IssueRepository.java b/src/main/java/com/example/ironlibrary/repository/IssueRepository.java new file mode 100644 index 00000000..322cd826 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/repository/IssueRepository.java @@ -0,0 +1,16 @@ +package com.example.ironlibrary.repository; + +import com.example.ironlibrary.models.Issue; + +import com.example.ironlibrary.models.Student; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface IssueRepository extends JpaRepository { + List findIssueByStudent(Student student); + + Issue findByBookIsbn(String isbn); +} \ No newline at end of file diff --git a/src/main/java/com/example/ironlibrary/repository/StudentRepository.java b/src/main/java/com/example/ironlibrary/repository/StudentRepository.java new file mode 100644 index 00000000..f1ab1e07 --- /dev/null +++ b/src/main/java/com/example/ironlibrary/repository/StudentRepository.java @@ -0,0 +1,14 @@ +package com.example.ironlibrary.repository; + +import com.example.ironlibrary.models.Student; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface StudentRepository extends JpaRepository { + Optional findStudentByUsnAndName(String usn, String name); + Optional findStudentByUsn(String usn); + +} \ No newline at end of file diff --git a/src/main/resources/SQL/AuthorInsert.sql b/src/main/resources/SQL/AuthorInsert.sql new file mode 100644 index 00000000..a56d4066 --- /dev/null +++ b/src/main/resources/SQL/AuthorInsert.sql @@ -0,0 +1,11 @@ +INSERT INTO author (author_name, author_email) VALUES + ('J.K. Rowling', 'jkrowling@example.com'), + ('George R.R. Martin', 'grrmartin@example.com'), + ('J.R.R. Tolkien', 'jrrtolkien@example.com'), + ('Agatha Christie', 'agathachristie@example.com'), + ('Stephen King', 'stephenking@example.com'), + ('Isaac Asimov', 'isaacasimov@example.com'), + ('Arthur Conan Doyle', 'arthurconan@example.com'), + ('Mark Twain', 'marktwain@example.com'), + ('Jane Austen', 'janeausten@example.com'), + ('Charles Dickens', 'charlesdickens@example.com'); \ No newline at end of file diff --git a/src/main/resources/SQL/insertBooks.sql b/src/main/resources/SQL/insertBooks.sql new file mode 100644 index 00000000..58c5bb12 --- /dev/null +++ b/src/main/resources/SQL/insertBooks.sql @@ -0,0 +1,31 @@ +INSERT INTO books (isbn, title, category, quantity, author_id) +VALUES ('978-3-16-148410-0', 'Harry Potter and the Philosopher\'s Stone', 'Fantasy', 5, 1), +('978-1-40-885560-6', 'Harry Potter and the Chamber of Secrets', 'Fantasy', 4, 1), +('978-0-55-310354-0', 'A Game of Thrones', 'Fantasy', 6, 2), +('978-0-55-310356-4', 'A Clash of Kings', 'Fantasy', 5, 2), +('978-0-61-800222-9', 'The Hobbit', 'Fantasy', 7, 3), +('978-0-61-800223-6', 'The Lord of the Rings', 'Fantasy', 3, 3), +('978-0-00-711931-8', 'Murder on the Orient Express', 'Mystery', 8, 4), +('978-0-00-712211-0', 'And Then There Were None', 'Mystery', 6, 4), +('978-0-38-531173-5', 'The Shining', 'Horror', 5, 5), +('978-0-67-003553-9', 'It', 'Horror', 4, 5), +('978-0-06-052844-7', 'Foundation', 'Science Fiction', 7, 6), +('978-0-06-105853-4', 'I, Robot', 'Science Fiction', 6, 6), +('978-1-85-326261-3', 'Sherlock Holmes: A Study in Scarlet', 'Mystery', 5, 7), +('978-1-85-326384-9', 'The Hound of the Baskervilles', 'Mystery', 4, 7), +('978-0-14-243717-9', 'Adventures of Huckleberry Finn', 'Adventure', 5, 8), +('978-0-14-303950-5', 'The Adventures of Tom Sawyer', 'Adventure', 5, 8), +('978-0-14-310542-8', 'Pride and Prejudice', 'Romance', 6, 9), +('978-0-14-043205-3', 'Sense and Sensibility', 'Romance', 5, 9), +('978-0-14-143956-3', 'Great Expectations', 'Classic', 5, 10), +('978-0-14-143954-9', 'A Tale of Two Cities', 'Classic', 6, 10), +('978-0-03-031932-0', 'Carrie', 'Horror', 4, 5), +('978-1-85-326434-1', 'Emma', 'Romance', 3, 9), +('978-0-14-143957-0', 'David Copperfield', 'Classic', 4, 10), +('978-0-61-826376-6', 'The Silmarillion', 'Fantasy', 3, 3), +('978-0-00-747715-0', 'The Casual Vacancy', 'Drama', 2, 1), +('978-1-78-116602-9', 'Fire & Blood', 'Fantasy', 4, 2), +('978-0-00-711943-1', 'Death on the Nile', 'Mystery', 5, 4), +('978-1-47-670299-3', 'The Last Question', 'Science Fiction', 3, 6), +('978-0-03-019861-3', 'Life on the Mississippi', 'Adventure', 2, 8), +('978-0-07-042787-3', 'The Memoirs of Sherlock Holmes', 'Mystery', 3, 7); \ No newline at end of file diff --git a/src/main/resources/SQL/issueInsert.sql b/src/main/resources/SQL/issueInsert.sql new file mode 100644 index 00000000..7903bb41 --- /dev/null +++ b/src/main/resources/SQL/issueInsert.sql @@ -0,0 +1,6 @@ +INSERT INTO issue (issue_date, return_date, student_id, book_id) VALUES +('2025-04-01', '2025-04-15', 1, 1), +('2025-04-05', '2025-04-19', 2, 2), +('2025-04-10', '2025-04-24', 3, 3), +('2025-04-12', '2025-04-26', 4, 4), +('2025-04-14', '2025-04-28', 5, 5); \ No newline at end of file diff --git a/src/main/resources/SQL/studentInsert.sql b/src/main/resources/SQL/studentInsert.sql new file mode 100644 index 00000000..ee5f9d8c --- /dev/null +++ b/src/main/resources/SQL/studentInsert.sql @@ -0,0 +1,6 @@ +INSERT INTO student (usn, name) VALUES + ('USN001', 'John Doe'), + ('USN002', 'Jane Smith'), + ('USN003', 'Mike Johnson'), + ('USN004', 'Emily Davis'), + ('USN005', 'James Brown'); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..232a1d79 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.application.name=ironlibrary +spring.datasource.url=jdbc:mysql://localhost:3306/ironlibrary?useSSL=false&serverTimezone=UTC +spring.datasource.username=root +spring.datasource.password=mysqlpass +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect \ No newline at end of file diff --git a/src/main/resources/uml/uml.png b/src/main/resources/uml/uml.png new file mode 100644 index 00000000..936b1234 Binary files /dev/null and b/src/main/resources/uml/uml.png differ diff --git a/src/test/java/com/example/ironlibrary/DataTransferToBBDDTest.java b/src/test/java/com/example/ironlibrary/DataTransferToBBDDTest.java new file mode 100644 index 00000000..03d2b39c --- /dev/null +++ b/src/test/java/com/example/ironlibrary/DataTransferToBBDDTest.java @@ -0,0 +1,129 @@ +package com.example.ironlibrary; + +import com.example.ironlibrary.models.Author; +import com.example.ironlibrary.models.Book; +import com.example.ironlibrary.models.Issue; +import com.example.ironlibrary.models.Student; +import com.example.ironlibrary.repository.AuthorRepository; +import com.example.ironlibrary.repository.BookRepository; +import com.example.ironlibrary.repository.IssueRepository; +import com.example.ironlibrary.repository.StudentRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +class DataTransferToBBDDTest { + + @Autowired + private BookRepository bookRepository; + @Autowired + private DataTransferToBBDD dataTransferToBBDD; + @Autowired + private AuthorRepository authorRepository; + @Autowired + private IssueRepository issueRepository; + @Autowired + private StudentRepository studentRepository; + + private Author author; + private Book book; + private Student student; + + private final String name = "J.K. Rowling"; + private final String email = "jkrowling@example.com"; + private final String isbn = "9783161484100"; + private final String title = "Harry Potter and the Philosopher's Stone"; + private final String category = "Fantasy"; + private final int quantity = 5; + private final String usn = "USN001"; + private final String nameStudent = "John Doe"; + + + + @Test + @DisplayName("Test find book by category") + void findBookByCategory() { + List bookList = bookRepository.findBookByCategory(category); + assertNotNull(bookList); + assertFalse(bookList.isEmpty()); + Book found = bookList.getFirst(); + assertEquals(isbn, found.getIsbn()); + assertEquals(title, found.getTitle()); + assertEquals(name, found.getAuthor().getName()); + assertEquals(email, found.getAuthor().getEmail()); + assertEquals(quantity, found.getQuantity()); + } + @Test + @DisplayName("Test find book by title") + void findBookByTitle() { + Book found = bookRepository.findByTitle(title); + assertNotNull(found); + assertEquals(title, found.getTitle()); + assertEquals(isbn, found.getIsbn()); + assertEquals(category, found.getCategory()); + assertEquals(quantity, found.getQuantity()); + } + + @Test + @DisplayName("Test find book by author") + void findBookByAuthor() { + List bookList = bookRepository.findBookByAuthorName(name); + assertNotNull(bookList); + assertFalse(bookList.isEmpty()); + Book found = bookList.getFirst(); + assertEquals(name, found.getAuthor().getName()); + assertEquals(email, found.getAuthor().getEmail()); + assertEquals(isbn, found.getIsbn()); + assertEquals(title, found.getTitle()); + assertEquals(category, found.getCategory()); + assertEquals(quantity, found.getQuantity()); + } + + @Test + @DisplayName("Test issue book to student") + void issueBookToStudent() { + Optional optionalStudent = studentRepository.findStudentByUsn(usn); + assertTrue(optionalStudent.isPresent()); + Student foundStudent = optionalStudent.get(); + List issues = issueRepository.findIssueByStudent(foundStudent); + assertFalse(issues.isEmpty()); + Issue foundIssue = issues.get(0); + + assertEquals(usn, foundStudent.getUsn()); + assertEquals(nameStudent, foundStudent.getName()); + assertEquals(isbn, foundIssue.getBook().getIsbn()); + assertEquals(title, foundIssue.getBook().getTitle()); + assertEquals(category, foundIssue.getBook().getCategory()); + assertEquals(quantity, foundIssue.getBook().getQuantity()); + assertEquals(name, foundIssue.getBook().getAuthor().getName()); + } + + @Test + @DisplayName("Test find books by USN") + void findBooksByUsn() { + Optional studentOpt = studentRepository.findStudentByUsn(usn); + assertTrue(studentOpt.isPresent()); + Student foundStudent = studentOpt.get(); + + List issues = issueRepository.findIssueByStudent(foundStudent); + assertNotNull(issues); + assertFalse(issues.isEmpty()); + + Issue issue = issues.get(0); + assertEquals(isbn, issue.getBook().getIsbn()); + assertEquals(title, issue.getBook().getTitle()); + assertEquals(category, issue.getBook().getCategory()); + assertEquals(name, issue.getBook().getAuthor().getName()); + } + + +}