diff --git a/README.md b/README.md index 2572668..4ea6c3f 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ This workshop aims to spread coding best practices to young developers (interns, < 3y XP ,..). For instance, we could provide exercices about logging or error handling best practices. Through a real life inspired application, the trainees could deal with coding basics: clean code, OOP principles, TDD and such like (see below) while submitting their first Pull Request. -They could do it either alone or ( it's strongly recommended) using the pair programming technique. + They could do it either alone or ( it's strongly recommended) using the pair programming technique. + ## Workshop diff --git a/docs/media/confucius.jpeg b/docs/media/confucius.jpeg new file mode 100644 index 0000000..8fa0022 Binary files /dev/null and b/docs/media/confucius.jpeg differ diff --git a/docs/media/fire-leaving.jpg b/docs/media/fire-leaving.jpg new file mode 100644 index 0000000..4631284 Binary files /dev/null and b/docs/media/fire-leaving.jpg differ diff --git a/docs/media/money.jpg b/docs/media/money.jpg new file mode 100644 index 0000000..e5d2f33 Binary files /dev/null and b/docs/media/money.jpg differ diff --git a/docs/media/movies.jpg b/docs/media/movies.jpg new file mode 100644 index 0000000..8ef03e7 Binary files /dev/null and b/docs/media/movies.jpg differ diff --git a/docs/workshop.md b/docs/workshop.md index d55bd6d..3a98084 100644 --- a/docs/workshop.md +++ b/docs/workshop.md @@ -539,3 +539,140 @@ Each of these examples follows the conventional commits format of `( + +> I hear and I forget. I see and I remember. I do and I understand. + +This workshop is designed to apply the principles of clean code and best practices in a real-life scenario. +It relies on a fictional application, which have many code qualities issues, will make you experience the pain of bad code quality, and the benefits of good practices. +The objective is to implement the requirements and improve the quality, not to over-think every aspect. + +## Workshop setup & timetable + +The dvd-store web-app is powered by Quarkus, Java 17 & H2 Database. + +How to run the project locally ? +* Checkout the repo https://github.com/worldline/code-quality-workshop.git +* Create your local branch +* Open the **pom.xml** located in **dvd-store** sub-folder with your favorite IDE +* Run the application + +Either use the dvd-store run configuration, create a new Quarkus run configuration, or launch via mvn goal. +``` script +compile quarkus:dev +``` + +The default application port is 8082, customizable in application.properties. +The database is reset at startup, see class `DataInitTool` to see how a minimal dataset is created. + +Several REST APIs are available, documented [here](http://localhost:8082/q/swagger-ui). + +Some assumptions you can make : +* No need to care about DB constraints +* No Null Entity or fields +* If you have trouble doing proper DB requests, it is fine to load all entries of a table, then filter it in Java. The objective + is not to master https://quarkus.io/guides/hibernate-orm-panache . + +You can expect to finish the requirements in 2-4 hours, depending on your experience and the refactoring effort you put in. + + +However, it is recommended to stay with Quarkus, Java 17 and H2 :-) + +## Setting the stage : DVD store + +This project is an app for a video/DVD renting company, and was developed by (too) many developers. Some of them were part of the owner's family ... and not even developers. +Hence quality and long-term vision are not the motto for this app. But this stops now ! + +The company has recently been bought, and the new owner got genius ideas to make the business great again. +As hiring a PO was too expensive, and his job can't be too complicated, the owner of the shop will be your PO for the day. + +Fortunately, your team has been selected to make his dreams a reality, implement features and increase the overall quality. +You're allowed to modify anything you want: +* Add new class, new package +* Change the data model +* Correct any problems you see +* Freedom to organize yourself : could be a good opportunity to do https://en.wikipedia.org/wiki/Pair_programming . + + +### Ready , set.... go ! + +## Requirements + +Leaving a burning project + + +#### It is strongly recommended to implement them in order, as the complexity increases. + +#### Don't worry if you don't have enough time to finish : Focus on the journey, not the destination + +* Requirement 0 is not very precise and there is several options to implement it, but introducing Movie object will be a huge benefit for the next requirement. +* Requirement 1 is tougher as you will discover lots of problems, hence lots of refactoring on top of the requirement itself + +To help you, some hints are available in the requirements, but don't hesitate to ask for more. + +### Requirement 0 : Refactor and introduce Movie concept + +
+Example image +

