Merge branch 'develop' into 'master'

Merge from Develop

See merge request meliurwen/2019_assignment3_MiVan!1
master
Donati Ivan 5 years ago
commit d1527a3954
  1. 5
      .gitignore
  2. 17
      Dockerfile
  3. 22
      LICENSE
  4. 12
      README.md
  5. 66
      assets/logo.svg
  6. BIN
      assignment3_mivan.pdf
  7. 26
      doc/bibliography.bib
  8. 55
      doc/chapters/01_introduzione.tex
  9. 49
      doc/chapters/02_progetto.tex
  10. 71
      doc/chapters/03_esecuzione.tex
  11. BIN
      doc/img/eer.pdf
  12. BIN
      doc/img/er.pdf
  13. BIN
      doc/img/logo.png
  14. BIN
      doc/img/logo_unimib.pdf
  15. 24
      doc/main.tex
  16. 6
      docker-compose.yml
  17. 14
      mivan/.editorconfig
  18. 31
      mivan/.gitignore
  19. 117
      mivan/.mvn/wrapper/MavenWrapperDownloader.java
  20. BIN
      mivan/.mvn/wrapper/maven-wrapper.jar
  21. 2
      mivan/.mvn/wrapper/maven-wrapper.properties
  22. 310
      mivan/mvnw
  23. 182
      mivan/mvnw.cmd
  24. 72
      mivan/pom.xml
  25. 14
      mivan/src/main/java/mivan/Mivan.java
  26. 75
      mivan/src/main/java/mivan/model/Author.java
  27. 90
      mivan/src/main/java/mivan/model/Book.java
  28. 62
      mivan/src/main/java/mivan/model/Item.java
  29. 112
      mivan/src/main/java/mivan/model/Loan.java
  30. 83
      mivan/src/main/java/mivan/model/Location.java
  31. 73
      mivan/src/main/java/mivan/model/Person.java
  32. 71
      mivan/src/main/java/mivan/model/Staff.java
  33. 65
      mivan/src/main/java/mivan/model/User.java
  34. 20
      mivan/src/main/java/mivan/repository/AuthorRepository.java
  35. 155
      mivan/src/main/java/mivan/repository/AuthorRepositoryImpl.java
  36. 22
      mivan/src/main/java/mivan/repository/BookRepository.java
  37. 158
      mivan/src/main/java/mivan/repository/BookRepositoryImpl.java
  38. 13
      mivan/src/main/java/mivan/repository/ItemRepository.java
  39. 82
      mivan/src/main/java/mivan/repository/ItemRepositoryImpl.java
  40. 15
      mivan/src/main/java/mivan/repository/LoanRepository.java
  41. 97
      mivan/src/main/java/mivan/repository/LoanRepositoryImpl.java
  42. 20
      mivan/src/main/java/mivan/repository/LocationRepository.java
  43. 114
      mivan/src/main/java/mivan/repository/LocationRepositoryImpl.java
  44. 9
      mivan/src/main/java/mivan/repository/Repository.java
  45. 20
      mivan/src/main/java/mivan/repository/StaffRepository.java
  46. 117
      mivan/src/main/java/mivan/repository/StaffRepositoryImpl.java
  47. 21
      mivan/src/main/java/mivan/repository/UserRepository.java
  48. 133
      mivan/src/main/java/mivan/repository/UserRepositoryImpl.java
  49. 27
      mivan/src/main/resources/META-INF/persistence.xml
  50. 2
      mivan/src/main/resources/application.properties
  51. 18
      mivan/src/test/java/mivan/AuthorBookTest.java
  52. 76
      mivan/src/test/java/mivan/AuthorTest.java
  53. 80
      mivan/src/test/java/mivan/BookTest.java
  54. 54
      mivan/src/test/java/mivan/ItemTest.java
  55. 99
      mivan/src/test/java/mivan/LoanTest.java
  56. 116
      mivan/src/test/java/mivan/LocationTest.java
  57. 145
      mivan/src/test/java/mivan/StaffTest.java
  58. 109
      mivan/src/test/java/mivan/UserTest.java

5
.gitignore vendored

@ -9,7 +9,12 @@
*.toc *.toc
*.out *.out
*.bbl *.bbl
*.bbl~
*.blg *.blg
*.bib~ *.bib~
*.pdf *.pdf
mivan/target
mivan/bin

@ -0,0 +1,17 @@
FROM openjdk:8-jdk-slim AS builder
COPY multibook /usr/src/
WORKDIR /usr/src/multibook
RUN apt-get update && apt-get install -y mvn && \
./mvnw clean package spring-boot:repackage
FROM openjdk:8-jdk-slim AS app
COPY --from=builder /usr/src/multibook/target/multibook.jar /usr/src/app.jar
WORKDIR /usr/src
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"]

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2020 Meliurwen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -13,11 +13,17 @@
L'applicazione oggetto di questo assigment è **_MiVan_**. L'applicazione oggetto di questo assigment è **_MiVan_**.
Si tratta di un'applicazione che rende possibile _prenotare_ ed _acquisire_ biglietti per il cinema. Essa mette a disposizione informazioni sulla programmazione, orari, locandine e sinossi. Grazie alla connessione diretta ai sistemi di biglietteria è possibile visualizzzare la mappa dei posti con lo stato di occupazione in tempo reale e selezionare i posti preferiti dall'utente. L'iscrizione è obbligatoria per permettere la _modifica_ e la _cancellazione_ delle prenotazioni, servizio richiesto da molti utenti. Si tratta di un'applicazione che gestisce _prestiti di libri_ di un sistema bibliotecario _con una o più sedi_. Essa, oltre ad essere in grado di gestire i prestiti, è anche in grado di _gestire i libri_, la loro _posizione_, lo _staff_ che amministra i prestiti e gli utenti che ne fanno richiesta.
Allo stato attuale l'applicazione è stata pensata per essere utilizzata nell'area metropolitana di _Brescia_ e _Novara_, con un target iniziale ristretto agli utenti delle principali sale di proiezione delle rispettive città. Grazie a questa applicazione è possibile _creare_, _visualizzzare_, _modificare_ e _rimuovere_ in tempo reale lo stato di prestito dei libri. I prestiti sono descritti da una _data di inizio_, _di fine_, uno _stato_, un _libro_, un _utente_ ed un _operatore_. Si ritiene che sia importante sottolineare che durante la progettazione si è presa la decisione che un prestito possa consistere in _esattamente una unità di libro_, in maniera tale che questo livello di granularità permetta all'utente, in caso di prestito contemporaneo di più libri, di _non_ doverli restituire tutti in blocco.
A seconda della trazione che potrebbe ricevere una volta lanciata, si potrà valutare un'eventuale _espansione_ del territorio coperto e delle sale interessate. Altra caratteristica è la separazione tra concetto di libro ed "unità di libro", questo per gestire in maniera efficiente il caso molto frequente in cui il sistema bibliotecario possieda più copie dello stesso libro; nella nostra implementazione ogni singola unità (Item) corrisponderebbe in maniera univoca all'unità fisica corrispondente.
Una feature degna di nota (che andrebbe a soddisfare il requisito del self-loop) è la possibilità di sapere se nel sistema bibliotecario è disponibile il sequel (ammesso che esista) di un determinato libro.
Allo stato attuale l'applicazione è stata pensata per essere utilizzata nell'area metropolitana di _Brescia_ e _Novara_, con un _target iniziale_ ristretto agli utenti delle _sedi del sistema blibliotecario comunale_ delle rispettive città.
A seconda della trazione che potrebbe ricevere una volta lanciata, si potrà valutare un'eventuale _espansione_ del territorio coperto e degli enti (sia pubblici che privati) interessati.
## Membri del Gruppo ## Membri del Gruppo

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="136.7896mm"
height="137.04852mm"
viewBox="0 0 136.7896 137.04852"
version="1.1"
id="svg8"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="logo.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.98994949"
inkscape:cx="269.87145"
inkscape:cy="206.81528"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:window-width="1918"
inkscape:window-height="1056"
inkscape:window-x="0"
inkscape:window-y="22"
inkscape:window-maximized="0" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Livello 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-29.917799,-56.73715)">
<path
style="opacity:1;fill:#f54700;fill-opacity:1;fill-rule:nonzero;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none"
d="m 34.966589,193.1029 c -1.8269,-0.75105 -3.52092,-2.30787 -4.41546,-4.05787 l -0.63333,-1.239 V 125.23207 62.658116 l 0.71508,-1.355553 c 0.91447,-1.733528 2.77999,-3.37349 4.62105,-4.062318 1.44237,-0.539661 1.56733,-0.540591 63.406634,-0.471844 l 61.961407,0.06888 1.32292,0.608369 c 1.66877,0.767422 3.15184,2.189008 4.05775,3.889547 l 0.70475,1.322917 v 62.573956 62.57396 l -0.70475,1.32292 c -0.84465,1.58554 -2.30325,3.02523 -3.92546,3.87455 l -1.19063,0.62337 -14.85041,0.0794 -14.85041,0.0794 -0.68558,-3.65123 c -0.92669,-4.93528 -0.92503,-4.92224 -1.2424,-9.73664 -0.5117,-7.76224 0.54801,-17.53241 2.43143,-22.417 0.48765,-1.26471 0.70612,-2.18925 0.57297,-2.42483 -0.11835,-0.20941 -1.22721,-1.44703 -2.46414,-2.75028 -3.32748,-3.50588 -4.3499,-4.77869 -7.27185,-9.05268 -3.96144,-5.79448 -8.33723,-14.07234 -10.76941,-20.37292 -1.41682,-3.67029 -2.81819,-7.53002 -3.26616,-8.99583 -0.2446,-0.80037 -0.60858,-1.93146 -0.80884,-2.51354 -3.07069,-8.92515 -6.42925,-27.226244 -7.52611,-41.010422 -0.235517,-2.959833 -0.350327,-3.504166 -0.823097,-3.902605 -0.72311,-0.609414 -1.98543,-0.601723 -2.31501,0.0141 -0.14044,0.262418 -0.38158,1.959059 -0.53585,3.770312 -1.54071,18.088518 -4.95572,34.744455 -9.81602,47.875485 -2.26781,6.12692 -5.284211,12.97269 -7.024181,15.94148 -0.49943,0.85216 -0.90806,1.59269 -0.90806,1.64563 0,0.12851 -2.08242,3.64478 -3.48496,5.88452 -2.27923,3.63973 -5.74768,7.99029 -9.16713,11.49855 l -1.978193,2.02956 0.94274,2.86523 c 1.746063,5.30681 2.359393,9.69353 2.379693,17.02045 0.008,2.83766 -0.13369,6.58812 -0.31455,8.33437 -0.31074,3.00027 -1.42291,9.14577 -1.75129,9.6771 -0.0898,0.14524 -5.981823,0.24223 -14.489323,0.2385 l -14.33803,-0.006 z m 14.66267,-18.12916 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z m 107.950001,0 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z M 49.629259,155.12999 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z m 107.950001,0 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z M 49.629259,135.28624 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z m 107.950001,0 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z M 49.629259,115.70707 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z m 107.950001,0 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z M 49.629259,95.863321 v -5.556246 h -5.55625 -5.55625 v 5.556246 5.556249 h 5.55625 5.55625 z m 107.950001,0 v -5.556246 h -5.55625 -5.55625 v 5.556246 5.556249 h 5.55625 5.55625 z M 49.629259,76.019575 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z m 107.950001,0 v -5.55625 h -5.55625 -5.55625 v 5.55625 5.55625 h 5.55625 5.55625 z"
id="path41"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

