Skip to content
Snippets Groups Projects
Commit 9d48f45a authored by Nicolas Dausque's avatar Nicolas Dausque
Browse files

Push

parents
Branches master
No related tags found
No related merge requests found
Showing
with 1163 additions and 0 deletions
README.md 0 → 100644
# TP Kotlin
---
**PS :** Vous pouvez skip l'intro et aller à __l'Étape 1__ si vous n'aimez pas les thrillers de science-fiction autobiographiques.
### Précédemment, dans _la vie_
Il était une fois une team de développeurs aguérris, forts d'une expérience quasi-infinie (i.e. 5 ans et demi) dans le domaine des applications web (chacuns ses délires, on ne juge pas).
Un beau jour alors que la migration de l'appli vers Java 12 battait son plein et que le pôle de recherche squattait le baby depuis 40 minutes, Jaquot Tlin, jeune dév en devenir, dingue de Dave, eut une idée. Une idée qu'aucun de ses compères développeurs ne pouvait appréhender :
  \- _"Eh les gars, et si au lieu de faire encore et toujours du Java (qui a presque 25 ans), on gardait ce qu'on avait là et on regardait comment faire du Kotlin ? On a quasiment rien à changer et ça pourrait nous simplifier notre vie de développeurs pas toujours facile !"_
  \- _\*silence dans l'open space\*_
Prise de stupeur et de tremblements, la dév sénior du pôle, Eve D. Lopper, attrapa Jaquot d'un regard, l'invitant silencieusement à _slide_ à son bureau avec sa chaise.
  \- _"OK Jaquot écoute moi bien. J'aime les gens qui prennent des initatives. Mais j'ai pas le temps de suivre des tutos youtube sur les nouvelles techs. Tu peux me montrer en deux-deux ce qu'est Kotlin ?"_
  \- _"Ça tombe bien j'ai justement un vieux TP d'IAGL sous la main, pousse toi, et admire..."_
![Alt Text](https://media.giphy.com/media/Z46IdUzMRYqyI/giphy.gif)
## Étape 1 : Du Java et des Hommes
Premièrement, ~~on va~~ vous allez faire du Java, parce que le Java, c'est connu.
Rien de bien compliqué pour commencer, juste un singleton [comme il ne faut plus en faire](https://en.wikipedia.org/wiki/Singleton_pattern) (<- c'est un lien, il [peut](https://www.conjugaisonfrancaise.com/pouvoir.html) y en avoir des utiles).
Vous vous en doutez, vu que c'est du Java et pas du Kotlin comme annoncé, vous pouvez le faire un peu où vous voulez. **MAIS** sachez que vous en aurez quand même besoin dans un futur très proche, donc on vous conseille de le faire sur un compilateur en ligne ou un projet bidon, histoire de voir si ça compile.
##### TODO (vous pouvez les cocher même si ça ne sert à rien) :
- [ ] Créer une classe `Meme` qui représente un [meme](https://en.wikipedia.org/wiki/Meme) et qui comporte un nom _nom_ et un url _url_ (ouais on fait dans la sobriété)
- [ ] Créer une classe `FavDir` **singleton** en _JAVA_ qui représente un dossier de favoris tout simple. Il contiendra une liste d'objets _Meme_.
Si vous voulez des images mais que vous n'avez pas d'idées (franchement [Google images](https://duckduckgo.com/) c'est pas compliqué), [rendez-vous ici](https://knowyourmeme.com/memes/popular). Tant que c'est une image, ça va (jpg, png, gif...)
## Étape 1,5 : Transformation Kotlin
Parfait, maintenant que le singleton est derrière vous, vous allez pouvoir l'oublier et le refaire. Cette fois-ci bien sûr, en Kotlin, tout beau tout propre, donc ne l'oubliez pas trop vite non plus.
Pensez à jeter un œil aux slides, on vous en a parlé dedans.
**PRO TIPS** : _object_, _data class_
Alternativement, les plus chanceux d'entre vous qui utilisent IntelliJ (pas Eclipse, dommage) peuvent directement [traduire du code Java en Kotlin](http://m.quickmeme.com/img/e4/e4e66bc437fb19844ca10d26f09dbe951a27b8e1da93b6054bb1f87a8ff06a62.jpg), mais y'en a qui ont essayé, ils ont eu des problèmes...
##### TODO :
- [ ] Créer les mêmes classes que dans l'étape 1, mais en _Kotlin_ (donc `Meme` et `FavDir`).
- [ ] Lui (`FavDIr`) ajouter un bloc _init_ qui print un truc dans la console (histoire de voir qu'il est bien initialisé une seule fois)
- [ ] Lui rajouter la méthode `addMeme(meme: Meme)`, pour ajouter un meme
- [ ] Et aussi `getAll()` qui (vous vous en doutez, bilingue que vous êtes) retourne à l'appelant la liste des memes du _FavDir_
## Étape 2 : Ajouter des memes a ses favoris
Dans l'onglet de l'étape 2, vous trouverez un formulaire pour ajouter un meme dans votre _FavDir_. Pour la petite histoire, un dev avait déjà fait tout ça, mais il s'est fait virer... Fou de rage, il a pris cette implem, a supprimé deux trois trucs, et a _force push_, puis est parti... Bref, triste histoire...
Donc vous l'avez deviné : il va falloir remettre en place ce mécanisme, qui récupère la data du formulaire dans le back, et qui l'ajoute aux favoris. É qué sapelorio _Controller_. É _Service_, puisque faire des choses dans un controller (autres qu'appeler un service) c'est sale, et vous devriez avoir honte de le faire !
##### TODO :
- [ ] Récupérer la data du formulaire dans un controller _Kotlin_ (vous gérez les noms, vous êtes grands).
- [ ] Créer un service _Kotlin_ qui se chargera de l'ajout de votre meme dans la liste des favoris (et donc implicitement de votre fichier).
**PRO TIPS :**
- Il ne faut pas oublier que vous avez Spring derrière tout ça (pour votre plus grand BONHEUR). Et Spring a sa façon de faire.
Donc n'oubliez pas :
- Les annotations @Service, @Controller, @Autowired, et j'en passe
- Les modificateurs éventuels à ajouter aux cibles des annotations (open, lateinit...)
Si tout se passe bien, ça marche (mais encore ?), et votre fichier est bien modifié en conséquence.
## Étape 3 : Qui a parlé de DB ?
Joli, **normalement** ça devait pas être trop long (surtout en _Kotlin_ hein), et vous devriez avoir un beau singleton.
Sinon nan pas une DB, c'est un peu overkill.
Par contre, les ["DB"](https://i.imgflip.com/136hly.jpg), on peut faire. Par exemple... les écritures dans un fichier ? Il ne faudrait tout de même pas que vous perdiez votre liste de memes à chaque reboot de l'application.
Bon pour une fois, vous ne partez pas de rien. Vous avez dans le package _tools_ de _src/kotlin/...._ un fichier _FileManager_ qui vous servira de "DB". Par contre il n'y a pour l'instant qu'une méthode, pour savoir si une ligne non commentée est présente. Mais elle vous servira de base (ça ou [Google](www.bing.com) ofc).
##### TODO :
- [ ] Agrémenter le _FileManager_ de deux méthodes, l'une pour charger le contenu du fichier dans votre _FavDir_, l'autre pour ajouter un meme au fichier.
- [ ] Ajouter de la meilleure façon possible ([vous serez jugés](https://vignette.wikia.nocookie.net/aceattorney/images/8/87/Judge_Anime.png/revision/latest?cb=20160501045659)) un moyen pour que votre _FavDir_ se charge tout seul (sans bouton du front ni rien)
- [ ] Faire (théoriquement, la pratique vient après) en sorte d'ajouter le meme au fichier quand vous l'ajoutez dans votre _FavDir_
## Étape 4 : Lister tout votre bordel
Bon c'est pas tout ça, mais il faut du visuel !
Donc pour cette quatrième étape, vous devez afficher votre dossier de favoris dans l'onglet de l'étape 3 (classique). Par contre, étant donné qu'on ne lit pas votre code du futur, la jsp est un peu broken pour le moment, mais j'ai confiance en vous ! [Si Bob peut le réparer alors vous aussi !](https://www.youtube.com/watch?v=WfbZyaXDem0)
##### TODO :
- [ ] Modifier la méthode du controller qui affiche les données dans l'onglet de l'étape 3 afin qu'elle affiche votre liste d'images favorites.
- [ ] Faites vous "plaisir" et ajouter un tri sur la liste, ça va assez vite
## Étape 5 : Gotta go fast
Mmmmmh... c'est bizarre... ça met environ 40 ans à se charger...
Je pense qu'il est temps de faire un truc qu'on sait bien faire : se plaindre de l'infra.
Ils ont mis en place la pire DB jamais vue dans l'histoire des pires DB. Elle. Est. Lente. Mais... très lente. Mais le client n'aime pas la lenteur, lui, il veut des trucs jolis et qui vont vite.
Donc pas le choix... Il va falloir... parallèliser... _[\*queue drama music\*](https://www.youtube.com/watch?v=cphNpqKpKc4)_
Mais pas d'inquiétudes, c'est pas si compliqué que ça. On vous en a parlé vers la fin du diapo.
Donc vous vous démerdez :-)
- [ ] Améliorez votre service qui get de façon à ce que vos images s'affichent en un temps raisonnable (environ 3 secondes, selon le nombre de memes que vous avez)
## Étape 6 : [Do what you want 'cause a pirate is free](https://www.youtube.com/watch?v=kRKAL-i-UbE)
Si vous arrivez ici, alors gg wp ! Normalement il devrait pas rester trop de temps à la séance, donc on a des propositions à vous faire, faites ce que vous voulez, notre travail ici est accompli (sauf s'il reste 1h30 auquel cas désolé M. Quinton de vous avoir fais faux pas)
- [ ] Traduire le controller java en Kotlin
- [ ] Faire des validateurs lors de la saisie d'url de meme (on peut faire des injections easy peasy atm (M. Cartigny aurait des envies de meurtre))
- [ ] Faire des tris ou que sais-je avec les listes
- [ ] Chercher d'autres memes sur l'internet
- [ ] Cocher et décocher cette ligne 3 fois en moins de 1.5 secondes pour voir ce qu'il se passe
- [ ] Se rendre compte que ça servait à rien
- [ ] [try not to cry](https://i.imgur.com/AdiBPrO.jpg)
- [ ] [cry a lot](https://i.imgur.com/AdiBPrO.jpg)
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# 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 "$@"
@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 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.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%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
<groupId>com.tpKotlin.glhf</groupId>
<artifactId>tpkotlin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tpkotlin</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<kotlin.version>1.3.50</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.tpKotlin.glhf.tpkotlin.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.tpKotlin.glhf.tpkotlin.entity.FavDir;
import com.tpKotlin.glhf.tpkotlin.entity.Meme;
import com.tpKotlin.glhf.tpkotlin.service.DossierFavService;
@Controller
public class SimpleController {
@Autowired
private DossierFavService dfs;
@RequestMapping({ "/", "/index" })
public ModelAndView index() {
return new ModelAndView("index", "msg", "Bienvenue !");
}
@RequestMapping("/ex1")
public ModelAndView exo1() {
String s = FavDir.affiche();
ModelAndView mav = new ModelAndView("ex1");
mav.addObject("dirfav", s );
return mav;
}
@RequestMapping("/ex2")
public ModelAndView exo2() {
return new ModelAndView("ex2", "formMeme", new Meme("", ""));
}
@RequestMapping("/ex3")
public ModelAndView exo3() {
return new ModelAndView("ex3");
}
@RequestMapping("/ex4")
public ModelAndView exo4() {
String s = dfs.getAllImagesFromFavFASTER();
ModelAndView mav = new ModelAndView("ex4");
mav.addObject("dirfav", s );
return mav;
}
@RequestMapping("/ex5")
public ModelAndView exo5() {
return new ModelAndView("ex5");
}
}
package com.tpKotlin.glhf.tpkotlin
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.boot.runApplication
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
import org.springframework.context.annotation.ComponentScan
@SpringBootApplication
@ComponentScan
open class TpkotlinApplication: SpringBootServletInitializer(){
override fun configure(application: SpringApplicationBuilder): SpringApplicationBuilder {
return application.sources(org.springframework.boot.autoconfigure.SpringBootApplication::class.java)
}
}
fun main(args: Array<String>) {
runApplication<TpkotlinApplication>(*args)
}
\ No newline at end of file
package com.tpKotlin.glhf.tpkotlin.controller
import com.tpKotlin.glhf.tpkotlin.entity.Meme
import com.tpKotlin.glhf.tpkotlin.service.DossierFavService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.servlet.ModelAndView
@Controller
@RequestMapping("meme")
class MemeController {
@Autowired
lateinit var favService: DossierFavService
@PostMapping("/add")
fun addMeme(@ModelAttribute("formMeme") formMeme: Meme): ModelAndView {
favService.insertMeme(formMeme)
var mav = ModelAndView("ex2", "succeed", "true")
mav.addObject("formMeme", Meme("", ""))
return mav
}
}
\ No newline at end of file
package com.tpKotlin.glhf.tpkotlin.dao
import com.tpKotlin.glhf.tpkotlin.entity.Meme
interface ImageAccessorDao {
fun getMeme(nom: String): Boolean
fun saveMeme(meme: Meme)
}
\ No newline at end of file
package com.tpKotlin.glhf.tpkotlin.dao
import com.tpKotlin.glhf.tpkotlin.entity.FavDir
import com.tpKotlin.glhf.tpkotlin.entity.Meme
import com.tpKotlin.glhf.tpkotlin.tools.FileManager
import kotlinx.coroutines.*
import org.springframework.stereotype.Component
import java.time.LocalDateTime
@Component
class ImageAccessorDaoImpl : ImageAccessorDao {
override fun getMeme(nom: String): Boolean {
//celui qui retire çeci sera maudit pendant 3 generations (la sienne incluse)
runBlocking {
println("" + LocalDateTime.now() + ">> on va attendre")
//delay(1000L)
Thread.sleep(1000L)
}
return true
}
override fun saveMeme(meme: Meme) {
FileManager.saveMemeInFile(meme.nom, meme.url)
}
}
\ No newline at end of file
package com.tpKotlin.glhf.tpkotlin.entity
import java.time.LocalDateTime
import com.tpKotlin.glhf.tpkotlin.tools.FileManager
object FavDir {
val list: MutableList<Meme> = mutableListOf()
init {
println("Dossier de favoris crée")
if (FileManager.thereIsSomethingInTheFile()) {
FileManager.loadAllFromFile()
}
}
fun addMeme(meme: Meme) {
list.add(meme)
FileManager.saveMemeInFile(meme.nom, meme.url)
}
fun loadMeme(meme: Meme) {
list.add(meme)
}
@JvmStatic
fun affiche(): String {
var s: String = ""
for (i in 0 until list.size) {
s = list.get(i).nom + " " + list.get(i).url + "&&&"+ s
}
return s
}
fun getAll(): MutableList<Meme> {
return list
}
}
data class Meme(var nom: String, var url: String)
package com.tpKotlin.glhf.tpkotlin.service
import com.tpKotlin.glhf.tpkotlin.entity.Meme
interface DossierFavService {
fun insertMeme(meme: Meme)
fun getAllImagesFromFav(): String
fun getAllImagesFromFavFASTER(): String
}
\ No newline at end of file
package com.tpKotlin.glhf.tpkotlin.service
import com.tpKotlin.glhf.tpkotlin.dao.ImageAccessorDao
import kotlinx.coroutines.*
import com.tpKotlin.glhf.tpkotlin.entity.FavDir
import com.tpKotlin.glhf.tpkotlin.entity.Meme
import org.springframework.stereotype.Service
import com.tpKotlin.glhf.tpkotlin.dao.ImageAccessorDaoImpl
import org.springframework.beans.factory.annotation.Autowired
import java.time.LocalDateTime
@Service
class DossierFavServiceImpl : DossierFavService {
@Autowired
lateinit var imgDao: ImageAccessorDao
//méthode check + ajout exo 2
override fun insertMeme(meme: Meme) {
FavDir.addMeme(meme)
}
//Truc lent pour l'exo 3
override fun getAllImagesFromFav(): String {
var liste = FavDir.getAll()
var s: String = ""
var res: Boolean = false
for (i in 0 until liste.size) {
s = liste.get(i).url + "&&&" + s
}
for (img in liste) {
println("> here we go")
res = imgDao.getMeme(img.nom)
}
return if (res) s else "fail"
}
//Truc rapide pour le 4
override fun getAllImagesFromFavFASTER(): String {
var liste = FavDir.getAll()
var jobList: MutableList<Job> = mutableListOf()
var s: String = ""
for (i in 0 until liste.size) {
s = liste.get(i).url + "&&&" + s
}
runBlocking {
for (img in liste) {
println("> service lance l'appel DAO")
jobList.add(GlobalScope.launch { imgDao.getMeme(img.nom) })
}
for (myJob in jobList) {
myJob.join()
println("" + LocalDateTime.now() + " >> affichage ? " + myJob.isActive)
}
}
return s
}
}
\ No newline at end of file
package com.tpKotlin.glhf.tpkotlin.tools
import java.io.File
import com.tpKotlin.glhf.tpkotlin.entity.FavDir
import com.tpKotlin.glhf.tpkotlin.entity.Meme
import java.io.FileOutputStream
object FileManager {
val FILE_NAME = "monTonton.sappellePasRichard"
val PATH_TO_FILE = "src/main/resources/files/"
fun thereIsSomethingInTheFile(): Boolean {
var res = false
File(PATH_TO_FILE + FILE_NAME).bufferedReader().lines().use { lines ->
for (line in lines) {
if (!line.startsWith('#')) {
res = true
break
}
}
}
return res
}
fun loadAllFromFile() {
lateinit var tab: List<String>
var nom: String = ""
File(PATH_TO_FILE + FILE_NAME).forEachLine {
if (!it.startsWith('#')) {
tab = it.split(" ")
if (tab.size == 2) {
FavDir.loadMeme(Meme(tab[0], tab[1]))
} else if(tab.size > 2) {
for(i in 0 until tab.size-1) {
nom += tab[i] + " "
}
FavDir.loadMeme(Meme(nom, tab[tab.size-1]))
}
}
}
}
fun saveMemeInFile(name: String, url: String) {
FileOutputStream(File(PATH_TO_FILE + FILE_NAME), true)
.bufferedWriter()
.use {
it.newLine()
it.write(name.trim() + " " + url.trim())
}
}
}
\ No newline at end of file
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
# Pour sauvegarder vos images pour qu'elles soient rechargées
# une fois l'appli redémarrée (déso on avait la flemme de faire
# une db), on stock les noms/url ici.
#
# FORMAT :
# titre url
#
tester cest pas viable https://i.pinimg.com/originals/5e/df/c6/5edfc6638e8068fcae834432e5ef8d33.jpg
noice https://media.giphy.com/media/QyWBTLDn9WHt0FXGJS/200w_d.gif
travoltek https://media3.giphy.com/media/czBIi0WnXX8L6/giphy.gif
Ricardo Milos https://media1.tenor.com/images/85caab51be730a4e1290cd99d7d6e085/tenor.gif
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<c:import url="/WEB-INF/jsp/header.jsp" />
<title>Etape 1</title>
</head>
<body>
<h1 class="content-title">Etape 1 : Singleton</h1>
<br>
<br>
<div class="row">
<div class="offset-sm-1 col-sm-10">
<h2>Mon Repo Favoris :</h2>
<br>
<br>
<ul>
<c:forTokens items="${dirfav}" delims="&&&" var="name">
<li> ${name} </li>
</c:forTokens>
</ul>
</div>
</div>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<c:import url="/WEB-INF/jsp/header.jsp" />
<title>Etape 2</title>
</head>
<body>
<h1 class="content-title">Etape 2 : Gestion de Liste</h1>
<br>
<h3 class="content-sub-title">Saisie d'un nouveau Meme : </h3>
<br><br>
<div class="container-fluid">
<form:form method="POST" action="/meme/add" modelAttribute="formMeme">
<div class="row">
<div class="col-sm-2 offset-md-4">
Meme name:
</div>
<div class="col-sm-auto">
<form:input type="text" path="nom" placeholder="Nom"/>
</div>
</div><br>
<div class="row">
<div class="col-sm-2 offset-md-4">
URL img:
</div>
<div class="col-sm-auto">
<form:input type="text" path="url" placeholder="URL de l'image"/>
</div>
</div><br>
<div class="row">
<div class="col-sm-4 offset-md-4 center">
<input type="submit" value="Submit"/>
</div>
</div>
</form:form><br>
<c:choose>
<c:when test="${not empty succeed}">
<div class="row">
<div class="col-sm-12">
<h2 class="success center">
Meme ajouté avec succ&eacute;s !
</h2>
</div>
</div>
</c:when>
</c:choose>
</div>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<c:import url="/WEB-INF/jsp/header.jsp" />
<title>Etape 3</title>
</head>
<body>
<h1 class="content-title">Etape 3 : File Management</h1>
<br><br>
<div class="container">
<div class="row justify-content-center">
Désolé Billy, on dirait que cette étape se passe uniquement en Back.<br>
Si tu veux voir le résultat de ce que tu viens de faire: Go to Etape 1.
</div>
</div>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<c:import url="/WEB-INF/jsp/header.jsp" />
<title>Etape 4</title>
</head>
<body>
<h1 class="content-title">Etape 4 : Coroutines</h1>
<br>
<br>
<div class="row">
<div class="offset-sm-1 col-sm-10">
<h2>Mon Repo Favoris :</h2>
<br>
<br>
<c:forTokens items="${dirfav}" delims="&&&" var="name">
<img src="${name}" />
</c:forTokens>
</div>
</div>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<c:import url="/WEB-INF/jsp/header.jsp" />
<title>Exercice 5</title>
</head>
<body>
<br><br><br>
<h1 class="center red">PRANKED
<br><br><br>
<img src="https://media1.tenor.com/images/04017b0c56665c471ec3dc1d84e15c23/tenor.gif?itemid=5132217"/>
</h1>
</body>
</html>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment