diff --git a/.gitignore b/.gitignore index df19b1b..38c7bc6 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,12 @@ *.toc *.out *.bbl +*.bbl~ *.blg *.bib~ *.pdf + + +mivan/target +mivan/bin diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f2ee30c --- /dev/null +++ b/Dockerfile @@ -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"] + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d5e8f4b --- /dev/null +++ b/LICENSE @@ -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. + diff --git a/README.md b/README.md index 00f9422..33652a8 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,17 @@ 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 diff --git a/assets/logo.svg b/assets/logo.svg deleted file mode 100644 index 5384441..0000000 --- a/assets/logo.svg +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/assignment3_mivan.pdf b/assignment3_mivan.pdf index 723d653..2b43d1c 100644 Binary files a/assignment3_mivan.pdf and b/assignment3_mivan.pdf differ diff --git a/doc/bibliography.bib b/doc/bibliography.bib index 8b13789..637fad3 100644 --- a/doc/bibliography.bib +++ b/doc/bibliography.bib @@ -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} +} diff --git a/doc/chapters/01_introduzione.tex b/doc/chapters/01_introduzione.tex index 19a0cad..4e388d3 100644 --- a/doc/chapters/01_introduzione.tex +++ b/doc/chapters/01_introduzione.tex @@ -3,7 +3,7 @@ \begin{figure}[H] \centering \begin{subfigure}[b]{0.680\linewidth} - \includegraphics[width=\linewidth]{img/logo.pdf} + \includegraphics[width=\linewidth]{img/logo.png} \caption{Logo dell'applicazione} \end{subfigure} \label{fig:coffee} @@ -15,17 +15,50 @@ Salanti Michele - 793091 \newline 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 . + .2 mivan/. + .2 doc/. + .2 .gitignore. + .2 Dockerfile. + .2 docker-compose.yml. + .2 LICENSE. + .2 README.md. + .2 assignment3\_mivan.pdf. +} + + \section{Applicazione} L'applicazione oggetto di questo assigment è \textbf{MiVan}. \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 -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 -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 -\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. -\newline -\textbf{Link:} \url{https://gitlab.com/meliurwen/2019_assignment3_MiVan} + +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. + +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. + +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. + +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à. + +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. diff --git a/doc/chapters/02_progetto.tex b/doc/chapters/02_progetto.tex new file mode 100644 index 0000000..dfe5cca --- /dev/null +++ b/doc/chapters/02_progetto.tex @@ -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. diff --git a/doc/chapters/03_esecuzione.tex b/doc/chapters/03_esecuzione.tex new file mode 100644 index 0000000..4b8e70a --- /dev/null +++ b/doc/chapters/03_esecuzione.tex @@ -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} diff --git a/doc/img/eer.pdf b/doc/img/eer.pdf new file mode 100644 index 0000000..19e81ad Binary files /dev/null and b/doc/img/eer.pdf differ diff --git a/doc/img/er.pdf b/doc/img/er.pdf new file mode 100644 index 0000000..63f6e5e Binary files /dev/null and b/doc/img/er.pdf differ diff --git a/doc/img/logo.png b/doc/img/logo.png index c65420f..fb766e6 100644 Binary files a/doc/img/logo.png and b/doc/img/logo.png differ diff --git a/doc/img/logo_unimib.pdf b/doc/img/logo_unimib.pdf new file mode 100644 index 0000000..d576169 Binary files /dev/null and b/doc/img/logo_unimib.pdf differ diff --git a/doc/main.tex b/doc/main.tex index 3bfdea1..3623621 100644 --- a/doc/main.tex +++ b/doc/main.tex @@ -19,11 +19,29 @@ \usepackage{csquotes} \usepackage{framed,lipsum} +\usepackage{dirtree} +\usepackage{xcolor} +\usepackage{xspace} + +\newcommand{\latex}{\LaTeX\xspace} + + \setcounter{secnumdepth}{6} \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 \usepackage{hyperref} \hypersetup{ @@ -51,6 +69,12 @@ \Large \input{chapters/01_introduzione} +\chapter{Implementazione} +\input{chapters/02_progetto} + +\chapter{Esecuzione} +\input{chapters/03_esecuzione} + \bibliographystyle{unsrt} \bibliography{bibliography.bib} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ff87bae --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,6 @@ +version: '3' +services: + app: + build: . + environment: + TZ: 'Europe/Rome' diff --git a/mivan/.editorconfig b/mivan/.editorconfig new file mode 100644 index 0000000..2eccc8b --- /dev/null +++ b/mivan/.editorconfig @@ -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 diff --git a/mivan/.gitignore b/mivan/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/mivan/.gitignore @@ -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/ diff --git a/mivan/.mvn/wrapper/MavenWrapperDownloader.java b/mivan/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..2281075 --- /dev/null +++ b/mivan/.mvn/wrapper/MavenWrapperDownloader.java @@ -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(); + } + +} diff --git a/mivan/.mvn/wrapper/maven-wrapper.jar b/mivan/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..0d5e649 Binary files /dev/null and b/mivan/.mvn/wrapper/maven-wrapper.jar differ diff --git a/mivan/.mvn/wrapper/maven-wrapper.properties b/mivan/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..7d59a01 --- /dev/null +++ b/mivan/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/mivan/mvnw b/mivan/mvnw new file mode 100755 index 0000000..21d3ee8 --- /dev/null +++ b/mivan/mvnw @@ -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 "$@" diff --git a/mivan/mvnw.cmd b/mivan/mvnw.cmd new file mode 100644 index 0000000..84d60ab --- /dev/null +++ b/mivan/mvnw.cmd @@ -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% diff --git a/mivan/pom.xml b/mivan/pom.xml new file mode 100644 index 0000000..4b75c2b --- /dev/null +++ b/mivan/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.1.RELEASE + + + mivan + 0.0.1-SNAPSHOT + mivan + Spring MVC and Hibernate project + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-entitymanager + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + true + ${project.artifactId} + + + + + + diff --git a/mivan/src/main/java/mivan/Mivan.java b/mivan/src/main/java/mivan/Mivan.java new file mode 100644 index 0000000..d367cc8 --- /dev/null +++ b/mivan/src/main/java/mivan/Mivan.java @@ -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); + } + +} diff --git a/mivan/src/main/java/mivan/model/Author.java b/mivan/src/main/java/mivan/model/Author.java new file mode 100644 index 0000000..0aa05e1 --- /dev/null +++ b/mivan/src/main/java/mivan/model/Author.java @@ -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 books; + + public Author() { + } + + public Author(String name) { + super(); + this.name = name; + this.books = new ArrayList(); + } + + 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 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); + } + +} diff --git a/mivan/src/main/java/mivan/model/Book.java b/mivan/src/main/java/mivan/model/Book.java new file mode 100644 index 0000000..6932874 --- /dev/null +++ b/mivan/src/main/java/mivan/model/Book.java @@ -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 authors; + + public Book() { + } + + public Book(long isbn, String title, Book prequel) { + this.isbn = isbn; + this.title = title; + this.prequel = prequel; + this.authors = new ArrayList(); + } + + 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 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); + } + + } + +} diff --git a/mivan/src/main/java/mivan/model/Item.java b/mivan/src/main/java/mivan/model/Item.java new file mode 100644 index 0000000..16f2117 --- /dev/null +++ b/mivan/src/main/java/mivan/model/Item.java @@ -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; + } + +} \ No newline at end of file diff --git a/mivan/src/main/java/mivan/model/Loan.java b/mivan/src/main/java/mivan/model/Loan.java new file mode 100644 index 0000000..8dfa84d --- /dev/null +++ b/mivan/src/main/java/mivan/model/Loan.java @@ -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; + } + +} diff --git a/mivan/src/main/java/mivan/model/Location.java b/mivan/src/main/java/mivan/model/Location.java new file mode 100644 index 0000000..58246d9 --- /dev/null +++ b/mivan/src/main/java/mivan/model/Location.java @@ -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 staffs; + + protected Location() { + } + + public Location(String name, String adress) { + this.name = name; + this.adress = adress; + this.staffs = new ArrayList(); + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getAdress() { + return adress; + } + + public List 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 staffs) { + this.staffs = staffs; + } + + public void addStaff(Staff staff) { + this.staffs.add(staff); + if (staff.getLocation() != this) { + staff.setLocation(this); + } + } + +} diff --git a/mivan/src/main/java/mivan/model/Person.java b/mivan/src/main/java/mivan/model/Person.java new file mode 100644 index 0000000..59f28cb --- /dev/null +++ b/mivan/src/main/java/mivan/model/Person.java @@ -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 + "]"; + } + +} diff --git a/mivan/src/main/java/mivan/model/Staff.java b/mivan/src/main/java/mivan/model/Staff.java new file mode 100644 index 0000000..cbec79c --- /dev/null +++ b/mivan/src/main/java/mivan/model/Staff.java @@ -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); + } + } + +} diff --git a/mivan/src/main/java/mivan/model/User.java b/mivan/src/main/java/mivan/model/User.java new file mode 100644 index 0000000..a153eab --- /dev/null +++ b/mivan/src/main/java/mivan/model/User.java @@ -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 + "]"; + } + +} diff --git a/mivan/src/main/java/mivan/repository/AuthorRepository.java b/mivan/src/main/java/mivan/repository/AuthorRepository.java new file mode 100644 index 0000000..007820e --- /dev/null +++ b/mivan/src/main/java/mivan/repository/AuthorRepository.java @@ -0,0 +1,20 @@ +package mivan.repository; + +import mivan.model.Author; + +public interface AuthorRepository extends Repository { + + 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(); +} diff --git a/mivan/src/main/java/mivan/repository/AuthorRepositoryImpl.java b/mivan/src/main/java/mivan/repository/AuthorRepositoryImpl.java new file mode 100644 index 0000000..57cbd3c --- /dev/null +++ b/mivan/src/main/java/mivan/repository/AuthorRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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(); + } + } + +} diff --git a/mivan/src/main/java/mivan/repository/BookRepository.java b/mivan/src/main/java/mivan/repository/BookRepository.java new file mode 100644 index 0000000..e60335e --- /dev/null +++ b/mivan/src/main/java/mivan/repository/BookRepository.java @@ -0,0 +1,22 @@ +package mivan.repository; + +import mivan.model.Book; + +public interface BookRepository extends Repository { + + // public Optional 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(); +} diff --git a/mivan/src/main/java/mivan/repository/BookRepositoryImpl.java b/mivan/src/main/java/mivan/repository/BookRepositoryImpl.java new file mode 100644 index 0000000..d83885c --- /dev/null +++ b/mivan/src/main/java/mivan/repository/BookRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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(); + } + } + +} diff --git a/mivan/src/main/java/mivan/repository/ItemRepository.java b/mivan/src/main/java/mivan/repository/ItemRepository.java new file mode 100644 index 0000000..924b528 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/ItemRepository.java @@ -0,0 +1,13 @@ +package mivan.repository; + +import mivan.model.Item; + +public interface ItemRepository extends Repository { + + public void deleteItemById(Long id); + + public void addItem(Item item); + + public int getSize(); + +} \ No newline at end of file diff --git a/mivan/src/main/java/mivan/repository/ItemRepositoryImpl.java b/mivan/src/main/java/mivan/repository/ItemRepositoryImpl.java new file mode 100644 index 0000000..3e3c89e --- /dev/null +++ b/mivan/src/main/java/mivan/repository/ItemRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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; + } + +} \ No newline at end of file diff --git a/mivan/src/main/java/mivan/repository/LoanRepository.java b/mivan/src/main/java/mivan/repository/LoanRepository.java new file mode 100644 index 0000000..3e28591 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/LoanRepository.java @@ -0,0 +1,15 @@ +package mivan.repository; + +import mivan.model.Loan; + +public interface LoanRepository extends Repository { + + public void deleteLoanById(Long id); + + public void addLoan(Loan loan); + + public void updateLoan(Long id, String stato); + + public int getSize(); + +} diff --git a/mivan/src/main/java/mivan/repository/LoanRepositoryImpl.java b/mivan/src/main/java/mivan/repository/LoanRepositoryImpl.java new file mode 100644 index 0000000..50a7da6 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/LoanRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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; + } +} diff --git a/mivan/src/main/java/mivan/repository/LocationRepository.java b/mivan/src/main/java/mivan/repository/LocationRepository.java new file mode 100644 index 0000000..2980213 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/LocationRepository.java @@ -0,0 +1,20 @@ +package mivan.repository; + +import java.util.List; + +import mivan.model.Location; +import mivan.model.Staff; + +public interface LocationRepository extends Repository { + + public void deleteLocationById(Long id); + + public void addLocation(Location user); + + public void updateLocation(Long id, String name, String adress, List staffs); + + public Location searchLocationByName(String name); + + public int getSize(); + +} diff --git a/mivan/src/main/java/mivan/repository/LocationRepositoryImpl.java b/mivan/src/main/java/mivan/repository/LocationRepositoryImpl.java new file mode 100644 index 0000000..a60cadc --- /dev/null +++ b/mivan/src/main/java/mivan/repository/LocationRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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 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; + } +} diff --git a/mivan/src/main/java/mivan/repository/Repository.java b/mivan/src/main/java/mivan/repository/Repository.java new file mode 100644 index 0000000..5bb9d01 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/Repository.java @@ -0,0 +1,9 @@ +package mivan.repository; + +import java.util.Optional; + +public interface Repository { + Optional findById(ID id); + + Iterable findAll(); +} diff --git a/mivan/src/main/java/mivan/repository/StaffRepository.java b/mivan/src/main/java/mivan/repository/StaffRepository.java new file mode 100644 index 0000000..f0b29a3 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/StaffRepository.java @@ -0,0 +1,20 @@ +package mivan.repository; + +import mivan.model.Location; +import mivan.model.Staff; + +public interface StaffRepository extends Repository { + + 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 searchStaffByRole(String role); + + public int getSize(); +} diff --git a/mivan/src/main/java/mivan/repository/StaffRepositoryImpl.java b/mivan/src/main/java/mivan/repository/StaffRepositoryImpl.java new file mode 100644 index 0000000..72b0543 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/StaffRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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; + } +} diff --git a/mivan/src/main/java/mivan/repository/UserRepository.java b/mivan/src/main/java/mivan/repository/UserRepository.java new file mode 100644 index 0000000..deb9834 --- /dev/null +++ b/mivan/src/main/java/mivan/repository/UserRepository.java @@ -0,0 +1,21 @@ +package mivan.repository; + +import mivan.model.User; + +public interface UserRepository extends Repository { + + // public Optional 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(); +} diff --git a/mivan/src/main/java/mivan/repository/UserRepositoryImpl.java b/mivan/src/main/java/mivan/repository/UserRepositoryImpl.java new file mode 100644 index 0000000..cb6fc0c --- /dev/null +++ b/mivan/src/main/java/mivan/repository/UserRepositoryImpl.java @@ -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 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 findAll() { + final EntityManager entityManager = this.entityManagerFactory.createEntityManager(); + List 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; + } +} diff --git a/mivan/src/main/resources/META-INF/persistence.xml b/mivan/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..fec0853 --- /dev/null +++ b/mivan/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,27 @@ + + + org.hibernate.jpa.HibernatePersistenceProvider + + + + + + + + + + + + + + + diff --git a/mivan/src/main/resources/application.properties b/mivan/src/main/resources/application.properties new file mode 100644 index 0000000..a860a0d --- /dev/null +++ b/mivan/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.application.name=Mivan +spring.datasource.url=jdbc:h2:file:./data/demo \ No newline at end of file diff --git a/mivan/src/test/java/mivan/AuthorBookTest.java b/mivan/src/test/java/mivan/AuthorBookTest.java new file mode 100644 index 0000000..b2533dc --- /dev/null +++ b/mivan/src/test/java/mivan/AuthorBookTest.java @@ -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(); + +} diff --git a/mivan/src/test/java/mivan/AuthorTest.java b/mivan/src/test/java/mivan/AuthorTest.java new file mode 100644 index 0000000..f5599d0 --- /dev/null +++ b/mivan/src/test/java/mivan/AuthorTest.java @@ -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 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); + } + +} diff --git a/mivan/src/test/java/mivan/BookTest.java b/mivan/src/test/java/mivan/BookTest.java new file mode 100644 index 0000000..bbfed95 --- /dev/null +++ b/mivan/src/test/java/mivan/BookTest.java @@ -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 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 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); + } + +} diff --git a/mivan/src/test/java/mivan/ItemTest.java b/mivan/src/test/java/mivan/ItemTest.java new file mode 100644 index 0000000..72ac89d --- /dev/null +++ b/mivan/src/test/java/mivan/ItemTest.java @@ -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 optItem2 = itemRepository.findById(item.getId()); + + Item item2 = optItem2.get(); + long ID = item2.getId(); + itemRepository.deleteItemById(ID); + + int finalSize = itemRepository.getSize(); + assertEquals(startSize, finalSize); + + } +} \ No newline at end of file diff --git a/mivan/src/test/java/mivan/LoanTest.java b/mivan/src/test/java/mivan/LoanTest.java new file mode 100644 index 0000000..efa1622 --- /dev/null +++ b/mivan/src/test/java/mivan/LoanTest.java @@ -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 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 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); + } +} diff --git a/mivan/src/test/java/mivan/LocationTest.java b/mivan/src/test/java/mivan/LocationTest.java new file mode 100644 index 0000000..77b0f92 --- /dev/null +++ b/mivan/src/test/java/mivan/LocationTest.java @@ -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 staffs = new ArrayList(); + 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 = 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); + } + +} diff --git a/mivan/src/test/java/mivan/StaffTest.java b/mivan/src/test/java/mivan/StaffTest.java new file mode 100644 index 0000000..2a3854a --- /dev/null +++ b/mivan/src/test/java/mivan/StaffTest.java @@ -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 = 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); + } + +} diff --git a/mivan/src/test/java/mivan/UserTest.java b/mivan/src/test/java/mivan/UserTest.java new file mode 100644 index 0000000..cea2a7f --- /dev/null +++ b/mivan/src/test/java/mivan/UserTest.java @@ -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 = 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); + } +}