diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a93630 --- /dev/null +++ b/.gitignore @@ -0,0 +1,59 @@ + +service_batchmail/target +lib_httpclient/target +service_crud/target +service_web/target + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + + +# See http://help.github.com/ignore-files/ for more about ignoring files. + +# compiled output +/dist +/tmp +/out-tsc +# Only exists if Bazel was run +/bazel-out + +# dependencies +/node_modules + +# profiling files +chrome-profiler-events*.json +speed-measure-plugin*.json + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history/* + +# misc +/.sass-cache +/connect.lock +/coverage +/libpeerconnection.log +npm-debug.log +yarn-error.log +testem.log +/typings + +# System Files +.DS_Store +Thumbs.db diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +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. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * 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/0.4.2/maven-wrapper-0.4.2.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 direcrory '" + 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 { + 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/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/README.md b/README.md new file mode 100644 index 0000000..b4a0029 --- /dev/null +++ b/README.md @@ -0,0 +1,91 @@ +Refonte : spring mvc thymeleaf +== + +Technique +== +Services Rest (Jar exécutables) +-- +* Un service pour les méthodes CRUD sur base PostgreSql +* Un service type "Cron" pour envoi de email + +WebApp Spring MVC/ThymeLeaf (Jar exécutable) +-- +* Une application qui gère les pages html ainsi que le controle d'accès (login/password) + +Spring Boot (OPENCLASSROOMS - cours en anglais) +-- +* Web Spring MVC avec ThymeLeaf (OPENCLASSROOMS - cours en anglais) +* Security ( Login-Password, CORS) +* Data/jpa +* Hibernate (API Criteria) +* Embedded tomcat +* Note : utilisation de la librairie Lombok + +Base de donnée +-- +* PostgreSql v12 + +Communication entre services +-- +* Httpclient (jdk 11) placée dans une lib déployeé dans un repo local + + +Build, gestion de source +-- +* Git version 2.24.0.windows.2 +* Apache Maven 3.6.0 +* Intellij IDEA 2019.3.1 Ultimate + +Mise en oeuvre sous Windows +== +* Note : Le compte local doit appartenir au groupe 'administrateurs' +#### Installer Apache Maven V3 et Oracle JDK 11 +#### Modifier la policy pour autoriser l'exécution des scripts 'Set-ExecutionPolicy Unrestricted' +#### Verifier avec mvn --version +* Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-24T20:41:47+02:00) +* Java version: 11.0.4, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-11.0.4 +* Default locale: fr_FR, platform encoding: Cp1252 +* OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" + +Clone et build des exécutables java +-- +#### Créer un repertoire racine du projet - exemple c:\prj07 +* Se placer dans le répertoire qui vient d'être créer +#### Cloner le projet : git clone https://github.com/lco3004/ocr-projet07-v3.git . +* Générer les Jar exécutables avec mvn clean install +* Puis aller dans le répertoire lib_httpclient pour déployer le repo local avec mvn deploy +#### installer PostgresSql +* Lancer le service windows PostgreSql (barre de recherche Windows, saisir services.msc) +* La version utilisée est la 12 +* Créer le répertoire des tablespaces :'c:\bd_data' +* Sous pgsql, exécuter le script sql_uml/prep_projet07.sql +* Installer pgadmin v4 +* Sous pgadmin, attribuer le password projet07 au role rl_projet07 +* Choisir la base db_projet07 - mdp identique au role rl_projet07 +* Enfin , exécuter sql_uml/create_tbl.sql +#### pour les services CRUD et WEB +* Ouvrir un terminal puis se placer dans le répertoire du service ( ex : service_crud) +* Lancer le service avec mvn spring-boot:run' +#### pour le service Batch +#####dans le contexte de demo, il faut lancer le CRON immédiatement +* Se placer dans le répertoire du service +* Editer le fichier application.yml et valoriser les champs de la rubrique Mail +* lancer le service avec mvn spring-boot:run -Dspring-boot.run.arguments="immediat" +#### répertoires particuliers +* logs contient les traces applicatives +* projet07-repo est le repo maven local (cf configuration "deploy" dans le pom de 'lib_httpclient' ) +* Note : Ces répertoires sont supprimés lors d'un mvn clean + +Utilisation de l'application +== +#### connexion avec un des usagers du jeu de test (ex : juie / julie) +#### Recherche d'ouvrage : +* Insensible à la Casse +* Fonctionne avec début de mot (ex : chris renvoie Christophe) +#### Prêts : +* le bouton "update" en regard d'un prêt déja prolongé n'apparait plus +#### Parametrage durée du prêt +* Par défaut 4 semaines +* Paramètre dans properties.yml +#### Batch +* Déclenché tous les jours à 10 heures CET diff --git a/lib_httpclient/mvnw b/lib_httpclient/mvnw new file mode 100644 index 0000000..f9d5a3d --- /dev/null +++ b/lib_httpclient/mvnw @@ -0,0 +1,298 @@ +#!/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-configuration --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 + ))" + # TODO classpath? +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 + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + 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 command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + 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 + +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/lib_httpclient/mvnw.cmd b/lib_httpclient/mvnw.cmd new file mode 100644 index 0000000..c3bfd9e --- /dev/null +++ b/lib_httpclient/mvnw.cmd @@ -0,0 +1,161 @@ +@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 my 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 userWebDtoWeb 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.4.2/maven-wrapper-0.4.2.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% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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/lib_httpclient/pom.xml b/lib_httpclient/pom.xml new file mode 100644 index 0000000..c46face --- /dev/null +++ b/lib_httpclient/pom.xml @@ -0,0 +1,243 @@ + + + + 4.0.0 + + + fr.ocr + prj07 + 1.0-SNAPSHOT + + + lib_httpclient + 1.0 + jar + + lib_httpclient + + + ${project.build.directory}/${project.name} + fr.ocr.RestClient + + + + + + org.projectlombok + lombok + true + + + + + org.springframework + spring-core + 5.2.1.RELEASE + + + + org.springframework + spring-context + 5.2.1.RELEASE + + + org.springframework + spring-web + + + + + + + + + org.apache.maven.plugins + maven-clean-plugin + + + clean-deploy + prepare-package + + clean + + + true + + + ${project.basedir}/../projet07-repo + + * + ** + + + + ${package.directory} + + * + ** + + + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + copy-resources + package + + copy-resources + + + ${package.directory} + + + src/main/resources/ + + *.xml + + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + package + + copy-dependencies + + + ${package.directory}/dependencies/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + compile-package + compile + + compile + + + 11 + 11 + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + default-jar + package + + jar + + + ${project.artifactId}-${project.version} + ${package.directory}/ + + + *.properties + + + + true + dependencies/ + ${main.class} + + + . + + + + + + + + + + maven-install-plugin + + + + + maven-deploy-plugin + + + deploy + + deploy-file + + + ${project.basedir}/target/lib_httpclient/lib_httpclient-1.0.jar + + fr.ocr + lib_httpclient + 1.0 + + jar + file:///${project.basedir}/../projet07-repo + projet07repo + true + + + + + + + + + + projet07repo + file:///${project.basedir}/../projet07-repo + + + + + + + false + default + projet07repo + Internal repo + file:///${project.basedir}/../projet07-repo + + + diff --git a/lib_httpclient/src/main/java/fr/ocr/RestClient.java b/lib_httpclient/src/main/java/fr/ocr/RestClient.java new file mode 100644 index 0000000..739bb95 --- /dev/null +++ b/lib_httpclient/src/main/java/fr/ocr/RestClient.java @@ -0,0 +1,48 @@ +/* +* componet +* gere les échanges entre service - lib : HttpClient + */ + +package fr.ocr; + +import lombok.Getter; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.Builder; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Map; + +@Component +@Getter +public class RestClient { + + private HttpClient httpClient; + + public RestClient() { + httpClient = HttpClient + .newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + } + + public Builder requestBuilder(URI uri, Map additionalHeaders) { + + Builder builder = HttpRequest.newBuilder() + .uri(uri) + .timeout(Duration.ofMinutes(1)) + .header("Content-Type", "application/json"); + + if ((additionalHeaders != null) && !additionalHeaders.isEmpty()) additionalHeaders.forEach(builder::header); + + return builder; + } + + public HttpResponse send(HttpRequest request) throws IOException, InterruptedException { + return httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } +} diff --git a/lib_httpclient/src/main/java/fr/ocr/exception/PrjExceptionHandler.java b/lib_httpclient/src/main/java/fr/ocr/exception/PrjExceptionHandler.java new file mode 100644 index 0000000..04ee931 --- /dev/null +++ b/lib_httpclient/src/main/java/fr/ocr/exception/PrjExceptionHandler.java @@ -0,0 +1,103 @@ +/* +* Component : +* spécialise les exceptions Http pour renvoyer un code Http personnalisé + */ + +package fr.ocr.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Component +public interface PrjExceptionHandler { + + static PrjExceptionHandler getInstance() { + return new PrjExceptionHandlerImpl(); + } + + void throwInternalServeurError(String msg); + void throwOuvrageNotContentForLoan(String msg); + void throwOuvrageNotFound() ; + void throwPretConflict(String msg) ; + void throwPretNotAcceptable(String msg) ; + void throwUserUnAuthorized() ; + void throwProlongationAlreadyReported(String msg) ; +} + + + +class PrjExceptionHandlerImpl implements PrjExceptionHandler{ + + public void throwInternalServeurError(String msg) { + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + class lolo extends RuntimeException{ + public lolo (String msg) { + super(msg); + } + } + throw new lolo(msg); + } + + public void throwOuvrageNotContentForLoan(String msg) { + @ResponseStatus(HttpStatus.NO_CONTENT) + class lolo extends RuntimeException{ + public lolo (String msg) { + super(msg); + } + } + throw new lolo(msg); + } + + public void throwOuvrageNotFound() { + @ResponseStatus(HttpStatus.NOT_FOUND) + class lolo extends RuntimeException{ + public lolo () { + super("Aucun Ouvrage trouvé"); + } + } + throw new lolo(); + } + + public void throwPretConflict(String msg) { + @ResponseStatus(HttpStatus.CONFLICT) + class lolo extends RuntimeException{ + public lolo (String msg) { + super(msg); + } + } + throw new lolo(msg); + } + + public void throwPretNotAcceptable(String msg) { + @ResponseStatus(HttpStatus.NOT_ACCEPTABLE) + class lolo extends RuntimeException{ + public lolo (String msg) { + super(msg); + } + } + throw new lolo(msg); + } + + public void throwUserUnAuthorized() { + @ResponseStatus(HttpStatus.UNAUTHORIZED) + class lolo extends RuntimeException{ + public lolo () { + super("Usager inconnu"); + } + } + throw new lolo(); + } + + public void throwProlongationAlreadyReported(String msg) { + @ResponseStatus(HttpStatus.ALREADY_REPORTED) + class lolo extends RuntimeException{ + public lolo (String msg) { + super(msg); + } + } + throw new lolo(msg); + } +} + + diff --git a/lib_httpclient/src/main/resources/application.yml b/lib_httpclient/src/main/resources/application.yml new file mode 100644 index 0000000..bc21d9e --- /dev/null +++ b/lib_httpclient/src/main/resources/application.yml @@ -0,0 +1,12 @@ +#Infos pour logging +logging: + level: + org.springframework: WARN + com.netflix: WARN + org.apache.catalina: WARN + fr.ocr: DEBUG + pattern: + console: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" + file: "%d %p %c{1.} [%t] %m%n" + file: + name: ./logs/lib_httpclient.log diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..f9d5a3d --- /dev/null +++ b/mvnw @@ -0,0 +1,298 @@ +#!/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-configuration --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 + ))" + # TODO classpath? +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 + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + 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 command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + 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 + +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/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..c3bfd9e --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@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 my 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 userWebDtoWeb 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.4.2/maven-wrapper-0.4.2.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% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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/pom.xml b/pom.xml new file mode 100644 index 0000000..0bf00ea --- /dev/null +++ b/pom.xml @@ -0,0 +1,133 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.RELEASE + + + + fr.ocr + prj07 + 1.0-SNAPSHOT + pom + Projet-07 + Projet 07 - Librairie - pom parent + + + service_crud + service_batchmail + lib_httpclient + service_frontmvc + + + + CP1252 + CP1252 + CP1252 + 11 + 11 + 11 + true + true + dd/MM/YYYY - hh:mm + ${maven.build.timestamp} + + + + + false + default + projet07repo + Internal repo + file:///${project.basedir}/../projet07-repo + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + projet07repo + file:///${project.basedir}/../projet07-repo + + false + + + + + + + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + + org.postgresql + postgresql + ${postgresql.version} + + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + provided + + + + + + + + + org.apache.maven.plugins + maven-clean-plugin + 3.1.0 + + + clean-logs + pre-clean + + clean + + + true + + + ${project.basedir}/logs + + * + ** + + + + + + + + + + \ No newline at end of file diff --git a/service_batchmail/.mvn/wrapper/MavenWrapperDownloader.java b/service_batchmail/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/service_batchmail/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +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. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * 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/0.4.2/maven-wrapper-0.4.2.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 direcrory '" + 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 { + 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/service_batchmail/.mvn/wrapper/maven-wrapper.jar b/service_batchmail/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/service_batchmail/.mvn/wrapper/maven-wrapper.jar differ diff --git a/service_batchmail/.mvn/wrapper/maven-wrapper.properties b/service_batchmail/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/service_batchmail/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/service_batchmail/go.cmd b/service_batchmail/go.cmd new file mode 100644 index 0000000..e4eef92 --- /dev/null +++ b/service_batchmail/go.cmd @@ -0,0 +1 @@ +mvn spring-boot:run -Dspring-boot.run.arguments="immediat" \ No newline at end of file diff --git a/service_batchmail/mvnw b/service_batchmail/mvnw new file mode 100644 index 0000000..bec1f43 --- /dev/null +++ b/service_batchmail/mvnw @@ -0,0 +1,286 @@ +#!/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-configuration --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)`" + # TODO classpath? +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 + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + 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 command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + 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 + +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/service_batchmail/mvnw.cmd b/service_batchmail/mvnw.cmd new file mode 100644 index 0000000..c3bfd9e --- /dev/null +++ b/service_batchmail/mvnw.cmd @@ -0,0 +1,161 @@ +@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 my 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 userWebDtoWeb 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.4.2/maven-wrapper-0.4.2.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% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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/service_batchmail/pom.xml b/service_batchmail/pom.xml new file mode 100644 index 0000000..ac1be5d --- /dev/null +++ b/service_batchmail/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + + fr.ocr + prj07 + 1.0-SNAPSHOT + + + + service_batchmail + 1.0-SNAPSHOT + service_batchmail + projet 07 batch mail scheduleur + jar + + + + fr.ocr + lib_httpclient + 1.0 + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework + spring-context + + + org.springframework + spring-context-support + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.springframework + spring-web + + + + + + service_batchmail + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/service_batchmail/src/main/java/fr/ocr/ServiceBatchmailApplication.java b/service_batchmail/src/main/java/fr/ocr/ServiceBatchmailApplication.java new file mode 100644 index 0000000..2556a50 --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/ServiceBatchmailApplication.java @@ -0,0 +1,58 @@ +package fr.ocr; + +import fr.ocr.task.ScheduledMailer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; +import org.springframework.scheduling.annotation.EnableScheduling; + +/* + mvn spring-boot:run -Dspring-boot.run.arguments="immediat" + */ + +@SpringBootApplication +@EnableScheduling +@PropertySources( { + @PropertySource(value = "classpath:application.properties"), + @PropertySource(value = "classpath:application.yml")}) +public class ServiceBatchmailApplication implements CommandLineRunner{ + + @Autowired + private ScheduledMailer scheduledMailer; + + private static final Logger log = LoggerFactory.getLogger(ServiceBatchmailApplication.class); + + public static void main(String[] args) { + + SpringApplication.run(ServiceBatchmailApplication.class, args); + + } + + @Bean + public RestClient libHttpClient() { + return new RestClient() ; + } + + @Override + public void run(String... args) { + if (args.length >0) + try { + scheduledMailer.emailingToOverDueBorrowers(); + + }catch (RuntimeException e) { + log.error("Exception levee suite appel de scheduledMailer.emailingToOverDueBorrowers()" + e.getLocalizedMessage()); + } + } + + @Bean + public ExitCodeGenerator exitCodeGenerator() { + return () -> 2017; + } +} diff --git a/service_batchmail/src/main/java/fr/ocr/model/InfosBatchMailDtoBatch.java b/service_batchmail/src/main/java/fr/ocr/model/InfosBatchMailDtoBatch.java new file mode 100644 index 0000000..251986b --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/model/InfosBatchMailDtoBatch.java @@ -0,0 +1,15 @@ +package fr.ocr.model; + +import lombok.Data; + +import java.util.Date; + +@Data +public class InfosBatchMailDtoBatch { + + String username; + String email; + String titre; + String auteur; + Date dateEmprunt; +} diff --git a/service_batchmail/src/main/java/fr/ocr/model/OuvrageBatchDtoBatch.java b/service_batchmail/src/main/java/fr/ocr/model/OuvrageBatchDtoBatch.java new file mode 100644 index 0000000..58c5e4e --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/model/OuvrageBatchDtoBatch.java @@ -0,0 +1,13 @@ +package fr.ocr.model; + +import lombok.Data; + + + +@Data +public class OuvrageBatchDtoBatch { + + String titre; + String auteur; + +} \ No newline at end of file diff --git a/service_batchmail/src/main/java/fr/ocr/model/PretBatchDtoBatch.java b/service_batchmail/src/main/java/fr/ocr/model/PretBatchDtoBatch.java new file mode 100644 index 0000000..de33164 --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/model/PretBatchDtoBatch.java @@ -0,0 +1,13 @@ +package fr.ocr.model; + +import lombok.Data; + +import java.util.Date; + +@Data +public class PretBatchDtoBatch { + + int userIduser; + int ouvrageIdouvrage; + Date dateEmprunt; +} diff --git a/service_batchmail/src/main/java/fr/ocr/model/UserBatchDtoBatch.java b/service_batchmail/src/main/java/fr/ocr/model/UserBatchDtoBatch.java new file mode 100644 index 0000000..7d8e646 --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/model/UserBatchDtoBatch.java @@ -0,0 +1,10 @@ +package fr.ocr.model; + +import lombok.Data; + + +@Data +public class UserBatchDtoBatch { + private String username; + private String email; +} diff --git a/service_batchmail/src/main/java/fr/ocr/task/ScheduledMailer.java b/service_batchmail/src/main/java/fr/ocr/task/ScheduledMailer.java new file mode 100644 index 0000000..f7138d3 --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/task/ScheduledMailer.java @@ -0,0 +1,183 @@ + +/* +* Composant : +* * récupére la liste des prets hors délai et les traite +* * Crontab Like : envoie mail vers usagers ayant au moins un pret hors delais + */ + +package fr.ocr.task; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.ocr.RestClient; +import fr.ocr.model.InfosBatchMailDtoBatch; +import fr.ocr.model.OuvrageBatchDtoBatch; +import fr.ocr.model.PretBatchDtoBatch; +import fr.ocr.model.UserBatchDtoBatch; +import fr.ocr.utility.ApplicationPropertiesConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.net.URI; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + + +@Component +public class ScheduledMailer { + + private static final Logger log = LoggerFactory.getLogger(ScheduledMailer.class); + + + private final JavaMailSender javaMailSender; + + private final ObjectMapper objectMapper; + private final RestClient restClient; + + private final ApplicationPropertiesConfiguration appProperties; + + + public ScheduledMailer(JavaMailSender javaMailSender, + ObjectMapper objectMapper, + RestClient restClient, + ApplicationPropertiesConfiguration appProperties) { + this.javaMailSender = javaMailSender; + this.objectMapper = objectMapper; + this.restClient = restClient; + this.appProperties = appProperties; + } + + //CRONTAB like - tous les jours à 10h. + @Scheduled(cron = "0 0 10 * * *") + public void emailingToOverDueBorrowers() throws RuntimeException{ + getPretHorsDelai().forEach(this::sendEmail); + } + + //émetteur mail pour un usager + void sendEmail(InfosBatchMailDtoBatch infosBatchMailDtoBatch) { + SimpleMailMessage mailMessage = new SimpleMailMessage(); + + mailMessage.setTo(infosBatchMailDtoBatch.getEmail()); + + mailMessage.setSubject("Relance User :" + infosBatchMailDtoBatch.getUsername()); + mailMessage.setText("\n*********************************************\n"+ + "\n Bonjour, vous avez emprunté l'ouvrage :"+ + "\n Titre..: " + infosBatchMailDtoBatch.getTitre() + + "\n De.....: " + infosBatchMailDtoBatch.getAuteur()+ + "\n Le.....: " + infosBatchMailDtoBatch.getDateEmprunt() + "\n"+ + "\n Le délai de "+appProperties.getDureePret() + " semaines est dépassé." + + "\n Merci de nous retourner cet ouvrage "+ + "\n L'equipe Municipale"+ + "\n*********************************************\n"); + + log.info(mailMessage.getText()); + try { + javaMailSender.send(mailMessage); + }catch (Exception e ) { + log.warn("Erreur : javalMail to "+ mailMessage.getTo()+ " - cause :" + e.getLocalizedMessage()); + } + } + + //fabrique la liste détaillée des infos liées aux prets hors delais + //en récuperant les prets hors delais puis les usagers et les ouvrages reliés à ces prets + public List getPretHorsDelai() + { + List infosBatchMailDtoBatchList = new ArrayList<>(); + + try { + List pretBatchDtoBatchList = listePretHorsDelai(); + + for (PretBatchDtoBatch pretBatchDtoBatch : pretBatchDtoBatchList) { + InfosBatchMailDtoBatch infosBatchMailDtoBatch = new InfosBatchMailDtoBatch(); + + UserBatchDtoBatch userBatchDtoBatch = getUnfairBorrower(pretBatchDtoBatch.getUserIduser()); + + OuvrageBatchDtoBatch ouvrageBatchDtoBatch = getInfosOuvrage(pretBatchDtoBatch.getOuvrageIdouvrage()); + + infosBatchMailDtoBatch.setEmail(userBatchDtoBatch.getEmail()); + infosBatchMailDtoBatch.setUsername(userBatchDtoBatch.getUsername()); + infosBatchMailDtoBatch.setDateEmprunt(pretBatchDtoBatch.getDateEmprunt()); + infosBatchMailDtoBatch.setTitre(ouvrageBatchDtoBatch.getTitre()); + infosBatchMailDtoBatch.setAuteur(ouvrageBatchDtoBatch.getAuteur()); + + infosBatchMailDtoBatchList.add(infosBatchMailDtoBatch); + + log.info(infosBatchMailDtoBatch.toString()); + } + + } catch (Exception e) { + infosBatchMailDtoBatchList.clear(); + log.warn("Exception leve dans reception infos : " +e.getLocalizedMessage() +e.getMessage()); + } + return infosBatchMailDtoBatchList; + } + + //récupere le infos de l'ouvrage dont l'id est passé en param + public OuvrageBatchDtoBatch getInfosOuvrage(int ParamsUriOuvrage ) throws Exception { + + OuvrageBatchDtoBatch ouvrageBatchDtoBatch =null; + + String uriOuvrageDtoById = "http://localhost:9090/OuvrageDtoByID/"; + HttpRequest request = restClient.requestBuilder(URI.create(uriOuvrageDtoById + ParamsUriOuvrage), null).GET().build(); + + HttpResponse response = restClient.send(request); + + if (response.statusCode() == HttpStatus.OK.value()) { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + ouvrageBatchDtoBatch = objectMapper.readValue(response.body(), OuvrageBatchDtoBatch.class); + } + return ouvrageBatchDtoBatch; + } + + //récupère la liste des prets hors-délais selon date du jour - 4 semaines + public List listePretHorsDelai() throws Exception { + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + + String ParamsUriPretsHorsdelai = "?currentDate="+ + dateFormat.format(Calendar.getInstance().getTime())+ + "&elapsedWeeks="+ appProperties.getDureePret(); + + List pretBatchDtoBatchList =null; + + String uriPretHorsDelai = "http://localhost:9090/ListePretsHorsDelai"; + HttpRequest request = restClient.requestBuilder(URI.create(uriPretHorsDelai + ParamsUriPretsHorsdelai), null).GET().build(); + + HttpResponse response = restClient.send(request); + + if (response.statusCode() == HttpStatus.OK.value()) { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + pretBatchDtoBatchList = objectMapper.readValue(response.body(), new TypeReference<>() { + }); + } + return pretBatchDtoBatchList; + } + + //récupere les infos de l'usager dont l'id est passé en param + public UserBatchDtoBatch getUnfairBorrower(int ParamsUriIdUser ) throws Exception { + + UserBatchDtoBatch userBatchDtoBatch =null; + + String uriUserById = "http://localhost:9090/UserById/"; + HttpRequest request = restClient.requestBuilder(URI.create(uriUserById + ParamsUriIdUser), null).GET().build(); + + HttpResponse response = restClient.send(request); + + if (response.statusCode() == HttpStatus.OK.value()) { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + userBatchDtoBatch = objectMapper.readValue(response.body(), UserBatchDtoBatch.class); + } + return userBatchDtoBatch; + } + +} \ No newline at end of file diff --git a/service_batchmail/src/main/java/fr/ocr/utility/ApplicationPropertiesConfiguration.java b/service_batchmail/src/main/java/fr/ocr/utility/ApplicationPropertiesConfiguration.java new file mode 100644 index 0000000..ea05886 --- /dev/null +++ b/service_batchmail/src/main/java/fr/ocr/utility/ApplicationPropertiesConfiguration.java @@ -0,0 +1,24 @@ + +/* +copier coller openclassrooms + + */ +package fr.ocr.utility; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties("mes-configs") +public class ApplicationPropertiesConfiguration { + + private int dureePret; + + public int getDureePret() { + return dureePret; + } + + public void setDureePret(int dureePret) { + this.dureePret = dureePret; + } +} diff --git a/service_batchmail/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/service_batchmail/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000..5047b75 --- /dev/null +++ b/service_batchmail/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,8 @@ +{ + "properties": [ + { + "name": "dureePret", + "type": "java.lang.Integer", + "description": "durée d'un pret d'ouvrage." + } +] } \ No newline at end of file diff --git a/service_batchmail/src/main/resources/application.properties b/service_batchmail/src/main/resources/application.properties new file mode 100644 index 0000000..be748e4 --- /dev/null +++ b/service_batchmail/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.devtools.livereload.enabled=false +spring.devtools.restart.enabled=false +spring.devtools.restart.exclude=META-INF/maven/**, META-INF/resources/**,resources/** +spring.devtools.restart.additional-exclude=./logs/**,logs/** \ No newline at end of file diff --git a/service_batchmail/src/main/resources/application.yml b/service_batchmail/src/main/resources/application.yml new file mode 100644 index 0000000..96de272 --- /dev/null +++ b/service_batchmail/src/main/resources/application.yml @@ -0,0 +1,26 @@ +server: + port: 9092 + +#Nos configurations +mes-configs: + dureePret: 4 + +# Email +spring: + main: + banner-mode: off + application: + name: service_batchmail + mail: + host: smtp.gmail.com + port: 587 + username: + password: + properties: + mail: + smtp: + auth: true + connectiontimeout: 10000 + starttls: + enable: true + diff --git a/service_batchmail/src/main/resources/logback-spring.xml b/service_batchmail/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..510eb86 --- /dev/null +++ b/service_batchmail/src/main/resources/logback-spring.xml @@ -0,0 +1,39 @@ + + + + + + [%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n + + + + + ./logs/service_batch.log + + [%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/service_crud/.mvn/wrapper/MavenWrapperDownloader.java b/service_crud/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/service_crud/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +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. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * 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/0.4.2/maven-wrapper-0.4.2.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 direcrory '" + 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 { + 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/service_crud/.mvn/wrapper/maven-wrapper.jar b/service_crud/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/service_crud/.mvn/wrapper/maven-wrapper.jar differ diff --git a/service_crud/.mvn/wrapper/maven-wrapper.properties b/service_crud/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/service_crud/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/service_crud/go.cmd b/service_crud/go.cmd new file mode 100644 index 0000000..27a9411 --- /dev/null +++ b/service_crud/go.cmd @@ -0,0 +1 @@ +mvn spring-boot:run \ No newline at end of file diff --git a/service_crud/mvnw b/service_crud/mvnw new file mode 100644 index 0000000..f9d5a3d --- /dev/null +++ b/service_crud/mvnw @@ -0,0 +1,298 @@ +#!/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-configuration --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 + ))" + # TODO classpath? +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 + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + 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 command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + 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 + +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/service_crud/mvnw.cmd b/service_crud/mvnw.cmd new file mode 100644 index 0000000..c3bfd9e --- /dev/null +++ b/service_crud/mvnw.cmd @@ -0,0 +1,161 @@ +@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 my 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 userWebDtoWeb 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.4.2/maven-wrapper-0.4.2.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% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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/service_crud/pom.xml b/service_crud/pom.xml new file mode 100644 index 0000000..fb7222d --- /dev/null +++ b/service_crud/pom.xml @@ -0,0 +1,97 @@ + + + 4.0.0 + + + fr.ocr + prj07 + 1.0-SNAPSHOT + + + service_crud + 1.0-SNAPSHOT + service_crud + projet 07 - service CRUD + jar + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + org.postgresql + postgresql + + + + + org.hibernate + hibernate-jpamodelgen + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + + + + + io.springfox + springfox-swagger2 + + + + + io.springfox + springfox-swagger-ui + + + + org.projectlombok + lombok + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + fr.ocr + lib_httpclient + 1.0 + compile + + + + + + service_crud + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + + \ No newline at end of file diff --git a/service_crud/src/main/java/fr/ocr/ServiceCrudApplication.java b/service_crud/src/main/java/fr/ocr/ServiceCrudApplication.java new file mode 100644 index 0000000..b44a844 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/ServiceCrudApplication.java @@ -0,0 +1,49 @@ +package fr.ocr; + +import fr.ocr.exception.PrjExceptionHandler; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; +/* + * http://localhost:9090/swagger-ui.html + */ +@SpringBootApplication +@PropertySources( { + @PropertySource(value = "classpath:application.properties"), + @PropertySource(value = "classpath:application.yml")}) +@EnableTransactionManagement +@EnableSwagger2 +public class ServiceCrudApplication { + + public static void main(String[] args) { + + SpringApplication.run(ServiceCrudApplication.class, args); + } + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("fr.ocr.web.controller")) + .paths(PathSelectors.any()) + .build(); + } + + @Bean + public PrjExceptionHandler libHttpClient_Exception() { + return PrjExceptionHandler.getInstance(); + } + + @Bean + public ExitCodeGenerator exitCodeGenerator() { + return () -> 2018; + } +} diff --git a/service_crud/src/main/java/fr/ocr/application/ouvrage/Ouvrage.java b/service_crud/src/main/java/fr/ocr/application/ouvrage/Ouvrage.java new file mode 100644 index 0000000..cd42b1a --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/ouvrage/Ouvrage.java @@ -0,0 +1,50 @@ +/* +* +* Model +* + */ + +package fr.ocr.application.ouvrage; + +import com.fasterxml.jackson.annotation.JsonFilter; +import fr.ocr.application.pret.Pret; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Collection; + +@Entity +@Table(name = "ouvrage", schema = "ouvrage", catalog = "db_projet07") +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonFilter("OuvrageFiltreDynamique") +public class Ouvrage implements Serializable { + + @Transient + static final long serialVersionUID = 2453281303625368221L; + + @Id + @Column(name = "idouvrage", nullable = false) + private int idouvrage; + + @Basic + @Column(name = "titre", nullable = false, length = 2048) + private String titre; + + @Basic + @Column(name = "auteur", nullable = false, length = 256) + private String auteur; + + @Basic + @Column(name = "quantite", nullable = false) + private int quantite; + + @ToString.Exclude + @OneToMany(mappedBy = "ouvrageByOuvrageIdouvrage") + private Collection pretsByIdouvrage; +} diff --git a/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudController.java b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudController.java new file mode 100644 index 0000000..8c60da4 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudController.java @@ -0,0 +1,43 @@ +/* + * + * Controlleur : + * * recherche Ouvrage par Id méthode GET + * * ou par titre/auteur méthode POST + * + */ + +package fr.ocr.application.ouvrage; + +import fr.ocr.utility.OuvrageJacksonFilters; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.http.converter.json.MappingJacksonValue; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; +@Api(value = "APIs de gestion des Ouvrages.") +@RestController +public class OuvrageCrudController { + + final OuvrageCrudService ouvrageCrudService; + + final OuvrageJacksonFilters> ouvrageJacksonFilters; + + public OuvrageCrudController(OuvrageCrudService ouvrageCrudService, OuvrageJacksonFilters> jf) { + this.ouvrageCrudService = ouvrageCrudService; + this.ouvrageJacksonFilters = jf; + } + + @ApiOperation(value = "Recherche d'ouvrage par titre ou par auteur") + @PostMapping(value="/LookForOuvrage") + public MappingJacksonValue getOuvrageByQuery(@RequestBody(required = false) Map criterionList) { + return ouvrageJacksonFilters.filtersOnAttributes(ouvrageCrudService.getOuvrageByQuerie(criterionList)); + } + + @ApiOperation(value = "Recherche d'ouvrage par /Id") + @GetMapping(value="/OuvrageDtoByID/{idOuvrage}") + public OuvrageCrudDtoBatch getOuvrageDtoById(@PathVariable Integer idOuvrage) { + return ouvrageCrudService.getOuvrageDtoById(idOuvrage); + } +} diff --git a/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudDtoBatch.java b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudDtoBatch.java new file mode 100644 index 0000000..4a65254 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudDtoBatch.java @@ -0,0 +1,17 @@ +/* + * + * Dto uilisé en lien avec le service Batch + * + */ + + +package fr.ocr.application.ouvrage; + +import lombok.Value; + +@Value +public class OuvrageCrudDtoBatch { + + String titre; String auteur; + +} \ No newline at end of file diff --git a/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudRepository.java b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudRepository.java new file mode 100644 index 0000000..f3a667c --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudRepository.java @@ -0,0 +1,32 @@ +/* + * + * les 'repositories' + * + */ + + +package fr.ocr.application.ouvrage; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface OuvrageCrudRepository extends JpaRepository +{ + List findAll(); + + List findOuvrageByAuteurLikeIgnoreCase(String gAuteur); + + List findOuvrageByTitreLikeIgnoreCase(String gTitre); + + List findOuvrageByAuteurLikeIgnoreCaseAndTitreLikeIgnoreCase(String gAuteur,String gTitre); + + Optional findOuvrageByIdouvrage(Integer idOuvrage); + + Optional findOuvrageDtoByIdouvrage(Integer id); + +} + diff --git a/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudService.java b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudService.java new file mode 100644 index 0000000..75a76c5 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/ouvrage/OuvrageCrudService.java @@ -0,0 +1,85 @@ +/* + * Service : + * renvoie la liste des ouvrages disponibles par recherche titre/auteur + * retourne l'enregistrement dont l'id est égal à celui passé en paramètre de recherche + * modifie la quantité d'ouvrage disponibles + * + */ + +package fr.ocr.application.ouvrage; + +import fr.ocr.exception.PrjExceptionHandler; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + + +@Service +public class OuvrageCrudService { + + final OuvrageCrudRepository ouvrageCrudRepository; + final PrjExceptionHandler prjExceptionHandler; + + public OuvrageCrudService(OuvrageCrudRepository ouvrageCrudRepository, PrjExceptionHandler prjExceptionHandler) { + this.ouvrageCrudRepository = ouvrageCrudRepository; + this.prjExceptionHandler = prjExceptionHandler; + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public List getOuvrageByQuerie(Map requeteSearch) { + + List ouvrageList; + + String gTitre = requeteSearch.get("titre"); + String gAuteur = requeteSearch.get("auteur"); + + if ((gAuteur != null && ! gAuteur.isEmpty()) && (gTitre != null && ! gTitre.isEmpty())) { + ouvrageList = ouvrageCrudRepository.findOuvrageByAuteurLikeIgnoreCaseAndTitreLikeIgnoreCase(gAuteur+"%",gTitre+"%"); + } + else if (gAuteur != null && ! gAuteur.isEmpty()) { + ouvrageList = ouvrageCrudRepository.findOuvrageByAuteurLikeIgnoreCase(gAuteur+"%"); + } else if (gTitre != null && ! gTitre.isEmpty()) { + ouvrageList = ouvrageCrudRepository.findOuvrageByTitreLikeIgnoreCase(gTitre+"%"); + } else { + ouvrageList = ouvrageCrudRepository.findAll(); + if (ouvrageList.isEmpty()) { + prjExceptionHandler.throwOuvrageNotFound(); + } + } + if (ouvrageList.isEmpty()) { + prjExceptionHandler.throwOuvrageNotFound(); + } + return ouvrageList; + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public OuvrageCrudDtoBatch getOuvrageDtoById(Integer id) { + Optional optionalOuvrageDtoBatch = ouvrageCrudRepository.findOuvrageDtoByIdouvrage(id); + + if (optionalOuvrageDtoBatch.isEmpty()) + prjExceptionHandler.throwOuvrageNotFound(); + return optionalOuvrageDtoBatch.get(); + } + + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public Ouvrage setQuantiteByIdOuvrage(Integer id, Integer quantiteOuvrage) { + + Optional optionalOuvrage = ouvrageCrudRepository.findOuvrageByIdouvrage(id); + + if (optionalOuvrage.isEmpty()) + prjExceptionHandler.throwOuvrageNotFound(); + + Ouvrage ouvrage = optionalOuvrage.get(); + + if (quantiteOuvrage < 0 && ouvrage.getQuantite() == 0) { + prjExceptionHandler.throwOuvrageNotContentForLoan("Aucun Ouvrage disponible en Bibliothèque !"); + } + ouvrage.setQuantite(ouvrage.getQuantite() +quantiteOuvrage); + ouvrageCrudRepository.saveAndFlush(ouvrage); + return ouvrage; + } +} diff --git a/service_crud/src/main/java/fr/ocr/application/package-info.java b/service_crud/src/main/java/fr/ocr/application/package-info.java new file mode 100644 index 0000000..d2bff1e --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/package-info.java @@ -0,0 +1,2 @@ +@org.springframework.lang.NonNullApi +package fr.ocr.application; \ No newline at end of file diff --git a/service_crud/src/main/java/fr/ocr/application/pret/InfosRecherchePret.java b/service_crud/src/main/java/fr/ocr/application/pret/InfosRecherchePret.java new file mode 100644 index 0000000..2a629a7 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/InfosRecherchePret.java @@ -0,0 +1,26 @@ +package fr.ocr.application.pret; + +import lombok.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +@Value +class InfosRecherchePret { + Integer idUser; + Integer idOuvrage; + + ResponseEntity> formeReponseEntity() { + Map stringIntegerMap = new HashMap<>(); + + stringIntegerMap.put("idUser", idUser); + stringIntegerMap.put("idOuvrage",idOuvrage); + + URI location = ServletUriComponentsBuilder.fromCurrentRequest().build().toUri(); + + return ResponseEntity.created(location).header("Content-Type", "application/json").body(stringIntegerMap); + } +} diff --git a/service_crud/src/main/java/fr/ocr/application/pret/Pret.java b/service_crud/src/main/java/fr/ocr/application/pret/Pret.java new file mode 100644 index 0000000..f467dc2 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/Pret.java @@ -0,0 +1,80 @@ +package fr.ocr.application.pret; + +import fr.ocr.application.ouvrage.Ouvrage; +import fr.ocr.application.user.User; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; + + +@Entity +@Table(name = "pret", schema = "pret", catalog = "db_projet07") +@IdClass(PretPK.class) +@Data +@AllArgsConstructor +@NoArgsConstructor + +@NamedQuery(name = "Pret.findPretsByUser", + query = "select p.dateEmprunt , o.auteur , o.titre from Pret p , " + + "in (p.ouvrageByOuvrageIdouvrage) as o " + + " where p.userByUserIduser = :User") + +public class Pret implements Serializable { + + @Transient + static final long serialVersionUID = 6453281303625368221L; + + @Id + @Column(name = "ouvrage_idouvrage", nullable = false) + private int ouvrageIdouvrage; + + @Id + @Column(name = "user_iduser", nullable = false) + private int userIduser; + + @Basic + @Column(name = "pret_prolonge", nullable = false) + private int pretprolonge; + + @Basic + @Column(name = "date_emprunt", nullable = false) + @Temporal(TemporalType.DATE) + private Date dateEmprunt; + + @ToString.Exclude + @ManyToOne + @JoinColumn(name = "ouvrage_idouvrage", referencedColumnName = "idouvrage", nullable = false, insertable=false, updatable=false) + private Ouvrage ouvrageByOuvrageIdouvrage; + + @ToString.Exclude + @ManyToOne + @JoinColumn(name = "user_iduser", referencedColumnName = "iduser", nullable = false, insertable=false, updatable=false) + private User userByUserIduser; + + @ToString.Exclude + @Transient + private String auteurOuvrage; + + @ToString.Exclude + @Transient + private String titreOuvrage; + + public Pret(int idouvrage, int iduser, int pretprolonge, Date dateEmprunt) { + this.ouvrageIdouvrage=idouvrage; + this.userIduser=iduser; + this.pretprolonge=pretprolonge; + this.dateEmprunt=dateEmprunt; + } + + @PostLoad + void chargeInfosOuvrage() { + auteurOuvrage=ouvrageByOuvrageIdouvrage.getAuteur(); + titreOuvrage=ouvrageByOuvrageIdouvrage.getTitre(); + } + +} diff --git a/service_crud/src/main/java/fr/ocr/application/pret/PretCrudController.java b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudController.java new file mode 100644 index 0000000..d2660dc --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudController.java @@ -0,0 +1,114 @@ +/* + * + * Controlleur : + * * + * * Renvoie la liste des prets d'un usager dont le nom est passé en param. méthode GET + * * Renvoie la liste des prets HORS-Delai selon date et periode (ex : date du jour et période = 4 semaines) + * * Prolonge un pret d'un usager. méthode PUT + * * Crée un pret pour un idOuvrage et un idUsager passé en params + * * Restitue un pret pour un idOuvrage et un idUsager passé en params + */ +package fr.ocr.application.pret; + +import fr.ocr.application.ouvrage.OuvrageCrudService; +import fr.ocr.application.user.UserCrudService; +import fr.ocr.exception.PrjExceptionHandler; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.Synchronized; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + + +@Api(value = "APIs de gestion des Prets.") +@RestController +public class PretCrudController { + + final PretCrudService pretCrudService; + final UserCrudService userCrudService; + final OuvrageCrudService ouvrageCrudService; + final PrjExceptionHandler prjExceptionHandler; + + public PretCrudController(PretCrudService pretCrudService, UserCrudService userCrudService, OuvrageCrudService ouvrageCrudService, PrjExceptionHandler prjExceptionHandler) { + this.pretCrudService = pretCrudService; + this.userCrudService = userCrudService; + this.ouvrageCrudService = ouvrageCrudService; + this.prjExceptionHandler = prjExceptionHandler; + } + + @ApiOperation(value = "Récupère les prêts d'un user grâce à son nom") + @GetMapping(value="/CriteriaListePrets/{userName}", produces= MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public List getPretByNomUsagerCriteria(@PathVariable String userName) throws RuntimeException{ + return pretCrudService.getPretsByUsagerNameWithCriteria(userCrudService.getUserByNom(userName).getIdUser()); + } + + @ApiOperation(value = "Prolonge le Pret d'un user") + @PutMapping(value = "/ProlongerPret", produces= MediaType.APPLICATION_JSON_VALUE) + @Synchronized + public PretCrudDtoWeb prolongerPret(@RequestBody InfosRecherchePret infosRecherchePret) throws RuntimeException{ + + PretCrudDtoWeb pretCrudDtoWeb = null; + try { + + Pret pret = pretCrudService.setProlongationPret(infosRecherchePret.getIdOuvrage(),infosRecherchePret.getIdUser()); + + pretCrudDtoWeb = new PretCrudDtoWeb(pret.getOuvrageIdouvrage(), pret.getUserIduser(), + pret.getPretprolonge(), pret.getDateEmprunt(), + pret.getAuteurOuvrage(), pret.getTitreOuvrage()); + + }catch (Exception e) { + prjExceptionHandler.throwProlongationAlreadyReported("ce prêt a déja été renouvelé ou est hors-délai"); + } + + return pretCrudDtoWeb; + } + + @ApiOperation(value = "Creation d'un Pret : un Ouvrage/un User") + @PostMapping(value = "/CreerPret") + @Synchronized + public ResponseEntity> CreerPret(@RequestBody InfosRecherchePret infosRecherchePret) { + Optional optionalPret = pretCrudService.isPretExiste(infosRecherchePret.getIdOuvrage(),infosRecherchePret.getIdUser()); + if (optionalPret.isPresent()) { + prjExceptionHandler.throwPretConflict("Pret deja existant"); + } + else { + ouvrageCrudService.setQuantiteByIdOuvrage(infosRecherchePret.getIdOuvrage(),-1); + pretCrudService.addPret(infosRecherchePret.getIdOuvrage(),infosRecherchePret.getIdUser()); + } + return infosRecherchePret.formeReponseEntity( ); + } + + @ApiOperation(value = "Restitution d'un Pret : un Ouvrage/un User") + @PostMapping (value = "/RestituerPret") + @Synchronized + public ResponseEntity> RestituerPret(@RequestBody InfosRecherchePret infosRecherchePret) { + Optional optionalPret = pretCrudService.isPretExiste(infosRecherchePret.getIdOuvrage(),infosRecherchePret.getIdUser()); + if (optionalPret.isEmpty()) { + prjExceptionHandler.throwPretNotAcceptable("Pret n'existe pas"); + } + else { + ouvrageCrudService.setQuantiteByIdOuvrage(infosRecherchePret.getIdOuvrage(),1); + pretCrudService.deletePret(infosRecherchePret.getIdOuvrage(),infosRecherchePret.getIdUser()); + } + return infosRecherchePret.formeReponseEntity( ); + } + + @ApiOperation(value = "Récupère les prêts hors-delai ") + @GetMapping(value="/ListePretsHorsDelai", produces= MediaType.APPLICATION_JSON_VALUE) + @Synchronized + public List getPretByIdUsagerHorsDelai(@RequestParam(value = "currentDate") String sDateCourante, + @RequestParam(value = "elapsedWeeks") Integer nbWeeks) throws ParseException { + GregorianCalendar calendar = new GregorianCalendar(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + calendar.setTime(sdf.parse(sDateCourante)); + calendar.add(Calendar.WEEK_OF_YEAR,nbWeeks * -1); + return pretCrudService.getPretByeDueDate(calendar.getTime()); + } + +} diff --git a/service_crud/src/main/java/fr/ocr/application/pret/PretCrudDtoBatch.java b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudDtoBatch.java new file mode 100644 index 0000000..c1662fa --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudDtoBatch.java @@ -0,0 +1,13 @@ +package fr.ocr.application.pret; + +import lombok.Value; + +import java.util.Date; + +@Value +public class PretCrudDtoBatch { + + int userIduser; + int ouvrageIdouvrage; + Date dateEmprunt; +} diff --git a/service_crud/src/main/java/fr/ocr/application/pret/PretCrudDtoWeb.java b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudDtoWeb.java new file mode 100644 index 0000000..fded137 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudDtoWeb.java @@ -0,0 +1,18 @@ +package fr.ocr.application.pret; + + +import lombok.Value; + +import java.util.Date; + +@Value +public class PretCrudDtoWeb { + int ouvrageIdouvrage; + int userIduser; + int pretprolonge; + Date dateEmprunt; + String auteur; + String titre; +} + + diff --git a/service_crud/src/main/java/fr/ocr/application/pret/PretCrudRepository.java b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudRepository.java new file mode 100644 index 0000000..3df4d76 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudRepository.java @@ -0,0 +1,88 @@ +/* + * + * les 'repositories' + * findPretBydUserIdWithCriteria est basée sur API Criteria + * le repo est étendu par cette interface findPretBydUserIdWithCriteria + * + * + */ + + +package fr.ocr.application.pret; + +import fr.ocr.application.ouvrage.Ouvrage; +import fr.ocr.application.ouvrage.Ouvrage_; +import fr.ocr.application.user.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.*; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Optional; + + +@Repository +public interface PretCrudRepository extends JpaRepository , JpaSpecificationExecutor,PretRepositoryCustom { + + Collection findPretsByUser(@Param("User") User user); + + Optional findPretByOuvrageIdouvrageAndUserIduser(int ouvrageIdouvrage, int userIduser); + + List findPretsByDateEmpruntIsBefore(Date dateCourante); + +} + +interface PretRepositoryCustom{ + List findPretBydUserIdWithCriteria(Integer idUsager); +} + +class PretRepositoryCustomImpl implements PretRepositoryCustom { + + @PersistenceContext + EntityManager entityManager; + + @Override + public List findPretBydUserIdWithCriteria(Integer idUser) { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(PretCrudDtoWeb.class); + + Root pretRoot = criteriaQuery.from(Pret.class); + + Join pretOuvrageJoin = pretRoot.join(Pret_.ouvrageByOuvrageIdouvrage); + + Predicate predicateUsager = criteriaBuilder.equal(pretRoot.get(Pret_.userIduser),idUser); + + Expression champIdOuvrageViaPret = pretRoot.get(Pret_.ouvrageIdouvrage); + Expression champIdOuvrage = pretOuvrageJoin.get(Ouvrage_.idouvrage); + Predicate joiturePredicateOuvrage = criteriaBuilder.equal(champIdOuvrage,champIdOuvrageViaPret); + + pretOuvrageJoin.on(joiturePredicateOuvrage); + + criteriaQuery.where(predicateUsager); + + criteriaQuery.multiselect( + pretRoot.get(Pret_.ouvrageIdouvrage), + pretRoot.get(Pret_.userIduser), + pretRoot.get(Pret_.pretprolonge), + pretRoot.get(Pret_.dateEmprunt), + pretOuvrageJoin.get(Ouvrage_.auteur), + pretOuvrageJoin.get(Ouvrage_.titre) + ); + + TypedQuery query = entityManager.createQuery(criteriaQuery); + List pretCrudDtoWebs = query.getResultList(); + + return pretCrudDtoWebs; + } + +} + diff --git a/service_crud/src/main/java/fr/ocr/application/pret/PretCrudService.java b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudService.java new file mode 100644 index 0000000..bc75aa6 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/PretCrudService.java @@ -0,0 +1,90 @@ +/* + * Service : + * renvoie la liste des prets d'un usager dont l'Id est passé en apramètre + * prolonge un pret dont l' idOuvrage et l' idUser sont passés en paramètres + * * "prolonger" signifie : mettre à jour la date du pret et le flaggé comme renouvelé + * ajoute un pret dont l' idOuvrage et l' idUser sont passés en paramètres + * supprime un pret dont l' idOuvrage et l' idUser sont passés en paramètres + * renvoie la liste des prets dont la date d'emprunt est < à la date passée en parametre + */ +package fr.ocr.application.pret; + +import fr.ocr.exception.PrjExceptionHandler; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + + +@Service +public class PretCrudService { + + final PretCrudRepository pretCrudRepository; + final PrjExceptionHandler prjExceptionHandler; + + public PretCrudService(PretCrudRepository pretCrudRepository, PrjExceptionHandler prjExceptionHandler) { + this.pretCrudRepository = pretCrudRepository; + this.prjExceptionHandler = prjExceptionHandler; + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public List getPretsByUsagerNameWithCriteria(int idUsager) throws RuntimeException{ + List pretCrudDtoWebs = pretCrudRepository.findPretBydUserIdWithCriteria(idUsager); + if (pretCrudDtoWebs.isEmpty()) + prjExceptionHandler.throwPretNotAcceptable("aucun prêt en cours"); + return pretCrudDtoWebs; + } + + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public Pret setProlongationPret(Integer idOuvrage, Integer idUsager)throws RuntimeException { + Optional optionalPret = isPretExiste(idOuvrage,idUsager); + if (optionalPret.isEmpty()) { + prjExceptionHandler.throwPretConflict("Pret n'existe pas"); + } + else { + if (optionalPret.get().getPretprolonge() >0 ) { + prjExceptionHandler.throwProlongationAlreadyReported("ce prêt a déja été renouvelé ou est hors-délai"); + } + optionalPret.get().setPretprolonge(1); + Date proloDate = new Date(); + optionalPret.get().setDateEmprunt(proloDate); + } + return pretCrudRepository.saveAndFlush(optionalPret.get()); + } + + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public Pret addPret(int idOuvrage , int idUsager) { + Pret pretTmp = new Pret(idOuvrage, idUsager,0,new Date()); + return pretCrudRepository.saveAndFlush(pretTmp); + } + + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public void deletePret(int idouvrage, int idusager) { + Pret pretTmp = getPretByPretPartiel(idouvrage,idusager); + pretCrudRepository.delete(pretTmp); + pretCrudRepository.flush(); + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public Optional isPretExiste(int idouvrage, int idusager) { + return pretCrudRepository.findPretByOuvrageIdouvrageAndUserIduser(idouvrage,idusager); + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public List getPretByeDueDate(Date dateCourante) { + return pretCrudRepository.findPretsByDateEmpruntIsBefore(dateCourante); + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public Pret getPretByPretPartiel(int idOuvrage, int idUsager) throws RuntimeException { + Optional optionalPret = pretCrudRepository.findPretByOuvrageIdouvrageAndUserIduser(idOuvrage,idUsager); + if (optionalPret.isEmpty()) + prjExceptionHandler.throwPretNotAcceptable("aucun prêt ne correspond à ces critères "); + return optionalPret.get(); + } + +} + diff --git a/service_crud/src/main/java/fr/ocr/application/pret/PretPK.java b/service_crud/src/main/java/fr/ocr/application/pret/PretPK.java new file mode 100644 index 0000000..5efbd0c --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/pret/PretPK.java @@ -0,0 +1,24 @@ +package fr.ocr.application.pret; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Column; +import javax.persistence.Id; +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class PretPK implements Serializable { + + @Column(name = "ouvrage_idouvrage", nullable = false) + @Id + private int ouvrageIdouvrage; + + @Column(name = "user_iduser", nullable = false) + @Id + private int userIduser; + +} diff --git a/service_crud/src/main/java/fr/ocr/application/user/User.java b/service_crud/src/main/java/fr/ocr/application/user/User.java new file mode 100644 index 0000000..3d5f5b5 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/user/User.java @@ -0,0 +1,42 @@ +package fr.ocr.application.user; + +import fr.ocr.application.pret.Pret; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Collection; + + +@Entity +@Table(name = "user", schema = "usager", catalog = "db_projet07") +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User implements Serializable{ + @Transient + static final long serialVersionUID = 2453281303625368221L; + + @Id + @Column(name = "iduser", nullable = false) + private int idUser; + + @Basic + @Column(name = "username", nullable = false, length = 256) + private String username; + + @Basic + @Column(name = "password", nullable = false, length = 1024) + private String password; + + @Basic + @Column(name = "email", nullable = false, length = 1024) + private String email; + + @ToString.Exclude + @OneToMany(mappedBy = "userByUserIduser") + private Collection pretsByIdusager; +} diff --git a/service_crud/src/main/java/fr/ocr/application/user/UserCrudController.java b/service_crud/src/main/java/fr/ocr/application/user/UserCrudController.java new file mode 100644 index 0000000..628bd74 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/user/UserCrudController.java @@ -0,0 +1,40 @@ +/* + * + * Controlleur : + * * renvoie un user "complet" selon le nom passé en param + * * renvoie un user "partiel" (c.a.d ni mail ni mdp) selon le idUser passé en param + */ +package fr.ocr.application.user; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + + +@Api(value = "APIs de gestion des Users (Usagers).") +@RestController +public class UserCrudController { + final + UserCrudService userCrudService; + + public UserCrudController(UserCrudService userCrudService) { + this.userCrudService = userCrudService; + } + + @ApiOperation(value = "user par son nom.") + @GetMapping(value = "/UserByName/{nom}") + public UserCrudDtoWeb getUsers(@PathVariable String nom) { + + return userCrudService.getUserByNom(nom); + } + + @ApiOperation(value = "Détails information User (Nom-Email).") + @GetMapping(value = "/UserById/{idUser}", produces= MediaType.APPLICATION_JSON_VALUE) + public UserCrudDto getUserDTOById(@PathVariable Integer idUser) { + + return userCrudService.getUserDTOById(idUser); + } +} diff --git a/service_crud/src/main/java/fr/ocr/application/user/UserCrudDto.java b/service_crud/src/main/java/fr/ocr/application/user/UserCrudDto.java new file mode 100644 index 0000000..e003f67 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/user/UserCrudDto.java @@ -0,0 +1,11 @@ +package fr.ocr.application.user; + +import lombok.Value; + +@Value +public class UserCrudDto { + + private String username; + private String email; + +} diff --git a/service_crud/src/main/java/fr/ocr/application/user/UserCrudDtoWeb.java b/service_crud/src/main/java/fr/ocr/application/user/UserCrudDtoWeb.java new file mode 100644 index 0000000..5bea94c --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/user/UserCrudDtoWeb.java @@ -0,0 +1,15 @@ +package fr.ocr.application.user; + +import lombok.Value; + + + + +@Value +public class UserCrudDtoWeb { + + private Integer idUser; + private String username; + private String password; + private String email; +} diff --git a/service_crud/src/main/java/fr/ocr/application/user/UserCrudRepository.java b/service_crud/src/main/java/fr/ocr/application/user/UserCrudRepository.java new file mode 100644 index 0000000..0189237 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/user/UserCrudRepository.java @@ -0,0 +1,14 @@ +package fr.ocr.application.user; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserCrudRepository extends JpaRepository +{ + Optional findUserByUsername(String userName); + Optional findUserByIdUser(Integer idUser); +} + diff --git a/service_crud/src/main/java/fr/ocr/application/user/UserCrudService.java b/service_crud/src/main/java/fr/ocr/application/user/UserCrudService.java new file mode 100644 index 0000000..5e003aa --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/application/user/UserCrudService.java @@ -0,0 +1,42 @@ +/* + * Service : + * * renvoie un user "complet" selon le nom passé en param + * * renvoie un user "partiel" (c.a.d ni mail ni mdp) selon le idUser passé en param + */ + +package fr.ocr.application.user; + + +import fr.ocr.exception.PrjExceptionHandler; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +public class UserCrudService { + final UserCrudRepository userCrudRepository; + final PrjExceptionHandler prjExceptionHandler; + + public UserCrudService(UserCrudRepository userCrudRepository, PrjExceptionHandler prjExceptionHandler) { + this.userCrudRepository = userCrudRepository; + this.prjExceptionHandler = prjExceptionHandler; + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public UserCrudDtoWeb getUserByNom(String nom) { + Optional optionalUsager = userCrudRepository.findUserByUsername(nom); + if (optionalUsager.isEmpty()) + prjExceptionHandler.throwUserUnAuthorized(); + return optionalUsager.get(); + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + public UserCrudDto getUserDTOById(Integer id) { + Optional optionalUsager = userCrudRepository.findUserByIdUser(id); + if (optionalUsager.isEmpty()) + prjExceptionHandler.throwUserUnAuthorized(); + + return optionalUsager.get(); + } +} diff --git a/service_crud/src/main/java/fr/ocr/utility/EntityJacksonFilters.java b/service_crud/src/main/java/fr/ocr/utility/EntityJacksonFilters.java new file mode 100644 index 0000000..3ee529f --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/utility/EntityJacksonFilters.java @@ -0,0 +1,28 @@ +package fr.ocr.utility; + +import com.fasterxml.jackson.databind.ser.FilterProvider; +import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; +import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import lombok.Data; +import org.springframework.http.converter.json.MappingJacksonValue; +import org.springframework.stereotype.Component; + +@Data +@Component +abstract class EntityJacksonFilters { + private String nameOfFilter; + private String [] listOfExceptions; + + public MappingJacksonValue filtersOnAttributes (T x ) { + + SimpleBeanPropertyFilter filtre = SimpleBeanPropertyFilter.serializeAllExcept(getListOfExceptions()); + + FilterProvider filterProvider = new SimpleFilterProvider().addFilter(nameOfFilter, filtre); + + MappingJacksonValue filteredReference = new MappingJacksonValue(x); + + filteredReference.setFilters(filterProvider); + + return filteredReference; + } +} diff --git a/service_crud/src/main/java/fr/ocr/utility/OuvrageJacksonFilters.java b/service_crud/src/main/java/fr/ocr/utility/OuvrageJacksonFilters.java new file mode 100644 index 0000000..73ca211 --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/utility/OuvrageJacksonFilters.java @@ -0,0 +1,14 @@ +package fr.ocr.utility; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class OuvrageJacksonFilters extends EntityJacksonFilters { + + public OuvrageJacksonFilters(@Value("${listeexclusionsjson.ouvrage}") String[] s) { + super(); + setListOfExceptions(s); + setNameOfFilter("OuvrageFiltreDynamique"); + } +} diff --git a/service_crud/src/main/java/fr/ocr/utility/PretJacksonFilters.java b/service_crud/src/main/java/fr/ocr/utility/PretJacksonFilters.java new file mode 100644 index 0000000..ee0147a --- /dev/null +++ b/service_crud/src/main/java/fr/ocr/utility/PretJacksonFilters.java @@ -0,0 +1,13 @@ +package fr.ocr.utility; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class PretJacksonFilters extends EntityJacksonFilters { + public PretJacksonFilters(@Value("${listeexclusionsjson.pret}") String[] s) { + super(); + setListOfExceptions(s); + setNameOfFilter("PretFiltreDynamique"); + } +} diff --git a/service_crud/src/main/resources/application.properties b/service_crud/src/main/resources/application.properties new file mode 100644 index 0000000..bcf6510 --- /dev/null +++ b/service_crud/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.devtools.livereload.enabled=false +spring.devtools.restart.enabled=false +spring.devtools.restart.exclude=META-INF/maven/**, META-INF/resources/**,resources/** +spring.devtools.restart.additional-exclude=./logs/**,logs/** +listeexclusionsjson.ouvrage=pretsByIdouvrage,serialVersionUID +listeexclusionsjson.pret=ouvrageByOuvrageIdouvrage,userByUserIduser \ No newline at end of file diff --git a/service_crud/src/main/resources/application.yml b/service_crud/src/main/resources/application.yml new file mode 100644 index 0000000..9917244 --- /dev/null +++ b/service_crud/src/main/resources/application.yml @@ -0,0 +1,22 @@ +server: + port: 9090 +spring: + main: + banner-mode: log + lazy-initialization: true + application: + name: service_crud + datasource: + platform: postgres + username: rl_projet07 + password: projet07 + driver-class-name: org.postgresql.Driver + url: jdbc:postgresql://localhost:5432/db_projet07 + jpa: + open-in-view: false + properties: + hibernate: + dialect: org.hibernate.dialect.PostgreSQL95Dialect + ddl-auto: validate + format_sql: true + show_sql: true diff --git a/service_crud/src/main/resources/logback-spring.xml b/service_crud/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..4f60524 --- /dev/null +++ b/service_crud/src/main/resources/logback-spring.xml @@ -0,0 +1,39 @@ + + + + + + [%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n + + + + + ./logs/service_crud.log + + [%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/service_frontmvc/.gitignore b/service_frontmvc/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/service_frontmvc/.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/service_frontmvc/.mvn/wrapper/MavenWrapperDownloader.java b/service_frontmvc/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/service_frontmvc/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present 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.6"; + /** + * 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/service_frontmvc/.mvn/wrapper/maven-wrapper.jar b/service_frontmvc/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/service_frontmvc/.mvn/wrapper/maven-wrapper.jar differ diff --git a/service_frontmvc/.mvn/wrapper/maven-wrapper.properties b/service_frontmvc/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/service_frontmvc/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/service_frontmvc/mvnw b/service_frontmvc/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/service_frontmvc/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven 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.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.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/service_frontmvc/mvnw.cmd b/service_frontmvc/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/service_frontmvc/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 Maven 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 keystroke 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.6/maven-wrapper-0.5.6.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.6/maven-wrapper-0.5.6.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/service_frontmvc/pom.xml b/service_frontmvc/pom.xml new file mode 100644 index 0000000..e0db0e3 --- /dev/null +++ b/service_frontmvc/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + + fr.ocr + prj07 + 1.0-SNAPSHOT + + + + service_frontmvc + 1.0-SNAPSHOT + service_frontmvc + projet 07 - service web + jar + + + + fr.ocr + lib_httpclient + 1.0 + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot-starter-security + + + + + io.springfox + springfox-swagger2 + + + + + io.springfox + springfox-swagger-ui + + + org.springframework + spring-context + + + + + + + service_frontmvc + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/ServiceFrontMvcApplication.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/ServiceFrontMvcApplication.java new file mode 100644 index 0000000..397a1c8 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/ServiceFrontMvcApplication.java @@ -0,0 +1,38 @@ +package fr.ocr.front_mvc; + +import fr.ocr.RestClient; +import fr.ocr.exception.PrjExceptionHandler; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@PropertySources( { + @PropertySource(value = "classpath:application.properties"), + @PropertySource(value = "classpath:application.yml")}) +@EnableSwagger2 +public class ServiceFrontMvcApplication { + + public static void main(String[] args) { + + SpringApplication.run(ServiceFrontMvcApplication.class, args); + } + @Bean + public RestClient libHttpClient() { + return new RestClient() ; + } + + @Bean + public PrjExceptionHandler libHttpClient_Exception() { + return PrjExceptionHandler.getInstance(); + } + + @Bean + public ExitCodeGenerator exitCodeGenerator() { + return () -> 2020; + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/authentication/CustomAuthenticationProvider.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/authentication/CustomAuthenticationProvider.java new file mode 100644 index 0000000..ecf27ae --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/authentication/CustomAuthenticationProvider.java @@ -0,0 +1,57 @@ +/* +* Component : +* spécialise l'authentification : comparaison de mot de pass +* UserWebUserDetails contient les informations d'authentification si connexion réussie + */ + +package fr.ocr.front_mvc.authentication; + + +import fr.ocr.front_mvc.userdetails.UserWebUserDetails; +import fr.ocr.front_mvc.userdetails.UserWebUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.stereotype.Component; + +import java.util.Collection; + +@Component +public class CustomAuthenticationProvider implements AuthenticationProvider { + + @Autowired + private UserWebUserDetailsService userWebUserDetailsService; + + public CustomAuthenticationProvider() { + super(); + } + + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + final String username = authentication.getName(); + final String password = authentication.getCredentials().toString(); + + UserWebUserDetails userWebUserDetails = userWebUserDetailsService.doesUserExist(authentication); + + if (userWebUserDetails == null || ! userWebUserDetails.getUsername().equalsIgnoreCase(username)) { + throw new BadCredentialsException("Username not found."); + } + + if (!password.equals(userWebUserDetails.getPassword())) { + throw new BadCredentialsException("Wrong password."); + } + + Collection authorities = userWebUserDetails.getAuthorities(); + + return new UsernamePasswordAuthenticationToken(userWebUserDetails, password, authorities); + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } + +} \ No newline at end of file diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/configuration/MvcConfig.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/configuration/MvcConfig.java new file mode 100644 index 0000000..2a1fe86 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/configuration/MvcConfig.java @@ -0,0 +1,14 @@ +package fr.ocr.front_mvc.configuration; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class MvcConfig implements WebMvcConfigurer { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("home.html"); + registry.addViewController("/home").setViewName("home.html"); + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/configuration/WebSecurityConfig.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/configuration/WebSecurityConfig.java new file mode 100644 index 0000000..05e62bf --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/configuration/WebSecurityConfig.java @@ -0,0 +1,66 @@ +/* + * Configuration + * les URI sont accesibles si usager est authentifié sinon refus + * l'URI de login est accessible à anonymous + * LA MAQUETTE est en DEBUG Spring SECURITY !! + * CSRF est invalidé + * CORS est présent (mais c'est par déf dans les navigateurs actuels) + * max session par user == 1 (ne semble pas fonctionné dans ce code) + */ + +package fr.ocr.front_mvc.configuration; + + +import fr.ocr.front_mvc.authentication.CustomAuthenticationProvider; +import org.springframework.boot.autoconfigure.security.SecurityProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; + + +@Configuration +@EnableWebSecurity +@Order(SecurityProperties.BASIC_AUTH_ORDER) + +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private final CustomAuthenticationProvider authProvider; + + public WebSecurityConfig(CustomAuthenticationProvider authProvider) { + this.authProvider = authProvider; + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(AuthenticationManagerBuilder authBuilder) { + authBuilder.authenticationProvider(this.authProvider); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.cors().and().csrf().disable(); + http.sessionManagement().maximumSessions(1); + http.authenticationProvider(authProvider).formLogin().disable(); + http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint() {}); + + http.authorizeRequests() + .antMatchers("/loginUser").permitAll() + .antMatchers("/listeOuvrages").permitAll() + .antMatchers("/rechercherOuvrages").permitAll() + .antMatchers("/gestionPrets/prolongerPret").authenticated() + .antMatchers("/gestionPrets/listePrets").authenticated(); + } + +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/controller/CustomErrorController.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/controller/CustomErrorController.java new file mode 100644 index 0000000..42f0f27 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/controller/CustomErrorController.java @@ -0,0 +1,21 @@ +package fr.ocr.front_mvc.controller; + +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletResponse; + +public class CustomErrorController implements ErrorController { + @Override + public String getErrorPath() { + return "/error"; + } + @GetMapping("/error") + public ModelAndView handleError (HttpServletResponse response){ + int errorCode = response.getStatus(); + System.out.println("Error with code " +errorCode+" happened"); + return new ModelAndView(""); + } + +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/controller/DispatchController.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/controller/DispatchController.java new file mode 100644 index 0000000..5746870 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/controller/DispatchController.java @@ -0,0 +1,254 @@ +package fr.ocr.front_mvc.controller; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.ocr.RestClient; +import fr.ocr.front_mvc.model.OuvrageWeb; +import fr.ocr.front_mvc.model.PretWeb; +import fr.ocr.front_mvc.model.UserWeb; +import fr.ocr.front_mvc.service.UserWebService; +import fr.ocr.front_mvc.userdetails.UserWebUserDetails; +import io.swagger.annotations.Api; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.stereotype.Controller; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.view.RedirectView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.text.SimpleDateFormat; +import java.util.*; + + +@Api(value = "APIs de gestion des Prets.") +@Controller +@CrossOrigin(origins= "*", methods = {RequestMethod.GET, RequestMethod.PUT, RequestMethod.POST}, allowCredentials = "true") +public class DispatchController { + + private final RestClient restClient; + private final ObjectMapper objectMapper; + + private final UserWebService userWebService; + + private final Map model; + + public DispatchController(RestClient restClient, ObjectMapper objectMapper, UserWebService userWebService, Map model){ + this.restClient = restClient; + this.objectMapper = objectMapper; + + this.userWebService = userWebService; + this.model = model; + } + /* + ===================================================================================== + */ + @RequestMapping(value="/listeOuvrages", method = RequestMethod.GET) + public ModelAndView getListeOuvragesCtrl(@RequestParam(required = false) String auteur, + @RequestParam(required = false) String titre) throws IOException, InterruptedException { + + List ouvrageWebList; + String maViewName = "ouvrages"; + model.clear(); + + String uriOuvrageDtoById = "http://localhost:9090/LookForOuvrage/"; + + Map criterionList = new HashMap<>(); + + if (auteur != null && ! (auteur.isEmpty() || auteur.isBlank() )) + criterionList.put("auteur",auteur); + + if (titre != null && ! (titre.isEmpty() || titre.isBlank() )) + criterionList.put("titre",titre); + + String requestBody = objectMapper + .writerWithDefaultPrettyPrinter() + .writeValueAsString(criterionList); + + HttpRequest request = restClient.requestBuilder(URI.create(uriOuvrageDtoById), null) + .POST(HttpRequest.BodyPublishers.ofString(requestBody)) + .build(); + + HttpResponse response = restClient.send(request); + + if (response.statusCode() == HttpStatus.OK.value()) { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + ouvrageWebList = objectMapper.readValue(response.body(), new TypeReference<>(){}); + model.put("ouvragesWebListe",ouvrageWebList); + + } + else { + ouvrageWebList =new ArrayList<>(); + OuvrageWeb ouvrageWeb = new OuvrageWeb("Aucun Ouvrage ","disponible",0); + ouvrageWebList.add(ouvrageWeb); + model.put("ouvragesWebListe",ouvrageWebList); + } + return new ModelAndView(maViewName,model); + + } + + @RequestMapping(value="/rechercherOuvrages", method = RequestMethod.POST) + public ModelAndView postRechercherOuvragesCtrl(OuvrageWeb ouvrageWeb) { + + String nomAuteur = ""; + String titreOuvrage=""; + String monUrlOuvrage = "/listeOuvrages"; + Map attributs = new HashMap<>(); + + if (ouvrageWeb.getAuteur() != null && ! (ouvrageWeb.getAuteur().isEmpty() || ouvrageWeb.getAuteur().isBlank() )) + nomAuteur = ouvrageWeb.getAuteur(); + + if (ouvrageWeb.getTitre() != null && ! (ouvrageWeb.getTitre().isEmpty() || ouvrageWeb.getTitre().isBlank() )) + titreOuvrage = ouvrageWeb.getTitre(); + + + if (!nomAuteur.equals("") && titreOuvrage.equals("")) { + attributs.put("auteur",nomAuteur); + } + if (nomAuteur.equals("") && !titreOuvrage.equals("")) { + attributs.put("titre",titreOuvrage); + } + if (!nomAuteur.equals("") && !titreOuvrage.equals("")) { + attributs.put("auteur",nomAuteur); + attributs.put("titre",titreOuvrage); + } + + RedirectView redirectView = new RedirectView(); + redirectView.setUrl(monUrlOuvrage); + redirectView.setAttributesMap(attributs); + + return new ModelAndView(redirectView); + } + + @RequestMapping(value="/rechercherOuvrages", method = RequestMethod.GET) + public ModelAndView getRechercherOuvragesCtrl() { + model.clear(); + model.put("ouvrageWeb", new OuvrageWeb()); + return new ModelAndView("recherche",model); + } + + + /* + ========================================================================= + */ + + @RequestMapping(value="/loginUser", method = RequestMethod.GET) + public ModelAndView getLoginUserCtrl(HttpServletRequest request, HttpServletResponse response) { + + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + model.clear(); + + if (authentication != null ) { + Object principal =authentication.getPrincipal(); + + if ( principal instanceof UserWebUserDetails) { + new SecurityContextLogoutHandler().logout(request,response,authentication); + return new ModelAndView("home"); + } + } + + model.put("userWeb", new UserWeb()); + return new ModelAndView("connexion",model); + } + @RequestMapping(value="/loginUser", method = RequestMethod.POST) + public ModelAndView postLoginUserCtrl(@Valid UserWeb userWeb, BindingResult bindingResult) { + + + try { + if (bindingResult.hasErrors()) { + return new ModelAndView("connexion"); + } + if (userWebService.attemptAuthentication(userWeb) == null) { + bindingResult.rejectValue("nom", "", "Usager/Mot de Passe Incorrect"); + return new ModelAndView("connexion"); + } + } + catch(RuntimeException e) { + bindingResult.rejectValue("username", "", "Usager/Mot de Passe Incorrect"); + return new ModelAndView("connexion"); + } + return new ModelAndView("home"); + } + + /* + ========================================================================================== + */ + @GetMapping(value="/listePrets") + public ModelAndView getListePrestCtrl() throws RuntimeException, IOException, InterruptedException { + + List pretWebList ; + model.clear(); + + String uriPretByNomUsager = "http://localhost:9090/CriteriaListePrets/"; + + Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + + assert principal instanceof UserWebUserDetails; + UserWebUserDetails userWebUserDetails = (UserWebUserDetails)principal; + String username = ((UserWebUserDetails)principal).getUserWeb().getUsername(); + + HttpRequest request = restClient.requestBuilder(URI.create(uriPretByNomUsager + username), null).GET().build(); + + HttpResponse response = restClient.send(request); + + if (response.statusCode() == HttpStatus.OK.value()) { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + pretWebList = objectMapper.readValue(response.body(), new TypeReference<>() {}); + } + else { + pretWebList = new ArrayList<>(); + PretWeb pretWeb = new PretWeb(); + pretWeb.setAuteur("Aucun"); + pretWeb.setTitre("prét en cours"); + GregorianCalendar calendar = new GregorianCalendar(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + pretWeb.setDateEmprunt(calendar.getTime()); + } + + model.put("pretWebList",pretWebList); + return new ModelAndView("prets",model); + } + + @GetMapping(value = "/prolongerPret") + public ModelAndView prolongerPret(@RequestParam Integer ouvrageIdouvrage) throws RuntimeException, IOException, InterruptedException { + + Map stringIntegerMap = new HashMap<>(); + String uriOuvrageDtoById = "http://localhost:9090/ProlongerPret/"; + + UserWebUserDetails userWebUserDetails = (UserWebUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + + Integer userId = userWebUserDetails.getUserWeb().getIdUser(); + + + stringIntegerMap.put("idUser", userId); + stringIntegerMap.put("idOuvrage",ouvrageIdouvrage); + + String requestBody = objectMapper + .writerWithDefaultPrettyPrinter() + .writeValueAsString(stringIntegerMap); + + HttpRequest request = restClient + .requestBuilder(URI.create(uriOuvrageDtoById), null) + .PUT(HttpRequest.BodyPublishers.ofString(requestBody)) + .build(); + + HttpResponse response = restClient.send(request); + + RedirectView redirectView = new RedirectView(); + redirectView.setUrl("/listePrets"); + + return new ModelAndView(redirectView); + + } + +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/PriorityCtrl.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/PriorityCtrl.java new file mode 100644 index 0000000..ecf3d26 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/PriorityCtrl.java @@ -0,0 +1,18 @@ +package fr.ocr.front_mvc.customAnnotation; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = PriorityValidator.class) +public @interface PriorityCtrl { + String message() default " Choix L M H" ; + Class[] groups() default {}; + Class < ? extends Payload> [] payload() default {}; + +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/PriorityValidator.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/PriorityValidator.java new file mode 100644 index 0000000..d5ea4b7 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/PriorityValidator.java @@ -0,0 +1,12 @@ +package fr.ocr.front_mvc.customAnnotation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class PriorityValidator implements ConstraintValidator { + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + return value.trim().length() ==1 && "LMH".contains(value.toUpperCase()); + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/RatingCtrl.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/RatingCtrl.java new file mode 100644 index 0000000..64ba132 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/RatingCtrl.java @@ -0,0 +1,17 @@ +package fr.ocr.front_mvc.customAnnotation; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = RatingCtrlValidator.class) +public @interface RatingCtrl { + String message() default "valeur doit etre 1.0 < x < 10.0" ; + Class[] groups() default {}; + Class < ? extends Payload> [] payload() default {}; +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/RatingCtrlValidator.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/RatingCtrlValidator.java new file mode 100644 index 0000000..6798252 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/customAnnotation/RatingCtrlValidator.java @@ -0,0 +1,18 @@ +package fr.ocr.front_mvc.customAnnotation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class RatingCtrlValidator implements ConstraintValidator { + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + Double rateVal ; + try { + rateVal = Double.parseDouble(value); + + }catch (NumberFormatException e) { + return false; + } + return (rateVal <=10.0 || rateVal >= 1.0); + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/OuvrageWeb.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/OuvrageWeb.java new file mode 100644 index 0000000..4547fc9 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/OuvrageWeb.java @@ -0,0 +1,41 @@ +package fr.ocr.front_mvc.model; + +public class OuvrageWeb { + + private String titre; + private String auteur; + private Integer quantite; + + public OuvrageWeb(String titre, String auteur, Integer quantite) { + this.titre = titre; + this.auteur = auteur; + this.quantite = quantite; + } + + public OuvrageWeb() { + } + + public String getTitre() { + return titre; + } + + public void setTitre(String titre) { + this.titre = titre; + } + + public String getAuteur() { + return auteur; + } + + public void setAuteur(String auteur) { + this.auteur = auteur; + } + + public Integer getQuantite() { + return quantite; + } + + public void setQuantite(Integer quantite) { + this.quantite = quantite; + } +} \ No newline at end of file diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/PretWeb.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/PretWeb.java new file mode 100644 index 0000000..ca88fe5 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/PretWeb.java @@ -0,0 +1,18 @@ +package fr.ocr.front_mvc.model; + + +import lombok.Data; + +import java.util.Date; + +@Data +public class PretWeb { + int ouvrageIdouvrage; + int userIduser; + int pretprolonge; + Date dateEmprunt; + String auteur; + String titre; +} + + diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/UserWeb.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/UserWeb.java new file mode 100644 index 0000000..606b154 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/model/UserWeb.java @@ -0,0 +1,63 @@ +package fr.ocr.front_mvc.model; + +import javax.validation.constraints.NotEmpty; + + + +public class UserWeb { + private Integer idUser; + + @NotEmpty(message = "Ne doit pas être vide") + private String username; + + @NotEmpty(message = "Ne doit pas être vide") + private String password; + + private String email; + + public UserWeb() { + + } + + public UserWeb(Integer idUser, + String username, + String password, + String email) { + this.idUser = idUser; + this.username = username; + this.password = password; + this.email = email; + } + + public Integer getIdUser() { + return idUser; + } + + public void setIdUser(Integer idUser) { + this.idUser = idUser; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/service/UserWebService.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/service/UserWebService.java new file mode 100644 index 0000000..3515ee1 --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/service/UserWebService.java @@ -0,0 +1,47 @@ +/* +* Service :authentifcation usager + */ + +package fr.ocr.front_mvc.service; + +import fr.ocr.exception.PrjExceptionHandler; +import fr.ocr.front_mvc.model.UserWeb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + + +@Service +public class UserWebService { + + private final PrjExceptionHandler prjExceptionHandler; + private final AuthenticationProvider authenticationProvider; + + @Autowired + public UserWebService(PrjExceptionHandler prjExceptionHandler, AuthenticationProvider authenticationProvider) { + this.prjExceptionHandler = prjExceptionHandler; + this.authenticationProvider = authenticationProvider; + } + + public UserDetails attemptAuthentication(UserWeb user) { + Authentication authentication = null; + + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()); + + try { + authentication = this.authenticationProvider.authenticate(token); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + } catch (Exception e) { + prjExceptionHandler.throwUserUnAuthorized(); + } + assert authentication != null; + return (UserDetails) authentication.getPrincipal(); + } + +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/userdetails/UserWebUserDetails.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/userdetails/UserWebUserDetails.java new file mode 100644 index 0000000..be6380e --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/userdetails/UserWebUserDetails.java @@ -0,0 +1,79 @@ +/* +* Extension de UserDetail pour ajouter les infos usager propre à l'applixation + */ + +package fr.ocr.front_mvc.userdetails; + +import fr.ocr.front_mvc.model.UserWeb; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; + +import java.net.http.HttpResponse; +import java.util.Collection; + +//@Component +public class UserWebUserDetails extends User implements UserDetails { + + public UserWeb getUserWeb() { + return userWeb; + } + + public void setUserWeb(UserWeb userWeb) { + this.userWeb = userWeb; + } + + private UserWeb userWeb ; + + private HttpResponse response; + + public void setAuthorities(Collection authorities) { + this.authorities = authorities; + } + + private Collection authorities; + + public UserWebUserDetails(UserWeb userWeb, Collection authorities) { + super(userWeb.getUsername(),userWeb.getPassword(),authorities); + this.userWeb = userWeb; + this.authorities = authorities; + userWeb.setIdUser(userWeb.getIdUser()); + userWeb.setEmail(userWeb.getEmail()); + userWeb.setUsername(userWeb.getUsername()); + userWeb.setPassword(userWeb.getPassword()); + } + + public HttpResponse getResponse() { + return response; + } + + public void setResponse(HttpResponse response) { + this.response = response; + } + + + @Override + public Collection getAuthorities() { + return authorities; //AuthorityUtils.createAuthorityList("ROLE_USER"); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/userdetails/UserWebUserDetailsService.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/userdetails/UserWebUserDetailsService.java new file mode 100644 index 0000000..d5d7a8c --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/userdetails/UserWebUserDetailsService.java @@ -0,0 +1,87 @@ +/* +* Composant : + * Extension de UserDetailservice pour ajouter les infos usager propre à l'applixation + * * en lien avec UUserWebDetailService + * * implemente l'override loaduserByusername + * * recupere infos usager en appelant l'API Rest du service_crud correspondante + */ + +package fr.ocr.front_mvc.userdetails; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.ocr.RestClient; +import fr.ocr.exception.PrjExceptionHandler; +import fr.ocr.front_mvc.model.UserWeb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Collection; + +@Component +public class UserWebUserDetailsService implements UserDetailsService { + UserWeb userWeb; + private final RestClient restClient; + private final PrjExceptionHandler prjExceptionHandler; + private final ObjectMapper objectMapper; + + + @Autowired + public UserWebUserDetailsService(RestClient restClient, PrjExceptionHandler prjExceptionHandler, ObjectMapper objectMapper) { + this.restClient = restClient; + this.prjExceptionHandler = prjExceptionHandler; + this.objectMapper = objectMapper; + } + + @Override + public UserWebUserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + UserWebUserDetails userWebUserDetails; + try { + userWebUserDetails = getFromServiceCrud(username); + } catch (IOException | InterruptedException e) { + throw new UsernameNotFoundException("Nom inconnu"); + } + return userWebUserDetails; + } + + public UserWebUserDetails doesUserExist(Authentication authentication) throws UsernameNotFoundException{ + UserWebUserDetails userWebUserDetails; + try { + userWebUserDetails = getFromServiceCrud(authentication.getName()); + } catch (IOException | InterruptedException e) { + throw new UsernameNotFoundException("Nom inconnu"); + } + return userWebUserDetails; + } + + + public UserWebUserDetails getFromServiceCrud(String nomUser) throws IOException, InterruptedException{ + String uriUserByName = "http://localhost:9090/UserByName/"+ nomUser; + + HttpRequest request = restClient.requestBuilder(URI.create(uriUserByName), null).GET().build(); + + HttpResponse response = restClient.send(request); + + if (response.statusCode() != HttpStatus.OK.value()) { + prjExceptionHandler.throwUserUnAuthorized(); + } else { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + userWeb = objectMapper.readValue(response.body(), UserWeb.class); + } + Collection authorities= AuthorityUtils.createAuthorityList("ROLE_USER"); + UserWebUserDetails userWebUserDetails = new UserWebUserDetails(userWeb, authorities); + userWebUserDetails.setResponse(response); + return userWebUserDetails; + } + +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/utility/InfosConnexionUser.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/utility/InfosConnexionUser.java new file mode 100644 index 0000000..4dd6d1b --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/utility/InfosConnexionUser.java @@ -0,0 +1,42 @@ +package fr.ocr.front_mvc.utility; + + +import fr.ocr.front_mvc.userdetails.UserWebUserDetails; +import lombok.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import javax.servlet.http.HttpServletResponse; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +@Value +@Component +public final class InfosConnexionUser { + + public static ResponseEntity> formeReponseEntity(HttpServletResponse response, + UserWebUserDetails userWeb, + String id) { + + Map stringObjectMap = new HashMap<>(); + + stringObjectMap.put("username", userWeb.getUsername()); + stringObjectMap.put("password", userWeb.getPassword()); + stringObjectMap.put("idUser",userWeb.getUserWeb().getIdUser()); + stringObjectMap.put("idSession", id); + stringObjectMap.put("messageCnx",HttpStatus.valueOf(response.getStatus()).toString()); + + URI location = ServletUriComponentsBuilder.fromCurrentRequest().build().toUri(); + + ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity. + status(HttpStatus.valueOf(response.getStatus())); + + bodyBuilder.location(location).header("Content-Type", "application/json"); + + return bodyBuilder.body(stringObjectMap); + + } +} diff --git a/service_frontmvc/src/main/java/fr/ocr/front_mvc/utility/InfosPretWeb.java b/service_frontmvc/src/main/java/fr/ocr/front_mvc/utility/InfosPretWeb.java new file mode 100644 index 0000000..e23260e --- /dev/null +++ b/service_frontmvc/src/main/java/fr/ocr/front_mvc/utility/InfosPretWeb.java @@ -0,0 +1,61 @@ +package fr.ocr.front_mvc.utility; + + +import fr.ocr.front_mvc.model.PretWeb; +import lombok.Data; +import org.springframework.http.ResponseEntity; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import javax.servlet.http.HttpServletResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Data +public final class InfosPretWeb { + + private Integer idUser; + private Integer idOuvrage; + + public static ResponseEntity> formeReponseEntity(HttpServletResponse httpResponse, + PretWeb pretWeb) { + + Map stringObjectMap = new HashMap<>(); + + stringObjectMap.put("ouvrageIdouvrage",pretWeb.getOuvrageIdouvrage()); + stringObjectMap.put("userIduser",pretWeb.getUserIduser()); + stringObjectMap.put("pretprolonge",pretWeb.getPretprolonge()); + stringObjectMap.put("dateEmprunt",pretWeb.getDateEmprunt()); + stringObjectMap.put("auteur",pretWeb.getAuteur()); + stringObjectMap.put("titre",pretWeb.getTitre()); + + URI location = ServletUriComponentsBuilder.fromCurrentRequest().build().toUri(); + + ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.status(httpResponse.getStatus()); + + bodyBuilder.location(location).header("Content-Type", "application/json"); + + return bodyBuilder.body(stringObjectMap); + + } + + public static ResponseEntity> formeReponseEntity(HttpServletResponse httpResponse, + List pretWebs) { + List pretWebArrayList = new ArrayList<>(); + + for (PretWeb pretWeb :pretWebs) { + pretWebArrayList.add(pretWeb); + } + + URI location = ServletUriComponentsBuilder.fromCurrentRequest().build().toUri(); + + ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.status(httpResponse.getStatus()); + + bodyBuilder.location(location).header("Content-Type", "application/json"); + + return bodyBuilder.body(pretWebArrayList); + + } +} \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/application.properties b/service_frontmvc/src/main/resources/application.properties new file mode 100644 index 0000000..4b1fafa --- /dev/null +++ b/service_frontmvc/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.devtools.livereload.enabled=false +spring.devtools.restart.enabled=false +spring.devtools.restart.exclude=META-INF/maven/**, META-INF/resources/**,resources/** +spring.devtools.restart.additional-exclude=./logs/**,logs/** diff --git a/service_frontmvc/src/main/resources/application.yml b/service_frontmvc/src/main/resources/application.yml new file mode 100644 index 0000000..3a49a42 --- /dev/null +++ b/service_frontmvc/src/main/resources/application.yml @@ -0,0 +1,7 @@ +server: + port: 80 +spring: + main: + banner-mode: log + application: + name: service_frontmvc diff --git a/service_frontmvc/src/main/resources/logback-spring.xml b/service_frontmvc/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..ab6180d --- /dev/null +++ b/service_frontmvc/src/main/resources/logback-spring.xml @@ -0,0 +1,39 @@ + + + + + + [%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n + + + + + ./logs/service_frontmvc.log + + [%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/templates/connexion.html b/service_frontmvc/src/main/resources/templates/connexion.html new file mode 100644 index 0000000..5f68477 --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/connexion.html @@ -0,0 +1,56 @@ + + + + + + + +
+ +
+ +
+

s'Identifier

+
+ +
+ +
+ +
+
+ +
+
+ +
+ +
+ +
+
+ +
+
+
+ + +
+ +
+
+
+ +
+ + + + + + + \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/templates/error.html b/service_frontmvc/src/main/resources/templates/error.html new file mode 100644 index 0000000..9750afc --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/error.html @@ -0,0 +1,31 @@ + + + + + + + +
+ + +
+
+

Oops!

+
+

This is embarrassing!😔 Please contact our support! 🙏

+
+
+ +
+ + + + + + + \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/templates/fragment/frag_barenav.html b/service_frontmvc/src/main/resources/templates/fragment/frag_barenav.html new file mode 100644 index 0000000..d14a153 --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/fragment/frag_barenav.html @@ -0,0 +1,85 @@ + + + + Acceuil + + + + + + + + + + + diff --git a/service_frontmvc/src/main/resources/templates/fragment/frag_header.html b/service_frontmvc/src/main/resources/templates/fragment/frag_header.html new file mode 100644 index 0000000..2dc4bd6 --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/fragment/frag_header.html @@ -0,0 +1,10 @@ + + + + + + + + + Bibliothèque Municipale + diff --git a/service_frontmvc/src/main/resources/templates/home.html b/service_frontmvc/src/main/resources/templates/home.html new file mode 100644 index 0000000..cb55799 --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/home.html @@ -0,0 +1,25 @@ + + + + + + + +
+ +

La bibliothèque!


+
Les prêts et les ouvrages disponibles
+ +
+ + + + + + + \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/templates/ouvrages.html b/service_frontmvc/src/main/resources/templates/ouvrages.html new file mode 100644 index 0000000..f228a6d --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/ouvrages.html @@ -0,0 +1,42 @@ + + + + + + + +
+ + + +

Les Ouvrages Disponibles

+ + + + + + + + + + + + + + + + +
AuteurTitreQuantite
LaurentSpringMvc3
+
+ + + + + + + \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/templates/prets.html b/service_frontmvc/src/main/resources/templates/prets.html new file mode 100644 index 0000000..6bc32c4 --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/prets.html @@ -0,0 +1,43 @@ + + + + + + + +
+ + + +

LesPrêts

+ + + + + + + + + + + + + + + + + +
AuteurTitreDate
Avatar7.802Update
+
+ + + + + + + \ No newline at end of file diff --git a/service_frontmvc/src/main/resources/templates/recherche.html b/service_frontmvc/src/main/resources/templates/recherche.html new file mode 100644 index 0000000..58ed68d --- /dev/null +++ b/service_frontmvc/src/main/resources/templates/recherche.html @@ -0,0 +1,49 @@ + + + + + + + +
+ +
+ +
+

Recherche Ouvrages

+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ + + + + + + \ No newline at end of file diff --git a/sql_uml/create_tbl.sql b/sql_uml/create_tbl.sql new file mode 100644 index 0000000..4616f5a --- /dev/null +++ b/sql_uml/create_tbl.sql @@ -0,0 +1,217 @@ +-- ------------------------------------------------------------------------- +-- et les Drop dans l'ordre +-- --------------------------------------------------------------------------- + +DROP TABLE IF EXISTS pret.pret; +DROP TABLE IF EXISTS usager.user ; +DROP TABLE IF EXISTS ouvrage.ouvrage ; + +DROP SEQUENCE IF EXISTS usager.user_iduser_seq; +DROP SEQUENCE IF EXISTS ouvrage.ouvrage_idouvrage_seq; + +DROP SCHEMA IF EXISTS usager CASCADE ; +DROP SCHEMA IF EXISTS pret; +DROP SCHEMA IF EXISTS ouvrage; + +-- --------------------- SEQUENCE -------------------------------------------- +-- pour commencer !! +-- SELECT * FROM pret.pret p inner join user.user u on p.usager_idusager = u.idusager where u.idusager=2; +-- ------------------------------------------------------------------------- + +CREATE SCHEMA usager + AUTHORIZATION rl_projet07; + +CREATE SCHEMA pret + AUTHORIZATION rl_projet07; + +CREATE SCHEMA ouvrage + AUTHORIZATION rl_projet07; + +CREATE SEQUENCE usager.user_iduser_seq + INCREMENT 1 + START 1 + MINVALUE 1 + MAXVALUE 2147483647 + CACHE 1; + +ALTER SEQUENCE usager.user_iduser_seq + OWNER TO rl_projet07; + +CREATE SEQUENCE ouvrage.ouvrage_idouvrage_seq + INCREMENT 1 + START 1 + MINVALUE 1 + MAXVALUE 2147483647 + CACHE 1; + +ALTER SEQUENCE ouvrage.ouvrage_idouvrage_seq + OWNER TO rl_projet07; + +-- --------------------- TABLE -------------------------------------------- +-- Tables : BIEN RESPECTER l'ORDRE +-- ------------------------------------------------------------------------- + +CREATE TABLE usager.user +( + iduser integer NOT NULL DEFAULT nextval('usager.user_iduser_seq'::regclass), + userName character varying(256) COLLATE pg_catalog."default" NOT NULL DEFAULT 'laurent'::character varying, + password character varying(1024) COLLATE pg_catalog."default" NOT NULL DEFAULT 'laurent'::character varying, + email character varying(1024) COLLATE pg_catalog."default" NOT NULL DEFAULT 'laurent.cordier3004@gmail.com'::character varying, + CONSTRAINT usager_pkey PRIMARY KEY (iduser) + USING INDEX TABLESPACE ts_projet07 +) + WITH ( OIDS = FALSE ) TABLESPACE ts_projet07; + +ALTER TABLE usager.user OWNER to rl_projet07; + +CREATE TABLE ouvrage.ouvrage +( + idouvrage integer NOT NULL DEFAULT nextval('ouvrage.ouvrage_idouvrage_seq'::regclass), + titre character varying(2048) COLLATE pg_catalog."default" NOT NULL, + auteur character varying(256) COLLATE pg_catalog."default" NOT NULL, + quantite integer NOT NULL DEFAULT 10, + CONSTRAINT ouvrage_pkey PRIMARY KEY (idouvrage) + USING INDEX TABLESPACE ts_projet07 +) + WITH + ( OIDS = FALSE ) TABLESPACE ts_projet07; + +ALTER TABLE ouvrage.ouvrage OWNER to rl_projet07; + +CREATE TABLE pret.pret +( + ouvrage_idouvrage integer NOT NULL, + user_iduser integer NOT NULL, + pret_prolonge integer NOT NULL DEFAULT 0, + date_emprunt date NOT NULL, + CONSTRAINT pret_pkey PRIMARY KEY (ouvrage_idouvrage, user_iduser) + USING INDEX TABLESPACE ts_projet07, + CONSTRAINT fk_usager FOREIGN KEY (user_iduser) + REFERENCES usager.user (iduser) MATCH FULL + ON UPDATE CASCADE + ON DELETE CASCADE + DEFERRABLE , + CONSTRAINT fk_reference FOREIGN KEY (ouvrage_idouvrage) + REFERENCES ouvrage.ouvrage (idouvrage) MATCH FULL + ON UPDATE CASCADE + ON DELETE CASCADE + DEFERRABLE +) + WITH ( + OIDS = FALSE + ) + TABLESPACE ts_projet07; + +ALTER TABLE pret.pret OWNER to rl_projet07; + +-- --------------------- JEU de TEST -------------------------------------------- +-- valeurs fixes pour ce projet - seul update sur "prolongation de l'emprunt" +-- ------------------------------------------------------------------------- + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('micro services with spring boot', 'ranga rao karanam', 10); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('learning spring boot 2.0', 'greg l. turnquist', 8); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('building web apps with spring 5 and angular', 'ranga ajitesh shukla', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('Java the complete eleventh edition', 'Herbert Schildt', 2); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('Apache Maven maitrisez l infra d un projet Java EE' , 'Maxime Greau Etienne Langlet', 4); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('Java JEE developpez des applicaitons Web en Java', 'Thierry richard', 2); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('JPA et Java Hibernate Apprenez le ORM avec Java', 'Martial Banon', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('PostgreSQL Admin et exploit de vos base de données', 'Sébastien Lardiere', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('Java Spring Le scocle technique des applis Java EE', 'Hervé le Morvan', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('HTML5 et CSS3 faite evoluez le design de vos sites web', 'Christophe Aubry', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('HTML5 et CSS3 maitrisez les standards de la creation de sites web', 'Christophe Aubry', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('Mastering MicroServices with Java', 'Sourabh Sharma', 12); + +INSERT INTO ouvrage.ouvrage(titre, auteur, quantite) +VALUES ('SCRUM piur une pratique vivante de l agilité', 'Claude Aubry', 12); + +-- -- + +INSERT INTO usager.user(userName, password) +VALUES ('ibtisem', 'ibtisem'); + +INSERT INTO usager.user(userName, password) +VALUES ('lola','lola'); + +INSERT INTO usager.user(userName, password) +VALUES ('julie', 'julie'); + +INSERT INTO usager.user(userName, password) +VALUES ('jeff', 'jeff'); + +INSERT INTO usager.user(userName, password) +VALUES ('herbert', 'herbert'); + +INSERT INTO usager.user(userName, password) +VALUES ('greg', 'greg'); + +INSERT INTO usager.user(userName, password) +VALUES ('lao', 'lao'); + + +-- -- +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (8, 1, 0, '2019-11-08'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (9, 1, 0, '2019-11-08'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (10, 1, 0, '2019-11-08'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (11, 1, 0, '2019-11-08'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (3, 2, 0, '2019-10-01'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (4, 2, 0, '2019-09-21'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (5, 2, 0, '2019-10-07'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (6, 2, 0, '2019-11-08'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (7, 2, 0, '2019-11-08'); + + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (2, 3, 1, '2019-11-08'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (1, 3, 0, '2019-11-10'); + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (12, 3, 0, '2019-11-08'); + + +INSERT INTO pret.pret (ouvrage_idouvrage, user_iduser, pret_prolonge, date_emprunt) +VALUES (13, 3, 0, '2019-11-08'); + + +-- fin -- \ No newline at end of file diff --git a/sql_uml/prep_projet07.sql b/sql_uml/prep_projet07.sql new file mode 100644 index 0000000..1405c08 --- /dev/null +++ b/sql_uml/prep_projet07.sql @@ -0,0 +1,54 @@ +-- *************************************** +-- Creation du Role: rl_projet07 +-- ************************************** + +DROP ROLE IF EXISTS rl_projet07; + +CREATE ROLE rl_projet07 WITH + LOGIN + SUPERUSER + CREATEDB + CREATEROLE + INHERIT + NOREPLICATION + CONNECTION LIMIT -1 + PASSWORD 'xxxxxx'; + + +-- *************************************** +-- Creation du Tablespace: ts_projet07 +-- ************************************** +DROP TABLESPACE IF EXISTS ts_projet07; + +CREATE TABLESPACE ts_projet07 + OWNER rl_projet07 + LOCATION 'c:/bd_data'; + +ALTER TABLESPACE ts_projet07 + OWNER TO rl_projet07; + + +-- *************************************** +-- Creation du Database: db_projet07 +-- ************************************** + +DROP DATABASE IF EXISTS db_projet07; + +CREATE DATABASE db_projet07 + WITH + OWNER = rl_projet07 + ENCODING = 'UTF8' + LC_COLLATE = 'French_France.1252' + LC_CTYPE = 'French_France.1252' + TABLESPACE = ts_projet07 + CONNECTION LIMIT = -1; + +GRANT TEMPORARY, CONNECT ON DATABASE db_projet07 TO PUBLIC; + +GRANT ALL ON DATABASE db_projet07 TO rl_projet07; + +ALTER DEFAULT PRIVILEGES +GRANT ALL ON TABLES TO rl_projet07; + + +