diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..549e00a2 --- /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/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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 +# +# http://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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/README.md b/README.md index d45458df..b4309c3c 100644 --- a/README.md +++ b/README.md @@ -1,79 +1,179 @@ ### 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 - -## Teste para vaga de Desenvolvedor Back-end -Criar uma API REST para gerenciar um estacionamento de carros e motos. - -## 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. - -**Todos** os campos são de preenchimento obrigatório. - -## Cadastro de veículos -Criar um cadastro de veículos com os seguintes campos: - - Marca; - - Modelo; - - Cor; - - Placa; - - Tipo. - -**Todos** os campos são de preenchimento obrigatório. - -## Funcionalidades - - **Estabelecimento:** CRUD; - - **Veículos:** CRUD; - - **Controle de entrada e saída de veículos.** +"A Força do Professor + +Um guerreiro sem espada +sem faca, foice ou facão +armado só de amor +segurando um giz na mão +o livro é seu escudo +que lhe protege de tudo +que possa lhe causar dor +por isso eu tenho dito +Tenho fé e acredito +na força do professor. + +Ah... se um dia governantes +prestassem mais atenção +nos verdadeiros heróis +que constroem a nação +ah... se fizessem justiça +sem corpo mole ou preguiça +lhe dando o real valor +eu daria um grande grito +Tenho fé e acredito +na força do professor. + +Porém não sinta vergonha +não se sinta derrotado +se o nosso país vai mal +você não é o culpado +Nas potências mundiais +são sempre heróis nacionais +e por aqui sem valor +mesmo triste e muito aflito +Tenho fé e acredito +na força do professor. + +Um arquiteto de sonhos +Engenheiro do futuro +Um motorista da vida +dirigindo no escuro +Um plantador de esperança +plantando em cada criança +um adulto sonhador +e esse cordel foi escrito +porque ainda acredito +na força do professor.." +Por: **Bráulio Bessa** + +## Estrutura do Projeto +O projeto será dividido em três módulos principais: + + 1. Cadastro do Estabelecimento (CRUD completo) + 2. Cadastro de Veículos (CRUD completo) + 3. Controle de Entrada e Saída de Veículos (registro de entrada/saída e relatórios) + +Além disso, teremos um módulo de autenticação, usando JWT (2 etapa), e a integração com o Flyway para migrações de banco de dados Postgres. +## Dependências +• Spring Web +• Spring Data JPA +• Postgres Database +• Flyway Migration +• Spring Security (para autenticação) +• Lombok (para reduzir código boilerplate) +• Springdoc OpenAPI (para Swagger) + +## Nome do Projeto: **ParkWise** +## Swagger +http://localhost:8080/ParkWise/swagger-ui/index.html#/ + +## TDD (Test-Driven Development) +- **Teste para criarEstabelecimento no EstabelecimentoController**; +- **Teste para criarVeiculo no VeiculoController**; +- **Teste para registrarEntrada no EntradaSaidaController**; ## 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. - -## Questionário para Avaliação de Competências +- Todos os endpoints estão retornando JSON e XML devido a dependência jackson-dataformat-xml no pom.xml +- Requisições GET, POST, PUT ou DELETE funcionando. +- Coloquei já o Spring Secrurity nas ainda não habilitei tudo ainda comentado, v2 ### 1. GraphQL (Implementação BFF - Backend For Frontend) - - **Implementação:** Crie um BFF com GraphQL localmente para permitir as operações de CRUD e controle de entrada e saída de veículos. O BFF deve expor as operações e lidar com as interações entre o front-end e o back-end. - - **Disponibilização:** Após implementar o BFF, disponibilize o projeto publicamente no GitHub, com um link no README para o repositório. - - **Documentação:** Explique no README os benefícios de usar GraphQL no contexto do projeto, descrevendo também como configurar e rodar o BFF localmente. - - **Questões:** Além da implementação, responda às seguintes perguntas no README: - - **Pergunta 1**: Explique o que é o GraphQL e como ele se diferencia de uma API REST tradicional. - - **Pergunta 2**: Descreva como você implementaria o uso do GraphQL como BFF (Backend for Frontend) neste projeto de gerenciamento de estacionamento. Forneça exemplos práticos. - - **Pergunta 3**: Quais são os benefícios de utilizar GraphQL em relação à flexibilidade das consultas? Cite possíveis desafios ao utilizá-lo. + +**Não possuo experiencia em GraphQL, mas posso aprender** ### 2. Banco de Dados (Nível Básico) - - **Pergunta 1**: Explique os principais conceitos de um banco de dados relacional, como tabelas, chaves primárias e estrangeiras. - - **Pergunta 2**: No contexto de uma aplicação de gerenciamento de estacionamento, como você organizaria a modelagem de dados para suportar as funcionalidades de controle de entrada e saída de veículos? - - **Pergunta 3**: Quais seriam as vantagens e desvantagens de utilizar um banco de dados NoSQL neste projeto? + +Resposta 1: + +Imagina que um banco de dados relacional é como uma cidadezinha organizada. As tabelas são como prédios: cada prédio (tabela) tem moradores (linhas) com características específicas, como nome e idade (colunas). + + • Chave Primária: Essa é como o RG de cada morador. Ninguém tem o mesmo e ele garante que cada um é único. Em uma tabela, a chave primária é o que identifica cada linha sem chance de erro. + • Chave Estrangeira: Sabe aquele prédio onde só entra quem é amigo de alguém que já mora lá? A chave estrangeira faz isso entre as tabelas. Ela conecta uma tabela a outra, tipo uma “indicação” para o morador que pertence a outro prédio. É o que liga tudo em uma grande rede de informações. + +Resposta 2: + +Pra montar o sistema de um estacionamento, imagina que a gente tem três blocos de informação: + + 1. Bloco dos Estacionamentos – Aqui é onde ficam os dados do estacionamento em si, como o nome, quantas vagas tem pra carro e moto, endereço, telefone, etc. Imagina uma tabela chamada Estabelecimento onde cada linha é um estacionamento diferente. + 2. Bloco dos Veículos – Agora temos o prédio dos veículos. Cada carro ou moto que entra ganha uma ficha com marca, modelo, cor, placa e tipo (se é carro ou moto). Esse bloco é a tabela Veiculo, e cada linha aqui é um veículo que passa pelo estacionamento. + 3. Bloco de Controle de Entradas e Saídas – Esse é tipo uma “portaria”, registrando a entrada e saída dos veículos. Aqui a gente liga o veículo ao estacionamento e marca os horários de entrada e saída, criando o nosso “histórico de visita”. + +No final das contas, com essas três tabelas conectadas, a gente consegue ver quem entrou e saiu, quanto tempo ficou e ainda monitorar a ocupação do estacionamento. Simples e eficiente! + +Resposta 3: + +Então, e se a gente resolvesse fazer isso tudo num banco de dados NoSQL, em vez do relacional? + +Vantagens: + + • Crescimento na Horizontal + • Flexibilidade de Dados + • Desempenho em Massa + +Desvantagens: + + • Relações Complicadas + • Consistência + • Consultas Complexas + ### 3. Agilidade (Nível Básico) - - **Pergunta 1**: Explique o conceito de metodologias ágeis e como elas impactam o desenvolvimento de software. - - **Pergunta 2**: No desenvolvimento deste projeto, como você aplicaria princípios ágeis para garantir entregas contínuas e com qualidade? - - **Pergunta 3**: Qual a importância da comunicação entre as equipes em um ambiente ágil? Dê exemplos de boas práticas. + +Resposta 1: + +Metodologias ágeis são tipo o jeito moderno de construir software. Em vez de esperar meses pra entregar o projeto inteiro, como numa maratona, o Agile divide o trabalho em várias corridinhas curtas chamadas sprints. Cada sprint é uma entrega, com uma funcionalidade ou melhoria pronta e funcionando. + +Pensar em Agile é lembrar de: + + • Adaptação + • Colaboração + • Entrega rápida + + +Resposta 2: + +Alguns princípios ágeis. + + 1. Dividir em Pequenos Blocos + 2. Reuniões Curtas e Constantes + 3. Feedback Rápido + + +Resposta 3: + +Comunicação é o coração de um ambiente ágil. Imagina tentar fazer um jantar em grupo sem conversar com ninguém. Cada um vai acabar fazendo um prato diferente, sem saber o que o outro tá preparando. No desenvolvimento ágil, sem comunicação, cada um pode acabar indo pra um lado diferente também. + +Boas práticas: + + 1. Daily Stand-Up + 2. Retrospectiva + 3. Ferramentas de Comunicação (Slack, Jira, Trello) + ### 4. DevOps (Nível Básico) - - **Pergunta 1**: O que é DevOps e qual a sua importância para o ciclo de vida de uma aplicação? - - **Pergunta 2**: Descreva como você integraria práticas de DevOps no desenvolvimento desta aplicação de estacionamento. Inclua exemplos de CI/CD. - - **Pergunta 3**: Cite as ferramentas que você usaria para automatizar o processo de deploy e monitoramento da aplicaçã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! 😄 +Resposta 1: + +DevOps é como aquele vizinho “faz-tudo” no prédio. DevOps acelera o ciclo de vida da aplicação, faz tudo fluir melhor e evita aquele clássico “jogo de empurra” entre desenvolvedores e o pessoal de operações. + +Resposta 2: + +Para botar DevOps no projeto ParkWise, usando algumas práticas bem práticas: + + 1. Integração Contínua (CI): Toda vez que alguém faz uma alteração no código, ela é automaticamente testada e integrada no projeto. Tipo uma verificação de qualidade. Exemplo: usando GitHub Actions ou Jenkins, cada vez que alguém faz um “push” no código, o sistema já roda os testes e garante que nada quebrou. + 2. Entrega Contínua (CD): Depois que o código passa nos testes, ele é automaticamente preparado pra deploy. Se tá tudo certo, a aplicação já vai pro ambiente de produção, meio que num “passe de mágica”. Então, qualquer melhoria ou correção que a gente faz vai rápido pro usuário final. + +Pra esse projeto de estacionamento, a gente poderia configurar o CI/CD assim: cada vez que sai uma nova funcionalidade, ela é testada, validada e pronta pra produção de maneira automática. Isso agiliza as entregas e mantém a qualidade lá em cima. + +Resposta 3: + +Pra automatizar o deploy/monitorar essa aplicação, a gente pode usar algumas ferramentas que são tipo “as armas secretas” do DevOps: + + 1. Docker + 2. Jenkins ou GitHub Actions + 3. Kubernetes (sonho de qualque dev) + + +**É tudo obrigado** \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 00000000..19529ddf --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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 +# +# http://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.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100755 index 00000000..249bdf38 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@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 http://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.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..14831c36 --- /dev/null +++ b/pom.xml @@ -0,0 +1,123 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.fcamara.testebackendjava + ParkWise + 0.0.1-SNAPSHOT + ParkWise + ParkWise + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + org.flywaydb + flyway-database-postgresql + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.5.0 + + + jakarta.validation + jakarta.validation-api + 3.0.2 + + + org.postgresql + postgresql + 42.6.0 + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/ParkWiseApplication.java b/src/main/java/com/fcamara/testebackendjava/parkwise/ParkWiseApplication.java new file mode 100644 index 00000000..d83703b2 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/ParkWiseApplication.java @@ -0,0 +1,13 @@ +package com.fcamara.testebackendjava.parkwise; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ParkWiseApplication { + + public static void main(String[] args) { + SpringApplication.run(ParkWiseApplication.class, args); + } + +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/config/SecurityConfig.java b/src/main/java/com/fcamara/testebackendjava/parkwise/config/SecurityConfig.java new file mode 100644 index 00000000..aae02d95 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/config/SecurityConfig.java @@ -0,0 +1,4 @@ +package com.fcamara.testebackendjava.parkwise.config; + +public class SecurityConfig { +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/controller/EntradaSaidaController.java b/src/main/java/com/fcamara/testebackendjava/parkwise/controller/EntradaSaidaController.java new file mode 100644 index 00000000..3cd0d63e --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/controller/EntradaSaidaController.java @@ -0,0 +1,94 @@ +package com.fcamara.testebackendjava.parkwise.controller; + +import com.fcamara.testebackendjava.parkwise.model.EntradaSaida; +import com.fcamara.testebackendjava.parkwise.model.Veiculo; +import com.fcamara.testebackendjava.parkwise.service.EntradaSaidaService; +import com.fcamara.testebackendjava.parkwise.service.VeiculoService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/entradas-saidas") +@Tag(name = "Entradas e Saídas", description = "Endpoints de gestão de entradas e saídas de veículos") +public class EntradaSaidaController { + @Autowired + private EntradaSaidaService entradaSaidaService; + @Autowired + private VeiculoService veiculoService; + + // Registrar entrada de veículo + @PostMapping("/entrada") + @Operation(summary = "Registrar entrada", description = "Registra a entrada de um veículo no estacionamento", + responses = { + @ApiResponse(responseCode = "201", description = "Entrada registrada com sucesso", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = EntradaSaida.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = EntradaSaida.class)) + }) + } + ) + public ResponseEntity registrarEntrada(@RequestBody Veiculo veiculo) { + EntradaSaida entradaSaida = entradaSaidaService.registrarEntrada(veiculo); + return ResponseEntity.status(HttpStatus.CREATED).body(entradaSaida); + } + + // Listar todos os registros de entrada e saída + @GetMapping + @Operation(summary = "Listar entradas e saídas", description = "Retorna uma lista de todos os registros de entrada e saída", + responses = { + @ApiResponse(responseCode = "200", description = "Lista de entradas e saídas", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = EntradaSaida.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = EntradaSaida.class)) + }) + } + ) + public ResponseEntity> listarEntradasSaidas() { + List entradasSaidas = entradaSaidaService.listarEntradasSaidas(); + return ResponseEntity.ok(entradasSaidas); + } + + // Registrar saída de veículo + @PutMapping("/saida/{id}") + @Operation(summary = "Registrar saída", description = "Registra a saída de um veículo no estacionamento", + responses = { + @ApiResponse(responseCode = "200", description = "Saída registrada com sucesso", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = EntradaSaida.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = EntradaSaida.class)) + }), + @ApiResponse(responseCode = "404", description = "Registro de entrada não encontrado") + } + ) + public ResponseEntity registrarSaida(@PathVariable Long id) { + try { + EntradaSaida entradaSaidaAtualizada = entradaSaidaService.registrarSaida(id); + return ResponseEntity.ok(entradaSaidaAtualizada); + } catch (RuntimeException e) { + return ResponseEntity.notFound().build(); + } + } + + // Deletar um registro de entrada e saída por ID + @DeleteMapping("/{id}") + @Operation(summary = "Excluir registro de entrada/saída", description = "Remove um registro de entrada e saída do sistema pelo ID", + responses = { + @ApiResponse(responseCode = "204", description = "Registro excluído com sucesso"), + @ApiResponse(responseCode = "404", description = "Registro não encontrado") + } + ) + public ResponseEntity deletarEntradaSaida(@PathVariable Long id) { + entradaSaidaService.deletarEntradaSaida(id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/controller/EstabelecimentoController.java b/src/main/java/com/fcamara/testebackendjava/parkwise/controller/EstabelecimentoController.java new file mode 100644 index 00000000..74092215 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/controller/EstabelecimentoController.java @@ -0,0 +1,108 @@ +package com.fcamara.testebackendjava.parkwise.controller; + + +import com.fcamara.testebackendjava.parkwise.model.Estabelecimento; +import com.fcamara.testebackendjava.parkwise.service.EstabelecimentoService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/estabelecimentos") +@Tag(name = "Estabelecimentos", description = "Endpoints de gestão de estabelecimentos") +public class EstabelecimentoController { + @Autowired + private EstabelecimentoService service; + @Autowired + private EstabelecimentoService estabelecimentoService; + + @PostMapping + @Operation(summary = "Criar estabelecimento", description = "Adiciona um novo estabelecimento ao sistema", + responses = { + @ApiResponse(responseCode = "201", description = "Estabelecimento criado com sucesso", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Estabelecimento.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Estabelecimento.class)) + }) + }) + public ResponseEntity criarEstabelecimento(@RequestBody @Valid Estabelecimento estabelecimento) { + return ResponseEntity.status(HttpStatus.CREATED).body(service.salvarEstabelecimento(estabelecimento)); + } + + // Obter um estabelecimento por ID + @GetMapping("/{id}") + @Operation(summary = "Obter estabelecimento por ID", description = "Retorna os detalhes de um estabelecimento específico", + responses = { + @ApiResponse(responseCode = "200", description = "Estabelecimento encontrado", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Estabelecimento.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Estabelecimento.class)) + }), + @ApiResponse(responseCode = "404", description = "Estabelecimento não encontrado") + } + ) + public ResponseEntity obterEstabelecimento(@PathVariable Long id) { + return service.obterEstabelecimentoPorId(id) + .map(ResponseEntity::ok) + .orElse(ResponseEntity.notFound().build()); + } + + // Listar todos os estabelecimentos + @GetMapping + @Operation(summary = "Listar estabelecimentos", description = "Retorna uma lista de todos os estabelecimentos", + responses = { + @ApiResponse(responseCode = "200", description = "Lista de estabelecimentos", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Estabelecimento.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Estabelecimento.class)) + }) + } + ) + public ResponseEntity> listarEstabelecimentos() { + List estabelecimentos = estabelecimentoService.listarEstabelecimentos(); + return ResponseEntity.ok(estabelecimentos); + } + + @PutMapping("/{id}") + @Operation(summary = "Atualizar estabelecimento", description = "Atualiza as informações de um estabelecimento existente", + responses = { + @ApiResponse(responseCode = "200", description = "Estabelecimento atualizado com sucesso", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Estabelecimento.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Estabelecimento.class)) + }), + @ApiResponse(responseCode = "404", description = "Estabelecimento não encontrado") + } + ) + public ResponseEntity atualizarEstabelecimento(@PathVariable Long id, @RequestBody Estabelecimento estabelecimento) { + try { + Estabelecimento estabelecimentoAtualizado = estabelecimentoService.atualizarEstabelecimento(id, estabelecimento); + return ResponseEntity.ok(estabelecimentoAtualizado); + } catch (RuntimeException e) { + return ResponseEntity.notFound().build(); + } + } + + @DeleteMapping("/{id}") + @Operation(summary = "Excluir estabelecimento", description = "Remove um estabelecimento do sistema pelo ID", + responses = { + @ApiResponse(responseCode = "204", description = "Estabelecimento excluído com sucesso"), + @ApiResponse(responseCode = "404", description = "Estabelecimento não encontrado") + } + ) + public ResponseEntity deletarEstabelecimento(@PathVariable Long id) { + estabelecimentoService.deletarEstabelecimento(id); + return ResponseEntity.noContent().build(); + } + +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/controller/VeiculoController.java b/src/main/java/com/fcamara/testebackendjava/parkwise/controller/VeiculoController.java new file mode 100644 index 00000000..0a6dc765 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/controller/VeiculoController.java @@ -0,0 +1,108 @@ +package com.fcamara.testebackendjava.parkwise.controller; + +import com.fcamara.testebackendjava.parkwise.model.Veiculo; +import com.fcamara.testebackendjava.parkwise.service.VeiculoService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/api/veiculos") +@Tag(name = "Veículos", description = "Endpoints de gestão de veículos") +public class VeiculoController { + @Autowired + private VeiculoService veiculoService; + + // Criar veículo + @PostMapping + @Operation(summary = "Criar veículo", description = "Adiciona um novo veículo ao sistema", + responses = { + @ApiResponse(responseCode = "201", description = "Veículo criado com sucesso", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Veiculo.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Veiculo.class)) + }) + } + ) + public ResponseEntity criarVeiculo(@RequestBody Veiculo veiculo) { + Veiculo novoVeiculo = veiculoService.salvarVeiculo(veiculo); + return ResponseEntity.status(HttpStatus.CREATED).body(novoVeiculo); + } + + // Listar todos os veículos + @GetMapping + @Operation(summary = "Listar veículos", description = "Retorna uma lista de todos os veículos", + responses = { + @ApiResponse(responseCode = "200", description = "Lista de veículos", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Veiculo.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Veiculo.class)) + }) + } + ) + public ResponseEntity> listarVeiculos() { + List veiculos = veiculoService.listarVeiculos(); + return ResponseEntity.ok(veiculos); + } + + // Obter um veículo por ID + @GetMapping("/{id}") + @Operation(summary = "Obter veículo por ID", description = "Retorna os detalhes de um veículo específico", + responses = { + @ApiResponse(responseCode = "200", description = "Veículo encontrado", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Veiculo.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Veiculo.class)) + }), + @ApiResponse(responseCode = "404", description = "Veículo não encontrado") + } + ) + public ResponseEntity obterVeiculoPorId(@PathVariable Long id) { + Optional veiculo = veiculoService.obterVeiculoPorId(id); + return veiculo.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + } + + // Atualizar um veículo por ID + @PutMapping("/{id}") + @Operation(summary = "Atualizar veículo", description = "Atualiza as informações de um veículo existente", + responses = { + @ApiResponse(responseCode = "200", description = "Veículo atualizado com sucesso", + content = { + @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Veiculo.class)), + @Content(mediaType = MediaType.APPLICATION_XML_VALUE, schema = @Schema(implementation = Veiculo.class)) + }), + @ApiResponse(responseCode = "404", description = "Veículo não encontrado") + } + ) + public ResponseEntity atualizarVeiculo(@PathVariable Long id, @RequestBody Veiculo veiculo) { + try { + Veiculo veiculoAtualizado = veiculoService.atualizarVeiculo(id, veiculo); + return ResponseEntity.ok(veiculoAtualizado); + } catch (RuntimeException e) { + return ResponseEntity.notFound().build(); + } + } + + // Deletar um veículo por ID + @DeleteMapping("/{id}") + @Operation(summary = "Excluir veículo", description = "Remove um veículo do sistema pelo ID", + responses = { + @ApiResponse(responseCode = "204", description = "Veículo excluído com sucesso"), + @ApiResponse(responseCode = "404", description = "Veículo não encontrado") + } + ) + public ResponseEntity deletarVeiculo(@PathVariable Long id) { + veiculoService.deletarVeiculo(id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/model/EntradaSaida.java b/src/main/java/com/fcamara/testebackendjava/parkwise/model/EntradaSaida.java new file mode 100644 index 00000000..9ebddd59 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/model/EntradaSaida.java @@ -0,0 +1,28 @@ +package com.fcamara.testebackendjava.parkwise.model; + + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.antlr.v4.runtime.misc.NotNull; + +import java.time.LocalDateTime; + +@Entity +@Data // Gera automaticamente getters, setters, equals, hashCode e toString +@NoArgsConstructor // Gera um construtor sem argumentos +@AllArgsConstructor +public class EntradaSaida { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne + private Veiculo veiculo; + + @NotNull + private LocalDateTime entrada; + + private LocalDateTime saida; +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/model/Estabelecimento.java b/src/main/java/com/fcamara/testebackendjava/parkwise/model/Estabelecimento.java new file mode 100644 index 00000000..2a6c74d4 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/model/Estabelecimento.java @@ -0,0 +1,42 @@ +package com.fcamara.testebackendjava.parkwise.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.antlr.v4.runtime.misc.NotNull; + + +@Entity +@Data // Gera automaticamente getters, setters, equals, hashCode e toString +@NoArgsConstructor // Gera um construtor sem argumentos +@AllArgsConstructor // Gera um construtor com todos os argumentos +public class Estabelecimento { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotNull + private String nome; + + @NotNull + private String cnpj; + + @NotNull + private String endereco; + + @NotNull + private String telefone; + + @NotNull + private int vagasMotos; + + @NotNull + private int vagasCarros; + + @NotNull + private String email; +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/model/Veiculo.java b/src/main/java/com/fcamara/testebackendjava/parkwise/model/Veiculo.java new file mode 100644 index 00000000..9f784893 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/model/Veiculo.java @@ -0,0 +1,39 @@ +package com.fcamara.testebackendjava.parkwise.model; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.antlr.v4.runtime.misc.NotNull; + +@Entity +@Data // Gera automaticamente getters, setters, equals, hashCode e toString +@NoArgsConstructor // Gera um construtor sem argumentos +@AllArgsConstructor // Gera um construtor com todos os argumentos +public class Veiculo { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotNull + private String marca; + + @NotNull + private String modelo; + + @NotNull + private String cor; + + @NotNull + private String placa; + + @Enumerated(EnumType.STRING) + @NotNull + private TipoVeiculo tipo; + + + public enum TipoVeiculo { + CARRO, MOTO + } +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/repository/EntradaSaidaRepository.java b/src/main/java/com/fcamara/testebackendjava/parkwise/repository/EntradaSaidaRepository.java new file mode 100644 index 00000000..d8afe2e5 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/repository/EntradaSaidaRepository.java @@ -0,0 +1,10 @@ +package com.fcamara.testebackendjava.parkwise.repository; + +import com.fcamara.testebackendjava.parkwise.model.EntradaSaida; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EntradaSaidaRepository extends JpaRepository { + // Métodos personalizados podem ser adicionados aqui, se necessário +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/repository/EstabelecimentoRepository.java b/src/main/java/com/fcamara/testebackendjava/parkwise/repository/EstabelecimentoRepository.java new file mode 100644 index 00000000..7e8ac0a3 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/repository/EstabelecimentoRepository.java @@ -0,0 +1,8 @@ +package com.fcamara.testebackendjava.parkwise.repository; + +import com.fcamara.testebackendjava.parkwise.model.Estabelecimento; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EstabelecimentoRepository extends JpaRepository { } diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/repository/VeiculoRepository.java b/src/main/java/com/fcamara/testebackendjava/parkwise/repository/VeiculoRepository.java new file mode 100644 index 00000000..3262c4c6 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/repository/VeiculoRepository.java @@ -0,0 +1,9 @@ +package com.fcamara.testebackendjava.parkwise.repository; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import com.fcamara.testebackendjava.parkwise.model.Veiculo; + +@Repository +public interface VeiculoRepository extends JpaRepository { + // Métodos personalizados podem ser adicionados aqui, se necessário +} \ No newline at end of file diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/service/EntradaSaidaService.java b/src/main/java/com/fcamara/testebackendjava/parkwise/service/EntradaSaidaService.java new file mode 100644 index 00000000..781607e2 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/service/EntradaSaidaService.java @@ -0,0 +1,49 @@ +package com.fcamara.testebackendjava.parkwise.service; + +import com.fcamara.testebackendjava.parkwise.model.EntradaSaida; +import com.fcamara.testebackendjava.parkwise.model.Veiculo; +import com.fcamara.testebackendjava.parkwise.repository.EntradaSaidaRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +@Service +public class EntradaSaidaService { + + @Autowired + private EntradaSaidaRepository entradaSaidaRepository; + + // Create (Registrar Entrada) + public EntradaSaida registrarEntrada(Veiculo veiculo) { + EntradaSaida entradaSaida = new EntradaSaida(); + entradaSaida.setVeiculo(veiculo); + entradaSaida.setEntrada(LocalDateTime.now()); + return entradaSaidaRepository.save(entradaSaida); + } + + // Read + public List listarEntradasSaidas() { + return entradaSaidaRepository.findAll(); + } + + public Optional obterEntradaSaidaPorId(Long id) { + return entradaSaidaRepository.findById(id); + } + + // Update (Registrar Saída) + public EntradaSaida registrarSaida(Long id) { + EntradaSaida entradaSaida = entradaSaidaRepository.findById(id) + .orElseThrow(() -> new RuntimeException("Entrada/Saída não encontrada")); + + entradaSaida.setSaida(LocalDateTime.now()); + return entradaSaidaRepository.save(entradaSaida); + } + + // Delete + public void deletarEntradaSaida(Long id) { + entradaSaidaRepository.deleteById(id); + } +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/service/EstabelecimentoService.java b/src/main/java/com/fcamara/testebackendjava/parkwise/service/EstabelecimentoService.java new file mode 100644 index 00000000..27e4ee0d --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/service/EstabelecimentoService.java @@ -0,0 +1,41 @@ +package com.fcamara.testebackendjava.parkwise.service; + +import com.fcamara.testebackendjava.parkwise.model.Estabelecimento; +import com.fcamara.testebackendjava.parkwise.repository.EstabelecimentoRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class EstabelecimentoService { + @Autowired + private EstabelecimentoRepository estabelecimentoRepository; + + // Create + public Estabelecimento salvarEstabelecimento(Estabelecimento estabelecimento) { + return estabelecimentoRepository.save(estabelecimento); + } + // Read + public List listarEstabelecimentos() { + return estabelecimentoRepository.findAll(); + } + + public Optional obterEstabelecimentoPorId(Long id) { + return estabelecimentoRepository.findById(id); + } + // Update + public Estabelecimento atualizarEstabelecimento(Long id, Estabelecimento estabelecimento) { + if (estabelecimentoRepository.existsById(id)) { + estabelecimento.setId(id); // Garantir que o ID seja mantido + return estabelecimentoRepository.save(estabelecimento); + } + throw new RuntimeException("Estabelecimento não encontrado"); + } + + // Delete + public void deletarEstabelecimento(Long id) { + estabelecimentoRepository.deleteById(id); + } +} diff --git a/src/main/java/com/fcamara/testebackendjava/parkwise/service/VeiculoService.java b/src/main/java/com/fcamara/testebackendjava/parkwise/service/VeiculoService.java new file mode 100644 index 00000000..24c69207 --- /dev/null +++ b/src/main/java/com/fcamara/testebackendjava/parkwise/service/VeiculoService.java @@ -0,0 +1,43 @@ +package com.fcamara.testebackendjava.parkwise.service; + +import com.fcamara.testebackendjava.parkwise.model.Veiculo; +import com.fcamara.testebackendjava.parkwise.repository.VeiculoRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class VeiculoService { + @Autowired + private VeiculoRepository veiculoRepository; + + // Create + public Veiculo salvarVeiculo(Veiculo veiculo) { + return veiculoRepository.save(veiculo); + } + + // Read + public List listarVeiculos() { + return veiculoRepository.findAll(); + } + + public Optional obterVeiculoPorId(Long id) { + return veiculoRepository.findById(id); + } + + // Update + public Veiculo atualizarVeiculo(Long id, Veiculo veiculo) { + if (veiculoRepository.existsById(id)) { + veiculo.setId(id); // Garantir que o ID seja mantido + return veiculoRepository.save(veiculo); + } + throw new RuntimeException("Veículo não encontrado"); + } + + // Delete + public void deletarVeiculo(Long id) { + veiculoRepository.deleteById(id); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..8a0b566d --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,34 @@ +spring.application.name=ParkWise +server.servlet.context-path=/ParkWise +# Configura��es do datasource +#spring.datasource.url=jdbc:h2:mem:estacionamento +#spring.datasource.driver-class-name=org.h2.Driver +#spring.datasource.username=sa +#spring.datasource.password=password + +# Configurações do datasource para PostgreSQL +spring.datasource.url=jdbc:postgresql://localhost:5432/estacionamento +spring.datasource.username=postgres +spring.datasource.password= +spring.datasource.driver-class-name=org.postgresql.Driver + +# Configurações do JPA +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect + + + +# Configurações do JPA +spring.jpa.hibernate.ddl-auto=validate + +# Configurações do Flyway +spring.flyway.enabled=true + +# Configurações do Springdoc OpenAPI para Swagger +springdoc.api-docs.enabled=true +springdoc.swagger-ui.path=/swagger-ui.html + + + +#spring.security.user.name=admin +#spring.security.user.password=admin + diff --git a/src/main/resources/db/migration/V1__Create_tables.sql b/src/main/resources/db/migration/V1__Create_tables.sql new file mode 100644 index 00000000..871038a9 --- /dev/null +++ b/src/main/resources/db/migration/V1__Create_tables.sql @@ -0,0 +1,26 @@ +CREATE TABLE estabelecimento ( + id BIGSERIAL PRIMARY KEY, + nome VARCHAR(100) NOT NULL, + cnpj VARCHAR(18) NOT NULL, + endereco VARCHAR(255) NOT NULL, + telefone VARCHAR(20) NOT NULL, + vagas_motos INT NOT NULL, + vagas_carros INT NOT NULL +); + +CREATE TABLE veiculo ( + id BIGSERIAL PRIMARY KEY, + marca VARCHAR(50) NOT NULL, + modelo VARCHAR(50) NOT NULL, + cor VARCHAR(50) NOT NULL, + placa VARCHAR(10) NOT NULL, + tipo VARCHAR(5) NOT NULL +); + +CREATE TABLE entrada_saida ( + id BIGSERIAL PRIMARY KEY, + veiculo_id BIGINT, + entrada TIMESTAMP NOT NULL, + saida TIMESTAMP, + FOREIGN KEY (veiculo_id) REFERENCES veiculo(id) +); \ No newline at end of file diff --git a/src/main/resources/db/migration/V2__Add_email_to_estabelecimento.sql b/src/main/resources/db/migration/V2__Add_email_to_estabelecimento.sql new file mode 100644 index 00000000..3a8172ae --- /dev/null +++ b/src/main/resources/db/migration/V2__Add_email_to_estabelecimento.sql @@ -0,0 +1 @@ +ALTER TABLE estabelecimento ADD COLUMN email VARCHAR(100); diff --git a/src/main/resources/db/migration/V3__Insert_initial_data.sql b/src/main/resources/db/migration/V3__Insert_initial_data.sql new file mode 100644 index 00000000..894778b0 --- /dev/null +++ b/src/main/resources/db/migration/V3__Insert_initial_data.sql @@ -0,0 +1,26 @@ +-- Carga inicial de dados para a tabela estabelecimento, incluindo o campo email +INSERT INTO estabelecimento (nome, cnpj, endereco, telefone, email, vagas_motos, vagas_carros) +VALUES + ('Estacionamento Central', '12.345.678/0001-00', 'Rua Principal, 123', '(85) 1234-5678', 'contato@central.com', 10, 50), + ('Estacionamento Norte', '98.765.432/0001-99', 'Avenida Norte, 456', '(85) 8765-4321', 'contato@norte.com', 15, 30); + +-- Carga inicial de dados para a tabela veiculo +INSERT INTO veiculo (marca, modelo, cor, placa, tipo) +VALUES + ('Toyota', 'Corolla', 'Prata', 'ABC-1234', 'CARRO'), + ('Honda', 'Civic', 'Preto', 'DEF-5678', 'CARRO'), + ('Yamaha', 'Fazer', 'Azul', 'GHI-9101', 'MOTO'), + ('Honda', 'CB500', 'Vermelha', 'JKL-1213', 'MOTO'); + +-- Carga inicial de dados para a tabela entrada_saida +-- Assume-se que os veículos com IDs 1 e 2 já tenham registros de entrada +INSERT INTO entrada_saida (veiculo_id, entrada, saida) +VALUES + (1, '2024-10-14 08:00:00', '2024-10-14 10:00:00'), + (2, '2024-10-14 09:00:00', '2024-10-14 11:30:00'); + +-- Inserindo entradas sem saída registrada +INSERT INTO entrada_saida (veiculo_id, entrada) +VALUES + (3, '2024-10-14 12:00:00'), + (4, '2024-10-14 12:30:00'); \ No newline at end of file diff --git a/src/test/java/com/fcamara/testebackendjava/parkwise/EntradaSaidaControllerTest.java b/src/test/java/com/fcamara/testebackendjava/parkwise/EntradaSaidaControllerTest.java new file mode 100644 index 00000000..a52d8990 --- /dev/null +++ b/src/test/java/com/fcamara/testebackendjava/parkwise/EntradaSaidaControllerTest.java @@ -0,0 +1,59 @@ +package com.fcamara.testebackendjava.parkwise; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.any; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fcamara.testebackendjava.parkwise.controller.EntradaSaidaController; +import com.fcamara.testebackendjava.parkwise.model.EntradaSaida; +import com.fcamara.testebackendjava.parkwise.model.Veiculo; +import com.fcamara.testebackendjava.parkwise.service.EntradaSaidaService; +import com.fcamara.testebackendjava.parkwise.service.VeiculoService; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.time.LocalDateTime; + +@WebMvcTest(EntradaSaidaController.class) +public class EntradaSaidaControllerTest { + @Autowired + private MockMvc mockMvc; + + @MockBean + private EntradaSaidaService entradaSaidaService; + + @MockBean + private VeiculoService veiculoService; // Adiciona o MockBean para VeiculoService + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void deveRegistrarEntrada() throws Exception { + // Dados do veículo e registro de entrada + Veiculo veiculo = new Veiculo( + 1L, "Toyota", "Corolla", "Prata", "ABC-1234", Veiculo.TipoVeiculo.CARRO + ); + + LocalDateTime entradaDataHora = LocalDateTime.of(2024, 10, 14, 8, 0); + EntradaSaida entradaSaida = new EntradaSaida(1L, veiculo, entradaDataHora, null); + + // Configura o mock para retornar o registro de entrada + when(entradaSaidaService.registrarEntrada(any(Veiculo.class))).thenReturn(entradaSaida); + + String veiculoJson = objectMapper.writeValueAsString(veiculo); + + mockMvc.perform(post("/api/entradas-saidas/entrada") + .contentType("application/json") + .content(veiculoJson)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.veiculo.marca").value("Toyota")) + .andExpect(jsonPath("$.entrada").value("2024-10-14T08:00:00")); + } +} \ No newline at end of file diff --git a/src/test/java/com/fcamara/testebackendjava/parkwise/EstabelecimentoControllerTest.java b/src/test/java/com/fcamara/testebackendjava/parkwise/EstabelecimentoControllerTest.java new file mode 100644 index 00000000..a329e875 --- /dev/null +++ b/src/test/java/com/fcamara/testebackendjava/parkwise/EstabelecimentoControllerTest.java @@ -0,0 +1,48 @@ +package com.fcamara.testebackendjava.parkwise; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fcamara.testebackendjava.parkwise.controller.EstabelecimentoController; +import com.fcamara.testebackendjava.parkwise.model.Estabelecimento; +import com.fcamara.testebackendjava.parkwise.service.EstabelecimentoService; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + +@WebMvcTest(EstabelecimentoController.class) +public class EstabelecimentoControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private EstabelecimentoService estabelecimentoService; + + @Autowired + private ObjectMapper objectMapper; + @Test + public void deveCriarEstabelecimento() throws Exception { + Estabelecimento estabelecimento = new Estabelecimento( + null, "Estacionamento Central", "12.345.678/0001-00", "Rua Principal, 123", + "(85) 1234-5678", 10, 50, "contato@central.com" + ); + + // Configura o mock para retornar o estabelecimento quando o método salvar for chamado + when(estabelecimentoService.salvarEstabelecimento(any(Estabelecimento.class))).thenReturn(estabelecimento); + + String estabelecimentoJson = objectMapper.writeValueAsString(estabelecimento); + + mockMvc.perform(post("/api/estabelecimentos") + .contentType("application/json") + .content(estabelecimentoJson)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.nome").value("Estacionamento Central")); + } +} \ No newline at end of file diff --git a/src/test/java/com/fcamara/testebackendjava/parkwise/ParkWiseApplicationTests.java b/src/test/java/com/fcamara/testebackendjava/parkwise/ParkWiseApplicationTests.java new file mode 100644 index 00000000..1c03fc96 --- /dev/null +++ b/src/test/java/com/fcamara/testebackendjava/parkwise/ParkWiseApplicationTests.java @@ -0,0 +1,13 @@ +package com.fcamara.testebackendjava.parkwise; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ParkWiseApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/fcamara/testebackendjava/parkwise/VeiculoControllerTest.java b/src/test/java/com/fcamara/testebackendjava/parkwise/VeiculoControllerTest.java new file mode 100644 index 00000000..61f281b1 --- /dev/null +++ b/src/test/java/com/fcamara/testebackendjava/parkwise/VeiculoControllerTest.java @@ -0,0 +1,51 @@ +package com.fcamara.testebackendjava.parkwise; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fcamara.testebackendjava.parkwise.controller.VeiculoController; +import com.fcamara.testebackendjava.parkwise.model.Veiculo; +import com.fcamara.testebackendjava.parkwise.service.VeiculoService; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + + +@WebMvcTest(VeiculoController.class) +public class VeiculoControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private VeiculoService veiculoService; + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void deveCriarVeiculo() throws Exception { + Veiculo veiculo = new Veiculo( + null, "Toyota", "Corolla", "Prata", "ABC-1234", Veiculo.TipoVeiculo.CARRO + ); + + // Mocka o retorno do serviço + when(veiculoService.salvarVeiculo(any(Veiculo.class))).thenReturn(veiculo); + + String veiculoJson = objectMapper.writeValueAsString(veiculo); + + mockMvc.perform(post("/api/veiculos") + .contentType("application/json") + .content(veiculoJson)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.marca").value("Toyota")) + .andExpect(jsonPath("$.modelo").value("Corolla")); + } +} \ No newline at end of file