diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c329c5e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ +/bin/* diff --git a/README.md b/README.md index e9e90833..673999d5 100755 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ He wants you to build a web app that has similar UI/UX. Similar way to go from t We have supplied you with a json file (`cards.json`) containing all the Heartstone cards currently available. -Hsiao is especially interested in the app showing `Legendary` cards with the `Deathrattle Mechanic`, below are examples of such a cards : +Hsiao is especially interested in the app showing `Legendary` cards with the `Deathrattle Mechanic`, below are examples of such cards: ```json { @@ -84,7 +84,7 @@ You are free to choose the patterns and architectures to create this web app, th ### Backend -* Create an API using a Java (plain java or Groovy/Cotlin) backend allowing you to get card information for at least legendary deathrattle cards +* Create an API using a Java (plain java or Groovy/Kotlin) backend allowing you to get card information for at least legendary deathrattle cards * The API should also support filtering based on relevant request parameters. Ideally, the API should enable the following, listed from easy to hard: * filter by least the following fields: `type`, `rarity`, `classes`, and `mechanics` * return sorted results (for example, alphabetically sorted), supporting both ascending and descending diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..eaf4a506 --- /dev/null +++ b/build.gradle @@ -0,0 +1,45 @@ +buildscript { + ext { + springBootVersion = '1.5.9.RELEASE' + } + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + classpath 'com.google.cloud.tools:appengine-gradle-plugin:+' + } +} + +apply plugin: 'war' +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'org.springframework.boot' +apply plugin: 'com.google.cloud.tools.appengine' + +group = 'nl.tom' +version = '0.0.2-SNAPSHOT' +sourceCompatibility = 1.8 + +repositories { // repositories for Jar's you access in your code + mavenCentral() +} + +configurations { + providedCompile + // comment for local + //compile.exclude module: "spring-boot-starter-tomcat" + compile.exclude module: "org.slf4j:jul-to-slf4j" +} + +dependencies { + compile("org.springframework.boot:spring-boot-starter-web:1.5.9.RELEASE") + + providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version:'3.1.0' + //FIXME: providedCompile group: 'org.slf4j', name: 'jul-to-slf4j' + + //compile('org.springframework.boot:spring-boot-devtools') + + testCompile('org.springframework.boot:spring-boot-starter-test') + //TODO: testCompile('org.springframework.restdocs:spring-restdocs-mockmvc') +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..1a958be6 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 00000000..90a06cec --- /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-3.5.1-bin.zip diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..4453ccea --- /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 00000000..e95643d6 --- /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/src/main/appengine/app.yaml.old b/src/main/appengine/app.yaml.old new file mode 100644 index 00000000..3e13ef83 --- /dev/null +++ b/src/main/appengine/app.yaml.old @@ -0,0 +1,9 @@ +runtime: java +env: flex + +handlers: +- url: /.* + script: this field is required, but ignored + +manual_scaling: + instances: 1 \ No newline at end of file diff --git a/src/main/java/nl/tom/hstone/HeartstoneAssessmentSpringApplication.java b/src/main/java/nl/tom/hstone/HeartstoneAssessmentSpringApplication.java new file mode 100644 index 00000000..9d5fbadb --- /dev/null +++ b/src/main/java/nl/tom/hstone/HeartstoneAssessmentSpringApplication.java @@ -0,0 +1,18 @@ +package nl.tom.hstone; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Entry point. + * + * @author Tom + * + */ +@SpringBootApplication +public class HeartstoneAssessmentSpringApplication { + + public static void main(String[] args) { + SpringApplication.run(HeartstoneAssessmentSpringApplication.class, args); + } +} diff --git a/src/main/java/nl/tom/hstone/ServletInitializer.java b/src/main/java/nl/tom/hstone/ServletInitializer.java new file mode 100644 index 00000000..8ae0c7fc --- /dev/null +++ b/src/main/java/nl/tom/hstone/ServletInitializer.java @@ -0,0 +1,17 @@ +package nl.tom.hstone; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +/** + * Required by the GAE Standard (webapp) deployment. + * + * @author Tom + * + */ +public class ServletInitializer extends SpringBootServletInitializer { + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(HeartstoneAssessmentSpringApplication.class); + } +} \ No newline at end of file diff --git a/src/main/java/nl/tom/hstone/model/AbstractCard.java b/src/main/java/nl/tom/hstone/model/AbstractCard.java new file mode 100644 index 00000000..6c2c737a --- /dev/null +++ b/src/main/java/nl/tom/hstone/model/AbstractCard.java @@ -0,0 +1,65 @@ +package nl.tom.hstone.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonView; + +import nl.tom.hstone.rest.View; + +/** + * Simple non-structured fields of a card that can also be filtered on. + * + * @author Tom + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public abstract class AbstractCard { + + @JsonView(View.ListScreen.class) + String cardId; + String name; + String cardSet; + + String type; + String rarity; + + public String getCardId() { + return cardId; + } + + public void setCardId(String cardId) { + this.cardId = cardId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCardSet() { + return cardSet; + } + + public void setCardSet(String cardSet) { + this.cardSet = cardSet; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getRarity() { + return rarity; + } + + public void setRarity(String rarity) { + this.rarity = rarity; + } + +} diff --git a/src/main/java/nl/tom/hstone/model/Card.java b/src/main/java/nl/tom/hstone/model/Card.java new file mode 100644 index 00000000..1dc9b27f --- /dev/null +++ b/src/main/java/nl/tom/hstone/model/Card.java @@ -0,0 +1,58 @@ +package nl.tom.hstone.model; + +import java.util.Arrays; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonView; + +import nl.tom.hstone.rest.View; + +/** + * The main model object. + * + * @author Tom + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Card extends AbstractCard { + + @JsonView(View.ListScreen.class) + String img;// filtering on this field is not allowed + + public String getImg() { + return img; + } + + public void setImg(String img) { + this.img = img; + } + + String[] classes; + Mechanics[] mechanics; + + public Mechanics[] getMechanics() { + return mechanics; + } + + public void setMechanics(Mechanics[] mechanics) { + this.mechanics = mechanics; + } + + public String[] getClasses() { + return classes; + } + + public void setClasses(String[] classes) { + this.classes = classes; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Card [cardId=").append(cardId).append(", cardSet=").append(cardSet).append(", name=") + .append(name).append(", rarity=").append(rarity).append(", type=").append(type).append(", classes=") + .append(Arrays.toString(classes)).append(", mechanics=").append(Arrays.toString(mechanics)).append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/nl/tom/hstone/model/CardFilter.java b/src/main/java/nl/tom/hstone/model/CardFilter.java new file mode 100644 index 00000000..c4cad7f5 --- /dev/null +++ b/src/main/java/nl/tom/hstone/model/CardFilter.java @@ -0,0 +1,31 @@ +package nl.tom.hstone.model; + +/** + * Represents all filter conditions. + * + * @author Tom + * + */ +public class CardFilter extends AbstractCard { + + String classFilter; + + String mechanicsFilter; + + public String getMechanicsFilter() { + return mechanicsFilter; + } + + public void setMechanicsFilter(String mechanicsFilter) { + this.mechanicsFilter = mechanicsFilter; + } + + public String getClassFilter() { + return classFilter; + } + + public void setClassFilter(String classFilter) { + this.classFilter = classFilter; + } + +} diff --git a/src/main/java/nl/tom/hstone/model/Mechanics.java b/src/main/java/nl/tom/hstone/model/Mechanics.java new file mode 100644 index 00000000..530150fc --- /dev/null +++ b/src/main/java/nl/tom/hstone/model/Mechanics.java @@ -0,0 +1,20 @@ +package nl.tom.hstone.model; + +public class Mechanics { + + String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Mechanics [name=" + name + "]"; + } + +} diff --git a/src/main/java/nl/tom/hstone/rest/CardResponse.java b/src/main/java/nl/tom/hstone/rest/CardResponse.java new file mode 100644 index 00000000..899ae134 --- /dev/null +++ b/src/main/java/nl/tom/hstone/rest/CardResponse.java @@ -0,0 +1,37 @@ +package nl.tom.hstone.rest; + +import java.util.List; + +import nl.tom.hstone.model.Card; + +/** + * Data transfer object. + * + * @author Tom + * + */ +public class CardResponse { + + List cards; + + public CardResponse(List list) { + this.cards = list; + } + + public int getTotalCount() { + return cards.size(); + } + + public List getCards() { + return cards; + } + + public void setCards(List cards) { + this.cards = cards; + } + + public void setTotalCount(int count) { + + } + +} diff --git a/src/main/java/nl/tom/hstone/rest/HStoneController.java b/src/main/java/nl/tom/hstone/rest/HStoneController.java new file mode 100644 index 00000000..5e7c833e --- /dev/null +++ b/src/main/java/nl/tom/hstone/rest/HStoneController.java @@ -0,0 +1,71 @@ +package nl.tom.hstone.rest; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.annotation.JsonView; + +import nl.tom.hstone.model.Card; +import nl.tom.hstone.model.CardFilter; +import nl.tom.hstone.service.CardDao; +import nl.tom.hstone.service.SortDirection; + +@RestController +public class HStoneController { + + private static final Logger logger = LoggerFactory.getLogger(HStoneController.class); + + /** + * If the maximum is not specified, this is the default + */ + private static final Integer DEFAULT_MAX = 5000; + + @Autowired + CardDao cardDao; + + // TODO: improve error handling + + @JsonView(View.ListScreen.class) + @RequestMapping("/rest/cards/{dir}/") + public Map filter(@PathVariable String dir, @ModelAttribute CardFilter filter, + @RequestParam(defaultValue = "0") int from, Integer max) throws IOException { + List list = cardDao.filter(filter, SortDirection.valueOf(dir)); + HashMap map = new HashMap(); + map.put("total", list.size()); + //FIXME: expand this and move it to the Dao, the pagination should be there + int toIndex = Math.min(list.size(), from + ((max == null) ? DEFAULT_MAX : max)); + List resultList = null; + if(from > toIndex) { + resultList = Collections.emptyList(); + } else { + resultList = list.subList(from, toIndex); + } + map.put("list", resultList); + return map; + } + + @RequestMapping("/rest/card/{cardId}") + public Card getCardById(@PathVariable String cardId) throws IOException { + return cardDao.getCardById(cardId); + } + + @RequestMapping("/hello") + public String hello() { + String msg = "Hello Splendo!"; + logger.info(msg); + return msg; + } + +} diff --git a/src/main/java/nl/tom/hstone/rest/View.java b/src/main/java/nl/tom/hstone/rest/View.java new file mode 100644 index 00000000..7ac7b1b3 --- /dev/null +++ b/src/main/java/nl/tom/hstone/rest/View.java @@ -0,0 +1,14 @@ +package nl.tom.hstone.rest; + +/** + * Limit certain fields to be included in certain responses by the JSON + * serializer + * + * @author Tom + * + */ +public class View { + + public interface ListScreen { + } +} \ No newline at end of file diff --git a/src/main/java/nl/tom/hstone/service/CardComparator.java b/src/main/java/nl/tom/hstone/service/CardComparator.java new file mode 100644 index 00000000..8394d3aa --- /dev/null +++ b/src/main/java/nl/tom/hstone/service/CardComparator.java @@ -0,0 +1,26 @@ +package nl.tom.hstone.service; + +import java.util.Comparator; + +import nl.tom.hstone.model.Card; + +/** + * Compares cards by cardId. + * + * @author Tom + * + */ +public class CardComparator implements Comparator { + + SortDirection dir; + + public CardComparator(SortDirection dir) { + this.dir = dir; + } + + @Override + public int compare(Card card1, Card card2) { + // TODO null safe + return dir.getMultiplier() * card1.getCardId().compareTo(card2.getCardId()); + } +} diff --git a/src/main/java/nl/tom/hstone/service/CardDao.java b/src/main/java/nl/tom/hstone/service/CardDao.java new file mode 100644 index 00000000..d6c56fa4 --- /dev/null +++ b/src/main/java/nl/tom/hstone/service/CardDao.java @@ -0,0 +1,23 @@ +package nl.tom.hstone.service; + +import java.util.List; + +import nl.tom.hstone.model.Card; +import nl.tom.hstone.model.CardFilter; + +/** + * Card Repository Data Access Object Interface to list / filter / count cards. + *

+ * Implementations can differ in their nature of repository (eg. in-memory, + * ElasticSearch, MongoDB), access method, caching, sorting and many more. + * + * @author Tom + * + */ +public interface CardDao { + + List filter(CardFilter filter, SortDirection sortDirection); + + Card getCardById(String cardId); + +} diff --git a/src/main/java/nl/tom/hstone/service/CardDaoJacksonImpl.java b/src/main/java/nl/tom/hstone/service/CardDaoJacksonImpl.java new file mode 100644 index 00000000..1f0c65fd --- /dev/null +++ b/src/main/java/nl/tom/hstone/service/CardDaoJacksonImpl.java @@ -0,0 +1,205 @@ +package nl.tom.hstone.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Repository; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import nl.tom.hstone.model.AbstractCard; +import nl.tom.hstone.model.Card; +import nl.tom.hstone.model.CardFilter; + +/** + * Card Repository Data Access Object to list / filter / count cards. + *

+ * Implementation details: + *

+ * On initialisation the data structure is read from the file, the 2-level tree + * (cardSet->cards) is flattened to set of cards (cardSet is also a property of each card, + * so the structure is redundant). No additional index-like data structures are + * created in this implementation, due to the small size of a dataset. The list + * is then searched and filtered. + *

+ * Assuming a very high query:init ratio in long-term, this approach is more + * cost effective than opening the file on every request and filter during + * parsing, and the constant memory footprint of the {@link #cardRepository} is + * negligible. + * + * @author Tom + * + */ +@Repository +public class CardDaoJacksonImpl implements CardDao { + + private static final String CARDS_JSON = "cards.json"; + private static final int EXPECTED_CARD_AMOUNT = 3116; + + private static final Logger logger = LoggerFactory.getLogger(CardDaoJacksonImpl.class); + + /** + * very simple object pool to avoid instantiation-gc of this frequently used + * object (over-optimization) + */ + private static final Map comparators; + static { + comparators = new HashMap<>(); + comparators.put(SortDirection.ASC, new CardComparator(SortDirection.ASC)); + comparators.put(SortDirection.DESC, new CardComparator(SortDirection.DESC)); + } + + /** + * cards are stored here by {@link #init()} and then retrieved by all the other + * functions + */ + private Set cardRepository = new HashSet<>(EXPECTED_CARD_AMOUNT); + + /** + * Initialisation method to populate {@link #cardRepository} from the json file + */ + @PostConstruct + public void init() { + logger.info("initialising the repository..."); + try (InputStream fis = new ClassPathResource(CARDS_JSON).getInputStream();) { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode rootNode = objectMapper.readTree(fis); + rootNode.iterator().forEachRemaining(cardSet -> cardSet.iterator().forEachRemaining(cardNode -> { + try { + Card card = objectMapper.treeToValue(cardNode, Card.class); + cardRepository.add(card); + } catch (JsonProcessingException e) { + String msg = "Can't process card database file. Repository was not initialised"; + logger.error(msg, e); + throw new IllegalStateException(msg, e); + } + })); + } catch (IOException e) { + String msg = "Can't open card database file. Repository was not initialised"; + logger.error(msg, e); + throw new IllegalStateException(msg, e); + } + logger.info("... initialised the repository with {} cards", cardRepository.size()); + } + + public Card getCardById(String cardId) { + if (cardId == null) + throw new IllegalArgumentException("cardId must be String"); + CardFilter filter = new CardFilter(); + filter.setCardId(cardId); + + List filtered = cardRepository.stream() + .filter(card -> simpleFilterCondition(card, filter, (c -> c.getCardId()))).collect(Collectors.toList()); + + if (filtered == null) + return null; + return filtered.get(0); + } + + /** + * Object oriented filtering approach instead of string / reflection based + */ + @Override + public List filter(CardFilter filter, SortDirection sortDirection) { + List filtered = cardRepository.stream() + .filter(card -> simpleFilterCondition(card, filter, (c -> c.getCardId())))// just to be consistent, + // won't be used by the UI + .filter(card -> simpleFilterCondition(card, filter, (c -> c.getType()))) + .filter(card -> simpleFilterCondition(card, filter, (c -> c.getRarity()))) + .filter(card -> simpleFilterCondition(card, filter, (c -> c.getName()))) + .filter(card -> simpleFilterCondition(card, filter, (c -> c.getCardSet()))) + .filter(card -> executeClassFilter(filter, card))// sepcial filter + .filter(card -> executeMechanicsFilter(filter, card))// sepcial filter + .sorted(comparators.get(sortDirection))// + .collect(Collectors.toList()); + + logger.info("returning {} card(s)", filtered.size()); + return filtered; + } + + /** + * Simple {@link java.lang.String#equals(Object)} comparison on the same fields + * (inherited from {@link AbstractCard} ) of card & filter. + * + * @param card + * card to be checked + * @param filter + * filter to be checked + * @param func + * method on both the card and filter to be called + * @return true if filter is active and card matches filter, false otherwise + */ + private boolean simpleFilterCondition(Card card, CardFilter filter, Function func) { + // extract filter value + String filterData = func.apply(filter); + + // if filter is empty, no filtering has to be done + if (filterData == null || filterData.isEmpty()) { + return true; + } + String cardData = func.apply(card); + return filterData.equals(cardData); + } + + /** + * Check if any class of the card matches the + * {@link CardFilter#getClassFilter()} + * + * @param filter + * @param card + * @return true if filter is active and card matches filter, false otherwise + */ + private boolean executeClassFilter(CardFilter filter, Card card) { + // if filter is empty, no filtering has to be done + if (filter.getClassFilter() == null || filter.getClassFilter().isEmpty()) { + return true; + } + + // if card has no classes it can't match the filter + if (card.getClasses() == null) { + return false; + } + + // check if any class matches the filter + return Arrays.stream(card.getClasses()).anyMatch(cl -> cl.equals(filter.getClassFilter())); + } + + /** + * Check if any class of the card matches the + * {@link CardFilter#getMechanicsFilter()} + * + * @param filter + * @param card + * @return true if filter is active and card matches filter, false otherwise + */ + private boolean executeMechanicsFilter(CardFilter filter, Card card) { + // if filter is empty, no filtering has to be done + if (filter.getMechanicsFilter() == null || filter.getMechanicsFilter().isEmpty()) { + return true; + } + + // if card has no mechanics it can't match the filter + if (card.getMechanics() == null) { + return false; + } + + // check if any mechanic name matches the filter + return Arrays.stream(card.getMechanics()).anyMatch(mech -> mech.getName().equals(filter.getMechanicsFilter())); + } + +} diff --git a/src/main/java/nl/tom/hstone/service/SortDirection.java b/src/main/java/nl/tom/hstone/service/SortDirection.java new file mode 100644 index 00000000..78b76292 --- /dev/null +++ b/src/main/java/nl/tom/hstone/service/SortDirection.java @@ -0,0 +1,15 @@ +package nl.tom.hstone.service; + +public enum SortDirection { + ASC(1), DESC(-1); + + private int multiplier; + + SortDirection(int multiplier) { + this.multiplier = multiplier; + } + + public int getMultiplier() { + return multiplier; + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..c10be675 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ +logging.level.=INFO \ No newline at end of file diff --git a/cards.json b/src/main/resources/cards.json similarity index 100% rename from cards.json rename to src/main/resources/cards.json diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties new file mode 100644 index 00000000..61a63d39 --- /dev/null +++ b/src/main/resources/log4j.properties @@ -0,0 +1,5 @@ +log4j.rootLogger=ALL, console + +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%-5p: %m at %C.(%F:%L) on %d{ISO8601}%n \ No newline at end of file diff --git a/src/main/resources/logging.properties b/src/main/resources/logging.properties new file mode 100644 index 00000000..1877ce37 --- /dev/null +++ b/src/main/resources/logging.properties @@ -0,0 +1,9 @@ +# A default java.util.logging configuration. +# (All App Engine logging is through java.util.logging by default). + +# Set the default logging level for all loggers to INFO +.level = INFO +handlers=java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level=FINEST +java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n \ No newline at end of file diff --git a/src/main/resources/static/css/simple.css b/src/main/resources/static/css/simple.css new file mode 100644 index 00000000..e6a33e1b --- /dev/null +++ b/src/main/resources/static/css/simple.css @@ -0,0 +1,77 @@ +.scrolltable > tbody > tr > td { + height: 305px; + width: 210px; +} +.scrolltable > tbody > tr > td > img { + cursor: pointer; +} + +//----- modal + +* { + box-sizing: border-box; +} + +.modal-mask { + position: fixed; + z-index: 9998; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, .5); + display: table; + transition: opacity .3s ease; +} + +.modal-wrapper { + display: table-cell; + vertical-align: middle; +} + +.modal-container { + width: 900px; + margin: 0px auto; + padding: 20px 30px; + background-color: #fff; + border-radius: 2px; + box-shadow: 0 2px 8px rgba(0, 0, 0, .33); + transition: all .3s ease; + font-family: Helvetica, Arial, sans-serif; +} + +.modal-header h3 { + margin-top: 0; + color: #42b983; +} + +.modal-body { + margin: 20px 0; +} + +.modal-default-button { + float: right; +} + +/* + * The following styles are auto-applied to elements with + * transition="modal" when their visibility is toggled + * by Vue.js. + * + * You can easily play with the modal transition by editing + * these styles. + */ + +.modal-enter { + opacity: 0; +} + +.modal-leave-active { + opacity: 0; +} + +.modal-enter .modal-container, +.modal-leave-active .modal-container { + -webkit-transform: scale(1.1); + transform: scale(1.1); +} \ No newline at end of file diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 00000000..e8d3db0c --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,39 @@ + + + + + + + +HeartstoneAssessment Index + + + + + + +

+ + + +
+

Under construction - Tom Magyar

+
+ + + \ No newline at end of file diff --git a/src/main/resources/static/js/hstone.js b/src/main/resources/static/js/hstone.js new file mode 100644 index 00000000..b0625ed4 --- /dev/null +++ b/src/main/resources/static/js/hstone.js @@ -0,0 +1,126 @@ +var CardOnList = Vue.extend({ + template: '#list-row-template', + props: ['m'] +}); + +Vue.component('modal', { + template: '#modal-template', + props: ['prevcond', 'nextcond'] + }); + +var app = new Vue({ + el: '#app', + data: { + total: 0, + downloadedList: [], + errors: [], + detailIndex : -1, + detailModel : null, + showModal: false, + isFav: false + }, + + mounted: function () { + this.loadMore(); + }, +methods: { + loadMore: function () { + axios.get('rest/cards/ASC/', { + params: { + from: this.downloadedList.length, + max: 200, + //rarity:'Legendary', + //mechanicsFilter:'Deathrattle' + } + }) + .then(response => { + console.log("Loading:", response.data.list.length, + "Loaded:",this.downloadedList.length, + "Total:", this.total); + this.total = response.data.total; + this.addToList(this.downloadedList.length, response.data.list); + this.downloadedList = this.downloadedList.concat(response.data.list); + + if(this.total > this.downloadedList.length) { + this.loadMore(); + } + }) + .catch(e => { + this.errors.push(e) + }) + }, + + addToList: function (startIndex, newData) { + var first = true; + var component = null; + + for (i in newData) { + if (i % 5 == 0) { + if(first){ + first = false; + } else { + this.appendToClusterize(component); + } + var component = new CardOnList(); + component.m=[]; + } + var cardData = newData[i]; + var listItem = {}; + listItem.src=cardData.img; + listItem.clk="app.lstClk("+(Number(startIndex)+Number(i))+",'"+cardData.cardId+"')"; + component.m.push(listItem); + } + this.appendToClusterize(component);//add the rest of items + }, + + appendToClusterize: function (component) { + component= component.$mount(); + clusterize.append([component.$el.outerHTML]); + }, + + lstClk: function (idx, cardId) { + console.log("clicked", idx, cardId); + this.detailIndex= idx; + this.isFav = (localStorage.getItem(cardId) == 1); + + axios.get('rest/card/'+cardId) + .then(response => { + this.detailModel = response.data; + this.showModal = true; + }) + .catch(e => { + this.errors.push(e) + }) + }, + + stepDetail: function (offset) { + this.detailIndex+=offset; + this.lstClk( + this.detailIndex, + this.downloadedList[this.detailIndex].cardId + ); + }, + + imgError: function (img) { + img.onerror=null; + img.src='//img.ogol.io/splendo.com/9y48478.png?w=100&h=185'; + }, + + fav: function () { + localStorage.setItem(this.detailModel.cardId, this.isFav ? 0 : 1); + this.isFav = !this.isFav; + } + +} + +}) + +var clData = []; +var clusterize = new Clusterize({ + rows: clData, + scrollId: 'scrollArea', + contentId: 'contentArea', + tag : 'tr', + rows_in_block:3, + keep_parity:false + }); \ No newline at end of file diff --git a/src/main/resources/static/tester.html b/src/main/resources/static/tester.html new file mode 100644 index 00000000..ca40252d --- /dev/null +++ b/src/main/resources/static/tester.html @@ -0,0 +1,57 @@ + + + + + + + +HeartstoneAssessment Index + + + + + + + + +
+
+
+

Details

+

card details by cardId

+ +

List (less attributes are included)

+

Filtering on rarity & mechanics, ascending order

+

from & max

+

from & default max (5000)

+

default from (0) & default max(5000)

+ +

Filtering on class & type

+

ascending; default from (0) & default max(5000)

+

descending; default from (0) & default max(5000)

+ +

Arbitrary filtering (ascending)

+
+
cardId: +
name: +
cardSet: +
type: +
rarity: +
class: +
mechanics: +
+
+
+
+
+ +
+

Under construction - Tom Magyar

+
+ + + \ No newline at end of file diff --git a/src/main/resources/static/ui.html b/src/main/resources/static/ui.html new file mode 100644 index 00000000..58403633 --- /dev/null +++ b/src/main/resources/static/ui.html @@ -0,0 +1,115 @@ + + + + HeartstoneAssessment UI + + + + + + + + + + + + + + + +
+ + +

Card #{{ detailIndex }}: {{ detailModel.name }} + +

+
+
+
+ +
+
+

Card set: {{ detailModel.cardSet }}

+

Type: {{ detailModel.type }}

+

Rarity: {{ detailModel.rarity }}

+

Classes: + {{ detailModel.classes == null ? "-" : detailModel.classes.join(", ") }}

+

Mechanics: +

    +
  • {{m.name}}
  • +
+
+
+
+ + "classes":null,"mechanics":[{"name":"Deathrattle"}]} +
+ +
+
+ + + + +
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/appengine-web.xml b/src/main/webapp/WEB-INF/appengine-web.xml new file mode 100644 index 00000000..0d890caa --- /dev/null +++ b/src/main/webapp/WEB-INF/appengine-web.xml @@ -0,0 +1,9 @@ + + 1 + true + java8 + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/logging.properties b/src/main/webapp/WEB-INF/logging.properties new file mode 100644 index 00000000..1877ce37 --- /dev/null +++ b/src/main/webapp/WEB-INF/logging.properties @@ -0,0 +1,9 @@ +# A default java.util.logging configuration. +# (All App Engine logging is through java.util.logging by default). + +# Set the default logging level for all loggers to INFO +.level = INFO +handlers=java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level=FINEST +java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n \ No newline at end of file diff --git a/src/test/java/nl/tom/hstone/FilterTests.java b/src/test/java/nl/tom/hstone/FilterTests.java new file mode 100644 index 00000000..28ed3639 --- /dev/null +++ b/src/test/java/nl/tom/hstone/FilterTests.java @@ -0,0 +1,106 @@ +package nl.tom.hstone; + +import static nl.tom.hstone.service.SortDirection.ASC; +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import nl.tom.hstone.model.Card; +import nl.tom.hstone.model.CardFilter; +import nl.tom.hstone.service.CardDao; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class FilterTests { + + private static final Logger logger = LoggerFactory.getLogger(FilterTests.class); + + @Autowired + CardDao cardDao; + + @Test + public void filterOneCard() { + CardFilter filter = new CardFilter(); + filter.setCardId("CFM_902"); + + List result = cardDao.filter(filter, ASC); + + assertEquals(1, result.size()); + assertEquals("Legendary", result.get(0).getRarity()); + assertEquals("Minion", result.get(0).getType()); + assertEquals("Aya Blackpaw", result.get(0).getName()); + assertEquals("Mean Streets of Gadgetzan", result.get(0).getCardSet()); + } + + @Test + public void getOneCard() { + Card result = cardDao.getCardById("CFM_902"); + + assertEquals("Legendary", result.getRarity()); + assertEquals("Minion", result.getType()); + assertEquals("Aya Blackpaw", result.getName()); + assertEquals("Mean Streets of Gadgetzan", result.getCardSet()); + } + + @Test + public void filterByNameAndCardSet() { + CardFilter filter = new CardFilter(); + filter.setName("Stalagg"); + filter.setCardSet("Naxxramas"); + + List result = cardDao.filter(filter, ASC); + + assertEquals(2, result.size()); + } + + @Test + public void filterClass() { + CardFilter filter = new CardFilter(); + filter.setClassFilter("Shaman"); + + List result = cardDao.filter(filter, ASC); + + assertEquals(3, result.size()); + } + + @Test + public void filterMechanics() { + CardFilter filter = new CardFilter(); + filter.setMechanicsFilter("Deathrattle"); + + List result = cardDao.filter(filter, ASC); + + assertEquals(155, result.size()); + } + + @Test + public void filterClassAndMechanics() { + CardFilter filter = new CardFilter(); + filter.setClassFilter("Shaman"); + filter.setMechanicsFilter("Deathrattle"); + + List result = cardDao.filter(filter, ASC); + + assertEquals(1, result.size()); + } + + @Test + public void filterHsiaoFavourites() { + CardFilter filter = new CardFilter(); + filter.setRarity("Legendary"); + filter.setMechanicsFilter("Deathrattle"); + + List result = cardDao.filter(filter, ASC); + + assertEquals(31, result.size()); + } + +} diff --git a/src/test/java/nl/tom/hstone/SortTests.java b/src/test/java/nl/tom/hstone/SortTests.java new file mode 100644 index 00000000..d40a5356 --- /dev/null +++ b/src/test/java/nl/tom/hstone/SortTests.java @@ -0,0 +1,71 @@ +package nl.tom.hstone; + +import static nl.tom.hstone.service.SortDirection.ASC; +import static nl.tom.hstone.service.SortDirection.DESC; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import nl.tom.hstone.model.Card; +import nl.tom.hstone.model.CardFilter; +import nl.tom.hstone.service.CardDao; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SortTests { + + private static final Logger logger = LoggerFactory.getLogger(SortTests.class); + + @Autowired + CardDao cardDao; + + @Test + public void filterMechanicsSorted() { + CardFilter filter = new CardFilter(); + filter.setMechanicsFilter("Deathrattle"); + List resultAsc = cardDao.filter(filter, ASC); + List resultDesc = cardDao.filter(filter, DESC); + assertEquals(resultDesc.size(), resultAsc.size()); + + reverseCheck(resultAsc, resultDesc); + } + + @Test + public void noFilterSorted() { + CardFilter filter = new CardFilter(); + List resultAsc = cardDao.filter(filter, ASC); + assertEquals(3116, resultAsc.size()); + List resultDesc = cardDao.filter(filter, DESC); + assertEquals(3116, resultDesc.size()); + + reverseCheck(resultAsc, resultDesc); + } + + private void reverseCheck(List resultAsc, List resultDesc) { + // manual + for (int i = 0; i < resultDesc.size()/2; i++) { + assertEquals(resultAsc.get(i), resultDesc.get(resultDesc.size()-1-i)); + } + + //using reverse + List reversed = new ArrayList<>(resultAsc); + Collections.reverse(reversed); + + assertArrayEquals( + resultDesc.stream().toArray(Card[]::new), + reversed.stream().toArray(Card[]::new)); + + } + +}