@ -1 +1,27 @@
@article{docker,
title = {Docker Documentation},
author = {Docker Inc},
year={2019},
journal = {docs.docker.com}
}
@article{pip,
title = {The Python Package Installer Documentation},
author = {PyPA},
year={2019},
journal = {pip.pypa.io/en/stable/}
}
@article{jpa,
title = {Using JPA},
author = {Spring},
year={2019},
journal = {https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/htmlsingle/\#boot-features-jpa-and-spring-data}
}
@article{maven,
title = {Apache Maven Documentation},
author = {Apache Software Foundation},
year={2019},
journal = {https://maven.apache.org/guides/index.html}
}

@ -3,7 +3,7 @@
\begin{figure}[H] \begin{figure}[H]
\centering \centering
\begin{subfigure}[b]{0.680\linewidth} \begin{subfigure}[b]{0.680\linewidth}
\includegraphics[width=\linewidth]{img/logo.pdf} \includegraphics[width=\linewidth]{img/logo.png}
\caption{Logo dell'applicazione} \caption{Logo dell'applicazione}
\end{subfigure} \end{subfigure}
\label{fig:coffee} \label{fig:coffee}
@ -15,17 +15,50 @@ Salanti Michele - 793091
\newline \newline
Ivan Donati - 781022 Ivan Donati - 781022
\section{Repository}
Come da consegna per l'assignment è stato fatto uso dello strumento di file versioning \code{git} gestito da \textit{GitLab}. Tutto il materiale finale del progetto è presente nel branch master del repository raggiungibile al seguente collegamento:
\begin{center}
\url{https://gitlab.com/meliurwen/2019_assignment3_MiVan}
\end{center}
La radice del branch raffigurata in basso presenta un'organizzazione semplice e minimale:
\begin{itemize}
\item \textbf{mivan:} È la cartella che contiene il sorgente dell'applicazione.
\item \textbf{doc:} È la cartella che contiene il sorgente della documentazione scritta in \latex .
\item \textbf{assignment3\_mivan.pdf:} È la versione compilata in pdf della documentazione.
\item \textbf{Dockerfile} e \textbf{docker-compose.yml:} Sono i file necessari per eseguire la versione containerizzata dell'applicazione.
\item \textbf{LICENSE} e \textbf{README.md:} Sono rispettivamente la licenza (MIT) assegnata per il progeto ed una sua breve introduzione.
\end{itemize}
\dirtree{%
.1 <repository>.
.2 mivan/.
.2 doc/.
.2 .gitignore.
.2 Dockerfile.
.2 docker-compose.yml.
.2 LICENSE.
.2 README.md.
.2 assignment3\_mivan.pdf.
}
\section{Applicazione} \section{Applicazione}
L'applicazione oggetto di questo assigment è \textbf{MiVan}. L'applicazione oggetto di questo assigment è \textbf{MiVan}.
\newline \newline
Si tratta di un'applicazione che rende possibile prenotare ed acquisire biglietti per il cinema. Essa mette a disposizione informazioni sulla programmazione, orari, locandine e sinossi. Grazie alla connessione diretta ai sistemi di biglietteria è possibile visualizzzare la mappa dei posti con lo stato di occupazione in tempo reale e selezionare i posti preferiti dall'utente. L'iscrizione è obbligatoria per permettere la modifica e la cancellazione delle prenotazioni, servizio richiesto da molti utenti.
\newline Si tratta di un'applicazione \textbf{back-end only} che \textit{gestisce prestiti di libri di un sistema bibliotecario} con \textit{una o più sedi}. Essa, oltre ad essere in grado di gestire i prestiti, possiede la capacità di gestire i libri, la loro \textit{posizione}, lo \textit{staff} che ne amministra i \textit{prestiti} e gli \textit{utenti} che ne fanno richiesta.
Allo stato attuale l'applicazione è stata pensata per essere utilizzata nell'area metropolitana di \underline{\textit{Brescia}} e \underline{\textit{Novara}}, con un \textit{\textbf{target iniziale}} ristretto agli utenti delle \textit{\textbf{principali sale di proiezione}} delle rispettive città.
\newline Grazie a questa applicazione è possibile \textit{creare, visualizzzare, modificare e rimuovere} in tempo reale lo stato di cessione dei libri. I prestiti sono descritti da una \textit{data di inizio}, \textit{di fine}, uno \textit{stato}, un \textit{libro}, un \textit{utente} ed un \textit{operatore}. Si ritiene che sia importante sottolineare che durante la progettazione si è presa la decisione che un prestito debba consistere in esattamente una unità di libro, in maniera tale che questo livello di granularità permetta all'utente, in caso di prestito "contemporaneo" (in realtà avviene in rapida sequenza dal punto di vista del backend) di più libri, di non doverli restituire tutti in blocco.
A seconda della trazione che potrebbe ricevere una volta lanciata, si potrà valutare un'eventuale \textit{espansione} del territorio coperto e delle sale interessate.
\newline Altra caratteristica è la \textit{separazione} tra \textit{"concetto di libro"} ed \textit{"unità di libro"}, questo per gestire in maniera efficiente il caso molto frequente in cui il sistema bibliotecario possieda più copie dello stesso libro; nella nostra implementazione ogni singola unità (descritta come \textit{"Item"}) corrisponderebbe in maniera univoca all'unità fisica corrispondente. In altre parole, se il sistema bibliotecario è in possesso di \textit{n} libri identici (stesso ISBN) ognuno di essi è identificabile univocamente.
\newline
Il qui presente documento ha lo scopo di stabilire i requisiti dell'utenza, del sistema e raccogliere informazioni utili e relativa ad eventuali evoluzioni. Questa documentazione è principalmente rivolta agli stakeholder e ai responsabili di sviluppo. Una feature degna di nota (che andrebbe a soddisfare il requisito del \textit{self-loop}) è la possibilità di sapere se nel sistema bibliotecario è presente il \textit{prequel} (ammesso che esista) di un determinato libro assieme al suos tato di disponibilità.
\newline
\textbf{Link:} \url{https://gitlab.com/meliurwen/2019_assignment3_MiVan} Allo stato attuale l'applicazione è stata pensata per essere utilizzata nell'area metropolitana di \underline{\textit{Brescia}} e \underline{\textit{Novara}}, con un \textit{\textbf{target iniziale}} ristretto agli utenti delle \textit{\textbf{sedi del sistema blibliotecario comunale}} delle rispettive città.
A seconda della trazione che potrebbe ricevere una volta lanciata, si potrà valutare un'eventuale \textit{espansione} del territorio coperto e degli enti (sia pubblici che privati) interessati.

@ -0,0 +1,49 @@
\section{Progettazione}
Nella fase iniziale di progettazione, invece che iniziare direttamente con la stesura di un \textit{diagramma UML delle Classi} si è ritenuto più comodo sviluppare prima l'idea su carta disegnando un semplice \textit{diagramma ER} (Entity Relationship), mostrato in figura \ref{fig:er}.
\begin{figure}[h!]
\centering
\includegraphics[scale=0.8]{img/er.pdf}
\caption{Diagramma ER}
\label{fig:er}
\end{figure}
Una volta stesa una bozza definitva e chiara sulle entità, relazioni e relativi attributi da definire si è passati a trasporre in una forma più dettagliata e \textit{più comoda} per noi da tenere come riferimento, ossia un \textit{EER} (\textit{Enhaced Entity Relationship}) disegnato con il tool \textit{MySQL Workbench}.
\begin{figure}[h!]
\centering
\includegraphics[scale=0.9]{img/eer.pdf}
\caption{Diagramma EER}
\label{fig:eer}
\end{figure}
\section{Struttura}
L'applicazione è strutturata in diversi \textit{package} con ognuno funzionalità specifiche:
\begin{itemize}
\item \textbf{com.mivan.model:} In questo package sono presenti tutte le entità del modello dati dell'applicazione, implementate in classi \textit{Author}, \textit{Book}, \textit{Location}, \textit{Staff}, \textit{User}, \textit{Loan}, \textit{Item} e \textit{Item}. Per gestire la persistenza dei dati di un database relazionere, per tali classi sono state utilizzate le annotazioni delle \textit{JPA} \cite{jpa} (\textit{Java Persistence API}).
\item \textbf{com.mivan.repository:} In questo package sono implementate le query per l'interrogazione al database.
\end{itemize}
\section{Test}
Per verificare l'effettivo funzionamento del programma sono stati sviluppati dei test d'integrazione, posizionati all'interno della cartella del'applicazione \code{mivan/src/test/java/mivan/}.
\newline
Le classi presenti nella cartella sono in seguito elencate:
\begin{itemize}
\item \textbf{AuthorTest:} Consente di testare l'\textit{inserimento}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) degli \textit{autori}.
\item \textbf{BookTest:} Consente di testare l'\textit{inserimento}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) dei libri.
\item \textbf{AuthorBookTest:} Consente di testare l'\textit{aggiunta}, la \textit{modifica} e l'\textit{eliminazione} (ed anche \textit{lettura} nei primi due test) degli \textit{autori} ai \textit{libri} e viceversa.
\item \textbf{LocationTest:} Consente di testare l'\textit{inserimento}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) delle \textit{sedi} del sistema bibliotecario.
\item \textbf{StaffTest:} Consente di testare l'\textit{inserimento}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) dello \textit{staff}.
\item \textbf{UserTest:} Consente di testare l'\textit{inserimento}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) degli \textit{utenti}.
\item \textbf{ItemTest:} Consente di testare l'\textit{aggiunta}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) delle singole \textit{unità di libro} (\textit{Item}).
\item \textbf{LoanTest:} Consente di testare l'\textit{aggiunta}, la \textit{modifica} e l'\textit{eliminazione} (implicitamente anche \textit{lettura} nei primi due test) dei \textit{prestiti}.
\end{itemize}
Come è possibile osservare nell'elenco sovrastante i \textit{JUnit test} volti a verificare la \textit{corretta esecuzione} delle operazioni \textit{CRUD} (\textit{Create, Read, Update, Delete}) è stato fatto uso dell'engine \textit{H2}, il quale consente di eseguire tali operazioni su un \textit{database temporaneo} caricato in memoria (\textit{RAM}).
Tale approccio consente \textit{arginare} del tutto il problema di intaccare il database persistente dai dati fittizzi dei test.

@ -0,0 +1,71 @@
\section{Requisiti}
L'applicazione è stata sviluppata, eseguita e testata su sistemi \textit{UNIX Like}, in particolare sulla distribuzione \textit{GNU/Linux Debian}.
Per questo questo motivo le istruzioni che seguono saranno incentrate su questo ambiente, ma dovrebbero valere per tutti gli altri sistemi.
Per rendere la propria macchina pronta ad eseguire l'applicazione è necessario installare i pacchetti \code{openjdk} (la versione 8 è sufficiente) e \code{mvn} corrispondenti rispettivamente a \textit{Open Java Development Kit} ed al tool \textit{Apache Maven} \cite{maven}; in caso di Debian o derivate si usa il seguente comando:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ sudo apt-get install openjdk-8-jdk mvn
\end{lstlisting}
In caso si volesse usare \textit{Docker} allora le dipendenze sono \textit{docker-compose}\cite{docker}, ed ovviamente \textit{docker} stesso. \textit{Compose} è presente nella maggior parte delle repo delle distro, il problema è che non è sempre aggiornato, per cui si ovvierà a questo possibile problema per mezzo di \code{pip}. \cite{pip}
La serie di comandi è la seguente, in caso di distro diversa da Debian usare il relativo gestore di pacchetti in sostituzione ad apt:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ sudo apt-get install docker-ce python3-pip
$ sudo pip3 install docker-compose
\end{lstlisting}
\section{Test}
Per eseguire i test è necessario spostarsi all'interno della cartella del sorgente dell'applicazione e poi lanciare il relativo comando:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ cd mivan
$ ./mvnw clean verify
\end{lstlisting}
\section{Build}
L'operazione di build genera un file \code{.jar} all'interno della cartella di nome \code{target}, la quale se non è già presente \textit{verrà creata a runtime}.
Per eseguire la build è necessario spostarsi all'interno della cartella del sorgente dell'applicazione e poi lanciare il wrapper \code{mvnw}:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ cd mivan
$ ./mvnw clean package spring-boot:repackage
\end{lstlisting}
\section{Avvio tramite linea di comando}
L'avvio immediato dell'applicazione, utile durante lo sviluppo si esegue con un solo comando. Si ricorda che prima è necessario spostarsi all'interno della cartella del sorgente dell'applicazione:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ cd mivan
$ ./mvnw spring-boot:run
\end{lstlisting}
\section{Avvio tramite Docker}
Per poter eseguire l'applicazione per mezzo di Docker container è necessario soddisfare i requisiti indicati all'inizio di questo capitolo. Il vantaggio di usare Docker è che semplifica \textit{notevolmente} sia la fase di sviluppo che di \textit{deploy} dell'applicazione, specialmente per l'ultimo punto che ne riduce in maniera sensibile sia il tempo che la complessità.
\begin{leftbar}
\noindent\textbf{Nota:}\newline Per poter utilizzare docker è necessario avere i privilegi di root od essere nel gruppo \code{docker}!
\end{leftbar}
Un comodo strumento di cui faremo uso per gestire i container è \textit{Compose}, di cui, dato il file \code{.yml} già compilato alla radice della repository eseguiamo il comando di build:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ sudo docker-compose build
\end{lstlisting}
E poi, una volta buildate l'immagine del container, lo lanciamo:
\newline
\begin{lstlisting}[style=BashInputStyle]
$ sudo docker-compose up
\end{lstlisting}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

@ -19,11 +19,29 @@
\usepackage{csquotes} \usepackage{csquotes}
\usepackage{framed,lipsum} \usepackage{framed,lipsum}
\usepackage{dirtree}
\usepackage{xcolor}
\usepackage{xspace}
\newcommand{\latex}{\LaTeX\xspace}
\setcounter{secnumdepth}{6} \setcounter{secnumdepth}{6}
\def\code#1{\texttt{#1}} \def\code#1{\texttt{#1}}
\lstdefinestyle{BashInputStyle}{
language=bash,
basicstyle=\tt,
frame=tb,
columns=fullflexible,
backgroundcolor=\color{lightgray!20},
linewidth=1.1\linewidth,
xleftmargin=0\linewidth
}
% Indice e citazioni linkate % Indice e citazioni linkate
\usepackage{hyperref} \usepackage{hyperref}
\hypersetup{ \hypersetup{
@ -51,6 +69,12 @@
\Large \Large
\input{chapters/01_introduzione} \input{chapters/01_introduzione}
\chapter{Implementazione}
\input{chapters/02_progetto}
\chapter{Esecuzione}
\input{chapters/03_esecuzione}
\bibliographystyle{unsrt} \bibliographystyle{unsrt}
\bibliography{bibliography.bib} \bibliography{bibliography.bib}

@ -0,0 +1,6 @@
version: '3'
services:
app:
build: .
environment:
TZ: 'Europe/Rome'

@ -0,0 +1,14 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
charset = utf-8
[*.{yml,yaml,json}]
insert_final_newline = false

31
mivan/.gitignore vendored

@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### 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/
### VS Code ###
.vscode/

@ -0,0 +1,117 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed 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
*
* https://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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar

310
mivan/mvnw vendored

@ -0,0 +1,310 @@
#!/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
#
# https://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mivan/mvnw.cmd vendored

@ -0,0 +1,182 @@
@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 https://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 Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<artifactId>mivan</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mivan</name>
<description>Spring MVC and Hibernate project</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
<finalName>${project.artifactId}</finalName>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,14 @@
package mivan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Mivan {
public static void main(String[] args) {
SpringApplication.run(Mivan.class, args);
}
}

@ -0,0 +1,75 @@
package mivan.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "author")
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true)
private long id;
@Column(name = "name", nullable = false)
private String name;
@ManyToMany(mappedBy = "authors")
private List<Book> books;
public Author() {
}
public Author(String name) {
super();
this.name = name;
this.books = new ArrayList<Book>();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBooks() {
return this.books;
}
public void addBook(Book book) {
if (!this.books.contains(book)) {
this.books.add(book);
book.addAuthor(this);
}
}
public void removeBook(Book book) {
if (this.books.contains(book))
this.books.remove(book);
book.removeAuthor(this);
}
}

@ -0,0 +1,90 @@
package mivan.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "book")
public class Book implements Serializable {
private static final long serialVersionUID = 19L;
@Id
@Column(name = "isbn", nullable = false, unique = true)
private long isbn;
@Column(name = "title", nullable = false)
private String title;
@OneToOne
private Book prequel;
@ManyToMany
@JoinTable(name = "book_has_author", joinColumns = @JoinColumn(name = "isbn", referencedColumnName = "isbn"), inverseJoinColumns = @JoinColumn(name = "id", referencedColumnName = "id"))
private List<Author> authors;
public Book() {
}
public Book(long isbn, String title, Book prequel) {
this.isbn = isbn;
this.title = title;
this.prequel = prequel;
this.authors = new ArrayList<Author>();
}
public long getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public Book getPrequel() {
return prequel;
}
public void setIsbn(long isbn) {
this.isbn = isbn;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrequel(Book prequel) {
this.prequel = prequel;
}
public List<Author> getAuthors() {
return this.authors;
}
public void addAuthor(Author author) {
if (!this.authors.contains(author)) {
this.authors.add(author);
author.addBook(this);
}
}
public void removeAuthor(Author author) {
if (this.authors.contains(author)) {
this.authors.remove(author);
author.removeBook(this);
}
}
}

@ -0,0 +1,62 @@
package mivan.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "item")
public class Item implements Serializable {
private static final long serialVersionUID = 1993L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "isbn")
private Book book;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "location")
private Location location;
public Item() {
}
public Item(Book book, Location location) {
super();
this.book = book;
this.location = location;
}
public long getId() {
return this.id;
}
public Book getBook() {
return this.book;
}
public void setBook(Book book) {
this.book = book;
}
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
}

@ -0,0 +1,112 @@
package mivan.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "loan")
public class Loan implements Serializable {
private static final long serialVersionUID = -5124436115031696628L;
@Id
@Column(name = "id", nullable = false, unique = true)
private long id;
@Column(name = "date_start", nullable = false)
private long date_start;
@Column(name = "date_end", nullable = false)
private long date_end;
@Column(name = "state", nullable = false)
private String state;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "item")
private Item item;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "staff")
private Staff staff;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user")
private User user;
public Loan() {
}
public Loan(long date_start, long date_end, String state, Item item, Staff staff, User user) {
this.date_start = date_start;
this.date_end = date_end;
this.state = state;
this.item = item;
this.staff = staff;
this.user = user;
}
public long getId() {
return id;
}
public long getDate_start() {
return date_start;
}
public long getDate_end() {
return date_end;
}
public String getState() {
return state;
}
public Item getItem() {
return item;
}
public Staff getStaff() {
return staff;
}
public User getUser() {
return user;
}
public void setId(long id) {
this.id = id;
}
public void setDate_start(long date_start) {
this.date_start = date_start;
}
public void setDate_end(long date_end) {
this.date_end = date_end;
}
public void setState(String state) {
this.state = state;
}
public void setItem(Item item) {
this.item = item;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
public void setUser(User user) {
this.user = user;
}
}

@ -0,0 +1,83 @@
package mivan.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "location")
public class Location implements Serializable {
private static final long serialVersionUID = -5124436115031696628L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true)
private Long id;
@Column(name = "name", nullable = false, unique = true)
private String name;
@Column(name = "adress", nullable = false)
private String adress;
@OneToMany(mappedBy = "location")
private List<Staff> staffs;
protected Location() {
}
public Location(String name, String adress) {
this.name = name;
this.adress = adress;
this.staffs = new ArrayList<Staff>();
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getAdress() {
return adress;
}
public List<Staff> getStaffs() {
return staffs;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAdress(String adress) {
this.adress = adress;
}
public void setStaffs(List<Staff> staffs) {
this.staffs = staffs;
}
public void addStaff(Staff staff) {
this.staffs.add(staff);
if (staff.getLocation() != this) {
staff.setLocation(this);
}
}
}

@ -0,0 +1,73 @@
package mivan.model;
import java.io.Serializable;
import javax.persistence.*;
@MappedSuperclass
public class Person implements Serializable {
private static final long serialVersionUID = -5124436115031696628L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true)
private long id;
@Column(name = "firstName", nullable = false)
private String firstName;
@Column(name = "lastName", nullable = false)
private String lastName;
@Column(name = "city")
private String city;
public Person() {
}
public Person(String firstName, String lastName, String city) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.city = city;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", city=" + city + "]";
}
}

@ -0,0 +1,71 @@
package mivan.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "staff")
public class Staff extends Person {
private static final long serialVersionUID = -5124436115031696628L;
@Column(name = "idka", nullable = false, unique = true)
private String idka;
@Column(name = "ruolo", nullable = false)
private String ruolo;
@ManyToOne
@JoinColumn(name = "location_id", referencedColumnName = "id")
private Location location;
public Staff() {
super();
// TODO Auto-generated constructor stub
}
public Staff(String firstName, String lastName, String city, String idka, String ruolo, Location location) {
super(firstName, lastName, city);
this.idka = idka;
this.ruolo = ruolo;
setLocation(location);
}
public Staff(String firstName, String lastName, String city, String idka, String ruolo) {
super(firstName, lastName, city);
this.idka = idka;
this.ruolo = ruolo;
}
public String getIdka() {
return idka;
}
public String getRuolo() {
return ruolo;
}
public Location getLocation() {
return location;
}
public void setIdka(String idka) {
this.idka = idka;
}
public void setRuolo(String ruolo) {
this.ruolo = ruolo;
}
public void setLocation(Location location) {
this.location = location;
if (!location.getStaffs().contains(this)) {
location.getStaffs().add(this);
}
}
}

@ -0,0 +1,65 @@
package mivan.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User extends Person {
private static final long serialVersionUID = -5124436115031696628L;
@Column(name = "username", nullable = false, unique = true)
private String username;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "password", nullable = false)
private String password;
protected User() {
}
public User(String firstName, String lastName, String city, String username, String email, String password) {
super(firstName, lastName, city);
this.username = username;
this.email = email;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "User [username=" + username + ", email=" + email + ", password=" + password + "]";
}
}

@ -0,0 +1,20 @@
package mivan.repository;
import mivan.model.Author;
public interface AuthorRepository extends Repository<Author, Long> {
public void deleteAuthorById(Long id);
public void addAuthor(Author author);
public void updateAuthor(Long id, String name);
public Author searchAuthorByName(String name);
public void addBook(Long isbn, Long id);
public void removeBook(Long isbn, Long id);
public int getSize();
}

@ -0,0 +1,155 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.Author;
import mivan.model.Book;
public class AuthorRepositoryImpl implements AuthorRepository {
private EntityManagerFactory entityManagerFactory;
public AuthorRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
@Override
public Optional<Author> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Author author = entityManager.find(Author.class, id);
entityManager.close();
return Optional.ofNullable(author);
}
@Override
public Iterable<Author> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<Author> author = entityManager.createQuery("FROM Author", Author.class).getResultList();
entityManager.close();
return author;
}
@Override
public void deleteAuthorById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Author author = entityManager.find(Author.class, id);
entityManager.remove(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void addAuthor(Author author) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void updateAuthor(Long id, String name) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Author author = entityManager.find(Author.class, id);
author.setName(name);
entityManager.persist(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public Author searchAuthorByName(String name) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Author author = null;
try {
author = (Author) entityManager
.createQuery("FROM Author u WHERE lower(u.name) = '" + name.toLowerCase() + "'").getSingleResult();
entityManager.close();
} catch (Exception ex) {
author = null;
}
return author;
}
@Override
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM Author").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
@Override
public void addBook(Long isbn, Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Book book = entityManager.find(Book.class, isbn);
Author author = entityManager.find(Author.class, id);
book.addAuthor(author);
entityManager.persist(book);
entityManager.persist(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void removeBook(Long isbn, Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Book book = entityManager.find(Book.class, isbn);
Author author = entityManager.find(Author.class, id);
book.removeAuthor(author);
entityManager.persist(book);
entityManager.persist(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
}

@ -0,0 +1,22 @@
package mivan.repository;
import mivan.model.Book;
public interface BookRepository extends Repository<Book, Long> {
// public Optional<AddressUser> findUserAddressById(Long id);
public void deleteBookById(Long isbn);
public void addBook(Book book);
public void updateBook(Long isbn, String title, Book prequel);
public Book searchBookByTitle(String title);
public void addAuthor(Long isbn, Long id);
public void removeAuthor(Long isbn, Long id);
public int getSize();
}

@ -0,0 +1,158 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.Author;
import mivan.model.Book;
public class BookRepositoryImpl implements BookRepository {
private EntityManagerFactory entityManagerFactory;
public BookRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
@Override
public Optional<Book> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Book book = entityManager.find(Book.class, id);
entityManager.close();
return Optional.ofNullable(book);
}
@Override
public Iterable<Book> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<Book> book = entityManager.createQuery("FROM Book", Book.class).getResultList();
entityManager.close();
return book;
}
@Override
public void deleteBookById(Long isbn) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Book book = entityManager.find(Book.class, isbn);
entityManager.remove(book);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void addBook(Book book) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(book);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void updateBook(Long isbn, String title, Book prequel) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Book book = entityManager.find(Book.class, isbn);
book.setTitle(title);
entityManager.persist(book);
if (prequel != null) {
book.setPrequel(prequel);
}
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public Book searchBookByTitle(String title) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Book book = null;
try {
book = (Book) entityManager.createQuery("FROM Book u WHERE lower(u.title) = '" + title.toLowerCase() + "'")
.getSingleResult();
entityManager.close();
} catch (Exception ex) {
book = null;
}
return book;
}
@Override
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM Book").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
@Override
public void addAuthor(Long isbn, Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Book book = entityManager.find(Book.class, isbn);
Author author = entityManager.find(Author.class, id);
book.addAuthor(author);
entityManager.persist(book);
entityManager.persist(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void removeAuthor(Long isbn, Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Book book = entityManager.find(Book.class, isbn);
Author author = entityManager.find(Author.class, id);
book.removeAuthor(author);
entityManager.persist(book);
entityManager.persist(author);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
}

@ -0,0 +1,13 @@
package mivan.repository;
import mivan.model.Item;
public interface ItemRepository extends Repository<Item, Long> {
public void deleteItemById(Long id);
public void addItem(Item item);
public int getSize();
}

@ -0,0 +1,82 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.Item;
public class ItemRepositoryImpl implements ItemRepository {
private EntityManagerFactory entityManagerFactory;
public ItemRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
@Override
public Optional<Item> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Item item = entityManager.find(Item.class, id);
entityManager.close();
return Optional.ofNullable(item);
}
@Override
public Iterable<Item> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<Item> items = entityManager.createQuery("FROM Item", Item.class).getResultList();
entityManager.close();
return items;
}
@Override
public void deleteItemById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Item item = entityManager.find(Item.class, id);
entityManager.remove(item);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void addItem(Item item) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(item);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM Item").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
}

@ -0,0 +1,15 @@
package mivan.repository;
import mivan.model.Loan;
public interface LoanRepository extends Repository<Loan, Long> {
public void deleteLoanById(Long id);
public void addLoan(Loan loan);
public void updateLoan(Long id, String stato);
public int getSize();
}

@ -0,0 +1,97 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.Loan;
public class LoanRepositoryImpl implements LoanRepository {
private EntityManagerFactory entityManagerFactory;
public LoanRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
public Optional<Loan> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Loan loan = entityManager.find(Loan.class, id);
entityManager.close();
return Optional.ofNullable(loan);
}
@Override
public Iterable<Loan> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<Loan> loan = entityManager.createQuery("FROM Loan", Loan.class).getResultList();
entityManager.close();
return loan;
}
@Override
public void deleteLoanById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Loan loan = entityManager.find(Loan.class, id);
entityManager.remove(loan);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void addLoan(Loan loan) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(loan);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public void updateLoan(Long id, String state) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Loan loan = entityManager.find(Loan.class, id);
loan.setState(state);
entityManager.persist(loan);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
@Override
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM Loan").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
}

