diff --git a/.gitignore b/.gitignore index a512c8b38..549e00a2a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,33 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ -# Test binary, built with `go test -c` -*.test +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache -# Output of the go coverage tool, specifically when used with LiteIDE -*.out +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr -# Dependency directories (remove the comment below to include it) -# vendor/ +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ -out/ - -.idea \ No newline at end of file +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..c1dd12f17 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..22f219d25 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-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/README.md b/README.md index 8df9d4d3a..7fe271bd4 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,34 @@ -### Requirements +# SINGLE TODO Api -- Implement one single API which accepts a todo task and records it - - There is a maximum **limit of N tasks per user** that can be added **per day**. - - Different users can have **different** maximum daily limit. -- Write integration (functional) tests -- Write unit tests -- Choose a suitable architecture to make your code simple, organizable, and maintainable -- Write a concise README - - How to run your code locally? - - A sample “curl” command to call your API - - How to run your unit tests locally? - - What do you love about your solution? - - What else do you want us to know about however you do not have enough time to complete? +Single API which accepts a todo task and records it +Contents: +- There is a maximum limit of N tasks per user that can be added per day. +- Different users can have different maximum daily limit. -### Notes -- We're using Golang at Manabie. **However**, we encourage you to use the programming language that you are most comfortable with because we want you to **shine** with all your skills and knowledge. +## Feature +- Create todo task (includes: UT & IT) -### How to submit your solution? +## Tech +- Spring Boot +- Spring JPA +- MySQL -- Fork this repo and show us your development progress via a PR -### Interesting facts about Manabie +## Setup local machine +Install the dependencies and devDependencies and start the server. -- Monthly there are about 2 million lines of code changes (inserted/updated/deleted) committed into our GitHub repositories. To avoid **regression bugs**, we write different kinds of **automated tests** (unit/integration (functionality)/end2end) as parts of the definition of done of our assigned tasks. -- We nurture the cultural values: **knowledge sharing** and **good communication**, therefore good written documents and readable, organizable, and maintainable code are in our blood when we build any features to grow our products. -- We have **collaborative** culture at Manabie. Feel free to ask trieu@manabie.com any questions. We are very happy to answer all of them. +```sh +1. Open eclipse or Spring tool suites +2. Import existing maven project +3. Create 3 database: todos and todos_test +4. Run sql file: create_tables_data.sql +5. Create tables for database todo_test before run unit test or integration test +6. Before run local you need change username and password to connect to mysql in 2 file: application.properties ( one for development, one for testing) +7. To run local: right click file "TodoController" > "Run As" > "Java Application" +``` -Thank you for spending time to read and attempt our take-home assessment. We are looking forward to your submission. +## Curl example +```sh +curl -X POST http://localhost:9090/api/todo/tasks -H 'Content-Type: application/json' -d '{"title":"title_test","description":"ABC","userId":1}' +``` diff --git a/mvnw b/mvnw new file mode 100755 index 000000000..8a8fb2282 --- /dev/null +++ b/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/mvnw.cmd b/mvnw.cmd new file mode 100644 index 000000000..1d8ab018e --- /dev/null +++ b/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/pom.xml b/pom.xml new file mode 100644 index 000000000..bcbfd19a2 --- /dev/null +++ b/pom.xml @@ -0,0 +1,114 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.0 + + + com.api + todo + 0.0.1-SNAPSHOT + todo + Todo API + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + mysql + mysql-connector-java + 8.0.29 + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-validation + + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-launcher + test + + + + + org.mockito + mockito-junit-jupiter + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + src/main/resources + true + + + + + src/test/resources + true + + + + + \ No newline at end of file diff --git a/src/main/java/com/api/todo/TodoApplication.java b/src/main/java/com/api/todo/TodoApplication.java new file mode 100644 index 000000000..82833a759 --- /dev/null +++ b/src/main/java/com/api/todo/TodoApplication.java @@ -0,0 +1,13 @@ +package com.api.todo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TodoApplication { + + public static void main(String[] args) { + SpringApplication.run(TodoApplication.class, args); + } + +} diff --git a/src/main/java/com/api/todo/controllers/ApiErrorHandler.java b/src/main/java/com/api/todo/controllers/ApiErrorHandler.java new file mode 100644 index 000000000..e917a4399 --- /dev/null +++ b/src/main/java/com/api/todo/controllers/ApiErrorHandler.java @@ -0,0 +1,30 @@ +package com.api.todo.controllers; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import com.api.todo.response.ApiError; + +@ControllerAdvice +public class ApiErrorHandler extends ResponseEntityExceptionHandler { + @Override + protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + ApiError apiError = new ApiError(); + apiError.setCount(ex.getBindingResult().getErrorCount()); + apiError.setStatus(HttpStatus.BAD_REQUEST); + apiError.setError("Validation failed"); + List errors = new ArrayList<>(); + BindingResult bindingResult = ex.getBindingResult(); + bindingResult.getAllErrors().forEach(error -> errors.add(error.getCode())); + apiError.setErrors(errors); + return new ResponseEntity<>(apiError, HttpStatus.BAD_REQUEST); + } +} diff --git a/src/main/java/com/api/todo/controllers/TodoController.java b/src/main/java/com/api/todo/controllers/TodoController.java new file mode 100644 index 000000000..e9133990f --- /dev/null +++ b/src/main/java/com/api/todo/controllers/TodoController.java @@ -0,0 +1,47 @@ +package com.api.todo.controllers; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.api.todo.entities.Task; +import com.api.todo.request.RequestTaskEntity; +import com.api.todo.services.TodoService; +import com.api.todo.validators.TaskValidator; + +@RestController +@RequestMapping("/api/todo") +public class TodoController { + @Autowired + private TodoService todoService; + + @Autowired + private TaskValidator taskValidator; + + @InitBinder(value = "requestTaskEntity") + void initTaskValidator(WebDataBinder binder) { + binder.setValidator(taskValidator); + } + + @PostMapping("/tasks") + public ResponseEntity createTask(@RequestBody @Valid RequestTaskEntity requestTaskEntity) { + Task task = buildEntityFromRequest(requestTaskEntity); + + // create task + Task savedTask = todoService.createTask(task); + return new ResponseEntity(savedTask, HttpStatus.CREATED); + } + + private Task buildEntityFromRequest(@Valid RequestTaskEntity requestTaskEntity) { + Task task = new Task(requestTaskEntity); + return task; + } +} diff --git a/src/main/java/com/api/todo/entities/Task.java b/src/main/java/com/api/todo/entities/Task.java new file mode 100644 index 000000000..dc7ab2def --- /dev/null +++ b/src/main/java/com/api/todo/entities/Task.java @@ -0,0 +1,101 @@ +package com.api.todo.entities; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import com.api.todo.request.RequestTaskEntity; + +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@NoArgsConstructor +@Data +@Table(name = "task") +public class Task { + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @NotEmpty + @Size(max = 50, message = "Title should have maximum 50 characters") + private String title; + + @NotEmpty + @Size(max = 250, message = "Description should have maximum 250 characters") + private String description; + + @NotNull(message="User id is not empty") + @Column(name = "user_id") + private long userId; + + @Column(name = "created_date") + private Date createdDate; + + @Column(name = "updated_date") + private Date updatedDate; + + public Task() {} + public Task(@Valid RequestTaskEntity requestTaskEntity) { + this.title = requestTaskEntity.getTitle(); + this.description = requestTaskEntity.getDescription(); + this.userId = requestTaskEntity.getUserId(); + this.createdDate = new Date(); + this.updatedDate = new Date(); + } + public Task(String title, String description, long userId) { + this.title = title; + this.description = description; + this.userId = userId; + this.createdDate = new Date(); + this.updatedDate = new Date(); + } + public long getId() { + return id; + } + public void setId(long id) { + this.id = id; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public long getUserId() { + return userId; + } + public void setUserId(long userId) { + this.userId = userId; + } + public Date getCreatedDate() { + return createdDate; + } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + public Date getUpdatedDate() { + return updatedDate; + } + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } + +} \ No newline at end of file diff --git a/src/main/java/com/api/todo/entities/User.java b/src/main/java/com/api/todo/entities/User.java new file mode 100644 index 000000000..0cb61d1e8 --- /dev/null +++ b/src/main/java/com/api/todo/entities/User.java @@ -0,0 +1,64 @@ +package com.api.todo.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotEmpty; + +import lombok.Builder; +import lombok.NoArgsConstructor; + +@Entity +@NoArgsConstructor +@Table(name = "user") +@Builder +public class User { + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @NotEmpty + private String name; + + @Column(name="limit_tasks_per_day") + private int limitTasksPerDay; + + public User(){} + public User(long id, String name, int limitTasksPerDay) { + this.id = id; + this.name = name; + this.limitTasksPerDay = limitTasksPerDay; + } + public User(String name, int limitTasksPerDay) { + this.name = name; + this.limitTasksPerDay = limitTasksPerDay; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public int getLimitTasksPerDay() { + return limitTasksPerDay; + } + + public void setLimitTasksPerDay(int limitTasksPerDay) { + this.limitTasksPerDay = limitTasksPerDay; + } +} \ No newline at end of file diff --git a/src/main/java/com/api/todo/exceptions/ErrorDetails.java b/src/main/java/com/api/todo/exceptions/ErrorDetails.java new file mode 100644 index 000000000..9ac4f8681 --- /dev/null +++ b/src/main/java/com/api/todo/exceptions/ErrorDetails.java @@ -0,0 +1,28 @@ +package com.api.todo.exceptions; + +import java.util.Date; + +public class ErrorDetails { + private Date timestamp; + private String message; + private String details; + + public ErrorDetails(Date timestamp, String message, String details) { + super(); + this.timestamp = timestamp; + this.message = message; + this.details = details; + } + + public Date getTimestamp() { + return timestamp; + } + + public String getMessage() { + return message; + } + + public String getDetails() { + return details; + } +} diff --git a/src/main/java/com/api/todo/exceptions/ResourceNotFoundException.java b/src/main/java/com/api/todo/exceptions/ResourceNotFoundException.java new file mode 100644 index 000000000..a71621cb3 --- /dev/null +++ b/src/main/java/com/api/todo/exceptions/ResourceNotFoundException.java @@ -0,0 +1,14 @@ +package com.api.todo.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends Exception{ + + private static final long serialVersionUID = 1L; + + public ResourceNotFoundException(String message){ + super(message); + } +} diff --git a/src/main/java/com/api/todo/repositories/TaskRepository.java b/src/main/java/com/api/todo/repositories/TaskRepository.java new file mode 100644 index 000000000..ca1d75f82 --- /dev/null +++ b/src/main/java/com/api/todo/repositories/TaskRepository.java @@ -0,0 +1,14 @@ +package com.api.todo.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.api.todo.entities.Task; + +@Repository +public interface TaskRepository extends JpaRepository { + @Query(value = "SELECT COUNT(t.id) FROM task t WHERE t.user_id=:user_id and DATE(t.created_date)=:created_date", nativeQuery = true) + int getCountTaskOfUser(@Param("user_id") long userId, @Param("created_date") String createdDate); +} diff --git a/src/main/java/com/api/todo/repositories/UserRepository.java b/src/main/java/com/api/todo/repositories/UserRepository.java new file mode 100644 index 000000000..c1ec2282b --- /dev/null +++ b/src/main/java/com/api/todo/repositories/UserRepository.java @@ -0,0 +1,10 @@ +package com.api.todo.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.api.todo.entities.User; + +@Repository +public interface UserRepository extends JpaRepository {} + diff --git a/src/main/java/com/api/todo/request/RequestTaskEntity.java b/src/main/java/com/api/todo/request/RequestTaskEntity.java new file mode 100644 index 000000000..6d0cd6b2f --- /dev/null +++ b/src/main/java/com/api/todo/request/RequestTaskEntity.java @@ -0,0 +1,39 @@ +package com.api.todo.request; + +import java.io.Serializable; + +import lombok.Builder; + +@Builder +public class RequestTaskEntity implements Serializable { + private static final long serialVersionUID = 1L; + + private String title; + private String description; + private long userId; + + public RequestTaskEntity() {} + public RequestTaskEntity(String title, String description, long userId) { + this.title = title; + this.description = description; + this.userId = userId; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public long getUserId() { + return userId; + } + public void setUserId(long userId) { + this.userId = userId; + } +} diff --git a/src/main/java/com/api/todo/response/ApiError.java b/src/main/java/com/api/todo/response/ApiError.java new file mode 100644 index 000000000..0b72e8f6f --- /dev/null +++ b/src/main/java/com/api/todo/response/ApiError.java @@ -0,0 +1,41 @@ +package com.api.todo.response; + +import java.io.Serializable; +import java.util.List; +import org.springframework.http.HttpStatus; +import lombok.Getter; +import lombok.Setter; +@Getter +@Setter +public class ApiError implements Serializable { + private static final long serialVersionUID = 1L; + private HttpStatus status; + private String error; + private Integer count; + private List errors; + + public HttpStatus getStatus() { + return status; + } + public void setStatus(HttpStatus status) { + this.status = status; + } + public String getError() { + return error; + } + public void setError(String error) { + this.error = error; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + public List getErrors() { + return errors; + } + public void setErrors(List errors) { + this.errors = errors; + } +} diff --git a/src/main/java/com/api/todo/services/TodoService.java b/src/main/java/com/api/todo/services/TodoService.java new file mode 100644 index 000000000..1d9757261 --- /dev/null +++ b/src/main/java/com/api/todo/services/TodoService.java @@ -0,0 +1,26 @@ +package com.api.todo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.api.todo.entities.Task; +import com.api.todo.repositories.TaskRepository; + +@Service +public class TodoService { + @Autowired + private TaskRepository taskRepository; + + public TodoService() {} + public TodoService(TaskRepository taskRepository) { + this.taskRepository = taskRepository; + } + + public Task createTask(Task task) { + return taskRepository.save(task); + } + + public int countTaskOfOneUser(long user_id, String createdDate) { + return taskRepository.getCountTaskOfUser(user_id, createdDate); + } +} diff --git a/src/main/java/com/api/todo/services/UserService.java b/src/main/java/com/api/todo/services/UserService.java new file mode 100644 index 000000000..9b328027f --- /dev/null +++ b/src/main/java/com/api/todo/services/UserService.java @@ -0,0 +1,30 @@ +package com.api.todo.services; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.api.todo.entities.User; +import com.api.todo.repositories.UserRepository; + +@Service +public class UserService { + @Autowired + private UserRepository userRepository; + + public UserService() {} + public User createUser(User user) { + return userRepository.save(user); + } + + public Optional findById(long id) { + return userRepository.findById(id); + } + + + public int getLimitTaskOfUser(long userId) { + Optional userRepo = userRepository.findById(userId); + return userRepo.isPresent() ? userRepo.get().getLimitTasksPerDay() : 0; + } +} diff --git a/src/main/java/com/api/todo/validators/TaskValidator.java b/src/main/java/com/api/todo/validators/TaskValidator.java new file mode 100644 index 000000000..3b46f2b3b --- /dev/null +++ b/src/main/java/com/api/todo/validators/TaskValidator.java @@ -0,0 +1,103 @@ +package com.api.todo.validators; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.api.todo.entities.User; +import com.api.todo.request.RequestTaskEntity; +import com.api.todo.services.TodoService; +import com.api.todo.services.UserService; + +@Component +public class TaskValidator implements Validator { + @Autowired + private MessageSource messageSource; + @Autowired + private UserService userService; + @Autowired + private TodoService todoService; + + public TaskValidator() {} + @Override + public boolean supports(Class clazz) { + return RequestTaskEntity.class.equals(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + RequestTaskEntity taskEntity = (RequestTaskEntity) target; + + // check empty + checkEmptyAndNegative(errors, taskEntity); + + // check max length + checkMaxLength(errors, taskEntity); + + // check userId existed or not + checkUserIdExistOrNot(taskEntity.getUserId(), errors); + + // check limit tasks of user + checkLimitTasksOfUser(taskEntity.getUserId(), errors); + } + + private void checkEmptyAndNegative(Errors errors, RequestTaskEntity taskEntity) { + ValidationUtils.rejectIfEmpty(errors, "title", + messageSource.getMessage("task.title.error", null, Locale.getDefault())); + ValidationUtils.rejectIfEmpty(errors, "description", + messageSource.getMessage("task.description.error", null, Locale.getDefault())); + + // check negative number + if (taskEntity.getUserId() <= 0) { + errors.rejectValue("userId", messageSource.getMessage("task.userId.error", null, Locale.getDefault()), + "User ID should be greater than zero"); + } + } + + private void checkMaxLength(Errors errors, RequestTaskEntity taskEntity) { + if (taskEntity.getTitle() != null && !taskEntity.getTitle().isEmpty() && taskEntity.getTitle().length() > 50) { + errors.rejectValue("title", messageSource.getMessage("task.title.maxlength", null, Locale.getDefault()), + "Title should be smaller than 50 characters"); + } + + if (taskEntity.getDescription() != null && !taskEntity.getDescription().isEmpty() + && taskEntity.getDescription().length() > 250) { + errors.rejectValue("description", + messageSource.getMessage("task.description.maxlength", null, Locale.getDefault()), + "Title should be smaller than 250 characters"); + } + } + + private void checkUserIdExistOrNot(long userId, Errors errors) { + if (!userService.findById(userId).isPresent()) { + errors.rejectValue("userId", messageSource.getMessage("task.userId.not_existed", null, Locale.getDefault()), + "userId field should be existed in table user"); + } + } + + private void checkLimitTasksOfUser(long userId, Errors errors) { + Optional user = userService.findById(userId); + if (!user.isPresent()) { + return; + } + + LocalDateTime ldt = LocalDateTime.now(); + System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt)); + int numTaskPerDay = todoService.countTaskOfOneUser(userId, + DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt)); + if (user.get().getLimitTasksPerDay() == 0 + || (user.get().getLimitTasksPerDay() > 0 && numTaskPerDay >= user.get().getLimitTasksPerDay())) { + errors.rejectValue("userId", messageSource.getMessage("task.userId.reject_task", null, Locale.getDefault()), + "userId field enough task"); + } + + } +} \ 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 000000000..4c278075d --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,10 @@ +server.port = 9090 +#jdbc:mysql://localhost:3306/db?allowPublicKeyRetrieval=true&useSSL=false + +spring.datasource.url = jdbc:mysql://localhost:3306/todos?allowPublicKeyRetrieval=true&useSSL=false +spring.datasource.username = root +spring.datasource.password = root123@ +spring.jpa.hibernate.ddl-auto = update +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect + + diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties new file mode 100644 index 000000000..604792b80 --- /dev/null +++ b/src/main/resources/messages.properties @@ -0,0 +1,7 @@ +task.title.error= title field can't be empty. +task.description.error= description field can't be empty. +task.title.maxlength= title field has max length is 50. +task.description.maxlength= description field has max length is 250. +task.userId.error= userId should not be empty or negative number. +task.userId.not_existed= userId field should be existed in table user. +task.userId.reject_task= userId field has be enough tasks per day. \ No newline at end of file diff --git a/src/main/resources/sql/create_tables_data.sql b/src/main/resources/sql/create_tables_data.sql new file mode 100644 index 000000000..7f099f942 --- /dev/null +++ b/src/main/resources/sql/create_tables_data.sql @@ -0,0 +1,21 @@ +CREATE TABLE user ( + id int NOT NULL AUTO_INCREMENT, + name varchar(255) NOT NULL, + limit_tasks_per_day int(11), + PRIMARY KEY (id) +); + + +CREATE TABLE task ( + id int NOT NULL AUTO_INCREMENT, + description varchar(250) NOT NULL, + title varchar(50) NOT NULL, + user_id int, + created_date Datetime, + updated_date Datetime, + PRIMARY KEY (id), + FOREIGN KEY (user_id) REFERENCES user(id) +); + +insert into `user` (name, limit_tasks_per_day) +values ("userA", 2), ("userB", 5) \ No newline at end of file diff --git a/src/test/java/com/api/todo/TodoApplicationTests.java b/src/test/java/com/api/todo/TodoApplicationTests.java new file mode 100644 index 000000000..b81e3edb5 --- /dev/null +++ b/src/test/java/com/api/todo/TodoApplicationTests.java @@ -0,0 +1,13 @@ +package com.api.todo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TodoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/api/todo/controllers/TodoControllerITests.java b/src/test/java/com/api/todo/controllers/TodoControllerITests.java new file mode 100644 index 000000000..054a57e49 --- /dev/null +++ b/src/test/java/com/api/todo/controllers/TodoControllerITests.java @@ -0,0 +1,91 @@ +package com.api.todo.controllers; + +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; + +import com.api.todo.entities.User; +import com.api.todo.repositories.TaskRepository; +import com.api.todo.repositories.UserRepository; +import com.api.todo.request.RequestTaskEntity; +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +public class TodoControllerITests { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + @Autowired + private TaskRepository taskRepository; + + @Autowired + private ObjectMapper objectMapper; + + private User userSaved; + + @BeforeEach + void setup(){ + // give + User user = new User("User A Test", 4); + userSaved = userRepository.save(user); + } + @AfterEach + void tearDown(){ + // clean + taskRepository.deleteAll(); + userRepository.deleteAll(); + } + + @Test + public void givenEmployeeObject_whenCreateTask_thenReturnSavedTask() throws Exception{ + + RequestTaskEntity requestTask = new RequestTaskEntity("title_test", "description_test", userSaved.getId()); + + // when - action or behavior that we are going test + ResultActions response = mockMvc.perform(post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestTask))); + + // then - verify the result or output using assert statements + response.andDo(print()). + andExpect(status().isCreated()) + .andExpect(jsonPath("$.title", + is(requestTask.getTitle()))) + .andExpect(jsonPath("$.description", + is(requestTask.getDescription()))) + .andExpect(jsonPath("$.userId", + is(Integer.parseInt(""+requestTask.getUserId())))); + + } + + @Test + public void givenEmployeeObject_whenCreateTask_thenReturn404() throws Exception{ + + RequestTaskEntity requestTask = new RequestTaskEntity("title_test", "description_test", userSaved.getId()); + + // when - action or behaviour that we are going test + ResultActions response = mockMvc.perform(post("/api/todo/task") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestTask))); + + // then - verify the result or output using assert statements + response.andExpect(status().isNotFound()).andDo(print()); + + } +} diff --git a/src/test/java/com/api/todo/controllers/TodoControllerTest.java b/src/test/java/com/api/todo/controllers/TodoControllerTest.java new file mode 100644 index 000000000..014b627f5 --- /dev/null +++ b/src/test/java/com/api/todo/controllers/TodoControllerTest.java @@ -0,0 +1,115 @@ +package com.api.todo.controllers; + +import static org.hamcrest.CoreMatchers.hasItem; +//import static org.hamcrest.Matchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.api.todo.request.RequestTaskEntity; +import com.api.todo.services.TodoService; +import com.api.todo.services.UserService; +import com.api.todo.validators.TaskValidator; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@WebMvcTest(TodoController.class) +public class TodoControllerTest { + @Autowired + MockMvc mockMvc; + @Autowired + ObjectMapper mapper; + @MockBean + TodoService todoService; + @MockBean + UserService userService; + @SpyBean + TaskValidator taskValidator; + + @Test + public void createTask_failed_with_title_is_empty() throws Exception { + RequestTaskEntity requestTask = new RequestTaskEntity("", "description_test", 123); + + MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) + .content(this.mapper.writeValueAsString(requestTask)); + + mockMvc.perform(mockRequest).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors").isArray()) + .andExpect(jsonPath("$.errors", hasItem("title field can't be empty."))); + } + + @Test + public void createTask_failed_with_description_is_empty() throws Exception { + RequestTaskEntity requestTask = new RequestTaskEntity("title", "", 123); + + MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) + .content(this.mapper.writeValueAsString(requestTask)); + + mockMvc.perform(mockRequest).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors").isArray()) + .andExpect(jsonPath("$.errors", hasItem("description field can't be empty."))); + } + + @Test + public void createTask_failed_with_user_is_negative_number() throws Exception { + RequestTaskEntity requestTask = new RequestTaskEntity("title", "fdsf", -123); + + MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) + .content(this.mapper.writeValueAsString(requestTask)); + + mockMvc.perform(mockRequest).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors").isArray()) + .andExpect(jsonPath("$.errors", hasItem("userId should not be empty or negative number."))); + } + + @Test + public void createTask_failed_with_user_is_not_existed() throws Exception { + RequestTaskEntity requestTask = new RequestTaskEntity("title", "fdsf", 12338173872187382L); + + MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) + .content(this.mapper.writeValueAsString(requestTask)); + + mockMvc.perform(mockRequest).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors").isArray()) + .andExpect(jsonPath("$.errors", hasItem("userId field should be existed in table user."))); + } + + @Test + public void createTask_failed_with_title_is_maxlength_50() throws Exception { + RequestTaskEntity requestTask = new RequestTaskEntity( + "title title title titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle titletitle title", + "description_test", 123); + + MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) + .content(this.mapper.writeValueAsString(requestTask)); + + mockMvc.perform(mockRequest).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors").isArray()) + .andExpect(jsonPath("$.errors", hasItem("title field has max length is 50."))); + } + + @Test + public void createTask_failed_with_description_is_maxlength_250() throws Exception { + RequestTaskEntity requestTask = new RequestTaskEntity("title", + "description_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_testdescription_test", + 123); + + MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/todo/tasks") + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) + .content(this.mapper.writeValueAsString(requestTask)); + + mockMvc.perform(mockRequest).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors").isArray()) + .andExpect(jsonPath("$.errors", hasItem("description field has max length is 250."))); + } +} diff --git a/src/test/java/com/api/todo/services/TodoServiceTest.java b/src/test/java/com/api/todo/services/TodoServiceTest.java new file mode 100644 index 000000000..77af82025 --- /dev/null +++ b/src/test/java/com/api/todo/services/TodoServiceTest.java @@ -0,0 +1,74 @@ +package com.api.todo.services; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.api.todo.entities.Task; +import com.api.todo.entities.User; +import com.api.todo.repositories.TaskRepository; +import com.api.todo.repositories.UserRepository; + +@SpringBootTest +public class TodoServiceTest { + @Autowired + private TaskRepository taskRepository; + @Autowired + private UserRepository userRepository; + @Autowired + private TodoService todoService; + private User userSaved; + + @BeforeEach + void setInitial() { + User user = new User("User A Test", 4); + userSaved = userRepository.save(user); + } + + @AfterEach + void cleanInitial() { + taskRepository.deleteAll(); + System.out.println("Deleted all data of task table"); + userRepository.deleteAll(); + System.out.println("Deleted all data of user table"); + } + + @DisplayName("Create task success") + @Test + void createTask_success() { + Task task = new Task("title", "description", userSaved.getId()); + + Task task_result = todoService.createTask(task); + + assertThat(task_result.getTitle()).isEqualTo(task.getTitle()); + assertThat(task_result.getDescription()).isEqualTo(task.getDescription()); + assertThat(task_result.getUserId()).isEqualTo(task.getUserId()); + } + + @DisplayName("Count tasks of user") + @Test + void countTaskOfOneUser_return_right() { + LocalDate dateObj = LocalDate.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String currentDate = dateObj.format(formatter); + + Task task = new Task("title", "description", userSaved.getId()); + Task task1 = new Task("title1", "description", userSaved.getId()); + Task task2 = new Task("title2", "description", userSaved.getId()); + + todoService.createTask(task); + todoService.createTask(task1); + todoService.createTask(task2); + int count = todoService.countTaskOfOneUser(userSaved.getId(), currentDate); + + assertThat(count).isEqualTo(3); + } +} diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 000000000..15b2f4ee1 --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url = jdbc:mysql://localhost:3306/todos_test?allowPublicKeyRetrieval=true&useSSL=false +spring.datasource.username = root +spring.datasource.password = root123@ +spring.jpa.hibernate.ddl-auto = update +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect