diff --git a/README.md b/README.md index 7c2ef08b0..d9c47af67 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,27 @@ -### FCamara 🚀 -*"Queremos ser como uma árvore, - crescer um pouco todos os dias e tentar tocar o céu, - sem perder a solidez de nossas raízes."* -Conheça: www.fcamara.com.br +# Estacionamento API REST 🅿️🚗 (em construção) -## Teste para vaga de Desenvolvedor Back-end -Criar uma API REST para gerenciar um estacionamento de carros e motos. +

+A fim de aprimorar meus conhecimentos na área de Back-End, fora construída uma API Rest em Java, utilizando o framework Spring-Boot. A aplicação fora construída através de pesquisa de documentação on-line, aulas on-line, sugestões e códigos similares. Considere que esta é minha primeira API, ficando aquém do desejado, porém isso era esperado. Sinta-se à vontade de sugerir mudanças que melhor se adequam às práticas de mercado ou que por experiência própria entenda por mais corretas. Aliás, estou tendo dificuldades em configurar o Swagger. Você verá que o código no arquivo SwaggerConfig.java está comentado. Isso é proposital, uma vez que ao rodar a aplicação com o código não comentado ocorrem erros que não soube corrigir. Deixarei aqui os prints - 1 e 2 -, caso ajudem. Se souber o motivo do erro, puder me explicar e sugerir como consertá-lo, agradeço de coração. +

-## Cadastro de estabelecimento - -Criar um cadastro da empresa com os seguintes campos: -- Nome; -- CNPJ; -- Endereço; -- Telefone; -- Quantidade de vagas para motos; -- Quantidade de vagas para carros. +## Funcionalidades -**Todos** os campos são de preenchimento obrigatório. +☑️Cadastrar, pesquisar, alterar e deletar estabelecimentos.
+☑️Cadastrar, pesquisar, alterar e deletar veículos.
+☑️Controle de entrada e saída de veículos.
-## Cadastro de veículos -Criar um cadastro de veículos com os seguintes campos: -- Marca; -- Modelo; -- Cor; -- Placa; -- Tipo. +## Tecnologias -**Todos** os campos são de preenchimento obrigatório. +- [Intellij IDEA](https://www.jetbrains.com/pt-br/idea/) +- [Maven](https://maven.apache.org/) +- [Spring Boot](https://spring.io/projects/spring-boot) +- [PostgreSQL](https://www.postgresql.org) -## Funcionalidades +## Diagrama de classes +
+ Clique aqui para ver o diagrama +
+
- - **Estabelecimento:** CRUD; - - **Veículos:** CRUD; - - **Controle de entrada e saída de veículos.** - -## Requisitos - - - Modelagem de dados; - - O retorno deverá ser em formato JSON e XML; - - Requisições GET, POST, PUT ou DELETE, conforme a melhor prática; - - A persistência dos dados pode ser realizada da maneira que preferir; - - Criar README do projeto descrevendo as tecnologias utilizadas, chamadas dos serviços e configurações necessário para executar a aplicação. - -## Ganha mais pontos - - Desenvolver utilizando TDD; - - Criar API de relatório; - - Sumário da quantidade de entrada e saída; - - Sumário da quantidade de entrada e saída de veículos por hora; - - Criar uma solução de autenticação. - -## Submissão -Crie um fork do teste para acompanharmos o seu desenvolvimento através dos seus commits. - -## Obrigado! -Agradecemos sua participação no teste. Boa sorte! 😄 +## Como testar diff --git a/restApiParkingLot/.gitignore b/restApiParkingLot/.gitignore new file mode 100644 index 000000000..549e00a2a --- /dev/null +++ b/restApiParkingLot/.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/restApiParkingLot/.mvn/wrapper/maven-wrapper.jar b/restApiParkingLot/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..cb28b0e37 Binary files /dev/null and b/restApiParkingLot/.mvn/wrapper/maven-wrapper.jar differ diff --git a/restApiParkingLot/.mvn/wrapper/maven-wrapper.properties b/restApiParkingLot/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..5f0536eb7 --- /dev/null +++ b/restApiParkingLot/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/restApiParkingLot/mvnw b/restApiParkingLot/mvnw new file mode 100644 index 000000000..66df28542 --- /dev/null +++ b/restApiParkingLot/mvnw @@ -0,0 +1,308 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# 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 + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -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 "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); 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 2>/dev/null; \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 + +# 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/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# 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. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +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 "$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 + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/restApiParkingLot/mvnw.cmd b/restApiParkingLot/mvnw.cmd new file mode 100644 index 000000000..95ba6f54a --- /dev/null +++ b/restApiParkingLot/mvnw.cmd @@ -0,0 +1,205 @@ +@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 Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@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 WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_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 WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_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('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@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/restApiParkingLot/pom.xml b/restApiParkingLot/pom.xml new file mode 100644 index 000000000..ab47a230b --- /dev/null +++ b/restApiParkingLot/pom.xml @@ -0,0 +1,129 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.3 + + + org.restApiParkingLot + restApiParkingLot + 0.0.1-SNAPSHOT + restApiParkingLot + restApiParkingLot + + 17 + 2023.0.0 + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + annotationProcessor + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + io.springfox + springfox-swagger2 + 3.0.0 + + io.springfox + springfox-boot-starter + 3.0.0 + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + jakarta.validation + jakarta.validation-api + 3.0.2 + + + + + + + org.asciidoctor + asciidoctor-maven-plugin + 2.2.1 + + + generate-docs + prepare-package + + process-asciidoc + + + html + book + + + + + + org.springframework.restdocs + spring-restdocs-asciidoctor + ${spring-restdocs.version} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + \ No newline at end of file diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/RestApiParkingLotApplication.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/RestApiParkingLotApplication.java new file mode 100644 index 000000000..ba2c455a0 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/RestApiParkingLotApplication.java @@ -0,0 +1,13 @@ +package org.restapiparkinglot.restapiparkinglot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestApiParkingLotApplication { + + public static void main(String[] args) { + SpringApplication.run(RestApiParkingLotApplication.class, args); + } + +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/config/SwaggerConfig.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/config/SwaggerConfig.java new file mode 100644 index 000000000..943eca635 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/config/SwaggerConfig.java @@ -0,0 +1,59 @@ +//package org.restapiparkinglot.restapiparkinglot.config; +// +//import java.util.Arrays; +//import java.util.HashSet; +// +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +// +//import springfox.documentation.builders.ApiInfoBuilder; +//import springfox.documentation.builders.PathSelectors; +//import springfox.documentation.builders.RequestHandlerSelectors; +//import springfox.documentation.service.Contact; +//import springfox.documentation.spi.DocumentationType; +//import springfox.documentation.spring.web.plugins.Docket; +//import springfox.documentation.swagger2.annotations.EnableSwagger2; +// +//@Configuration +//@EnableSwagger2 +//public class SwaggerConfig { +// +// private Contact contato() { +// return new Contact( +// "Seu nome", +// "http://www.seusite.com.br", +// "voce@seusite.com.br"); +// } +// +// private ApiInfoBuilder informacoesApi() { +// +// ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder(); +// +// apiInfoBuilder.title("Title - Rest API"); +// apiInfoBuilder.description("API exemplo de uso de Springboot REST API"); +// apiInfoBuilder.version("1.0"); +// apiInfoBuilder.termsOfServiceUrl("Termo de uso: Open Source"); +// apiInfoBuilder.license("Licença - Sua Empresa"); +// apiInfoBuilder.licenseUrl("http://www.seusite.com.br"); +// apiInfoBuilder.contact(this.contato()); +// +// return apiInfoBuilder; +// +// } +// @Bean +// public Docket detalheApi() { +// Docket docket = new Docket(DocumentationType.SWAGGER_2); +// +// docket +// .select() +// .apis(RequestHandlerSelectors.basePackage("pacote.comseus.controllers")) +// .paths(PathSelectors.any()) +// .build() +// .apiInfo(this.informacoesApi().build()) +// .consumes(new HashSet(Arrays.asList("application/json"))) +// .produces(new HashSet(Arrays.asList("application/json"))); +// +// return docket; +// } +// +//} \ No newline at end of file diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingLotController.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingLotController.java new file mode 100644 index 000000000..5c9819a56 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingLotController.java @@ -0,0 +1,66 @@ +package org.restapiparkinglot.restapiparkinglot.controller; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.restapiparkinglot.restapiparkinglot.dtos.ParkingLotDTO; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.model.ParkingLot; +import org.restapiparkinglot.restapiparkinglot.services.ParkingLotService; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; + +import java.util.List; + +@RestController +@RequestMapping("/parkingLot") +@Api("Rest Api Parking Lot") +public class ParkingLotController { + @Autowired + private ParkingLotService parkingLotService; + + @GetMapping + @ApiOperation("Route for listing all parking lots") + public ResponseEntity> findAllParkingLot(){ + return ResponseEntity.status(HttpStatus.OK).body(parkingLotService.findAll()); + } + + @GetMapping ("/{id}") + @ApiOperation("Route for searching a parking lot by its id") + public ResponseEntity findParkingLotById(@PathVariable("id") int id) throws NotFoundException{ + return ResponseEntity.status(HttpStatus.OK).body(parkingLotService.retrieveById(id)); + } + + @GetMapping ("/{cnpj}") + @ApiOperation("Route for searching a parking lot by its cnpj") + public ResponseEntity findParkingLotByCnpj(@PathVariable("cnpj") String cnpj) throws NotFoundException{ + return ResponseEntity.status(HttpStatus.OK).body(parkingLotService.retrieveByCnpj(cnpj)); + } + + @PostMapping + @ApiOperation("Route for creating a parking lot") + public ResponseEntity createParkingLot(@RequestBody @Valid ParkingLotDTO parkingLotDTO) { + return ResponseEntity.status(HttpStatus.CREATED).body(parkingLotService.create(parkingLotDTO)); + } + + @PutMapping ("/{id}") + @ApiOperation("Route for updating a parking lot") + public ResponseEntity updateParkingLot(@RequestBody @Valid ParkingLotDTO parkingLotDTO, @PathVariable("id") int id) throws NotFoundException{ + ParkingLot parkingLot = parkingLotService.retrieveById(id); + + BeanUtils.copyProperties(parkingLotDTO, parkingLot); + return ResponseEntity.status(HttpStatus.OK).body(parkingLotService.update(parkingLot, id)); + } + + @DeleteMapping ("/{id}") + @ApiOperation("Route for deleting a parking lot") + public ResponseEntity deleteParkingLot(@PathVariable("id") int id) throws NotFoundException{ + return ResponseEntity.status(HttpStatus.OK).body(parkingLotService.delete(id)); + + } + +} \ No newline at end of file diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingServiceController.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingServiceController.java new file mode 100644 index 000000000..bdf4972eb --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingServiceController.java @@ -0,0 +1,33 @@ +package org.restapiparkinglot.restapiparkinglot.controller; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.restapiparkinglot.restapiparkinglot.services.ParkingService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + + +@RestController +@RequestMapping ("/parkingService" ) +@Api("Rest Api Parking Lot") +public class ParkingServiceController { + @Autowired + private ParkingService parkingService; + + @PostMapping("/{parkingLot}/entry/{vehicle}") + @ApiOperation("Route for entry of vehicle") + public ResponseEntity entryVehicle(@PathVariable("parkingLot") int parkingLotId, @PathVariable("vehicle") int vehicleId){ + return ResponseEntity.status(HttpStatus.OK).body(parkingService.entry(parkingLotId, vehicleId)); + } + + @PostMapping("/{parkingLot}/exit/{vehicle}") + @ApiOperation("Route for exit of vehicle") + public ResponseEntity exitVehicle(@PathVariable("parkingLot") int parkingLotId, @PathVariable("vehicle") int vehicleId){ + return ResponseEntity.status(HttpStatus.OK).body(parkingService.exit(parkingLotId, vehicleId)); + } + + + +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/VehicleController.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/VehicleController.java new file mode 100644 index 000000000..a2b18c7ee --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/controller/VehicleController.java @@ -0,0 +1,65 @@ +package org.restapiparkinglot.restapiparkinglot.controller; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import jakarta.validation.Valid; +import org.restapiparkinglot.restapiparkinglot.dtos.VehicleDTO; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.model.Vehicle; +import org.restapiparkinglot.restapiparkinglot.services.VehicleService; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/vehicle") +@Api("Rest Api Parking Lot") +public class VehicleController { + @Autowired + private VehicleService vehicleService; + + @GetMapping + @ApiOperation("Route for listing all vehicles") + public ResponseEntity> findAllVehicles(){ + return ResponseEntity.status(HttpStatus.OK).body(vehicleService.findAll()); + } + + @GetMapping ( "/{id}") + @ApiOperation("Route for searching a vehicle by its id") + public ResponseEntity findVehicleById(@PathVariable("id") int id) throws NotFoundException { + return ResponseEntity.status(HttpStatus.OK).body(vehicleService.retrieveById(id)); + } + + @GetMapping ("/{licensePlate}") + @ApiOperation("Route for searching a vehicle by its license plate") + public ResponseEntity findVehicleByLicensePlate(@PathVariable("licensePlate") String licensePlate) throws NotFoundException{ + return ResponseEntity.status(HttpStatus.OK).body(vehicleService.retrieveByLicensePlate(licensePlate)); + } + + @PostMapping + @ApiOperation("Route for creating a vehicle") + public ResponseEntity createVehicle(@RequestBody @Valid VehicleDTO vehicleDTO) { + return ResponseEntity.status(HttpStatus.CREATED).body(vehicleService.create(vehicleDTO)); + } + + @PutMapping ("/{id}") + @ApiOperation("Route for updating a vehicle") + public ResponseEntity updateVehicle(@RequestBody @Valid VehicleDTO vehicleDTO, @PathVariable("id") int id) throws NotFoundException{ + Vehicle vehicle = vehicleService.retrieveById(id); + + BeanUtils.copyProperties(vehicleDTO,vehicle); + return ResponseEntity.status(HttpStatus.OK).body(vehicleService.update(vehicle, id)); + } + + @DeleteMapping ("/{id}") + @ApiOperation("Route for deleting a vehicle") + public ResponseEntity deleteVehicle(@PathVariable("id") int id) throws NotFoundException{ + return ResponseEntity.status(HttpStatus.OK).body(vehicleService.delete(id)); + + } + +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/dtos/ParkingLotDTO.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/dtos/ParkingLotDTO.java new file mode 100644 index 000000000..839308d02 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/dtos/ParkingLotDTO.java @@ -0,0 +1,27 @@ +package org.restapiparkinglot.restapiparkinglot.dtos; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.Builder; +import lombok.Data; +import org.hibernate.validator.constraints.br.CNPJ; + +@Data +@Builder +public class ParkingLotDTO { + @NotBlank(message = "Must inform name") + private String name; + @NotBlank(message = "Must inform CNPJ") + @CNPJ + private String cnpj; + @NotBlank(message = "Must inform address") + private String address; + @NotBlank(message = "Must inform phone number") + @Pattern(regexp = "\\d{11}", message = "Phone number must contain exactly 11 digits") + private String phoneNumber; + @NotNull + private int carSpaces; + @NotNull + private int motorcycleSpaces; +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/dtos/VehicleDTO.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/dtos/VehicleDTO.java new file mode 100644 index 000000000..4fc137ca8 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/dtos/VehicleDTO.java @@ -0,0 +1,23 @@ +package org.restapiparkinglot.restapiparkinglot.dtos; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.Builder; +import lombok.Data; +import org.restapiparkinglot.restapiparkinglot.model.VehicleType; + +@Data +@Builder +public class VehicleDTO { + @NotBlank(message = "Must inform brand") + private String brand; + @NotBlank(message = "Must inform model") + private String model; + @NotBlank(message = "Must inform color") + @Pattern(regexp = "^[a-zA-Z]*") + private String color; + @NotBlank(message = "Must inform license plate") + private String licensePlate; + @NotBlank(message = "Vehicle type must be car or motorcycle") + private VehicleType vehicleType; +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/AlreadyRegisteredException.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/AlreadyRegisteredException.java new file mode 100644 index 000000000..a83fc2d5f --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/AlreadyRegisteredException.java @@ -0,0 +1,8 @@ +package org.restapiparkinglot.restapiparkinglot.exception; + + +public class AlreadyRegisteredException extends RuntimeException{ + public AlreadyRegisteredException(String warning){ + super(warning); + } +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/NotFoundException.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/NotFoundException.java new file mode 100644 index 000000000..0490cb67d --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/NotFoundException.java @@ -0,0 +1,8 @@ +package org.restapiparkinglot.restapiparkinglot.exception; + + +public class NotFoundException extends RuntimeException{ + public NotFoundException (String warning){ + super(warning); + } +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/ParkingLotFullException.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/ParkingLotFullException.java new file mode 100644 index 000000000..11d215b94 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/ParkingLotFullException.java @@ -0,0 +1,8 @@ +package org.restapiparkinglot.restapiparkinglot.exception; + +public class ParkingLotFullException extends RuntimeException{ + public ParkingLotFullException (String warning) { + super(warning); + + } +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/AlreadyRegisteredExceptionWarning.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/AlreadyRegisteredExceptionWarning.java new file mode 100644 index 000000000..f37889e58 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/AlreadyRegisteredExceptionWarning.java @@ -0,0 +1,10 @@ +package org.restapiparkinglot.restapiparkinglot.exception.warning; + + +import java.time.LocalDateTime; + +public class AlreadyRegisteredExceptionWarning extends ExceptionWarning { + public AlreadyRegisteredExceptionWarning(String warning, int status, LocalDateTime timestamp) { + super(warning, status, timestamp); + } +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/ExceptionWarning.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/ExceptionWarning.java new file mode 100644 index 000000000..7d675b44a --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/ExceptionWarning.java @@ -0,0 +1,18 @@ +package org.restapiparkinglot.restapiparkinglot.exception.warning; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.experimental.SuperBuilder; + +import java.time.LocalDateTime; + +@Data +@SuperBuilder +@AllArgsConstructor +public class ExceptionWarning { + private String warning; + private int status; + private LocalDateTime timestamp; + + +} \ No newline at end of file diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/NotFoundExceptionWarning.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/NotFoundExceptionWarning.java new file mode 100644 index 000000000..256575456 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/NotFoundExceptionWarning.java @@ -0,0 +1,10 @@ +package org.restapiparkinglot.restapiparkinglot.exception.warning; + +import java.time.LocalDateTime; + +public class NotFoundExceptionWarning extends ExceptionWarning{ + public NotFoundExceptionWarning (String warning, int status, LocalDateTime timestamp) { + super(warning, status, timestamp); + } +} + diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/ParkingLotFullExceptionWarning.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/ParkingLotFullExceptionWarning.java new file mode 100644 index 000000000..f81d4b1eb --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/exception/warning/ParkingLotFullExceptionWarning.java @@ -0,0 +1,9 @@ +package org.restapiparkinglot.restapiparkinglot.exception.warning; + +import java.time.LocalDateTime; + +public class ParkingLotFullExceptionWarning extends ExceptionWarning { + public ParkingLotFullExceptionWarning(String warning, int status, LocalDateTime timestamp){ + super(warning, status, timestamp); + } +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/handler/RestExceptionHandler.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/handler/RestExceptionHandler.java new file mode 100644 index 000000000..50a474e66 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/handler/RestExceptionHandler.java @@ -0,0 +1,33 @@ +package org.restapiparkinglot.restapiparkinglot.handler; + +import org.restapiparkinglot.restapiparkinglot.exception.AlreadyRegisteredException; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.exception.ParkingLotFullException; +import org.restapiparkinglot.restapiparkinglot.exception.warning.AlreadyRegisteredExceptionWarning; +import org.restapiparkinglot.restapiparkinglot.exception.warning.NotFoundExceptionWarning; +import org.restapiparkinglot.restapiparkinglot.exception.warning.ParkingLotFullExceptionWarning; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDateTime; + +@ControllerAdvice +public class RestExceptionHandler { + @ExceptionHandler(NotFoundException.class) + public ResponseEntity handleNotFound(NotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new NotFoundExceptionWarning(e.getMessage(), HttpStatus.NOT_FOUND.value(), LocalDateTime.now())); + + } + @ExceptionHandler(AlreadyRegisteredException.class) + public ResponseEntity handleAlreadyExists(AlreadyRegisteredException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new AlreadyRegisteredExceptionWarning(e.getMessage(), HttpStatus.BAD_REQUEST.value(), LocalDateTime.now())); + } + @ExceptionHandler(ParkingLotFullException.class) + public ResponseEntity handleAlreadyFull(ParkingLotFullException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ParkingLotFullExceptionWarning(e.getMessage(), HttpStatus.BAD_REQUEST.value(), LocalDateTime.now())); + } + +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/ParkingLot.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/ParkingLot.java new file mode 100644 index 000000000..4edcfd861 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/ParkingLot.java @@ -0,0 +1,137 @@ +package org.restapiparkinglot.restapiparkinglot.model; + +import jakarta.persistence.*; + +import lombok.Builder; + +import java.util.List; + +@Builder +@Entity +@Table(name = "parkinglot") +public class ParkingLot { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + @Column(name = "name", nullable = false) + private String name; + @Column(name = "cnpj", nullable = false, unique = true, length = 14) + private String cnpj; + @Column(name = "address", nullable = false) + private String address; + @Column(name = "phonenumber", nullable = false, unique = true, length = 11) + private String phoneNumber; + @Column(name = "motorcycleSpaces", nullable = false) + private int motorcycleSpaces; + @Column(name = "carSpaces", nullable = false) + private int carSpaces; + @Column(name = "totalparkedmotorcycle") + private int totalParkedMotorcycle; + @Column(name = "totalparkedcar") + private int totalParkedCar; + + @OneToMany(cascade = CascadeType.ALL) + @JoinTable(name = "vehicles", + joinColumns = @JoinColumn(name = "parkinglot_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "vehicle_id", referencedColumnName = "id")) + + private List vehicles; + + public ParkingLot() { + + } + + public ParkingLot(int id, String name, String cnpj, String address, String phoneNumber, int motorcycleSpaces, int carSpaces, int totalParkedMotorcycle, int totalParkedCar, List vehicles) { + this.id = id; + this.name = name; + this.cnpj = cnpj; + this.address = address; + this.phoneNumber = phoneNumber; + this.motorcycleSpaces = motorcycleSpaces; + this.carSpaces = carSpaces; + this.totalParkedMotorcycle = totalParkedMotorcycle; + this.totalParkedCar = totalParkedCar; + this.vehicles = vehicles; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCnpj() { + return cnpj; + } + + public void setCnpj(String cnpj) { + this.cnpj = cnpj; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public int getMotorcycleSpaces() { + return motorcycleSpaces; + } + + public void setMotorcycleSpaces(int motorcycleSpaces) { + this.motorcycleSpaces = motorcycleSpaces; + } + + public int getCarSpaces() { + return carSpaces; + } + + public void setCarSpaces(int carSpaces) { + this.carSpaces = carSpaces; + } + + public int getTotalParkedMotorcycle() { + return totalParkedMotorcycle; + } + + public void setTotalParkedMotorcycle(int totalParkedMotorcycle) { + this.totalParkedMotorcycle = totalParkedMotorcycle; + } + + public int getTotalParkedCar() { + return totalParkedCar; + } + + public void setTotalParkedCar(int totalParkedCar) { + this.totalParkedCar = totalParkedCar; + } + + public List getVehicles() { + return vehicles; + } + + public void setVehicles(List vehicles) { + this.vehicles = vehicles; + } +} + diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/Vehicle.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/Vehicle.java new file mode 100644 index 000000000..4e5d23106 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/Vehicle.java @@ -0,0 +1,105 @@ +package org.restapiparkinglot.restapiparkinglot.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import lombok.Builder; + + +@Builder +@Entity +@Table(name = "vehicle") +public class Vehicle { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + @Column(name = "brand", nullable = false) + private String brand; + @Column(name = "model", nullable = false) + private String model; + @Column(name = "color", nullable = false) + private String color; + @Column(name = "licensePlate", nullable = false, unique = true) + private String licensePlate; + @Column(name = "vehicleType", nullable = false) + private VehicleType vehicleType; + + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "parkinglot_id") + @JsonIgnore + private ParkingLot parkingLot; + + + public Vehicle() { + + } + + public Vehicle(int id, String brand, String model, String color, String licensePlate, VehicleType vehicleType, ParkingLot parkingLot) { + this.id = id; + this.brand = brand; + this.model = model; + this.color = color; + this.licensePlate = licensePlate; + this.vehicleType = vehicleType; + this.parkingLot = parkingLot; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public String getLicensePlate() { + return licensePlate; + } + + public void setLicensePlate(String licensePlate) { + this.licensePlate = licensePlate; + } + + public VehicleType getVehicleType() { + return vehicleType; + } + + public void setVehicleType(VehicleType vehicleType) { + this.vehicleType = vehicleType; + } + + public ParkingLot getParkingLot() { + return parkingLot; + } + + public void setParkingLot(ParkingLot parkingLot) { + this.parkingLot = parkingLot; + } +} + + diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/VehicleType.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/VehicleType.java new file mode 100644 index 000000000..03f325424 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/model/VehicleType.java @@ -0,0 +1,6 @@ +package org.restapiparkinglot.restapiparkinglot.model; + +public enum VehicleType { + CAR, + MOTORCYCLE +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/repository/ParkingLotRepository.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/repository/ParkingLotRepository.java new file mode 100644 index 000000000..4de6ef66c --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/repository/ParkingLotRepository.java @@ -0,0 +1,13 @@ +package org.restapiparkinglot.restapiparkinglot.repository; + +import org.restapiparkinglot.restapiparkinglot.model.ParkingLot; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface ParkingLotRepository extends JpaRepository { + Optional findByCnpj(String cnpj); + +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/repository/VehicleRepository.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/repository/VehicleRepository.java new file mode 100644 index 000000000..a1fb561b5 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/repository/VehicleRepository.java @@ -0,0 +1,13 @@ +package org.restapiparkinglot.restapiparkinglot.repository; + +import org.restapiparkinglot.restapiparkinglot.model.Vehicle; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface VehicleRepository extends JpaRepository { + Optional findByLicensePlate(String licensePlate); + +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/ParkingLotService.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/ParkingLotService.java new file mode 100644 index 000000000..db7071208 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/ParkingLotService.java @@ -0,0 +1,60 @@ +package org.restapiparkinglot.restapiparkinglot.services; + +import org.restapiparkinglot.restapiparkinglot.dtos.ParkingLotDTO; +import org.restapiparkinglot.restapiparkinglot.exception.AlreadyRegisteredException; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.model.ParkingLot; +import org.restapiparkinglot.restapiparkinglot.repository.ParkingLotRepository; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class ParkingLotService { + @Autowired + ParkingLotRepository parkingLotRepository; + + public List findAll() { + return parkingLotRepository.findAll(); + } + + public ParkingLot create(ParkingLotDTO parkingLotDTO) { + isRegistered(parkingLotDTO.getCnpj()); + ParkingLot parkingLotModel = convertParking(parkingLotDTO); + return parkingLotRepository.save(parkingLotModel); + } + + public ParkingLot retrieveById(int id) throws NotFoundException { + return parkingLotRepository.findById(id) + .orElseThrow(() -> new NotFoundException("Parking lot not found")); + } + + public ParkingLot retrieveByCnpj(String cnpj) throws NotFoundException { + return parkingLotRepository.findByCnpj(cnpj) + .orElseThrow(() -> new NotFoundException("Parking lot not found")); + } + + public ParkingLot update(ParkingLot parkingLot, int id) throws NotFoundException { + retrieveById(id); + return parkingLotRepository.save(parkingLot); + } + + public String delete(int id) throws NotFoundException{ + retrieveById(id); + parkingLotRepository.deleteById(id); + return "Parking lot successfully deleted"; + } + + private ParkingLot convertParking(ParkingLotDTO parkingLotDTO) { + ParkingLot parkingLotModel = new ParkingLot(); + BeanUtils.copyProperties(parkingLotDTO, parkingLotModel); + return parkingLotModel; + } + + private void isRegistered(String cnpj) throws AlreadyRegisteredException { + parkingLotRepository.findByCnpj(cnpj) + .orElseThrow(() -> new AlreadyRegisteredException("Parking lot already registered")); + } +} \ No newline at end of file diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/ParkingService.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/ParkingService.java new file mode 100644 index 000000000..a90fffd23 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/ParkingService.java @@ -0,0 +1,66 @@ +package org.restapiparkinglot.restapiparkinglot.services; + +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.exception.ParkingLotFullException; +import org.restapiparkinglot.restapiparkinglot.model.ParkingLot; +import org.restapiparkinglot.restapiparkinglot.model.Vehicle; +import org.restapiparkinglot.restapiparkinglot.repository.ParkingLotRepository; +import org.restapiparkinglot.restapiparkinglot.repository.VehicleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ParkingService { + @Autowired + private VehicleRepository vehicleRepository; + + @Autowired + private ParkingLotRepository parkingLotRepository; + + public String entry(int parkingLotId, int vehicleId) throws NotFoundException{ + ParkingLot parkingLot = parkingLotRepository.findById(parkingLotId) + .orElseThrow(() -> new NotFoundException("Parking lot not found")); + Vehicle vehicle = vehicleRepository.findById(vehicleId) + .orElseThrow(() -> new NotFoundException("Vehicle not found")); + + switch(vehicle.getVehicleType()){ + case CAR: + if (parkingLot.getCarSpaces()==parkingLot.getTotalParkedCar()) throw new ParkingLotFullException("Parking lot is full"); + parkingLot.setTotalParkedCar(parkingLot.getTotalParkedCar()+1); + + case MOTORCYCLE: + if (parkingLot.getMotorcycleSpaces()==parkingLot.getTotalParkedMotorcycle()) throw new ParkingLotFullException("Parking lot is full"); + parkingLot.setTotalParkedMotorcycle(parkingLot.getTotalParkedMotorcycle()+1); + } + parkingLot.getVehicles().add(vehicle); + vehicle.setParkingLot(parkingLot); + + vehicleRepository.save(vehicle); + parkingLotRepository.save(parkingLot); + + return "Entry successfully"; + + } + + public String exit(int parkingLotId, int vehicleId){ + ParkingLot parkingLot = parkingLotRepository.findById(parkingLotId) + .orElseThrow(() -> new NotFoundException("Parking lot not found")); + Vehicle vehicle = vehicleRepository.findById(vehicleId) + .orElseThrow(() -> new NotFoundException("Vehicle not found")); + + switch(vehicle.getVehicleType()){ + case CAR: + parkingLot.setTotalParkedCar(parkingLot.getTotalParkedCar()-1); + + case MOTORCYCLE: + parkingLot.setTotalParkedMotorcycle(parkingLot.getTotalParkedMotorcycle()-1); + } + parkingLot.getVehicles().remove(vehicle); + vehicle.setParkingLot(null); + + vehicleRepository.save(vehicle); + parkingLotRepository.save(parkingLot); + + return "Exit successfully"; + } +} diff --git a/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/VehicleService.java b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/VehicleService.java new file mode 100644 index 000000000..2a63b7f41 --- /dev/null +++ b/restApiParkingLot/src/main/java/org/restapiparkinglot/restapiparkinglot/services/VehicleService.java @@ -0,0 +1,59 @@ +package org.restapiparkinglot.restapiparkinglot.services; + +import org.restapiparkinglot.restapiparkinglot.dtos.VehicleDTO; +import org.restapiparkinglot.restapiparkinglot.exception.AlreadyRegisteredException; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.model.Vehicle; +import org.restapiparkinglot.restapiparkinglot.repository.VehicleRepository; +import org.springframework.beans.BeanUtils; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class VehicleService { + @Autowired + VehicleRepository vehicleRepository; + + public List findAll() { + return vehicleRepository.findAll(); + } + + public Vehicle create(VehicleDTO vehicleDTO){ + isRegistered(vehicleDTO.getLicensePlate()); + Vehicle vehicleModel = convertVehicle(vehicleDTO); + return vehicleRepository.save(vehicleModel); + } + + public Vehicle retrieveById(int id) throws NotFoundException{ + return vehicleRepository.findById(id) + .orElseThrow(() -> new NotFoundException("Vehicle not found")); + } + + public Vehicle retrieveByLicensePlate(String licensePlate) throws NotFoundException{ + return vehicleRepository.findByLicensePlate(licensePlate). + orElseThrow(() -> new NotFoundException("Vehicle not found")); + } + + public Vehicle update(Vehicle vehicle, int id) throws NotFoundException { + retrieveById(id); + return vehicleRepository.save(vehicle); + } + + public String delete(int id) throws NotFoundException { + retrieveById(id); + vehicleRepository.deleteById(id); + return "Vehicle successfully deleted"; + } + + private Vehicle convertVehicle(VehicleDTO vehicleDTO){ + Vehicle vehicleModel = new Vehicle(); + BeanUtils.copyProperties(vehicleDTO, vehicleModel); + return vehicleModel; + } + + private void isRegistered(String licensePlate) throws AlreadyRegisteredException { + vehicleRepository.findByLicensePlate(licensePlate) + .orElseThrow(() -> new AlreadyRegisteredException("Vehicle already registered")); + } +} diff --git a/restApiParkingLot/src/main/resources/application.properties b/restApiParkingLot/src/main/resources/application.properties new file mode 100644 index 000000000..7278e1772 --- /dev/null +++ b/restApiParkingLot/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.jpa.database=POSTGRESQL +spring.jpa.hibernate.ddl-auto = create-drop + +spring.datasource.url=jdbc:postgresql://localhost:5432/restApiParkingLot +spring.datasource.username=postgres +spring.datasource.password=7615Rjai!0 + +spring.mvc.pathmatch.matching-strategy=ant_path_matcher \ No newline at end of file diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/RestApiParkingLotApplicationTests.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/RestApiParkingLotApplicationTests.java new file mode 100644 index 000000000..5e6f11fd2 --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/RestApiParkingLotApplicationTests.java @@ -0,0 +1,13 @@ +package org.restapiparkinglot.restapiparkinglot; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RestApiParkingLotApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingLotControllerTest.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingLotControllerTest.java new file mode 100644 index 000000000..901dbcd9b --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/controller/ParkingLotControllerTest.java @@ -0,0 +1,118 @@ +package org.restapiparkinglot.restapiparkinglot.controller; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.restapiparkinglot.restapiparkinglot.dtos.ParkingLotDTO; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.restapiparkinglot.restapiparkinglot.model.ParkingLot; +import org.restapiparkinglot.restapiparkinglot.services.ParkingLotService; +import org.restapiparkinglot.restapiparkinglot.setup.ParkingLotDTOSetup; +import org.restapiparkinglot.restapiparkinglot.setup.ParkingLotSetup; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.when; + +@ExtendWith(SpringExtension.class) +public class ParkingLotControllerTest { + @InjectMocks + private ParkingLotController parkingLotController; + + @Mock + private ParkingLotService parkingLotService; + + private static final ParkingLot VALID_PARKINGLOT = ParkingLotSetup.createValidParkingLot(); + + @BeforeEach + void setUp() throws NotFoundException{ + when(parkingLotService.create(ArgumentMatchers.any(ParkingLotDTO.class))).thenReturn(VALID_PARKINGLOT); + when(parkingLotService.findAll()).thenReturn(List.of(VALID_PARKINGLOT)); + when(parkingLotService.retrieveById(ArgumentMatchers.anyInt())).thenReturn(VALID_PARKINGLOT); + when(parkingLotService.retrieveByCnpj(ArgumentMatchers.anyString())).thenReturn(VALID_PARKINGLOT); + when(parkingLotService.delete(ArgumentMatchers.anyInt())).thenReturn("Parking Lot deleted"); + } + + @Test + void createSaveParkingLotWhenSuccessful(){ + ResponseEntity parkingLotResponseEntity = parkingLotController.createParkingLot(ParkingLotDTOSetup.createValidParkingLot()); + ParkingLot body = (ParkingLot) parkingLotResponseEntity.getBody(); + + Assertions.assertThat(parkingLotResponseEntity).isNotNull(); + Assertions.assertThat(body).isNotNull(); + Assertions.assertThat(parkingLotResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.CREATED); + + assertParkingLotFields(body); + } + @Test + void deleteReturnDeletedParkingLotWhenSuccessful(){ + ResponseEntity parkingLotResponseEntity = parkingLotController.deleteParkingLot(VALID_PARKINGLOT.getId()); + + Assertions.assertThat(parkingLotResponseEntity).isNotNull(); + Assertions.assertThat(parkingLotResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void listAllReturnListOfParkingLotWhenSuccessful() { + ResponseEntity> parkingLotResponseEntity = parkingLotController.findAllParkingLot(); + List body = parkingLotResponseEntity.getBody(); + + Assertions.assertThat(parkingLotResponseEntity).isNotNull(); + Assertions.assertThat(body).isNotNull().isNotEmpty().hasSize(1).contains(VALID_PARKINGLOT); + Assertions.assertThat(parkingLotResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void listAllReturnEmptyListOfParkingLotWhenSuccessful() { + when(parkingLotService.findAll()).thenReturn(Collections.emptyList()); + ResponseEntity> parkingLotResponseEntity = parkingLotController.findAllParkingLot(); + List body = parkingLotResponseEntity.getBody(); + + Assertions.assertThat(parkingLotResponseEntity).isNotNull(); + Assertions.assertThat(body).isNotNull().isEmpty(); + Assertions.assertThat(parkingLotResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void findByIdReturnParkingLotWhenSuccessful() throws NotFoundException { + ResponseEntity parkingLotResponseEntity = parkingLotController.findParkingLotById(VALID_PARKINGLOT.getId()); + ParkingLot body = (ParkingLot) parkingLotResponseEntity.getBody(); + + Assertions.assertThat(parkingLotResponseEntity).isNotNull(); + Assertions.assertThat(body.getId()).isNotNull().isEqualTo(1); + Assertions.assertThat(parkingLotResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void findByCnpjReturnParkingLotWhenSuccessful() throws NotFoundException { + ResponseEntity parkingLotResponseEntity = parkingLotController.findParkingLotByCnpj(VALID_PARKINGLOT.getCnpj()); + ParkingLot body = (ParkingLot) parkingLotResponseEntity.getBody(); + + Assertions.assertThat(parkingLotResponseEntity).isNotNull(); + Assertions.assertThat((body.getCnpj())).isNotNull().isEqualTo("12233344445555"); + Assertions.assertThat(parkingLotResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + + } + @Test + void update_UpdateEstabelecimento_whenSucessful (){ + + + } + private void assertParkingLotFields(ParkingLot parkingLot) { + Assertions.assertThat(parkingLot.getName()).isNotNull().isNotEmpty(); + Assertions.assertThat(parkingLot.getCnpj()).isNotNull().isNotEmpty(); + Assertions.assertThat(parkingLot.getAddress()).isNotNull().isNotEmpty(); + Assertions.assertThat(parkingLot.getPhoneNumber()).isNotNull().isNotEmpty(); + Assertions.assertThat(parkingLot.getCarSpaces()).isNotNull(); + Assertions.assertThat(parkingLot.getMotorcycleSpaces()).isNotNull(); + } + +} diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/controller/VehicleControllerTest.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/controller/VehicleControllerTest.java new file mode 100644 index 000000000..292629718 --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/controller/VehicleControllerTest.java @@ -0,0 +1,117 @@ +package org.restapiparkinglot.restapiparkinglot.controller; + + +import org.restapiparkinglot.restapiparkinglot.dtos.VehicleDTO; +import org.restapiparkinglot.restapiparkinglot.exception.NotFoundException; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.restapiparkinglot.restapiparkinglot.model.Vehicle; +import org.restapiparkinglot.restapiparkinglot.services.VehicleService; +import org.restapiparkinglot.restapiparkinglot.setup.VehicleDTOSetup; +import org.restapiparkinglot.restapiparkinglot.setup.VehicleSetup; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.when; + +@ExtendWith(SpringExtension.class) +public class VehicleControllerTest { + + @InjectMocks + private VehicleController vehicleController; + + @Mock + private VehicleService vehicleService; + + private static final Vehicle VALID_VEHICLE = VehicleSetup.createValidVehicle(); + + @BeforeEach + void setUp() throws NotFoundException { + when(vehicleService.create(ArgumentMatchers.any(VehicleDTO.class))).thenReturn(VALID_VEHICLE); + when(vehicleService.findAll()).thenReturn(List.of(VALID_VEHICLE)); + when(vehicleService.retrieveById(ArgumentMatchers.anyInt())).thenReturn(VALID_VEHICLE); + when(vehicleService.retrieveByLicensePlate(ArgumentMatchers.anyString())).thenReturn(VALID_VEHICLE); + when(vehicleService.delete(ArgumentMatchers.anyInt())).thenReturn("Vehicle deleted"); + } + + @Test + void createSaveVehicleWhenSuccessful() { + + ResponseEntity vehicleResponseEntity = vehicleController.createVehicle(VehicleDTOSetup.createValidVehicle()); + Vehicle body = (Vehicle) vehicleResponseEntity.getBody(); + + Assertions.assertThat(vehicleResponseEntity).isNotNull(); + Assertions.assertThat(body).isNotNull(); + Assertions.assertThat(vehicleResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.CREATED); + + assertVehicleFields(body); + } + + + @Test + void deleteReturnDeletedVehicleWhenSuccessful() { + ResponseEntity vehicleResponseEntity = vehicleController.deleteVehicle(VALID_VEHICLE.getId()); + + Assertions.assertThat(vehicleResponseEntity).isNotNull(); + Assertions.assertThat(vehicleResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void listAllReturnListOfVehicleWhenSuccessful() { + ResponseEntity> vehicleResponseEntity = vehicleController.findAllVehicles(); + List body = vehicleResponseEntity.getBody(); + + Assertions.assertThat(vehicleResponseEntity).isNotNull(); + Assertions.assertThat(body).isNotNull().isNotEmpty().hasSize(1).contains(VALID_VEHICLE); + Assertions.assertThat(vehicleResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void listAllReturnEmptyListOfVehicleWhenSuccessful() { + when(vehicleService.findAll()).thenReturn(Collections.emptyList()); + ResponseEntity> vehicleResponseEntity = vehicleController.findAllVehicles(); + List body = vehicleResponseEntity.getBody(); + + Assertions.assertThat(vehicleResponseEntity).isNotNull(); + Assertions.assertThat(body).isNotNull().isEmpty(); + Assertions.assertThat(vehicleResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void findByIdReturnVehicleWhenSuccessful() throws NotFoundException { + ResponseEntity vehicleResponseEntity = vehicleController.findVehicleById(VALID_VEHICLE.getId()); + Vehicle body = (Vehicle) vehicleResponseEntity.getBody(); + + Assertions.assertThat(vehicleResponseEntity).isNotNull(); + Assertions.assertThat(body.getId()).isNotNull().isEqualTo(1); + Assertions.assertThat(vehicleResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + } + + @Test + void findByLicensePlateReturnVehicleWhenSuccessful() throws NotFoundException { + ResponseEntity vehicleResponseEntity = vehicleController.findVehicleByLicensePlate(VALID_VEHICLE.getLicensePlate()); + Vehicle body = (Vehicle) vehicleResponseEntity.getBody(); + + Assertions.assertThat(vehicleResponseEntity).isNotNull(); + Assertions.assertThat((body.getLicensePlate())).isNotNull().isEqualTo("JVA1A70"); //testando p da errado + Assertions.assertThat(vehicleResponseEntity.getStatusCode()).isNotNull().isEqualTo(HttpStatus.OK); + + } + + private void assertVehicleFields(Vehicle vehicle) { + Assertions.assertThat(vehicle.getBrand()).isNotNull().isNotEmpty(); + Assertions.assertThat(vehicle.getModel()).isNotNull().isNotEmpty(); + Assertions.assertThat(vehicle.getColor()).isNotNull().isNotEmpty(); + Assertions.assertThat(vehicle.getLicensePlate()).isNotNull().isNotEmpty(); + Assertions.assertThat(vehicle.getVehicleType()).isNotNull(); + } +} diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/ParkingLotDTOSetup.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/ParkingLotDTOSetup.java new file mode 100644 index 000000000..5b36840c2 --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/ParkingLotDTOSetup.java @@ -0,0 +1,18 @@ +package org.restapiparkinglot.restapiparkinglot.setup; + +import org.restapiparkinglot.restapiparkinglot.dtos.ParkingLotDTO; + +public class ParkingLotDTOSetup { + public static ParkingLotDTO createValidParkingLot(){ + return defaultBuilder().build(); + } + public static ParkingLotDTO.ParkingLotDTOBuilder defaultBuilder(){ + return ParkingLotDTO.builder() + .name("Parking lot test") + .cnpj("12233344445555") + .address("Avenue Test") + .phoneNumber("11122233344") + .carSpaces(10) + .motorcycleSpaces(10); + } +} diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/ParkingLotSetup.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/ParkingLotSetup.java new file mode 100644 index 000000000..a1856e87c --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/ParkingLotSetup.java @@ -0,0 +1,24 @@ +package org.restapiparkinglot.restapiparkinglot.setup; + +import org.restapiparkinglot.restapiparkinglot.model.ParkingLot; + +public class ParkingLotSetup { + public static ParkingLot createValidParkingLot(){ + return defaultBuilder().build(); + } + public static ParkingLot updateValidParkingLot(){ + return defaultBuilder().id(1) + .name("New parking lot test") + .cnpj("12233344445555") + .build(); + } + public static ParkingLot.ParkingLotBuilder defaultBuilder(){ + return ParkingLot.builder().id(1) + .name("Parking lot test") + .cnpj("12233344445555") + .address("Avenue Test") + .phoneNumber("11122233344") + .carSpaces(10) + .motorcycleSpaces(10); + } +} diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/VehicleDTOSetup.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/VehicleDTOSetup.java new file mode 100644 index 000000000..e978ec7b3 --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/VehicleDTOSetup.java @@ -0,0 +1,21 @@ +package org.restapiparkinglot.restapiparkinglot.setup; + +import org.restapiparkinglot.restapiparkinglot.dtos.VehicleDTO; +import org.restapiparkinglot.restapiparkinglot.model.VehicleType; + +public class VehicleDTOSetup { + public static VehicleDTO createValidVehicle(){ + return defaultBuilder().build(); + } + + public static VehicleDTO.VehicleDTOBuilder defaultBuilder(){ + return VehicleDTO.builder() + .model("Model test") + .brand("Brand test") + .licensePlate("JVA1A70") + .color("blue") + .vehicleType(VehicleType.valueOf("CAR")); + } +} + + diff --git a/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/VehicleSetup.java b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/VehicleSetup.java new file mode 100644 index 000000000..954378050 --- /dev/null +++ b/restApiParkingLot/src/test/java/org/restapiparkinglot/restapiparkinglot/setup/VehicleSetup.java @@ -0,0 +1,19 @@ +package org.restapiparkinglot.restapiparkinglot.setup; + +import org.restapiparkinglot.restapiparkinglot.model.Vehicle; +import org.restapiparkinglot.restapiparkinglot.model.VehicleType; + +public class VehicleSetup { + public static Vehicle createValidVehicle(){ + return defaultBuilder().build(); + } + + public static Vehicle.VehicleBuilder defaultBuilder(){ + return Vehicle.builder().id(1) + .model("Model test") + .brand("Brand test") + .licensePlate("JVA1A70") + .color("blue") + .vehicleType(VehicleType.valueOf("CAR")); + } +}