@ -0,0 +1,20 @@
package mivan.repository;
import java.util.List;
import mivan.model.Location;
import mivan.model.Staff;
public interface LocationRepository extends Repository<Location, Long> {
public void deleteLocationById(Long id);
public void addLocation(Location user);
public void updateLocation(Long id, String name, String adress, List<Staff> staffs);
public Location searchLocationByName(String name);
public int getSize();
}

@ -0,0 +1,114 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.Location;
import mivan.model.Staff;
public class LocationRepositoryImpl implements LocationRepository {
private EntityManagerFactory entityManagerFactory;
public LocationRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
@Override
public Optional<Location> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Location location = entityManager.find(Location.class, id);
entityManager.close();
return Optional.ofNullable(location);
}
@Override
public Iterable<Location> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<Location> location = entityManager.createQuery("FROM Location", Location.class).getResultList();
entityManager.close();
return location;
}
public void deleteLocationById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Location location = entityManager.find(Location.class, id);
entityManager.remove(location);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public void addLocation(Location location) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(location);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public void updateLocation(Long id, String name, String adress, List<Staff> staffs) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Location location = entityManager.find(Location.class, id);
location.setName(name);
location.setAdress(adress);
location.setStaffs(staffs);
entityManager.persist(location);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public Location searchLocationByName(String name) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Location location = null;
try {
location = (Location) entityManager
.createQuery("FROM Location u WHERE lower(u.name) = '" + name.toLowerCase() + "'")
.getSingleResult();
entityManager.close();
} catch (Exception ex) {
location = null;
}
return location;
}
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM Location").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
}

@ -0,0 +1,9 @@
package mivan.repository;
import java.util.Optional;
public interface Repository<T, ID> {
Optional<T> findById(ID id);
Iterable<T> findAll();
}

@ -0,0 +1,20 @@
package mivan.repository;
import mivan.model.Location;
import mivan.model.Staff;
public interface StaffRepository extends Repository<Staff, Long> {
public void deleteStaffById(Long id);
public void addStaff(Staff user);
public void updateStaff(Long id, String firstname, String lastname, String city, String idka, String ruolo,
Location location);
public Staff searchStaffByidka(String idka);
// public List<Staff> searchStaffByRole(String role);
public int getSize();
}

@ -0,0 +1,117 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.Location;
import mivan.model.Staff;
public class StaffRepositoryImpl implements StaffRepository {
private EntityManagerFactory entityManagerFactory;
public StaffRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
@Override
public Optional<Staff> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Staff staff = entityManager.find(Staff.class, id);
entityManager.close();
return Optional.ofNullable(staff);
}
@Override
public Iterable<Staff> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<Staff> staffs = entityManager.createQuery("FROM Staff", Staff.class).getResultList();
entityManager.close();
return staffs;
}
public void deleteStaffById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Staff staff = entityManager.find(Staff.class, id);
entityManager.remove(staff);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public void addStaff(Staff staff) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(staff);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public void updateStaff(Long id, String firstname, String lastname, String city, String idka, String ruolo,
Location location) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Staff staff = entityManager.find(Staff.class, id);
staff.setFirstName(firstname);
staff.setLastName(lastname);
staff.setCity(city);
staff.setIdka(idka);
staff.setRuolo(ruolo);
staff.setLocation(location);
entityManager.persist(staff);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public Staff searchStaffByidka(String idka) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Staff staff = null;
try {
staff = (Staff) entityManager.createQuery("FROM Staff u WHERE lower(u.idka) = '" + idka.toLowerCase() + "'")
.getSingleResult();
entityManager.close();
} catch (Exception ex) {
staff = null;
}
return staff;
}
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM Staff").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
}

@ -0,0 +1,21 @@
package mivan.repository;
import mivan.model.User;
public interface UserRepository extends Repository<User, Long> {
// public Optional<AddressUser> findUserAddressById(Long id);
public void deleteUserById(Long id);
public void addUser(User user);
public void updateUser(Long id, String firstname, String lastname, String city, String username, String email,
String password);
public User searchUserByName(String username);
public User searchUserByEmail(String email);
public int getSize();
}

@ -0,0 +1,133 @@
package mivan.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import mivan.model.User;
public class UserRepositoryImpl implements UserRepository {
private EntityManagerFactory entityManagerFactory;
public UserRepositoryImpl() {
this.entityManagerFactory = Persistence.createEntityManagerFactory("mivan");
}
@Override
public Optional<User> findById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
User user = entityManager.find(User.class, id);
entityManager.close();
return Optional.ofNullable(user);
}
@Override
public Iterable<User> findAll() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
List<User> users = entityManager.createQuery("FROM User", User.class).getResultList();
entityManager.close();
return users;
}
public void deleteUserById(Long id) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
User user = entityManager.find(User.class, id);
entityManager.remove(user);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public void addUser(User user) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public void updateUser(Long id, String firstname, String lastname, String city, String username, String email,
String password) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
User user = entityManager.find(User.class, id);
user.setFirstName(firstname);
user.setLastName(lastname);
user.setCity(city);
user.setUsername(username);
user.setEmail(email);
user.setPassword(password);
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManager.close();
} catch (Exception ex) {
entityManager.getTransaction().rollback();
}
}
public User searchUserByName(String username) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
User user = null;
try {
user = (User) entityManager
.createQuery("FROM User u WHERE lower(u.username) = '" + username.toLowerCase() + "'")
.getSingleResult();
entityManager.close();
} catch (Exception ex) {
user = null;
}
return user;
}
public User searchUserByEmail(String email) {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
User user = null;
try {
user = (User) entityManager.createQuery("FROM User u WHERE lower(u.email) = '" + email.toLowerCase() + "'")
.getSingleResult();
entityManager.close();
} catch (Exception ex) {
user = null;
}
return user;
}
public int getSize() {
final EntityManager entityManager = this.entityManagerFactory.createEntityManager();
int size = 0;
try {
size = entityManager.createQuery("FROM User").getResultList().size();
entityManager.close();
} catch (Exception ex) {
size = 0;
}
return size;
}
}

@ -0,0 +1,27 @@
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit
name="mivan">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:mivanDB" />
<property name="javax.persistence.jdbc.user"
value="password" />
<property name="javax.persistence.jdbc.password"
value="password" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>

@ -0,0 +1,2 @@
spring.application.name=Mivan
spring.datasource.url=jdbc:h2:file:./data/demo

@ -0,0 +1,18 @@
package mivan;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import mivan.repository.AuthorRepository;
import mivan.repository.AuthorRepositoryImpl;
import mivan.repository.BookRepository;
import mivan.repository.BookRepositoryImpl;
@TestMethodOrder(OrderAnnotation.class)
public class AuthorBookTest {
private AuthorRepository authorRepository = new AuthorRepositoryImpl();
private BookRepository bookRepository = new BookRepositoryImpl();
}