The future is in content... so the business doesn't know the difference between a DVD and a VideoTape... everything you can watch will now be a Movie ! +All next requirements will be for Movies from now on

+
+ +
Hint +Movie could be a new interface,or a new abstract class, you may also need a new enum for the type of movie (DVD, VideoTape). +This is a good opportunity to get rid of all the petty details slowing you down: + +* Confusing names +* Lack of unit-tests +* Language barrier +
+ + +### Requirement 1 : new pricing logic + + +
+Example image +

We're running out of business because we're not making enough money! + We're gonna change the way we price : + The quality of a DVD will drop down with each renting..... so the value should decrease as well.

+
+ +##### Here are the pricing rules : + +* Price for a DVD = 10 if it was released more than 10 years ago +* Actual logic other case , max price is 23 for any movie +* Oh, and I'm a huge fan of Tom Cruise, every movie is a masterpiece ! Then price when Tom is within a movie should be 15 + +Add an API that gives the price for a movie ( ISBN ), provide the two prices DVD / VideoTape if possible. + +#### Response example + +```json +{ + DVDPrice : xxx, + VideoPrice : yyy +} +``` +OR +```json +[ +{ price : xxx, type: DVD }, +{ price : yyy, type : Video } +] +``` +
Hint +Add unit-test for the existing and the new pricing rules. +I'm not sure the owner realized some of his instructions are contradictory... +As he's in holiday in the Bahamas, you have to decide what to do with the Tom Cruise rule. +
+ +## Conclusion + +An implementation of the requirements is available in the branch `TODO`, and there are many way to compare what you did with the solution. +* Open a PR with your branch, and compare the changes. +* Use a diff tool to compare your code with the solution + +We hope that you enjoyed this workshop, and that you learned a lot about clean code and best practices. diff --git a/dvd-store/.dockerignore b/dvd-store/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/dvd-store/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/dvd-store/.gitignore b/dvd-store/.gitignore new file mode 100644 index 0000000..bdf57ce --- /dev/null +++ b/dvd-store/.gitignore @@ -0,0 +1,39 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env diff --git a/dvd-store/.mvn/wrapper/MavenWrapperDownloader.java b/dvd-store/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..17add53 --- /dev/null +++ b/dvd-store/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader +{ + private static final String WRAPPER_VERSION = "3.1.0"; + + /** + * 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/org/apache/maven/wrapper/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/dvd-store/.mvn/wrapper/maven-wrapper.properties b/dvd-store/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..41d8213 --- /dev/null +++ b/dvd-store/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar diff --git a/dvd-store/.runConfiguration/dvd-store.run.xml b/dvd-store/.runConfiguration/dvd-store.run.xml new file mode 100644 index 0000000..844c8e0 --- /dev/null +++ b/dvd-store/.runConfiguration/dvd-store.run.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dvd-store/mvnw b/dvd-store/mvnw new file mode 100644 index 0000000..8a8fb22 --- /dev/null +++ b/dvd-store/mvnw @@ -0,0 +1,316 @@ +#!/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 /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + 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="`\\unset -f command; \\command -v 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/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.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" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$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 \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/dvd-store/mvnw.cmd b/dvd-store/mvnw.cmd new file mode 100644 index 0000000..1d8ab01 --- /dev/null +++ b/dvd-store/mvnw.cmd @@ -0,0 +1,188 @@ +@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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + +FOR /F "usebackq 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%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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% + +cmd /C exit /B %ERROR_CODE% diff --git a/dvd-store/pom.xml b/dvd-store/pom.xml new file mode 100644 index 0000000..46bbd69 --- /dev/null +++ b/dvd-store/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + com.quality.workshop + dvd-store + 1.0.0-SNAPSHOT + + 3.8.1 + false + 17 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.9.2.Final + 3.0.0-M5 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-resteasy-reactive-jackson + + + io.quarkus + quarkus-jackson + 2.12.0.Final + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + io.quarkus + quarkus-hibernate-orm-panache + + + io.quarkus + quarkus-hibernate-orm + + + io.quarkus + quarkus-jdbc-h2 + + + + + io.quarkus + quarkus-smallrye-openapi + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + + + + + native + + + native + + + + + + + + + native + + + + diff --git a/dvd-store/src/main/docker/Dockerfile.jvm b/dvd-store/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000..df2723e --- /dev/null +++ b/dvd-store/src/main/docker/Dockerfile.jvm @@ -0,0 +1,93 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/dvd-store-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/dvd-store-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/dvd-store-jvm +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-17:1.11 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=185 target/quarkus-app/*.jar /deployments/ +COPY --chown=185 target/quarkus-app/app/ /deployments/app/ +COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + diff --git a/dvd-store/src/main/docker/Dockerfile.legacy-jar b/dvd-store/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000..be3af21 --- /dev/null +++ b/dvd-store/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,89 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/dvd-store-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/dvd-store-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/dvd-store-legacy-jar +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-17:1.11 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + + +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/quarkus-run.jar + +EXPOSE 8080 +USER 185 +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" diff --git a/dvd-store/src/main/docker/Dockerfile.native b/dvd-store/src/main/docker/Dockerfile.native new file mode 100644 index 0000000..e130672 --- /dev/null +++ b/dvd-store/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/dvd-store . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/dvd-store +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.5 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/dvd-store/src/main/docker/Dockerfile.native-micro b/dvd-store/src/main/docker/Dockerfile.native-micro new file mode 100644 index 0000000..a24954e --- /dev/null +++ b/dvd-store/src/main/docker/Dockerfile.native-micro @@ -0,0 +1,30 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# It uses a micro base image, tuned for Quarkus native executables. +# It reduces the size of the resulting container image. +# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image. +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/dvd-store . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/dvd-store +# +### +FROM quay.io/quarkus/quarkus-micro-image:1.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/dvd-store/src/main/java/com/quality/workshop/GreetingResource.java b/dvd-store/src/main/java/com/quality/workshop/GreetingResource.java new file mode 100644 index 0000000..71b783a --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/GreetingResource.java @@ -0,0 +1,16 @@ +package com.quality.workshop; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/hello") +public class GreetingResource { + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String hello() { + return "Hello from RESTEasy Reactive"; + } +} \ No newline at end of file diff --git a/dvd-store/src/main/java/com/quality/workshop/db/DBRepo.java b/dvd-store/src/main/java/com/quality/workshop/db/DBRepo.java new file mode 100644 index 0000000..502a85c --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/db/DBRepo.java @@ -0,0 +1,17 @@ +package com.quality.workshop.db; + +import javax.enterprise.context.ApplicationScoped; + + +import com.quality.workshop.entity.DVDRentEvents; + +import io.quarkus.hibernate.orm.panache.PanacheRepository; + +@ApplicationScoped +public class DBRepo implements PanacheRepository { + + + public void save(DVDRentEvents event){ + persist(event); + } +} diff --git a/dvd-store/src/main/java/com/quality/workshop/db/DataInitTool.java b/dvd-store/src/main/java/com/quality/workshop/db/DataInitTool.java new file mode 100644 index 0000000..5aed4a0 --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/db/DataInitTool.java @@ -0,0 +1,126 @@ +package com.quality.workshop.db; + +import java.time.LocalDate; +import java.util.Arrays; +import java.util.stream.Collectors; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +import javax.transaction.Transactional; + +import com.quality.workshop.entity.DVD; +import com.quality.workshop.entity.DVDRentEvents; +import com.quality.workshop.entity.Schauspieler; +import com.quality.workshop.entity.VideoTape; + +import io.quarkus.runtime.StartupEvent; + +@ApplicationScoped +public class DataInitTool { + + @Transactional + public void initData(@Observes StartupEvent event){ + System.out.println("Init database"); + + //Usefull objets + LocalDate date2006 = LocalDate.parse("2007-02-03"); + LocalDate date2007 = LocalDate.parse("2007-02-03"); + LocalDate date2017 = LocalDate.parse("2017-02-03"); + LocalDate date2018 = LocalDate.parse("2018-05-05"); + LocalDate date2019Xmas = LocalDate.parse("2019-12-24"); + LocalDate date2015 = LocalDate.parse("2015-04-04"); + + + // Actors + Schauspieler tomC = createActor("Cruise","Tom"); + Schauspieler leoC = createActor("DiCaprio","Leonardo"); + Schauspieler angie = createActor("Jolie","Angelina"); + Schauspieler brad = createActor("Pitt","Brad"); + Schauspieler scaJo = createActor("Johansson","Scarlett"); + Schauspieler galG = createActor("Gadot","Gal"); + + // DVD + DVD ninja1 = createDVD("1233","Ninja-revenge-II","Ninja's revenge ! He will not let it go!",tomC,date2007,angie,brad); + DVD ninja2 = createDVD("1234","Ninja-revenge-III","The return of the ninja, let's kick names and take ass!",tomC,date2015,angie,brad); + DVD ninja3 = createDVD("1235","Ninja-revenge-IV","Origin of the saga",tomC,date2017,angie,brad); + DVD ninja4 = createDVD("1236","Ninja-revenge-V","Will Ninja's kids get their father's revenge ?",tomC,date2018,angie,brad); + DVD ninja4Bis = createDVD("1236","Ninja-revenge-V","Will Ninja's kids get their father's revenge ?",angie,date2018,tomC,brad); + + DVD ninjaXmas = createDVD("127","Ninja-revenge-Xmas's-special","No gifts, only kicks",leoC,date2019Xmas,angie,brad); + + //Video + VideoTape ninja2V = createVideo("1234","Ninja-revenge-III","The return of the ninja, let's kick names and take ass!",date2015,10,125,brad,angie,tomC); + + VideoTape ninja0 = createVideo("1232","Ninja-revenge-I","War between ninja brothers",date2006,10,125,brad,angie); + VideoTape ladyWar = createVideo("1232","Crossover-Starwars-VS-Marvel","Who will save the earth",date2006,120,125,galG,scaJo); + VideoTape ladyWar2 = createVideo("1232","Crossover-Starwars-VS-Marvel-2","Who will save the universe",date2018,20,90,brad,angie); + VideoTape ninja4V = createVideo("","Ninja-revenge-V","Will Ninja's kids get their father's revenge ?",date2018,10,125,brad,angie,tomC); + + + LocalDate rent12122012 = LocalDate.parse("2012-12-12"); + LocalDate rent03032020 = LocalDate.parse("2020-03-03"); + LocalDate rent04042018 = LocalDate.parse("2018-04-04"); + + //DVDEvents + DVDRentEvents event_ninja1_1= createEvent(ninja1,rent12122012,5); + DVDRentEvents event_ninja1_2= createEvent(ninja1,rent03032020,3); + DVDRentEvents event_ninja1_3= createEvent(ninja1,rent04042018,1); + + DVDRentEvents event_ninjaXMAS_1= createEvent(ninjaXmas,rent03032020,10); + + + } + + Schauspieler createActor(String lastName, String firstName){ + Schauspieler actor = new Schauspieler(); + actor.lastName=lastName; + actor.name=firstName; + actor.persist(); + + return actor; + } + + + DVD createDVD(String ISBN, String title, String description, Schauspieler actor, LocalDate releaseDate, Schauspieler... actors) { + DVD dvd = new DVD(); + dvd.setISBN(ISBN); + dvd.setTitle(title); + dvd.setDescription(description); + dvd.setMainActor(actor); + dvd.setReleaseDate(releaseDate); + dvd.setOtherActors(Arrays.stream(actors).collect(Collectors.toList()) ); + + dvd.persist(); + + return dvd; + } + + DVDRentEvents createEvent(DVD dvd, LocalDate rentingDate ,int durationInDays){ + DVDRentEvents event = new DVDRentEvents(); + + event.dvd=dvd; + event.rentingDate=rentingDate; + event.durationInDays= durationInDays; + + event.persist(); + return event; + } + + VideoTape createVideo(String ISBN,String title, String description, LocalDate releaseDate, double locations, long duration, Schauspieler... actors) { + VideoTape video = new VideoTape(); + video.ISBN = ISBN; + video.title=title; + video.desciption = description; + video.releaseDate = releaseDate; + video.locations = locations; + video.duration= duration; + video.actors= Arrays.stream(actors).collect(Collectors.toList()); + + video.persist(); + + return video; + } + + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/entity/DVD.java b/dvd-store/src/main/java/com/quality/workshop/entity/DVD.java new file mode 100644 index 0000000..fffcebc --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/entity/DVD.java @@ -0,0 +1,92 @@ +package com.quality.workshop.entity; + +import java.time.LocalDate; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; + +@Entity +@Table(name = "DVD") +public class DVD extends PanacheEntity { + + String ISBN; + String title; + + @JsonIgnore + private String fullTitle; + String description; + + @ManyToOne + Schauspieler mainActor; + + @ManyToMany + List otherActors; + + LocalDate releaseDate; + + public static DVD findByTitle(String title){ + return find("title", title).firstResult(); + } + + + public String getISBN() { + return ISBN; + } + + public void setISBN(String ISBN) { + this.ISBN = ISBN; + } + + public String getTitle() { + return title; + } + + public String getFullTitle() { + return fullTitle; + } + + public void setTitle(String title) { + this.title = title.substring(0,Math.min(20,title.length())); + this.fullTitle = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Schauspieler getMainActor() { + return mainActor; + } + + public void setMainActor(Schauspieler mainActor) { + this.mainActor = mainActor; + } + + public List getOtherActors() { + return otherActors; + } + + public void setOtherActors(List otherActors) { + this.otherActors = otherActors; + } + + public LocalDate getReleaseDate() { + return releaseDate; + } + + public void setReleaseDate(LocalDate releaseDate) { + this.releaseDate = releaseDate; + } + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/entity/DVDRentEvents.java b/dvd-store/src/main/java/com/quality/workshop/entity/DVDRentEvents.java new file mode 100644 index 0000000..a5f603d --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/entity/DVDRentEvents.java @@ -0,0 +1,32 @@ +package com.quality.workshop.entity; + +import java.sql.Date; +import java.time.LocalDate; +import java.util.stream.Stream; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; + +@Entity +@Table(name = "EVENTS") +public class DVDRentEvents extends PanacheEntity { + + + public LocalDate rentingDate; + + @ManyToOne + public DVD dvd; + + public int durationInDays; + + public static Stream findByDvd(DVD dvd){ + return find("dvd", dvd).stream(); + } + public static Stream findByDate(LocalDate localDate){ + Date date = Date.valueOf(localDate); + return find("rentingDate", localDate).stream(); + } +} diff --git a/dvd-store/src/main/java/com/quality/workshop/entity/Schauspieler.java b/dvd-store/src/main/java/com/quality/workshop/entity/Schauspieler.java new file mode 100644 index 0000000..e8fecf3 --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/entity/Schauspieler.java @@ -0,0 +1,21 @@ +package com.quality.workshop.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; + +@Entity +@Table(name = "ACTOR") +public class Schauspieler extends PanacheEntity { + public String name; + public String lastName; + + public static Schauspieler findByName(String name){ + return find("name", name).firstResult(); + } + + + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/entity/VideoTape.java b/dvd-store/src/main/java/com/quality/workshop/entity/VideoTape.java new file mode 100644 index 0000000..d1c5ae4 --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/entity/VideoTape.java @@ -0,0 +1,29 @@ +package com.quality.workshop.entity; + +import java.time.LocalDate; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; + +@Entity +@Table(name = "VIDEO_TAPE") +public class VideoTape extends PanacheEntity { + + public String ISBN; + public String desciption; + public String title; + + @ManyToMany + public List actors; // name as key, firstName + name as value + + public LocalDate releaseDate; + public Double locations; + public Long duration; // Duration in minuts ( between 60 and 180 ) + + + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/money/PriceCalculator.java b/dvd-store/src/main/java/com/quality/workshop/money/PriceCalculator.java new file mode 100644 index 0000000..ca6f471 --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/money/PriceCalculator.java @@ -0,0 +1,18 @@ +package com.quality.workshop.money; + +import com.quality.workshop.entity.DVD; +import com.quality.workshop.entity.VideoTape; + +public class PriceCalculator { + + public static int computeDVDPrice(DVD dvd){ + return (int) 13.4f + 10/ ( Math.abs(dvd.getReleaseDate().getYear()-2018)); + } + + + public static int computeDVDPrice(VideoTape vt){ + return (int) ((int) 5 + 0.0001d * vt.duration); + } + + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/money/PriceCalculatorTest.java b/dvd-store/src/main/java/com/quality/workshop/money/PriceCalculatorTest.java new file mode 100644 index 0000000..0c528fd --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/money/PriceCalculatorTest.java @@ -0,0 +1,28 @@ +package com.quality.workshop.money; + +import static com.quality.workshop.TestEntityHelper.getVideo; +import static com.quality.workshop.money.PriceCalculator.computeDVDPrice; +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import com.quality.workshop.entity.VideoTape; + + +public class PriceCalculatorTest { + + @ParameterizedTest + @MethodSource("videos") + public void testVideoTapePrice(VideoTape videoTape,Integer expectedPrice){ + int price = computeDVDPrice(videoTape); + assertEquals(expectedPrice,price); + } + + public static Stream videos(){ + return Stream.of( + Arguments.of(getVideo("1234"),5), + Arguments.of(getVideo("1232"),5) + ); + } +} diff --git a/dvd-store/src/main/java/com/quality/workshop/rest/ActorResource.java b/dvd-store/src/main/java/com/quality/workshop/rest/ActorResource.java new file mode 100644 index 0000000..98a38ae --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/rest/ActorResource.java @@ -0,0 +1,37 @@ +package com.quality.workshop.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +import com.quality.workshop.entity.Schauspieler; + +@Path("/actor") +public class ActorResource { + + @GET + public List listActors() { + return Schauspieler.listAll(); + } + + @GET + @Path("/{id}") + public Schauspieler get( @PathParam("id") String id) { + Schauspieler result = null; + + try { + Long idL = Long.parseLong(id); + result = Schauspieler.findById(idL); + } catch (Exception e){ } + + if ( result == null){ + result = Schauspieler.findByName(id); + } + + return result; + } + +} + diff --git a/dvd-store/src/main/java/com/quality/workshop/rest/ActorResourceIT.java b/dvd-store/src/main/java/com/quality/workshop/rest/ActorResourceIT.java new file mode 100644 index 0000000..107267a --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/rest/ActorResourceIT.java @@ -0,0 +1,52 @@ +package com.quality.workshop.rest; + +import static com.quality.workshop.rest.RESTUtils.retrieveResourceFromResponse; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.IOException; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.HttpClientBuilder; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import com.quality.workshop.entity.Schauspieler; + +/*** + * Quick example of an integration-test. + * Run the project locally, then run the test + */ +public class ActorResourceIT { + + @Test + public void testGetActorById() throws IOException { + + HttpUriRequest request = new HttpGet( "http://localhost:8082/actor/1" ); + + // When + HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request ); + + // Then + Schauspieler actor = retrieveResourceFromResponse( + httpResponse, Schauspieler.class); + assertThat( actor.lastName, Matchers.is("Cruise" ) ); + } + + @Test + public void testGetActorByName() throws IOException { + + HttpUriRequest request = new HttpGet( "http://localhost:8082/actor/Tom" ); + + // When + HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request ); + + // Then + Schauspieler actor = retrieveResourceFromResponse( + httpResponse, Schauspieler.class); + assertThat( actor.lastName, Matchers.is("Cruise" ) ); + } + + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/rest/DVDEventsResource.java b/dvd-store/src/main/java/com/quality/workshop/rest/DVDEventsResource.java new file mode 100644 index 0000000..a1883bb --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/rest/DVDEventsResource.java @@ -0,0 +1,56 @@ +package com.quality.workshop.rest; + +import java.sql.Date; +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; + +import com.quality.workshop.entity.DVD; +import com.quality.workshop.entity.DVDRentEvents; + +@Path("/dvdevents") +@Produces +public class DVDEventsResource { + + + @GET + public List listDVDs() { + return DVDRentEvents.listAll(); + } + + @GET + @Path("/{idOrName}") + public List listDVDByIdOrName(@PathParam("idOrName") String idOrName) { + + DVD dvvd = null; + + try { + Long idL = Long.parseLong(idOrName); + dvvd = DVD.findById(idL); + } catch (Exception e){ } + + if ( dvvd == null){ + dvvd = DVD.findByTitle(idOrName); + } + + if ( dvvd!=null){ + return DVDRentEvents.findByDvd(dvvd).collect(Collectors.toList()); + } + + return null; + } + + @GET + @Path("/byDate/{dateS}") + public List listDVDByDate(@PathParam("dateS") String dateS) { + List result = DVDRentEvents.findByDate( LocalDate.parse(dateS)).collect(Collectors.toList()); + return result; + } +} + + diff --git a/dvd-store/src/main/java/com/quality/workshop/rest/DVDResource.java b/dvd-store/src/main/java/com/quality/workshop/rest/DVDResource.java new file mode 100644 index 0000000..777c66f --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/rest/DVDResource.java @@ -0,0 +1,38 @@ +package com.quality.workshop.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +import com.quality.workshop.entity.DVD; +import com.quality.workshop.entity.Schauspieler; + +@Path("/dvd") +public class DVDResource { + + + @GET + public List listDVDs() { + return DVD.listAll(); + } + + @GET + @Path("/{id}") + public DVD get( @PathParam("id") String idOrName) { + DVD result = null; + + try { + Long idL = Long.parseLong(idOrName); + result = DVD.findById(idL); + } catch (Exception e){ } + + if ( result == null){ + result = DVD.findByTitle(idOrName); + } + + return result; + } + +} diff --git a/dvd-store/src/main/java/com/quality/workshop/rest/RESTUtils.java b/dvd-store/src/main/java/com/quality/workshop/rest/RESTUtils.java new file mode 100644 index 0000000..fffe409 --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/rest/RESTUtils.java @@ -0,0 +1,21 @@ +package com.quality.workshop.rest; + +import java.io.IOException; + +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RESTUtils { + + public static T retrieveResourceFromResponse(HttpResponse response, Class clazz) + throws IOException { + + String jsonFromResponse = EntityUtils.toString(response.getEntity()); + ObjectMapper mapper = new ObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + return mapper.readValue(jsonFromResponse, clazz); + } +} diff --git a/dvd-store/src/main/java/com/quality/workshop/rest/VideoTapeResource.java b/dvd-store/src/main/java/com/quality/workshop/rest/VideoTapeResource.java new file mode 100644 index 0000000..0b0b454 --- /dev/null +++ b/dvd-store/src/main/java/com/quality/workshop/rest/VideoTapeResource.java @@ -0,0 +1,35 @@ +package com.quality.workshop.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +import com.quality.workshop.entity.Schauspieler; +import com.quality.workshop.entity.VideoTape; + +@Path("/video") +public class VideoTapeResource { + + @GET + public List listActors() { + return VideoTape.listAll(); + } + + @GET + @Path("/{id}") + public VideoTape get( @PathParam("id") String id) { + VideoTape result = null; + + try { + Long idL = Long.parseLong(id); + result = VideoTape.findById(idL); + } catch (Exception e){ } + + + return result; + } + +} + diff --git a/dvd-store/src/main/resources/application.properties b/dvd-store/src/main/resources/application.properties new file mode 100644 index 0000000..5640c4b --- /dev/null +++ b/dvd-store/src/main/resources/application.properties @@ -0,0 +1,8 @@ +quarkus.http.port=8082 + +quarkus.hibernate-orm.database.generation=drop-and-create +quarkus.hibernate-orm.log.format-sql=true +quarkus.hibernate-orm.log.sql=true +quarkus.hibernate-orm.sql-load-script=postStart.sql + +quarkus.jackson.fail-on-unknown-properties=true \ No newline at end of file diff --git a/dvd-store/src/main/resources/postStart.sql b/dvd-store/src/main/resources/postStart.sql new file mode 100644 index 0000000..8a25a9a --- /dev/null +++ b/dvd-store/src/main/resources/postStart.sql @@ -0,0 +1,2 @@ +-- This file will be executed ONCE after the server start-up, then after the DB is populated +-- You could use this to apply DB changes ;-) \ No newline at end of file diff --git a/dvd-store/src/test/java/com/quality/workshop/TestEntityHelper.java b/dvd-store/src/test/java/com/quality/workshop/TestEntityHelper.java new file mode 100644 index 0000000..e78cf16 --- /dev/null +++ b/dvd-store/src/test/java/com/quality/workshop/TestEntityHelper.java @@ -0,0 +1,82 @@ +package com.quality.workshop; + +import java.time.LocalDate; +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import com.quality.workshop.entity.Schauspieler; +import com.quality.workshop.entity.VideoTape; + +/** + * Helper class to get Entity-like objects for unit-tests + * + * This may be improve, but it is easy to adapt to other entities + */ +public class TestEntityHelper { + + //Usefull objets + static LocalDate date2006 = LocalDate.parse("2007-02-03"); + static LocalDate date2007 = LocalDate.parse("2007-02-03"); + static LocalDate date2017 = LocalDate.parse("2017-02-03"); + static LocalDate date2018 = LocalDate.parse("2018-05-05"); + static LocalDate date2019Xmas = LocalDate.parse("2019-12-24"); + static LocalDate date2015 = LocalDate.parse("2015-04-04"); + + // Famous Actors + static Schauspieler TOM_C = createActor("Cruise","Tom"); + static Schauspieler LEO_C = createActor("DiCaprio","Leonardo"); + static Schauspieler ANGIE = createActor("Jolie","Angelina"); + static Schauspieler BRAF = createActor("Pitt","Brad"); + static Schauspieler SCAJO = createActor("Johansson","Scarlett"); + static Schauspieler GALG = createActor("Gadot","Gal"); + + //Video + static VideoTape NINJA2V = createVideo("1234","Ninja-revenge-III","The return of the ninja, let's kick names and take ass!",date2015,10,125,BRAF,ANGIE,TOM_C); + static VideoTape NINJA0 = createVideo("1232","Ninja-revenge-I","War between ninja brothers",date2006,10,125,BRAF,ANGIE); + static VideoTape LADY_WAR = createVideo("1232","Crossover-Starwars-VS-Marvel","Who will save the earth",date2006,120,125,GALG,SCAJO); + static VideoTape LADY_WAR_2 = createVideo("1232","Crossover-Starwars-VS-Marvel-2","Who will save the universe",date2018,20,90,BRAF,ANGIE); + static VideoTape NINJA4V = createVideo("","Ninja-revenge-V","Will Ninja's kids get their father's revenge ?",date2018,10,125,BRAF,ANGIE,TOM_C); + + + + + private static Schauspieler createActor(String lastName, String firstName){ + Schauspieler actor = new Schauspieler(); + actor.lastName=lastName; + actor.name=firstName; + + return actor; + } + + public static Stream getTestActors() { + return Stream.of(TOM_C, LEO_C, ANGIE, BRAF, SCAJO, GALG); + } + + public static Schauspieler getActor(String criteria){ + return getTestActors().filter(actor -> actor.name.equals(criteria) || actor.lastName.equals(criteria)) + .findFirst().orElse(null); + } + + public static Stream getTestVideos() { + return Stream.of(NINJA2V, NINJA0, LADY_WAR, LADY_WAR_2, NINJA4V); + } + + public static VideoTape getVideo(String criteria){ + return getTestVideos().filter(video -> video.title.equals(criteria) || video.ISBN.equals(criteria)) + .findFirst().orElse(null); + } + + static VideoTape createVideo(String ISBN,String title, String description, LocalDate releaseDate, double locations, long duration, Schauspieler... actors) { + VideoTape video = new VideoTape(); + video.ISBN = ISBN; + video.title=title; + video.desciption = description; + video.releaseDate = releaseDate; + video.locations = locations; + video.duration= duration; + video.actors= Arrays.stream(actors).collect(Collectors.toList()); + + return video; + } + +}