diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed 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. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a 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 0000000..ffdc10e --- /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.1/apache-maven-3.8.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/README.md b/README.md new file mode 100644 index 0000000..393ee50 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# TracMobility Backend Assignment + +An RESTful API for the software assessment. It is build with Java, and Spring Boot. For testing the application I used Junit 5, Mockito and AssertJ. + +### Requirements + +You have been tasked with building part of a simple vehicle system that allows +customers to borrow vehicles. Your code should provide the following functionality: +* List all available vehicles. +* Borrow and return vehicle. + +## Design + +For the development of the architecture I have used a concept of OOP and SOLID principles. By following these concepts +I wanted to achieve strong encapsulation and improve the maintainability and extensibility of the project. + +I designed the application to consist of five modules: + +* Controllers +* Services +* Repositories +* Models +* Exceptions - this module consist only of the custom exception classes. + +### Controllers + +The controller class is created in a way to keep it simple and without any complicated logic. That way, +the controller class is only responsible for receiving the request and passing it to the service, where all the business logic happen. + +In the same package, there is a separate class designed specifically for error handling. By this class, I handle custom errors +for Service and Repository layers. + +### Models + +During the designing of the models, I tried to keep strong encapsulation. +By moving all classes related to the Vehicle into a separate package and declare all instance variables of the Vehicle class as default, I was able to +expose only minimum information outside the package. + +To communicate outside the API there are separate DTO classes. DTO classes contains only minimum information related to the request and +have timestamped of the specific action performed on the vehicle. To accomplish requirements, I created only DTO for renting, returning and listing vehicles. + +### Repositories + +One of the requirement is not to use JDBC. To meet this requirement I created VehicleRepository class with instance Variable of type +List to mimic the database. Inside the class, I implemented only methods necessary to achieve assessment requirements. + +###Services + +The only service used in the application is VehicleService class. The service contains all the logic to manipulate the vehicle object. + +##Test +To test my application, I created interface Fixtures under package named fixtures with valid data for tests. + +## Steps to Setup + +**1. Clone the application** + +```bash +git clone https://github.com/KonarzewskiP/backend-assignment-1.git +``` + +**2. Run the app using maven** + +```bash +mvn spring-boot:run +``` +The app will start running at . You can test it in Postman at . +To be able to test it in Postman, you have to uncomment the hardcoded data in the VehicleRepository class. diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/mvnw @@ -0,0 +1,322 @@ +#!/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 /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="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.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" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$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 \ + -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 0000000..c8d4337 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,182 @@ +@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 "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.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 "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..92aef98 --- /dev/null +++ b/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + konarzewski + tracmobility + 0.0.1 + tracmobility + Backend Assignment + + + 15 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.4.1 + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/konarzewski/tracmobility/TracmobilityApplication.java b/src/main/java/konarzewski/tracmobility/TracmobilityApplication.java new file mode 100644 index 0000000..1e26abe --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/TracmobilityApplication.java @@ -0,0 +1,13 @@ +package konarzewski.tracmobility; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TracmobilityApplication { + + public static void main(String[] args) { + SpringApplication.run(TracmobilityApplication.class, args); + } + +} diff --git a/src/main/java/konarzewski/tracmobility/controllers/VehicleController.java b/src/main/java/konarzewski/tracmobility/controllers/VehicleController.java new file mode 100644 index 0000000..eecf140 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/controllers/VehicleController.java @@ -0,0 +1,75 @@ +package konarzewski.tracmobility.controllers; + +import konarzewski.tracmobility.models.general.dto.ResponseDataDto; +import konarzewski.tracmobility.models.vehicle.dto.BorrowVehicleResponseDto; +import konarzewski.tracmobility.models.vehicle.dto.GetVehicleDto; +import konarzewski.tracmobility.models.vehicle.dto.ReturnVehicleResponseDto; +import konarzewski.tracmobility.services.VehicleService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * RestController that creates service end-points related to the vehicle. + * + * @author Pawel Konarzewski + */ + +@RestController +@RequestMapping("/vehicles") +@RequiredArgsConstructor +public class VehicleController { + + private final VehicleService vehicleService; + + /** + * The method that searches for all vehicles available to use. + * + * @return ResponseDataDto object with list of available vehicles and + * Http status code 200 - ok. + */ + + @GetMapping("/available") + public ResponseDataDto> getAllAvailableVehicles() { + + return ResponseDataDto. + >builder() + .data(vehicleService.findAvailableVehicles()) + .build(); + } + + /** + * The method used to borrow the vehicle. + * It finds the vehicle by QR-code and changes its status to RUNNING. + * + * @return ResponseDataDto object with list of available vehicles and + * Http status code 200 - ok. + */ + + @PatchMapping("/borrow/{qrCode}") + public ResponseDataDto borrowVehicle(@PathVariable String qrCode) { + + return ResponseDataDto. + builder() + .data(vehicleService.borrowVehicle(qrCode)) + .build(); + } + + /** + * The method used to return the vehicle. + * It finds the vehicle by QR-code and changes its status to AVAILABLE. + * + * @return ResponseDataDto object with list of available vehicles and + * Http status code 200 - ok. + */ + + @PatchMapping("/return/{qrCode}") + public ResponseDataDto returnVehicle(@PathVariable String qrCode) { + + return ResponseDataDto. + builder() + .data(vehicleService.returnVehicle(qrCode)) + .build(); + } +} diff --git a/src/main/java/konarzewski/tracmobility/controllers/handlers/ErrorControllerHandler.java b/src/main/java/konarzewski/tracmobility/controllers/handlers/ErrorControllerHandler.java new file mode 100644 index 0000000..dc2b8f2 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/controllers/handlers/ErrorControllerHandler.java @@ -0,0 +1,74 @@ +package konarzewski.tracmobility.controllers.handlers; + +import konarzewski.tracmobility.exceptions.VehicleNotFoundException; +import konarzewski.tracmobility.exceptions.VehicleRepositoryException; +import konarzewski.tracmobility.exceptions.VehicleServiceException; +import konarzewski.tracmobility.models.general.dto.ResponseErrorDto; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.time.LocalDateTime; + +/** + * Class that implements a handler of exceptions and errors in the API, + * and sending the proper response to the client. + * + * @author Pawel Konarzewski + */ + +@RestControllerAdvice +public class ErrorControllerHandler { + + /** + * Method that handles a VehicleRepositoryException and returns an error with + * status code = 400. + * + * @param exception + * @return ResponseErrorDto + */ + + @ExceptionHandler(value = VehicleRepositoryException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseErrorDto handleVehicleRepositoryException(VehicleRepositoryException exception){ + return ResponseErrorDto.builder() + .timestamp(LocalDateTime.now()) + .errorMsg(exception.getLocalizedMessage()) + .build(); + } + + /** + * Method that handles a VehicleServiceException and returns an error with + * status code = 400. + * + * @param exception + * @return ResponseErrorDto + */ + + @ExceptionHandler(value = VehicleServiceException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseErrorDto handleVehicleServiceException(VehicleServiceException exception){ + return ResponseErrorDto.builder() + .timestamp(LocalDateTime.now()) + .errorMsg(exception.getLocalizedMessage()) + .build(); + } + + /** + * Method that handles a VehicleNotFoundException and returns an error with + * status code = 404. + * + * @param exception + * @return ResponseErrorDto + */ + + @ExceptionHandler(value = VehicleNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseErrorDto handleVehicleNotFoundException(VehicleNotFoundException exception){ + return ResponseErrorDto.builder() + .timestamp(LocalDateTime.now()) + .errorMsg(exception.getLocalizedMessage()) + .build(); + } +} diff --git a/src/main/java/konarzewski/tracmobility/exceptions/VehicleNotFoundException.java b/src/main/java/konarzewski/tracmobility/exceptions/VehicleNotFoundException.java new file mode 100644 index 0000000..6c8c7f9 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/exceptions/VehicleNotFoundException.java @@ -0,0 +1,12 @@ +package konarzewski.tracmobility.exceptions; + +/** + * Class that implements VehicleNotFoundException in the API + * + * @author Pawel Konarzewski + */ +public class VehicleNotFoundException extends RuntimeException{ + public VehicleNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/konarzewski/tracmobility/exceptions/VehicleRepositoryException.java b/src/main/java/konarzewski/tracmobility/exceptions/VehicleRepositoryException.java new file mode 100644 index 0000000..d6bda21 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/exceptions/VehicleRepositoryException.java @@ -0,0 +1,13 @@ +package konarzewski.tracmobility.exceptions; + +/** + * Class that implements VehicleRepositoryException in the API + * + * @author Pawel Konarzewski + */ + +public class VehicleRepositoryException extends RuntimeException { + public VehicleRepositoryException(String message) { + super(message); + } +} diff --git a/src/main/java/konarzewski/tracmobility/exceptions/VehicleServiceException.java b/src/main/java/konarzewski/tracmobility/exceptions/VehicleServiceException.java new file mode 100644 index 0000000..bc551d8 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/exceptions/VehicleServiceException.java @@ -0,0 +1,13 @@ +package konarzewski.tracmobility.exceptions; + +/** + * Class that implements VehicleServiceException in the API + * + * @author Pawel Konarzewski + */ + +public class VehicleServiceException extends RuntimeException { + public VehicleServiceException(String message) { + super(message); + } +} diff --git a/src/main/java/konarzewski/tracmobility/models/enums/Status.java b/src/main/java/konarzewski/tracmobility/models/enums/Status.java new file mode 100644 index 0000000..8baf862 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/enums/Status.java @@ -0,0 +1,21 @@ +package konarzewski.tracmobility.models.enums; + +import lombok.Getter; + +/** + * Enum that classifies the vehicle status in the API. + * + * @author Pawel Konarzewski + */ +@Getter +public enum Status { + AVAILABLE("AVAILABLE"), + RUNNING("RUNNING"), + REPAIRING("REPAIRING"); + + private final String status; + + Status(String status) { + this.status = status; + } +} diff --git a/src/main/java/konarzewski/tracmobility/models/enums/Type.java b/src/main/java/konarzewski/tracmobility/models/enums/Type.java new file mode 100644 index 0000000..ab2c7fb --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/enums/Type.java @@ -0,0 +1,22 @@ +package konarzewski.tracmobility.models.enums; + +import lombok.Getter; + +/** + * Enum that classifies the vehicle type in the API. + * + * @author Pawel Konarzewski + */ + +@Getter +public enum Type { + SCOOTER("SCOOTER"), + BIKE("BIKE"), + E_BIKE("E-BIKE"); + + private final String type; + + Type(String type) { + this.type = type; + } +} diff --git a/src/main/java/konarzewski/tracmobility/models/general/dto/ResponseDataDto.java b/src/main/java/konarzewski/tracmobility/models/general/dto/ResponseDataDto.java new file mode 100644 index 0000000..f0ea334 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/general/dto/ResponseDataDto.java @@ -0,0 +1,17 @@ +package konarzewski.tracmobility.models.general.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +/** + * Class that implements a generic response to the API end-points. + * + * @author Pawel Konarzewski + * */ +@Data +@AllArgsConstructor +@Builder +public class ResponseDataDto { + private T data; +} diff --git a/src/main/java/konarzewski/tracmobility/models/general/dto/ResponseErrorDto.java b/src/main/java/konarzewski/tracmobility/models/general/dto/ResponseErrorDto.java new file mode 100644 index 0000000..d7c40e1 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/general/dto/ResponseErrorDto.java @@ -0,0 +1,25 @@ +package konarzewski.tracmobility.models.general.dto; + + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * Class that implements a generic response error object to the API end-points. + * + * @author Pawel Konarzewski + * */ + +@Data +@AllArgsConstructor +@Builder +public class ResponseErrorDto { + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime timestamp; + private String errorMsg; +} diff --git a/src/main/java/konarzewski/tracmobility/models/vehicle/Vehicle.java b/src/main/java/konarzewski/tracmobility/models/vehicle/Vehicle.java new file mode 100644 index 0000000..e34999c --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/vehicle/Vehicle.java @@ -0,0 +1,114 @@ +package konarzewski.tracmobility.models.vehicle; + +import konarzewski.tracmobility.models.vehicle.dto.BorrowVehicleResponseDto; +import konarzewski.tracmobility.models.vehicle.dto.GetVehicleDto; +import konarzewski.tracmobility.models.vehicle.dto.ReturnVehicleResponseDto; +import konarzewski.tracmobility.models.enums.Type; +import lombok.*; + + +/** + * Class that implements Vehicle structure. + * + * @author Pawel Konarzewski + */ + +@EqualsAndHashCode +@ToString +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class Vehicle { + Long id; + Type type; + String qrCode; + VehicleStatus vehicleStatus; + + /** + * The method to check if vehicle has specific QR code. + * + * @param qrCode - unique code of vehicle + * @return true if vehicle has specific QR code, false otherwise. + */ + + public boolean hasQrCode(String qrCode) { + return this.qrCode.equals(qrCode); + } + + /** + * The method to check Vehicle availability + */ + public boolean isAvailable() { + return vehicleStatus.isAvailable(); + } + + /** + * The method to borrow Vehicle + */ + public void borrowVehicle() { + vehicleStatus.borrowVehicle(); + } + + /** + * The method to return Vehicle + */ + public void returnVehicle() { + vehicleStatus.returnVehicle(); + } + + /** + * The method to return date and time of last status change + */ + public String getLastStatusChanged() { + return vehicleStatus.lastStatusChanged(); + } + + /** + * The method to return actual status of vehicle + */ + public String getActualStatus() { + return vehicleStatus.actualStatus(); + } + + /** + * The method to map Vehicle object to dto response for + * service end-point related to listing all vehicles + */ + + public GetVehicleDto toGetVehicleDto() { + return GetVehicleDto.builder() + .id(id) + .type(type.getType()) + .qrCode(qrCode) + .status(vehicleStatus.status) + .build(); + } + + /** + * The method to map Vehicle object to dto response for + * service end-points related to borrowing vehicle + */ + + public BorrowVehicleResponseDto toBorrowVehicleResponseDto() { + return BorrowVehicleResponseDto + .builder() + .qrCode(qrCode) + .status(vehicleStatus.status) + .build(); + } + + /** + * The method to map Vehicle object to dto response for + * service end-point related to returning vehicle + */ + + public ReturnVehicleResponseDto toReturnVehicleResponseDto() { + return ReturnVehicleResponseDto + .builder() + .qrCode(qrCode) + .status(vehicleStatus.status) + .build(); + } + + +} diff --git a/src/main/java/konarzewski/tracmobility/models/vehicle/VehicleStatus.java b/src/main/java/konarzewski/tracmobility/models/vehicle/VehicleStatus.java new file mode 100644 index 0000000..a5db2fa --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/vehicle/VehicleStatus.java @@ -0,0 +1,63 @@ +package konarzewski.tracmobility.models.vehicle; + +import com.fasterxml.jackson.annotation.JsonFormat; +import konarzewski.tracmobility.models.enums.Status; +import lombok.*; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Class that implements Vehicle status structure. + * + * @author Pawel Konarzewski + */ + +@EqualsAndHashCode +@ToString +@AllArgsConstructor +@Builder +public class VehicleStatus { + + Status status; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") + @Builder.Default + LocalDateTime timeOfLastStatusChange = LocalDateTime.now(); + + /** + * The method to check if Vehicle is available to use + */ + public boolean isAvailable() { + return status == Status.AVAILABLE; + } + + /** + * The method to change Vehicle status to RUNNING + */ + public void borrowVehicle() { + timeOfLastStatusChange = LocalDateTime.now(); + status = Status.RUNNING; + } + + /** + * The method to change Vehicle status to RETURN + */ + public void returnVehicle() { + timeOfLastStatusChange = LocalDateTime.now(); + status = Status.AVAILABLE; + } + + /** + * The method to return date and time of last status change + */ + public String lastStatusChanged() { + return timeOfLastStatusChange.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); + } + + /** + * The method to return actual status of vehicle + */ + public String actualStatus() { + return status.toString(); + } +} diff --git a/src/main/java/konarzewski/tracmobility/models/vehicle/VehicleUtils.java b/src/main/java/konarzewski/tracmobility/models/vehicle/VehicleUtils.java new file mode 100644 index 0000000..75bac59 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/vehicle/VehicleUtils.java @@ -0,0 +1,21 @@ +package konarzewski.tracmobility.models.vehicle; + +import konarzewski.tracmobility.models.enums.Status; + +import java.util.function.Predicate; + +/** + * Class that implements the Vehicle API utility methods + * + * @author Pawel Konarzewski + */ + +public interface VehicleUtils { + + /** + * Functional Interface created to allow filtering Vehicles by + * availability without damaging encapsulation of class Vehicle + */ + + Predicate isAvailable = vehicle -> vehicle.vehicleStatus.status == Status.AVAILABLE; +} diff --git a/src/main/java/konarzewski/tracmobility/models/vehicle/dto/BorrowVehicleResponseDto.java b/src/main/java/konarzewski/tracmobility/models/vehicle/dto/BorrowVehicleResponseDto.java new file mode 100644 index 0000000..4eda1b4 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/vehicle/dto/BorrowVehicleResponseDto.java @@ -0,0 +1,29 @@ +package konarzewski.tracmobility.models.vehicle.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import konarzewski.tracmobility.models.enums.Status; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +/** + * Class that implements response to the API end-point + * related to borrowing vehicle. + * + * @author Pawel Konarzewski + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class BorrowVehicleResponseDto { + + private String qrCode; + private Status status; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") + private final LocalDateTime timeOfBorrowing = LocalDateTime.now(); +} diff --git a/src/main/java/konarzewski/tracmobility/models/vehicle/dto/GetVehicleDto.java b/src/main/java/konarzewski/tracmobility/models/vehicle/dto/GetVehicleDto.java new file mode 100644 index 0000000..5aa1c4d --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/vehicle/dto/GetVehicleDto.java @@ -0,0 +1,24 @@ +package konarzewski.tracmobility.models.vehicle.dto; + +import konarzewski.tracmobility.models.enums.Status; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +/** + * Class that implements response to the API end-point + * related to listing vehicles + * + * @author Pawel Konarzewski + * + */ + +@Data +@AllArgsConstructor +@Builder +public class GetVehicleDto { + Long id; + String type; + String qrCode; + Status status; +} diff --git a/src/main/java/konarzewski/tracmobility/models/vehicle/dto/ReturnVehicleResponseDto.java b/src/main/java/konarzewski/tracmobility/models/vehicle/dto/ReturnVehicleResponseDto.java new file mode 100644 index 0000000..e5aa780 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/models/vehicle/dto/ReturnVehicleResponseDto.java @@ -0,0 +1,30 @@ +package konarzewski.tracmobility.models.vehicle.dto; + + +import com.fasterxml.jackson.annotation.JsonFormat; +import konarzewski.tracmobility.models.enums.Status; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +/** + * Class that implements response to the API end-point + * related to returning vehicle. + * + * @author Pawel Konarzewski + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ReturnVehicleResponseDto { + + private String qrCode; + private Status status; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") + private final LocalDateTime timeOfReturn = LocalDateTime.now(); +} diff --git a/src/main/java/konarzewski/tracmobility/repository/VehicleRepository.java b/src/main/java/konarzewski/tracmobility/repository/VehicleRepository.java new file mode 100644 index 0000000..acf1943 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/repository/VehicleRepository.java @@ -0,0 +1,122 @@ +package konarzewski.tracmobility.repository; + +import konarzewski.tracmobility.exceptions.VehicleRepositoryException; +import konarzewski.tracmobility.models.vehicle.Vehicle; +import konarzewski.tracmobility.models.vehicle.VehicleStatus; +import konarzewski.tracmobility.models.vehicle.VehicleUtils; +import konarzewski.tracmobility.models.enums.Status; +import konarzewski.tracmobility.models.enums.Type; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Class that implements basic methods related to Vehicle Repository + * + * @author Pawel Konarzewski + */ + +@Repository +public class VehicleRepository { + + private final List vehicles = new ArrayList<>(); + + public VehicleRepository() { + /* vehicles.add(Vehicle.builder() + .id(1L) + .type(Type.SCOOTER) + .qrCode("QR_0001") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build()); + vehicles.add(Vehicle.builder() + .id(2L) + .type(Type.SCOOTER) + .qrCode("QR_0002") + .vehicleStatus(VehicleStatus.builder() + .status(Status.RUNNING) + .build()) + .build()); + vehicles.add(Vehicle.builder() + .id(3L) + .type(Type.SCOOTER) + .qrCode("QR_0003") + .vehicleStatus(VehicleStatus.builder() + .status(Status.REPAIRING) + .build()) + .build()); + vehicles.add(Vehicle.builder() + .id(4L) + .type(Type.BIKE) + .qrCode("QR_0004") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build()); + vehicles.add(Vehicle.builder() + .id(5L) + .type(Type.E_BIKE) + .qrCode("QR_0005") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build()); + vehicles.add(Vehicle.builder() + .id(6L) + .type(Type.SCOOTER) + .qrCode("QR_0006") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build());*/ + } + + /** + * The method that searches through all vehicles and finds + * only vehicles which are available to use. + * + * @return list of all vehicles with Status.AVAILABLE + */ + + public List findAvailableVehicles() { + return vehicles + .stream() + .filter(VehicleUtils.isAvailable) + .collect(Collectors.toList()); + } + + /** + * The method that searches through all vehicles and finds + * vehicle with specific QR-code + * + * @param qrCode QR-code of the vehicle to be searched for + * @return list of all vehicles with Status.AVAILABLE + */ + + public Optional findByQrCode(String qrCode) { + return vehicles + .stream() + .filter(vehicle -> vehicle.hasQrCode(qrCode)) + .findFirst(); + } + + /** + * The method that add vehicle to list of vehicles + * only vehicles which are available to use. + * + * @param vehicle vehicle object to be saved + * @return returns saved vehicle object + */ + + public Vehicle save(Vehicle vehicle) { + if (vehicle == null) { + throw new VehicleRepositoryException("Vehicle is null"); + } + vehicles.add(vehicle); + return vehicle; + } +} diff --git a/src/main/java/konarzewski/tracmobility/services/VehicleService.java b/src/main/java/konarzewski/tracmobility/services/VehicleService.java new file mode 100644 index 0000000..400d1a9 --- /dev/null +++ b/src/main/java/konarzewski/tracmobility/services/VehicleService.java @@ -0,0 +1,102 @@ +package konarzewski.tracmobility.services; + +import konarzewski.tracmobility.exceptions.VehicleNotFoundException; +import konarzewski.tracmobility.exceptions.VehicleServiceException; +import konarzewski.tracmobility.models.vehicle.Vehicle; +import konarzewski.tracmobility.models.vehicle.dto.BorrowVehicleResponseDto; +import konarzewski.tracmobility.models.vehicle.dto.GetVehicleDto; +import konarzewski.tracmobility.models.vehicle.dto.ReturnVehicleResponseDto; +import konarzewski.tracmobility.repository.VehicleRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Class that implements the vehicle service methods + * + * @author Pawel Konarzewski + */ + +@Service +@RequiredArgsConstructor +public class VehicleService { + + private final VehicleRepository vehicleRepository; + + /** + * The method that searches for all vehicles with status AVAILABLE. + * + * @return list of available vehicles. + * @throws VehicleServiceException if all vehicles are not available. + */ + + public synchronized List findAvailableVehicles() { + var availableVehicles = vehicleRepository + .findAvailableVehicles() + .stream() + .map(Vehicle::toGetVehicleDto) + .collect(Collectors.toList()); + + if (availableVehicles.isEmpty()) { + throw new VehicleServiceException("No available vehicles"); + } + + return availableVehicles; + } + + /** + * The method that borrows a specific vehicle from a repository + * + * @param qrCode QR-code of the vehicle to be searched for + * @return dto of borrowed vehicle with unique QR-code and status RUNNING + * @throws VehicleServiceException if the vehicle is not available to borrow. Include message + * with date and time about last time when the vehicle was used and its QR-code. + */ + + public synchronized BorrowVehicleResponseDto borrowVehicle(String qrCode) { + var vehicle = findVehicleByQrCode(qrCode); + + if (!vehicle.isAvailable()) { + throw new VehicleServiceException( + "Vehicle with QR-code: " + qrCode + ", is not available. " + + "Vehicle status: " + vehicle.getActualStatus() + + ", Last status change: " + vehicle.getLastStatusChanged()); + } + + vehicle.borrowVehicle(); + return vehicleRepository + .save(vehicle) + .toBorrowVehicleResponseDto(); + } + + /** + * The method that returns a specific vehicle back to the repository + * + * @param qrCode QR-code of the vehicle to be searched for + * @return dto of the returned vehicle with unique QR-code and status AVAILABLE + * @throws VehicleNotFoundException if vehicle is not available. + */ + + public synchronized ReturnVehicleResponseDto returnVehicle(String qrCode) { + var vehicle = findVehicleByQrCode(qrCode); + vehicle.returnVehicle(); + vehicleRepository.save(vehicle); + return vehicle.toReturnVehicleResponseDto(); + } + + /** + * The method that searches for a vehicle with a specific QR-code. + * + * @param qrCode QR-code of the vehicle to be searched for + * @return vehicle with a specific QR-code + * @throws VehicleNotFoundException if vehicle is not available. + */ + + private Vehicle findVehicleByQrCode(String qrCode) { + return vehicleRepository + .findByQrCode(qrCode) + .orElseThrow(() -> new VehicleNotFoundException("Can not find vehicle with QR-code: " + qrCode)); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/src/test/java/konarzewski/tracmobility/TracmobilityApplicationTests.java b/src/test/java/konarzewski/tracmobility/TracmobilityApplicationTests.java new file mode 100644 index 0000000..2a914f2 --- /dev/null +++ b/src/test/java/konarzewski/tracmobility/TracmobilityApplicationTests.java @@ -0,0 +1,13 @@ +package konarzewski.tracmobility; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TracmobilityApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/konarzewski/tracmobility/controllers/VehicleControllerTest.java b/src/test/java/konarzewski/tracmobility/controllers/VehicleControllerTest.java new file mode 100644 index 0000000..609379c --- /dev/null +++ b/src/test/java/konarzewski/tracmobility/controllers/VehicleControllerTest.java @@ -0,0 +1,38 @@ +package konarzewski.tracmobility.controllers; + +import org.junit.jupiter.api.DisplayName; +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.test.web.servlet.MockMvc; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Class that implements Vehicle integration tests. + * + * @author Pawel Konarzewski + */ + +@AutoConfigureMockMvc +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class VehicleControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Test + @DisplayName("should trigger 404 status code if can not find QR-code") + void shouldTrigger404StatusCodeIfCanNotFindQrCode() throws Exception { + //given + var qrCode = "QR_0010"; + //when + var mockResult = mockMvc.perform(patch("/vehicles/borrow/" + qrCode)) + .andExpect(status().isNotFound()); + } + + +} \ No newline at end of file diff --git a/src/test/java/konarzewski/tracmobility/fixtures/Fixtures.java b/src/test/java/konarzewski/tracmobility/fixtures/Fixtures.java new file mode 100644 index 0000000..273ae60 --- /dev/null +++ b/src/test/java/konarzewski/tracmobility/fixtures/Fixtures.java @@ -0,0 +1,126 @@ +package konarzewski.tracmobility.fixtures; + +import konarzewski.tracmobility.models.vehicle.Vehicle; +import konarzewski.tracmobility.models.enums.Status; +import konarzewski.tracmobility.models.enums.Type; +import konarzewski.tracmobility.models.vehicle.VehicleStatus; + +import java.time.LocalDateTime; +import java.util.List; + +public interface Fixtures { + + static List createListOfVehicles() { + return List.of( + Vehicle.builder() + .id(1L) + .type(Type.SCOOTER) + .qrCode("QR_0001") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build(), + Vehicle.builder() + .id(2L) + .type(Type.SCOOTER) + .qrCode("QR_0002") + .vehicleStatus(VehicleStatus.builder() + .status(Status.RUNNING) + .build()) + .build(), + Vehicle.builder() + .id(3L) + .type(Type.SCOOTER) + .qrCode("QR_0003") + .vehicleStatus(VehicleStatus.builder() + .status(Status.REPAIRING) + .build()) + .build(), + Vehicle.builder() + .id(4L) + .type(Type.BIKE) + .qrCode("QR_0004") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .timeOfLastStatusChange(LocalDateTime.of(2021,2,20,15,0,0)) + .build()) + .build(), + Vehicle.builder() + .id(5L) + .type(Type.E_BIKE) + .qrCode("QR_0005") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build(), + Vehicle.builder() + .id(6L) + .type(Type.SCOOTER) + .qrCode("QR_0006") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build() + ); + } + + static List createListOfNoAvailableVehicles() { + return List.of( + Vehicle.builder() + .id(1L) + .type(Type.SCOOTER) + .qrCode("QR_0001") + .vehicleStatus(VehicleStatus.builder() + .status(Status.RUNNING) + .build()) + .build(), + Vehicle.builder() + .id(2L) + .type(Type.SCOOTER) + .qrCode("QR_0002") + .vehicleStatus(VehicleStatus.builder() + .status(Status.RUNNING) + .build()) + .build(), + Vehicle.builder() + .id(3L) + .type(Type.SCOOTER) + .qrCode("QR_0003") + .vehicleStatus(VehicleStatus.builder() + .status(Status.REPAIRING) + .build()) + .build() + ); + } + + static List createListOfAvailableVehicles() { + return List.of( + Vehicle.builder() + .id(1L) + .type(Type.SCOOTER) + .qrCode("QR_0001") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build(), + Vehicle.builder() + .id(2L) + .type(Type.SCOOTER) + .qrCode("QR_0002") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build(), + Vehicle.builder() + .id(3L) + .type(Type.SCOOTER) + .qrCode("QR_0003") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .build()) + .build() + ); + } + + +} diff --git a/src/test/java/konarzewski/tracmobility/repository/VehicleRepositoryTest.java b/src/test/java/konarzewski/tracmobility/repository/VehicleRepositoryTest.java new file mode 100644 index 0000000..ee42180 --- /dev/null +++ b/src/test/java/konarzewski/tracmobility/repository/VehicleRepositoryTest.java @@ -0,0 +1,125 @@ +package konarzewski.tracmobility.repository; + +import konarzewski.tracmobility.exceptions.VehicleRepositoryException; +import konarzewski.tracmobility.models.enums.Status; +import konarzewski.tracmobility.models.enums.Type; +import konarzewski.tracmobility.models.vehicle.Vehicle; +import konarzewski.tracmobility.models.vehicle.VehicleStatus; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.util.ReflectionTestUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; + +import static konarzewski.tracmobility.fixtures.Fixtures.createListOfNoAvailableVehicles; +import static konarzewski.tracmobility.fixtures.Fixtures.createListOfVehicles; +import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertAll; + + +@ExtendWith(SpringExtension.class) +class VehicleRepositoryTest { + + @InjectMocks + private VehicleRepository vehicleRepository; + + @BeforeEach + public void setUp(){ + ReflectionTestUtils.setField(vehicleRepository, "vehicles", createListOfVehicles()); + } + + @Test + @DisplayName("should return all available vehicles") + void shouldReturnAllAvailableVehicles() { + //given + //when + var result = vehicleRepository.findAvailableVehicles(); + //then + assertThat(result.size()).isEqualTo(4); + } + + @Test + @DisplayName("should return empty list if no available vehicles") + void shouldReturnEmptyListIfNoAvailableVehicles() { + ReflectionTestUtils.setField(vehicleRepository, "vehicles", createListOfNoAvailableVehicles()); + //when + var result = vehicleRepository.findAvailableVehicles(); + //then + assertThat(result.size()).isEqualTo(0); + } + + @Test + @DisplayName("should find vehicle by QR-code") + void shouldFindVehicleByQrCode() { + //given + var qrCode = "QR_0004"; + var vehicle = Vehicle.builder() + .id(4L) + .type(Type.BIKE) + .qrCode("QR_0004") + .vehicleStatus(VehicleStatus.builder() + .status(Status.AVAILABLE) + .timeOfLastStatusChange(LocalDateTime.of(2021, 2, 20, 15, 0, 0)) + .build()) + .build(); + //when + var result = vehicleRepository.findByQrCode(qrCode); + //then + assertAll( + () -> assertThat(result).isNotEmpty(), + () -> assertThat(result).hasValue(vehicle) + ); + } + + + @Test + @DisplayName("should return empty Optional if can not find vehicle with specific QR-code") + void shouldReturnEmptyOptionalIfCanNotFindVehicleWithSpecificQrCode() { + //given + var qrCode = "QR_0040"; + //when + var result = vehicleRepository.findByQrCode(qrCode); + //then + assertThat(result).isEmpty(); + } + + @Test + @DisplayName("should save new vehicle to list") + void shouldSaveNewVehicleToList() { + //given + ReflectionTestUtils.setField(vehicleRepository, "vehicles", new ArrayList()); + var newVehicle = Vehicle + .builder() + .id(10L) + .type(Type.E_BIKE) + .qrCode("QR_0010") + .vehicleStatus(VehicleStatus + .builder() + .status(Status.AVAILABLE) + .build()) + .build(); + //when + var result = vehicleRepository.save(newVehicle); + //then + assertThat(result).hasFieldOrPropertyWithValue("qrCode", "QR_0010"); + } + + @Test + @DisplayName("should throw VehicleRepositoryException if try to save null") + void shouldThrowVehicleRepositoryExceptionIfTryToSaveNull() { + //given + //when + var thrown = catchThrowable(() -> vehicleRepository.save(null)); + //then + assertThat(thrown) + .isInstanceOf(VehicleRepositoryException.class) + .hasMessageContaining("Vehicle is null"); + } + +} \ No newline at end of file diff --git a/src/test/java/konarzewski/tracmobility/services/VehicleServiceTest.java b/src/test/java/konarzewski/tracmobility/services/VehicleServiceTest.java new file mode 100644 index 0000000..820fd30 --- /dev/null +++ b/src/test/java/konarzewski/tracmobility/services/VehicleServiceTest.java @@ -0,0 +1,152 @@ +package konarzewski.tracmobility.services; + +import konarzewski.tracmobility.exceptions.VehicleNotFoundException; +import konarzewski.tracmobility.exceptions.VehicleRepositoryException; +import konarzewski.tracmobility.exceptions.VehicleServiceException; +import konarzewski.tracmobility.fixtures.Fixtures; +import konarzewski.tracmobility.models.enums.Status; +import konarzewski.tracmobility.models.enums.Type; +import konarzewski.tracmobility.models.vehicle.Vehicle; +import konarzewski.tracmobility.models.vehicle.VehicleStatus; +import konarzewski.tracmobility.repository.VehicleRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.List; +import java.util.Optional; + +import static konarzewski.tracmobility.fixtures.Fixtures.createListOfAvailableVehicles; +import static konarzewski.tracmobility.fixtures.Fixtures.createListOfNoAvailableVehicles; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(SpringExtension.class) +class VehicleServiceTest { + + @InjectMocks + private VehicleService vehicleService; + + @Mock + private VehicleRepository repository; + + @Test + @DisplayName("should return all available vehicles") + void shouldReturnAllAvailableVehicles() { + //given + var vehicles = createListOfAvailableVehicles(); + when(repository.findAvailableVehicles()).thenReturn(vehicles); + //when + var result = vehicleService.findAvailableVehicles(); + //then + assertAll( + () -> assertThat(result.size()).isEqualTo(3), + () -> assertThat(result.get(1)).hasFieldOrPropertyWithValue("qrCode","QR_0002"), + () -> assertThat(result.get(1)).hasFieldOrPropertyWithValue("id",2L), + () -> assertThat(result.get(1)).hasFieldOrPropertyWithValue("type", "SCOOTER"), + () -> assertThat(result.get(1)).hasFieldOrPropertyWithValue("status", Status.AVAILABLE) + + ); + } + + @Test + @DisplayName("should throw VehicleServiceException if no available vehicles and list is empty") + void shouldThrowVehicleServiceExceptionIfNoAvailableVehicles() { + //given + when(repository.findAvailableVehicles()).thenReturn(List.of()); + //when + var thrown = catchThrowable(() -> vehicleService.findAvailableVehicles()); + //then + assertThat(thrown) + .isInstanceOf(VehicleServiceException.class) + .hasMessageContaining("No available vehicles"); + } + + @Test + @DisplayName("should return response for borrowed vehicle ") + void shouldReturnResponseForBorrowedVehicle() { + //given + var vehicle = Vehicle + .builder() + .qrCode("QR_0010") + .vehicleStatus(VehicleStatus + .builder() + .status(Status.AVAILABLE) + .build()) + .build(); + when(repository.findByQrCode(any())).thenReturn(Optional.of(vehicle)); + when(repository.save(any())).thenReturn(vehicle); + //when + var result = vehicleService.borrowVehicle(""); + //then + assertAll( + () -> assertThat(result).hasFieldOrPropertyWithValue("qrCode","QR_0010"), + () -> assertThat(result).hasFieldOrPropertyWithValue("status", Status.RUNNING) + ); + } + + @Test + @DisplayName("should throw VehicleServiceException if specific vehicle is not available ") + void shouldThrowVehicleServiceExceptionIfSpecificVehicleIsNotAvailable() { + //given + var vehicle = Vehicle + .builder() + .qrCode("QR_0010") + .vehicleStatus(VehicleStatus + .builder() + .status(Status.RUNNING) + .build()) + .build(); + when(repository.findByQrCode(any())).thenReturn(Optional.of(vehicle)); + //when + var thrown = catchThrowable(() -> vehicleService.borrowVehicle("")); + //then + assertThat(thrown) + .isInstanceOf(VehicleServiceException.class) + .hasMessageContaining("Vehicle with QR-code:") + .hasMessageContaining("Vehicle status: ") + .hasMessageContaining("Last status change: "); + } + + @Test + @DisplayName("should return response for returned vehicle") + void shouldReturnResponseForReturnedVehicle() { + //given + var vehicle = Vehicle + .builder() + .qrCode("QR_0010") + .vehicleStatus(VehicleStatus + .builder() + .status(Status.RUNNING) + .build()) + .build(); + when(repository.findByQrCode(any())).thenReturn(Optional.of(vehicle)); + when(repository.save(any())).thenReturn(vehicle); + //when + var result = vehicleService.returnVehicle(""); + //then + assertAll( + () -> assertThat(result).hasFieldOrPropertyWithValue("qrCode","QR_0010"), + () -> assertThat(result).hasFieldOrPropertyWithValue("status", Status.AVAILABLE) + ); + } + + @Test + @DisplayName("should throw VehicleNotFoundException when can not find Qr-Code") + void shouldThrowVehicleNotFoundExceptionWhenCanNotFindQrCode() { + //given + var qrCode = "QR_00040"; + //when + var thrown = catchThrowable(() -> vehicleService.returnVehicle(qrCode)); + //then + assertThat(thrown).isInstanceOf(VehicleNotFoundException.class) + .hasMessageContaining("Can not find vehicle with QR-code:"); + } +} \ No newline at end of file