@ -0,0 +1,76 @@
package mivan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Optional;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import mivan.model.Author;
import mivan.repository.AuthorRepository;
import mivan.repository.AuthorRepositoryImpl;
@TestMethodOrder(OrderAnnotation.class)
public class AuthorTest {
private AuthorRepository authorRepository = new AuthorRepositoryImpl();
@Test
@Order(1)
void testAddAuthor() {
String name = "Ivan";
Author author = new Author(name);
authorRepository.addAuthor(author);
int size = authorRepository.getSize();
assertEquals(size, 1);
}
@Test
@Order(2)
void testUpdateAuthor() {
String name = "Ivan";
Author author = new Author(name);
authorRepository.addAuthor(author);
String updatedName = "Javoso";
authorRepository.updateAuthor(author.getId(), updatedName);
Optional<Author> updated_author = authorRepository.findById(author.getId());
updated_author.ifPresent(a -> {
assertEquals(a.getName(), updatedName);
});
}
@Test
@Order(3)
void testDeleteUser() {
int size = authorRepository.getSize();
String name = "gollum";
Author author = new Author(name);
authorRepository.addAuthor(author);
Author editAuthor = authorRepository.searchAuthorByName(name);
long ID = editAuthor.getId();
authorRepository.deleteAuthorById(ID);
int end_size = authorRepository.getSize();
assertEquals(end_size, size);
}
}

@ -0,0 +1,80 @@
package mivan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import mivan.model.Book;
import mivan.repository.BookRepository;
import mivan.repository.BookRepositoryImpl;
public class BookTest {
private BookRepository bookRepository = new BookRepositoryImpl();
@Test
@Order(1)
void testAddBook() {
long isbn = 1234;
String title = "illiade";
Book prequel = null;
Book book = new Book(isbn, title, prequel);
bookRepository.addBook(book);
int size = bookRepository.getSize();
assertEquals(size, 1);
}
@Test
@Order(2)
void testUpdateBook() {
long isbn = 12348;
String title = "odissea";
Book prequel = null;
Book book = new Book(isbn, title, prequel);
bookRepository.addBook(book);
String update_title = "eneide";
bookRepository.updateBook(isbn, update_title, prequel);
Optional<Book> opt_book2 = bookRepository.findById(isbn);
Book book2 = opt_book2.get();
assertTrue(update_title.equals(book2.getTitle()));
}
@Test
@Order(3)
void testDeleteBook() {
int start_size = bookRepository.getSize();
long isbn = 12345;
String title = "illiade";
Book prequel = null;
Book book = new Book(isbn, title, prequel);
bookRepository.addBook(book);
Optional<Book> opt_book2 = bookRepository.findById(isbn);
Book book2 = opt_book2.get();
long ID = book2.getIsbn();
bookRepository.deleteBookById(ID);
int size = bookRepository.getSize();
assertEquals(start_size, size);
}
}

@ -0,0 +1,54 @@
package mivan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Optional;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import mivan.model.Book;
import mivan.model.Item;
import mivan.model.Location;
import mivan.repository.ItemRepository;
import mivan.repository.ItemRepositoryImpl;
@TestMethodOrder(OrderAnnotation.class)
public class ItemTest {
private ItemRepository itemRepository = new ItemRepositoryImpl();
@Test
@Order(1)
void testAddItem() {
Book book = null;
Location location = null;
Item item = new Item(book, location);
itemRepository.addItem(item);
int size = itemRepository.getSize();
assertEquals(1, size);
}
@Test
@Order(2)
void testRemoveItem() {
int startSize = itemRepository.getSize();
Book book = null;
Location location = null;
Item item = new Item(book, location);
itemRepository.addItem(item);
int size = itemRepository.getSize();
assertEquals(startSize + 1, size);
Optional<Item> optItem2 = itemRepository.findById(item.getId());
Item item2 = optItem2.get();
long ID = item2.getId();
itemRepository.deleteItemById(ID);
int finalSize = itemRepository.getSize();
assertEquals(startSize, finalSize);
}
}

@ -0,0 +1,99 @@
package mivan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import mivan.model.Item;
import mivan.model.Loan;
import mivan.model.Staff;
import mivan.model.User;
import mivan.repository.LoanRepository;
import mivan.repository.LoanRepositoryImpl;
public class LoanTest {
private LoanRepository loanRepository = new LoanRepositoryImpl();
@Test
@Order(1)
void testAddLoan() {
long date_start = 1234;
long date_end = 2345;
String state = "loaning";
Item item = null;
Staff staff = null;
User user = null;
Loan loan = new Loan(date_start, date_end, state, item, staff, user);
loanRepository.addLoan(loan);
int size = loanRepository.getSize();
assertEquals(size, 1);
}
@Test
@Order(2)
void testUpdateLoan() {
long date_start = 1234;
long date_end = 2345;
String state = "loaning";
Item item = null;
Staff staff = null;
User user = null;
Loan loan = new Loan(date_start, date_end, state, item, staff, user);
loanRepository.addLoan(loan);
String update_state = "returned";
loanRepository.updateLoan(0L, update_state);
Optional<Loan> opt_loan = loanRepository.findById(0L);
Loan loan2 = opt_loan.get();
assertTrue(update_state.equals(loan2.getState()));
}
@Test
@Order(3)
void testDeleteLoan() {
int start_size = loanRepository.getSize();
long date_start = 1876;
long date_end = 9876;
String state = "loaning";
Item item = null;
Staff staff = null;
User user = null;
Loan loan = new Loan(date_start, date_end, state, item, staff, user);
loanRepository.addLoan(loan);
Optional<Loan> opt_loan2 = loanRepository.findById(0L);
Loan book2 = opt_loan2.get();
long ID = book2.getId();
loanRepository.deleteLoanById(ID);
int size = loanRepository.getSize();
assertEquals(start_size, size);
}
}

@ -0,0 +1,116 @@
package mivan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import mivan.model.Location;
import mivan.model.Staff;
import mivan.repository.LocationRepository;
import mivan.repository.LocationRepositoryImpl;
import mivan.repository.StaffRepository;
import mivan.repository.StaffRepositoryImpl;
@TestMethodOrder(OrderAnnotation.class)
public class LocationTest {
private StaffRepository staffRepository = new StaffRepositoryImpl();
private LocationRepository locationRepository = new LocationRepositoryImpl();
@Test
@Order(1)
void testAddLocation() {
String lname = "test_add_location_name";
String ladress = "test_add_location_adress";
Location location = new Location(lname, ladress);
int size = locationRepository.getSize();
locationRepository.addLocation(location);
int newsize = locationRepository.getSize();
assertEquals(newsize, size + 1);
}
@Test
@Order(2)
void testUpdateLocation() {
// creo nuovo menìmbro dello staff
String firstname1 = "test_update_location_name1";
String lastname1 = "test_update_location_lastname1";
String city1 = "test_update_location_city1";
String idka1 = "test_update_location_idka1";
String ruolo1 = "test_update_location_role1";
Staff newstaff1 = new Staff(firstname1, lastname1, city1, idka1, ruolo1);
String firstname2 = "test_update_location_name2";
String lastname2 = "test_update_location_lastname2";
String city2 = "test_update_location_city2";
String idka2 = "test_update_location_idka2";
String ruolo2 = "test_update_location_role2";
Staff newstaff2 = new Staff(firstname2, lastname2, city2, idka2, ruolo2);
staffRepository.addStaff(newstaff1);
staffRepository.addStaff(newstaff2);
List<Staff> staffs = new ArrayList<Staff>();
staffs.add(newstaff1);
staffs.add(newstaff2);
// creo una locazione
String lname = "test_update_location_name";
String ladress = "test_update_location_adress";
Location newlocation = new Location(lname, ladress);
locationRepository.addLocation(newlocation);
Location editLocation = locationRepository.searchLocationByName(lname);
long id = editLocation.getId();
// nuovi dati per modificare i vecchi
String newlname = "test_update_location_newname";
String newladress = "test_update_location_newadress";
// aggungo i membri dello staff / modifico i dati della location
locationRepository.updateLocation(id, newlname, newladress, staffs);
Optional<Location> location = locationRepository.findById(id);
location.ifPresent(a -> {
assertEquals(a.getName(), newlname);
assertEquals(a.getAdress(), newladress);
assertEquals(a.getStaffs(), staffs);
});
}
@Test
@Order(3)
void testDeleteLocation() {
String lname = "test_delete_location_name";
String ladress = "test_delete_location_adress";
Location location = new Location(lname, ladress);
locationRepository.addLocation(location);
Location removeLocation = locationRepository.searchLocationByName(lname);
long ID = removeLocation.getId();
int size = locationRepository.getSize();
locationRepository.deleteLocationById(ID);
int newsize = locationRepository.getSize();
assertEquals(newsize, size - 1);
}
}

