diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6c234cdb79640f2147fad6b43c5394692e20ba67 --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Created by .ignore support plugin (hsz.mobi) +### Gradle template +.gradle +/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# User-specific stuff: +**/.idea/ + +# CMake +cmake-build-debug/ + +## File-based project format: +*.iws +*.iml + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..1a567fa0a6d22ae1b897c5a97def33c3e2d325e5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,44 @@ +buildscript { + repositories { + mavenCentral() + jcenter() + } + + dependencies { + classpath "com.github.ben-manes:gradle-versions-plugin:$gradle_versions_plugin_version" + classpath "org.junit.platform:junit-platform-gradle-plugin:$gradle_junit_plugin_version" + } +} + +apply plugin: 'java' +apply plugin: 'application' +apply plugin: 'com.github.ben-manes.versions' +apply plugin: 'org.junit.platform.gradle.plugin' + +repositories { + mavenLocal() + jcenter() + mavenCentral() +} + +dependencies { + /* Commons Lang3 */ + compile "org.apache.commons:commons-lang3:$commons_lang_version" + + /* Retrofit */ + compile "com.squareup.retrofit2:retrofit:$retrofit2_version" + compile "com.squareup.retrofit2:converter-gson:$retrofit2_version" + compile "com.squareup.retrofit2:adapter-java8:$retrofit2_version" + + /* JUnit 5 */ + testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}") + testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}") + testRuntime("org.junit.platform:junit-platform-launcher:${junitPlatformVersion}") + testRuntime("org.apache.logging.log4j:log4j-core:${log4jVersion}") + testRuntime("org.apache.logging.log4j:log4j-jul:${log4jVersion}") +} + +mainClassName = 'de.fhro.inf.prg3.a12.App' + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..03f07ffd4e95a4a130f1e5963ca4b81260df3da9 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,8 @@ +gradle_versions_plugin_version=0.17.0 +gradle_junit_plugin_version=1.1.0-M1 + +commons_lang_version=3.7 +retrofit2_version=2.3.0 +junitPlatformVersion = 1.1.0-M1 +junitJupiterVersion = 5.1.0-M1 +log4jVersion = 2.10.0 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..01b8bf6b1f99cad9213fc495b33ad5bbab8efd20 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..933b6473ce1ea83ca681969501e2c05453c313a1 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000000000000000000000000000000000..cccdd3d517fc5249beaefa600691cf150f2fa3e6 --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +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 +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..f9553162f122c71b34635112e717c3e733b5b212 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..b2b6e8f8abbef65bdb75b9742536e77191c8a48c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,18 @@ +/* + * This settings file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/4.4/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = '12-functional-cli' diff --git a/src/main/java/de/fhro/inf/prg3/a12/App.java b/src/main/java/de/fhro/inf/prg3/a12/App.java new file mode 100644 index 0000000000000000000000000000000000000000..6d2d31d0e3960fb1b47e3ac3289eee4851f0c8e9 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/App.java @@ -0,0 +1,83 @@ +package de.fhro.inf.prg3.a12; + +import de.fhro.inf.prg3.a12.icndb.JokeGenerator; +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; + +import java.util.Scanner; +import java.util.stream.Stream; + +public abstract class App { + + private static final Scanner inputScanner = new Scanner(System.in); + private static final JokeGenerator jokeGenerator = new JokeGenerator(); + + public static void main(String[] args) { + boolean shouldQuit = false; + int jokeCount; + int skipCount; + do { + jokeCount = readInt("How many jokes do you want?"); + skipCount = readInt("How many jokes do you want to skip"); + + Stream<ResponseWrapper<JokeDto>> jokesSource; + switch (readJokeSource()) { + case Random: + jokesSource = jokeGenerator.randomJokesStream(); + break; + default: + jokesSource = jokeGenerator.jokesStream(); + } + + /* TODO consume the `jokesSource` + * filter it for non null objects + * use `skip` and `limit` to retrieve the required elements + * use `map` to unwrap the ResponseWrapper value + * and print the jokes to the STDOUT */ + + System.out.println("If you want to quit press [Q] otherwise press [C] to continue."); + String input = inputScanner.next(); + if (input.equals("q") || input.equals("Q")) { + shouldQuit = true; + } + } while (!shouldQuit); + System.exit(0); + } + + private static int readInt(String message) { + System.out.println(message); + do { + try { + int input = inputScanner.nextInt(); + if (input >= 0) return input; + } catch (Exception e) { + System.out.println("Error while reading integer."); + } + } while (true); + } + + private static JokeSource readJokeSource() { + System.out.println("Which joke source do you want to use?"); + System.out.println("1) Random jokes"); + System.out.println("2) Linear by id"); + + do { + try { + int selection = inputScanner.nextInt(); + switch (selection) { + case 1: + return JokeSource.Random; + default: + return JokeSource.Linear; + } + } catch (Exception e) { + System.out.println("No valid selection"); + } + } while (true); + } + + enum JokeSource { + Random, + Linear + } +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/icndb/ICNDBApi.java b/src/main/java/de/fhro/inf/prg3/a12/icndb/ICNDBApi.java new file mode 100644 index 0000000000000000000000000000000000000000..6693eede88a3e7763407c4ce3927787eb65d78b1 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/icndb/ICNDBApi.java @@ -0,0 +1,29 @@ +package de.fhro.inf.prg3.a12.icndb; + +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import retrofit2.http.GET; +import retrofit2.http.Path; +import retrofit2.http.Query; + +import java.util.concurrent.CompletableFuture; + +/** + * @author Peter Kurfer + * Created on 12/28/17. + */ +public interface ICNDBApi { + + @GET("/jokes/count") + CompletableFuture<ResponseWrapper<Integer>> getJokeCount(); + + @GET("/jokes/random") + CompletableFuture<ResponseWrapper<JokeDto>> getRandomJoke(); + + @GET("/jokes/random") + CompletableFuture<ResponseWrapper<JokeDto>> getRandomJoke(@Query("firstName") String firstName, @Query("lastName") String lastName); + + @GET("/jokes/{id}") + CompletableFuture<ResponseWrapper<JokeDto>> getJoke(@Path("id") int number); + +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/icndb/ICNDBService.java b/src/main/java/de/fhro/inf/prg3/a12/icndb/ICNDBService.java new file mode 100644 index 0000000000000000000000000000000000000000..d443be6bc1585792515bae8f21f13b9bf2799029 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/icndb/ICNDBService.java @@ -0,0 +1,55 @@ +package de.fhro.inf.prg3.a12.icndb; + +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import retrofit2.Retrofit; +import retrofit2.adapter.java8.Java8CallAdapterFactory; +import retrofit2.converter.gson.GsonConverterFactory; + +import java.util.concurrent.CompletableFuture; + +/** + * @author Peter Kurfer + * Created on 12/28/17. + */ +public final class ICNDBService implements ICNDBApi { + + private static final ICNDBService instance = new ICNDBService(); + + private final ICNDBApi icndbApi; + + public static ICNDBService getInstance() { + return instance; + } + + private ICNDBService() { + /* Initialize Retrofit */ + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("http://api.icndb.com") + .addConverterFactory(GsonConverterFactory.create()) + .addCallAdapterFactory(Java8CallAdapterFactory.create()) + .build(); + + icndbApi = retrofit.create(ICNDBApi.class); + } + + @Override + public CompletableFuture<ResponseWrapper<Integer>> getJokeCount() { + return icndbApi.getJokeCount(); + } + + @Override + public CompletableFuture<ResponseWrapper<JokeDto>> getRandomJoke() { + return icndbApi.getRandomJoke(); + } + + @Override + public CompletableFuture<ResponseWrapper<JokeDto>> getRandomJoke(String firstName, String lastName) { + return icndbApi.getRandomJoke(firstName, lastName); + } + + @Override + public CompletableFuture<ResponseWrapper<JokeDto>> getJoke(int number) { + return icndbApi.getJoke(number); + } +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/icndb/JokeGenerator.java b/src/main/java/de/fhro/inf/prg3/a12/icndb/JokeGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..e22479a12d921f1720b34f159e676390437c6889 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/icndb/JokeGenerator.java @@ -0,0 +1,24 @@ +package de.fhro.inf.prg3.a12.icndb; + +import java.util.stream.Stream; + +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import org.apache.commons.lang3.NotImplementedException; + +/** + * @author Peter Kurfer + */ + +public final class JokeGenerator { + + public Stream<ResponseWrapper<JokeDto>> randomJokesStream() { + /* TODO create new Stream of random jokes */ + throw new NotImplementedException("Method `randomJokeStream()` is not implemented"); + } + + public Stream<ResponseWrapper<JokeDto>> jokesStream() { + /* TODO create a new Stream of all jokes */ + throw new NotImplementedException("Method `jokesStream()` is not implemented"); + } +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/icndb/suppliers/AllJokesSupplier.java b/src/main/java/de/fhro/inf/prg3/a12/icndb/suppliers/AllJokesSupplier.java new file mode 100644 index 0000000000000000000000000000000000000000..ea247cc17f87ac7d88cf03182dbfe7d5d3978bb5 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/icndb/suppliers/AllJokesSupplier.java @@ -0,0 +1,35 @@ +package de.fhro.inf.prg3.a12.icndb.suppliers; + +import java.util.function.Supplier; + +import de.fhro.inf.prg3.a12.icndb.ICNDBApi; +import de.fhro.inf.prg3.a12.icndb.ICNDBService; +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import org.apache.commons.lang3.NotImplementedException; + +/** + * @author Peter Kurfer + */ + +public final class AllJokesSupplier implements Supplier<ResponseWrapper<JokeDto>> { + + private final ICNDBApi icndbApi; + + public AllJokesSupplier() { + icndbApi = ICNDBService.getInstance(); + /* TODO fetch the total count of jokes the API is aware of + * to determine when all jokes are iterated and the counters have to be reset */ + } + + @Override + public ResponseWrapper<JokeDto> get() { + /* TODO retrieve the next joke + * note that there might be IDs that are not present in the database + * you have to catch an exception and continue if no joke was retrieved to an ID + * if you retrieved all jokes (count how many jokes you successfully fetched from the API) + * reset the counters and continue at the beginning */ + throw new NotImplementedException("Method `get()` is not implemented"); + } + +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/icndb/suppliers/RandomJokeSupplier.java b/src/main/java/de/fhro/inf/prg3/a12/icndb/suppliers/RandomJokeSupplier.java new file mode 100644 index 0000000000000000000000000000000000000000..7c35ad496a7669fbd33db3e9479614f2b5ae52e5 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/icndb/suppliers/RandomJokeSupplier.java @@ -0,0 +1,29 @@ +package de.fhro.inf.prg3.a12.icndb.suppliers; + +import java.util.function.Supplier; + +import de.fhro.inf.prg3.a12.icndb.ICNDBApi; +import de.fhro.inf.prg3.a12.icndb.ICNDBService; +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import org.apache.commons.lang3.NotImplementedException; + +/** + * @author Peter Kurfer + */ + +public final class RandomJokeSupplier implements Supplier<ResponseWrapper<JokeDto>> { + + private final ICNDBApi icndbApi; + + public RandomJokeSupplier() { + icndbApi = ICNDBService.getInstance(); + } + + @Override + public ResponseWrapper<JokeDto> get() { + /* TODO fetch a random joke synchronously + * if an exception occurs return null */ + throw new NotImplementedException("Method `get()` is not implemented"); + } +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/model/JokeDto.java b/src/main/java/de/fhro/inf/prg3/a12/model/JokeDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9998c87437a0a7f819a5c5ef3d5149ac30f870da --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/model/JokeDto.java @@ -0,0 +1,82 @@ +package de.fhro.inf.prg3.a12.model; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Peter Kurfer + * Created on 12/28/17. + */ +public class JokeDto { + + private int id; + private String joke; + private List<String> categories; + + public JokeDto() { + categories = new ArrayList<>(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getJoke() { + return joke; + } + + public void setJoke(String joke) { + this.joke = joke; + } + + public List<String> getCategories() { + return categories; + } + + public void setCategories(List<String> categories) { + if(categories == null) return; + this.categories = categories; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + + if (!(o instanceof JokeDto)) return false; + + JokeDto joke1 = (JokeDto) o; + + return new EqualsBuilder() + .append(getId(), joke1.getId()) + .append(getJoke(), joke1.getJoke()) + .append(getCategories(), joke1.getCategories()) + .isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37) + .append(getId()) + .append(getJoke()) + .append(getCategories()) + .toHashCode(); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("id", id) + .append("joke", joke) + .append("categories", categories) + .toString(); + } + +} diff --git a/src/main/java/de/fhro/inf/prg3/a12/model/ResponseWrapper.java b/src/main/java/de/fhro/inf/prg3/a12/model/ResponseWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..bba5378bb1fbb44cd326c458d739914e8d783292 --- /dev/null +++ b/src/main/java/de/fhro/inf/prg3/a12/model/ResponseWrapper.java @@ -0,0 +1,62 @@ +package de.fhro.inf.prg3.a12.model; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; + +/** + * @author Peter Kurfer + * Created on 12/28/17. + */ +public class ResponseWrapper<T> { + + private String type; + + private T value; + + public ResponseWrapper() { + type = "error"; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } + + public boolean isSuccessfull() { + return type != null && type.equals("success"); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + + if (!(o instanceof ResponseWrapper)) return false; + + ResponseWrapper<?> that = (ResponseWrapper<?>) o; + + return new EqualsBuilder() + .append(getType(), that.getType()) + .append(getValue(), that.getValue()) + .isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37) + .append(getType()) + .append(getValue()) + .toHashCode(); + } + +} diff --git a/src/test/java/de/fhro/inf/prg3/a12/icndb/ICNDBTests.java b/src/test/java/de/fhro/inf/prg3/a12/icndb/ICNDBTests.java new file mode 100644 index 0000000000000000000000000000000000000000..80cd1d6e8176bb10bf669b00eba3d145efdcfd6e --- /dev/null +++ b/src/test/java/de/fhro/inf/prg3/a12/icndb/ICNDBTests.java @@ -0,0 +1,87 @@ +package de.fhro.inf.prg3.a12.icndb; + +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * @author Peter Kurfer + */ + +public class ICNDBTests { + private static final Logger logger = Logger.getLogger(ICNDBTests.class.getName()); + private static final int REQUEST_COUNT = 100; + + private ICNDBApi icndbApi; + + public ICNDBTests() { + this.icndbApi = ICNDBService.getInstance(); + } + + @Test + void testCollision() throws ExecutionException, InterruptedException { + Set<Integer> jokeNumbers = new HashSet<>(); + int requests = 0; + boolean collision = false; + + while (requests++ < REQUEST_COUNT) { + CompletableFuture<ResponseWrapper<JokeDto>> jokeCall = icndbApi.getRandomJoke(); + JokeDto joke = jokeCall.get().getValue(); + + if(jokeNumbers.contains(joke.getId())) { + logger.info(String.format("Collision at joke %s", joke.getId())); + collision = true; + break; + } + + jokeNumbers.add(joke.getId()); + logger.info(joke.toString()); + } + + assertTrue(collision, String.format("Completed %d requests without collision; consider increasing REQUEST_COUNT", requests)); + } + + @Test + void testGetRandomJokeWithChangedName() throws ExecutionException, InterruptedException { + JokeDto j = icndbApi.getRandomJoke("Bruce", "Wayne").get().getValue(); + assertNotNull(j); + assertFalse(j.getJoke().contains("Chuck")); + assertFalse(j.getJoke().contains("Norris")); + logger.info(j.toString()); + } + + @Test + void testGetJokeById() throws ExecutionException, InterruptedException { + + List<Integer> randomIds = new ArrayList<>(10); + + for(int i = 0; i < 10; i++) { + randomIds.add(icndbApi.getRandomJoke().get().getValue().getId()); + } + + for(Integer id : randomIds) { + JokeDto j = icndbApi.getJoke(id).get().getValue(); + assertNotNull(j); + assertTrue(randomIds.contains(j.getId())); + logger.info(j.toString()); + } + } + + @Test + void testGetJokeCount() throws ExecutionException, InterruptedException { + int jokeCount = icndbApi.getJokeCount().get().getValue(); + + assertNotEquals(0, jokeCount); + } + +} diff --git a/src/test/java/de/fhro/inf/prg3/a12/icndb/JokesGeneratorTests.java b/src/test/java/de/fhro/inf/prg3/a12/icndb/JokesGeneratorTests.java new file mode 100644 index 0000000000000000000000000000000000000000..688c710457a44a32a5c5b456d7e5df051a73a107 --- /dev/null +++ b/src/test/java/de/fhro/inf/prg3/a12/icndb/JokesGeneratorTests.java @@ -0,0 +1,55 @@ +package de.fhro.inf.prg3.a12.icndb; + +import de.fhro.inf.prg3.a12.model.JokeDto; +import de.fhro.inf.prg3.a12.model.ResponseWrapper; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Objects; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; + +/** + * @author Peter Kurfer + * Created on 12/28/17. + */ +class JokesGeneratorTests { + + private JokeGenerator jokeGenerator = new JokeGenerator(); + + @Test + void testRandomStream() { + assertTimeout(Duration.ofSeconds(5L), () -> { + Stream<ResponseWrapper<JokeDto>> randomJokesStream = jokeGenerator.randomJokesStream(); + + randomJokesStream + .filter(Objects::nonNull) + .map(ResponseWrapper::getValue) + .skip(3) + .limit(5) + .forEach(j -> { + assertNotNull(j.getJoke()); + System.out.println(j.getJoke()); + }); + }); + } + + + @Test + void testJokesStream() { + assertTimeout(Duration.ofMinutes(1L), () -> { + jokeGenerator.jokesStream() + .filter(Objects::nonNull) + .map(ResponseWrapper::getValue) + .skip(200L) + .limit(400L) + .forEach(j -> { + assertNotNull(j.getJoke()); + System.out.println(j.getJoke()); + }); + }); + } + +}