@ -0,0 +1,145 @@
package mivan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Optional;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import mivan.model.Location;
import mivan.model.Staff;
import mivan.repository.LocationRepository;
import mivan.repository.LocationRepositoryImpl;
import mivan.repository.StaffRepository;
import mivan.repository.StaffRepositoryImpl;
@TestMethodOrder(OrderAnnotation.class)
public class StaffTest {
private StaffRepository staffRepository = new StaffRepositoryImpl();
private LocationRepository locationRepository = new LocationRepositoryImpl();
@Test
@Order(1)
void testAddStaff() {
String firstname = "test_add_staff_name";
String lastname = "test_add_staff_lastname";
String city = "test_add_staff_city";
String idka = "test_add_staff_idka";
String ruolo = "test_add_staff_role";
String lname = "test_add_staff_loc_name";
String ladress = "test_add_staff_loc_adress";
Location location = new Location(lname, ladress);
locationRepository.addLocation(location);
Staff newstaff = new Staff(firstname, lastname, city, idka, ruolo, location);
int size = staffRepository.getSize();
staffRepository.addStaff(newstaff);
int newsize = staffRepository.getSize();
assertEquals(newsize, size + 1);
}
@Test
@Order(2)
void testUpdateStaff() {
// creo una locazione
String lname = "test_update_staff_loc_name";
String ladress = "test_update_staff_loc_adress";
Location location = new Location(lname, ladress);
// creo una seconda locazione
String newlName = "test_update_staff_loc_newname";
String newlAdress = "test_update_staff_loc_newname";
Location newlocation = new Location(newlName, newlAdress);
int losize = locationRepository.getSize();
locationRepository.addLocation(location);
locationRepository.addLocation(newlocation);
int newlosize = locationRepository.getSize();
assertEquals(newlosize, losize + 2); // ci sono 2 locazioni aggunte
// creo un membro dello staff
String firstname = "test_update_staff_name";
String lastname = "test_update_staff_lastname";
String city = "test_update_staff_city";
String idka = "test_update_staff_idka";
String ruolo = "test_update_staff_role";
Staff newstaff = new Staff(firstname, lastname, city, idka, ruolo);
int size = staffRepository.getSize();
staffRepository.addStaff(newstaff);
int newsize = staffRepository.getSize();
assertEquals(newsize, size + 1); // c'è 1 nuovo membro dello staff
Staff editStaff = staffRepository.searchStaffByidka(idka);
long id = editStaff.getId();
String newfirstname = "test_update_staff_newname";
String newlastname = "test_update_staff_newlastname";
String newcity = "test_update_staff_newcity";
String newidka = "test_update_staff_newidka";
String newruolo = "test_update_staff_newrole";
staffRepository.updateStaff(id, newfirstname, newlastname, newcity, newidka, newruolo, newlocation);
Optional<Staff> staff = staffRepository.findById(id);
staff.ifPresent(a -> {
assertEquals(a.getFirstName(), newfirstname);
assertEquals(a.getLastName(), newlastname);
assertEquals(a.getCity(), newcity);
assertEquals(a.getIdka(), newidka);
assertEquals(a.getRuolo(), newruolo);
assertEquals(a.getLocation().getName(), newlName);
assertEquals(a.getLocation().getAdress(), newlAdress);
});
}
@Test
@Order(3)
void testDeleteStaff() {
String firstname = "test_delete_staff_name";
String lastname = "test_delete_staff_lastname";
String city = "test_delete_staff_city";
String idka = "test_delete_staff_idka";
String ruolo = "test_delete_staff_role";
String lname = "test_delete_staff_loc_name";
String ladress = "test_delete_staff_loc_adress";
Location location = new Location(lname, ladress);
locationRepository.addLocation(location);
Staff newstaff = new Staff(firstname, lastname, city, idka, ruolo, location);
staffRepository.addStaff(newstaff);
Staff editStaff = staffRepository.searchStaffByidka(idka);
long ID = editStaff.getId();
staffRepository.deleteStaffById(ID);
;
int size = staffRepository.getSize();
assertEquals(size, 0);
}
}

@ -0,0 +1,109 @@
package mivan;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Optional;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import mivan.model.User;
import mivan.repository.UserRepository;
import mivan.repository.UserRepositoryImpl;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(OrderAnnotation.class)
class UserTest {
private UserRepository userRepository = new UserRepositoryImpl();
@Test
@Order(1)
void testAddUser() {
String firstname = "test_add_user_name";
String lastname = "test_add_user_lastname";
String city = "test_add_user_city";
String username = "test_add_user_username";
String email = "test_add_user_email";
String password = "test_add_user_password";
User user = new User(firstname, lastname, city, username, email, password);
int size = userRepository.getSize();
userRepository.addUser(user);
int newsize = userRepository.getSize();
assertEquals(newsize, size + 1);
}
@Test
@Order(2)
void testUpdateUser() {
String firstname = "test_update_user_name";
String lastname = "test_update_user_lastname";
String city = "test_update_user_city";
String username = "test_update_user_username";
String email = "test_update_user_email";
String password = "test_update_user_password";
User newuser = new User(firstname, lastname, city, username, email, password);
userRepository.addUser(newuser);
User editUser = userRepository.searchUserByName(username);
long id = editUser.getId();
String newfirstname = "test_update_user_newname";
String newlastname = "test_update_user_newlastname";
String newcity = "test_update_user_newcity";
String newusername = "test_update_user_newusername";
String newemail = "test_update_user_newemail";
String newpassword = "test_update_user_newpassword";
userRepository.updateUser(id, newfirstname, newlastname, newcity, newusername, newemail, newpassword);
Optional<User> user = userRepository.findById(id);
user.ifPresent(a -> {
assertEquals(a.getFirstName(), newfirstname);
assertEquals(a.getLastName(), newlastname);
assertEquals(a.getCity(), newcity);
assertEquals(a.getUsername(), newusername);
assertEquals(a.getEmail(), newemail);
assertEquals(a.getPassword(), newpassword);
});
}
@Test
@Order(3)
void testDeleteUser() {
String firstname = "test_delete_user_name";
String lastname = "test_delete_user_lastname";
String city = "test_delete_user_city";
String username = "test_delete_user_username";
String email = "test_delete_user_email";
String password = "test_delete_user_password";
User newuser = new User(firstname, lastname, city, username, email, password);
userRepository.addUser(newuser);
User editUser = userRepository.searchUserByName(username);
long ID = editUser.getId();
int size = userRepository.getSize();
userRepository.deleteUserById(ID);
int newsize = userRepository.getSize();
assertEquals(newsize, size - 1);
}
}
Loading…
Cancel
Save