diff --git a/README.md b/README.md index 9af96c3d7..bf45271d8 100644 --- a/README.md +++ b/README.md @@ -115,3 +115,14 @@ A tela do tipo SELECAO exibe uma lista de opções para que o usuário. O aplicativo envia uma requisição POST para a url informada e com o body definido pelo objeto dentro de cada item da lista de seleção, quando o mesmo é acionado, semelhando ao funcionamento dos botões da tela FORMULARIO. # desafio-votacao + +# regras para rodar o teste +Estou sando o Spring boot versão 3.4.0 +MySQL 8.0 e estou usando o DBeaver para interagir com os dados do banco não estou usando Docker. +As configurações estão dentro do Application.properties +A IDE que estou usando é o Intellij. +Tive alguns bugs na pordução da API com a classe de Validação de CPF e isso me atrasou muito e ainda +não consegui resolver estes problemas, está salvando o CPF no banco está gerando a sessão mais ainda +não está fazendo a validação do cpf se me derem até sexta feira eu entrego com a validação de CPF e +tempo que a sessão ficará online. + \ No newline at end of file diff --git a/votacao-old/.gitattributes b/votacao-old/.gitattributes new file mode 100644 index 000000000..3b41682ac --- /dev/null +++ b/votacao-old/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/votacao-old/.gitignore b/votacao-old/.gitignore new file mode 100644 index 000000000..549e00a2a --- /dev/null +++ b/votacao-old/.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/votacao-old/.mvn/wrapper/maven-wrapper.properties b/votacao-old/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..d58dfb70b --- /dev/null +++ b/votacao-old/.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/votacao-old/mvnw b/votacao-old/mvnw new file mode 100644 index 000000000..19529ddf8 --- /dev/null +++ b/votacao-old/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/votacao-old/mvnw.cmd b/votacao-old/mvnw.cmd new file mode 100644 index 000000000..249bdf382 --- /dev/null +++ b/votacao-old/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/votacao-old/pom.xml b/votacao-old/pom.xml new file mode 100644 index 000000000..5a028338a --- /dev/null +++ b/votacao-old/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.0 + + + com.dbserver.votacao + votacao + 0.0.1-SNAPSHOT + Votação api back end + Votação project for Spring Boot + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework + spring-context + 6.1.2 + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-hateoas + + + org.springframework + spring-beans + 6.1.2 + + + com.mysql + mysql-connector-j + runtime + + + org.projectlombok + lombok + true + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java new file mode 100644 index 000000000..1c7950370 --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java @@ -0,0 +1,13 @@ +package com.dbserver.votacao.votacao; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VotacaoApplication { + + public static void main(String[] args) { + SpringApplication.run(VotacaoApplication.class, args); + } + +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java new file mode 100644 index 000000000..8d6b7be9e --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java @@ -0,0 +1,65 @@ +package com.dbserver.votacao.votacao.controller; + +import com.dbserver.votacao.votacao.dto.ClienteRecordDto; +import com.dbserver.votacao.votacao.model.Cliente; +import com.dbserver.votacao.votacao.service.ClienteService; +import jakarta.validation.Valid; +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; +import java.util.Optional; + +@RestController +@RequestMapping +public class ClienteController { + @Autowired + private ClienteService clienteService; + + @PostMapping("/clientes") + @ResponseBody + public ResponseEntity salveCliente(@RequestBody @Valid ClienteRecordDto clienteRecordDto) { + var cliente = new Cliente(); + BeanUtils.copyProperties(clienteRecordDto, cliente); + return ResponseEntity.status(HttpStatus.CREATED).body(clienteService.salvarCliente(cliente)); + } + /* + @GetMapping("/clientes") + public ResponseEntity> getAllCliente() { + return ResponseEntity.status(HttpStatus.OK).body(clienteService.getAll()); + } + + @GetMapping("/clientes/{idCliente}") + public ResponseEntity getOneCliente(@PathVariable(value = "idCliente")UUID idCliente) { + Optional clienteOptional = clienteService.getById(idCliente); + if(clienteOptional.isEmpty()){ + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cliente não encontrado!"); + } + return ResponseEntity.status(HttpStatus.OK).body(clienteOptional.get()); + } + + @PutMapping("/clientes/{idCliente}") + public ResponseEntity atualizaCliente(@PathVariable(value = "idCliente") UUID idCliente, @RequestBody @Valid ClienteRecordDto clienteRecordDto) { + Optional clienteOptional = clienteService.getById(idCliente); + if(clienteOptional.isEmpty()){ + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cliente não encontrado!"); + } + var cliente = clienteOptional.get(); + BeanUtils.copyProperties(clienteRecordDto, cliente); + return ResponseEntity.status(HttpStatus.OK).body(clienteService.salvarCliente(cliente)); + } + + @DeleteMapping("/clientes/{idCliente}") + public ResponseEntity deleteCliente(@PathVariable(value = "idCliente") UUID idCliente) throws EntityInUseException { + if (idCliente != null) { + clienteService.deletarCliente(idCliente); + return ResponseEntity.status(HttpStatus.OK).body("Cliente deletado com sucesso!"); + + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cliente não encontrado!"); + } + */ +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRecordDto.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRecordDto.java new file mode 100644 index 000000000..67e5b354e --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRecordDto.java @@ -0,0 +1,6 @@ +package com.dbserver.votacao.votacao.dto; + +import jakarta.validation.constraints.NotBlank; + +public record ClienteRecordDto (@NotBlank String nomeCliente, @NotBlank String cpf){ +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRequestDto.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRequestDto.java new file mode 100644 index 000000000..e323b3b79 --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRequestDto.java @@ -0,0 +1,16 @@ +package com.dbserver.votacao.votacao.dto; + +import lombok.*; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class ClienteRequestDto { + + private String nomeCliente; + + private String cpf; + +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java new file mode 100644 index 000000000..08ac41fc4 --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java @@ -0,0 +1,31 @@ +package com.dbserver.votacao.votacao.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.io.Serializable; +import java.util.UUID; + +@Setter +@Getter +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "tbl_clientes") +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +public class Cliente implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @EqualsAndHashCode.Include + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "cliente_id") + private UUID idCliente; + + @Column(name = "cpf", length = 14, nullable = false) + private String cpf; + + @Column(name = "nome_cliente", length = 40, nullable = false) + private String nomeCliente; +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java new file mode 100644 index 000000000..128233fbd --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java @@ -0,0 +1,13 @@ +package com.dbserver.votacao.votacao.model; + +public class Sessao { + + private Long idSessao; + + + private String voto; + + + // private Cliente cliente; + +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java new file mode 100644 index 000000000..1e3d6d983 --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java @@ -0,0 +1,14 @@ +package com.dbserver.votacao.votacao.repository; + +import com.dbserver.votacao.votacao.model.Cliente; +import jakarta.persistence.Id; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.yaml.snakeyaml.events.Event; + +import java.util.UUID; + +@Repository +public interface ClienteRepository extends JpaRepository { + +} diff --git a/votacao-old/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java b/votacao-old/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java new file mode 100644 index 000000000..1ec68d83d --- /dev/null +++ b/votacao-old/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java @@ -0,0 +1,55 @@ +package com.dbserver.votacao.votacao.service; + +import com.dbserver.votacao.votacao.model.Cliente; +import com.dbserver.votacao.votacao.repository.ClienteRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class ClienteService { + + @Autowired + private ClienteRepository clienteRepository; + + public Cliente salvarCliente(Cliente cliente){ + if(cliente != null){ + clienteRepository.save(cliente); + System.out.println("O cliente, " + cliente + ", foi salvo com sucesso!!"); + + }else{ + System.out.println("O cliente já existe!!!"); + + } + return cliente; + } +/* + public List getAll(){ + + return (clienteRepository.findAll()); + } + + public Optional getById(UUID idCliente){ + + return clienteRepository.findById(idCliente); + } + + public Cliente atualizarCliente(UUID idCliente) { + + return clienteRepository.getReferenceById(idCliente); + } + + public void deletarCliente (UUID idCliente) throws EntityInUseException { + try { + clienteRepository.deleteById(idCliente); + } catch (EmptyResultDataAccessException e) { + throw new EntityNotFoundException(String.format("Não há registro de cliente com código %d", idCliente)); + } catch (DataIntegrityViolationException e) { + throw new EntityInUseException(String.format("O cliente do código %d não pode ser removido porque está em uso ", idCliente)); + } + } + + */ +} diff --git a/votacao-old/src/main/resources/application.properties b/votacao-old/src/main/resources/application.properties new file mode 100644 index 000000000..02d86a084 --- /dev/null +++ b/votacao-old/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=votacao + +server.port=8080 + +spring.datasource.url=jdbc:mysql://${DB_HOST:localhost}/db_votacao?createDatabaseIfNotExist=true&serverTimezone=UTC +spring.datasource.username=root +spring.datasource.password=12345 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect + +spring.jpa.show-sql=true +spring.jpa.generate-ddl=true + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.open-in-view=false diff --git a/votacao-old/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java b/votacao-old/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java new file mode 100644 index 000000000..2ab70c51a --- /dev/null +++ b/votacao-old/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java @@ -0,0 +1,15 @@ +/* +package com.dbserver.votacao.votacao; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class VotacaoApplicationTests { + + @Test + void contextLoads() { + } + +} + */ diff --git a/votacao.zip b/votacao.zip new file mode 100644 index 000000000..be3292e4e Binary files /dev/null and b/votacao.zip differ diff --git a/votacao/.gitattributes b/votacao/.gitattributes new file mode 100644 index 000000000..3b41682ac --- /dev/null +++ b/votacao/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/votacao/.gitignore b/votacao/.gitignore new file mode 100644 index 000000000..549e00a2a --- /dev/null +++ b/votacao/.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/votacao/.mvn/wrapper/maven-wrapper.properties b/votacao/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..d58dfb70b --- /dev/null +++ b/votacao/.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/votacao/Dockerfile b/votacao/Dockerfile new file mode 100644 index 000000000..ed5d502ab --- /dev/null +++ b/votacao/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:24-ea-17-slim +WORKDIR /app +COPY target/*.jar /app/votacao.jar +EXPOSE 8080 +CMD ["java", "-jar", "votacao.jar"] \ No newline at end of file diff --git a/votacao/README.md b/votacao/README.md new file mode 100644 index 000000000..64954f0e9 --- /dev/null +++ b/votacao/README.md @@ -0,0 +1,189 @@ +# Votação + +## Objetivo + +No cooperativismo, cada associado possui um voto e as decisões são tomadas em assembleias, por votação. Imagine que você deve criar uma solução para dispositivos móveis para gerenciar e participar dessas sessões de votação. +Essa solução deve ser executada na nuvem e promover as seguintes funcionalidades através de uma API REST: + +- Cadastrar uma nova pauta +- Abrir uma sessão de votação em uma pauta (a sessão de votação deve ficar aberta por + um tempo determinado na chamada de abertura ou 1 minuto por default) +- Receber votos dos associados em pautas (os votos são apenas 'Sim'/'Não'. Cada associado + é identificado por um id único e pode votar apenas uma vez por pauta) +- Contabilizar os votos e dar o resultado da votação na pauta + +Para fins de exercício, a segurança das interfaces pode ser abstraída e qualquer chamada para as interfaces pode ser considerada como autorizada. A solução deve ser construída em java, usando Spring-boot, mas os frameworks e bibliotecas são de livre escolha (desde que não infrinja direitos de uso). + +É importante que as pautas e os votos sejam persistidos e que não sejam perdidos com o restart da aplicação. + +O foco dessa avaliação é a comunicação entre o backend e o aplicativo mobile. Essa comunicação é feita através de mensagens no formato JSON, onde essas mensagens serão interpretadas pelo cliente para montar as telas onde o usuário vai interagir com o sistema. A aplicação cliente não faz parte da avaliação, apenas os componentes do servidor. O formato padrão dessas mensagens será detalhado no anexo 1. + +## Como proceder + +Por favor, realize o FORK desse repositório e implemente sua solução no FORK em seu repositório GItHub, ao final, notifique da conclusão para que possamos analisar o código implementado. + +Lembre de deixar todas as orientações necessárias para executar o seu código. + +### Tarefas bônus + +- Tarefa Bônus 1 - Integração com sistemas externos + - Criar uma Facade/Client Fake que retorna aleátoriamente se um CPF recebido é válido ou não. + - Caso o CPF seja inválido, a API retornará o HTTP Status 404 (Not found). Você pode usar geradores de CPF para gerar CPFs válidos + - Caso o CPF seja válido, a API retornará se o usuário pode (ABLE_TO_VOTE) ou não pode (UNABLE_TO_VOTE) executar a operação. Essa operação retorna resultados aleatórios, portanto um mesmo CPF pode funcionar em um teste e não funcionar no outro. + +``` +// CPF Ok para votar +{ + "status": "ABLE_TO_VOTE +} +// CPF Nao Ok para votar - retornar 404 no client tb +{ + "status": "UNABLE_TO_VOTE +} +``` + +Exemplos de retorno do serviço + +### Tarefa Bônus 2 - Performance + +- Imagine que sua aplicação possa ser usada em cenários que existam centenas de + milhares de votos. Ela deve se comportar de maneira performática nesses + cenários +- Testes de performance são uma boa maneira de garantir e observar como sua + aplicação se comporta + +### Tarefa Bônus 3 - Versionamento da API + +○ Como você versionaria a API da sua aplicação? Que estratégia usar? + +## O que será analisado + +- Simplicidade no design da solução (evitar over engineering) +- Organização do código +- Arquitetura do projeto +- Boas práticas de programação (manutenibilidade, legibilidade etc) +- Possíveis bugs +- Tratamento de erros e exceções +- Explicação breve do porquê das escolhas tomadas durante o desenvolvimento da solução +- Uso de testes automatizados e ferramentas de qualidade +- Limpeza do código +- Documentação do código e da API +- Logs da aplicação +- Mensagens e organização dos commits + +## Dicas + +- Teste bem sua solução, evite bugs +- Deixe o domínio das URLs de callback passiveis de alteração via configuração, para facilitar + o teste tanto no emulador, quanto em dispositivos fisicos. + Observações importantes +- Não inicie o teste sem sanar todas as dúvidas +- Iremos executar a aplicação para testá-la, cuide com qualquer dependência externa e + deixe claro caso haja instruções especiais para execução do mesmo + Classificação da informação: Uso Interno + +## Anexo 1 + +### Introdução + +A seguir serão detalhados os tipos de tela que o cliente mobile suporta, assim como os tipos de campos disponíveis para a interação do usuário. + +### Tipo de tela – FORMULARIO + +A tela do tipo FORMULARIO exibe uma coleção de campos (itens) e possui um ou dois botões de ação na parte inferior. + +O aplicativo envia uma requisição POST para a url informada e com o body definido pelo objeto dentro de cada botão quando o mesmo é acionado. Nos casos onde temos campos de entrada +de dados na tela, os valores informados pelo usuário são adicionados ao corpo da requisição. Abaixo o exemplo da requisição que o aplicativo vai fazer quando o botão “Ação 1” for acionado: + +``` +POST http://seudominio.com/ACAO1 +{ + “campo1”: “valor1”, + “campo2”: 123, + “idCampoTexto”: “Texto”, + “idCampoNumerico: 999 + “idCampoData”: “01/01/2000” +} +``` + +Obs: o formato da url acima é meramente ilustrativo e não define qualquer padrão de formato. + +### Tipo de tela – SELECAO + +A tela do tipo SELECAO exibe uma lista de opções para que o usuário. + +O aplicativo envia uma requisição POST para a url informada e com o body definido pelo objeto dentro de cada item da lista de seleção, quando o mesmo é acionado, semelhando ao funcionamento dos botões da tela FORMULARIO. + +# desafio-votacao + +# regras para rodar o teste +# INSTRUÇÕES DA API DE VOTAÇÃO +# 1° passo +OBS: Para rodar a API localmente, faça um clone do projeto, instale o MySQL na sua maquina ou crie um +container Docker das duas formas funciona adicione as regras de usuário senha e as siga as intruções de +instalação do MySQL na sua máquina que vc pode ver em qualquer tutorial no youtube ou na documentação da +Oracle. + +# 2° passo MySQL +Criar a base de dados no MySQL. VERSÃO DO MySQL:8.0.39 + +# 3° passo rodar o projeto na sua máquina. +Feito isso é só subir o projeto na tua máquina, usando o STS, Eclipse ou Intellij qualquer uma dessas +interfaces vai funcionar ou IDE de sua preferência. + +# 4° passo framework do projeto +O Spring Boot 3.4.0 é a versão que eu uso no momento para gerar o projeto e vai gerar as tabelas e +adcionar os dados já existentes se tiverem ou criar novos dados. + +# 5° passo fazer o build do projeto +RODAR O COMANDO build: Clique com botão direito do mouse na raiz do projeto, vá até a opção Maven e ai +clique em (RELOAD PROJECT) para que o Maven atualize as dependêcias do projeto. + +# 6° passo url usadas para teste +POST http://localhost:8080/clientes GET http://localhost:8080/clientes +POST http://localhost:8080/sessoes GET http://localhost:8080/sessoes + +# 7° passo comando para rodar o docker +docker-compose -f mysql-docker-compose.yml up -d OBS: rodei na porta:3307, porque na minha máquina, +eu tenho o MySQL instalado e ele usa a porta 3306 se vc não tiver o MySQL instalado na sua máquina vc +pode rodar o container na porta 3306. E a porta para rodar o container é: http://localhost:8000/ +Usuário: root Senha:12345 + +# 7°.1 passo configurando o properties +Fazer a configuração no properties para que a aplicação se conecte com o container e vc possa estar +usando o banco de dados em container, não vou colocar o passo a passo porque essas configurações são +basicas então acredito que vcs consigam fazer sem as instruços. Pode ser usado a interface: PhpAdmin, +DBeaver, Workbenck, HeidSQL e etc... + +# 7°.2 passo Criando a imagem docker da api +Comando para gerar o build da imagem dokcerfile: docker image build -t votacao-projeto-reserva . Comando +para subir a imagem e manter a imagem no ar: docker container run -p 8080:8080 votacao-projeto-reserva +Comando para subir a imagem e encerrar: docker container run --rm -p 8080:8080 votacao-projeto-reserva + +# 7°.3 passos para subir os containers na network +Comando para fazer o build da imagem: +Rodar esse comando dentro da pasta do projeto para que ele faça a atualização do jar do projeto: +(./mvnw clean package) +Depois roda o comando do Docker para jerar o build: +docker image build -t desafio-votacao . + +Comando para subir a imagem da API: +docker container run --rm -p 8080:8080 desafio-votacao +Nome da imagem desafio-votacao + +Comando para iniciar o container do MySQL: +docker run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=12345 --name desafio-votacao-mysql mysql:8.0 + +Comando para criar a network para acolocar os container criados: +docker network create desafio-votacao-network + +Comando para adicionar o container do MySQL dentro da rede: +docker container run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=12345 --network desafio-votacao-network --name desafio-votacao-mysql mysql:8.0 +Nome da rede desafio-votacao-network + +Comando para adicionar o container da API dentro da rede: +docker container run --rm -p 8080:8080 -e DB_HOST=desafio-votacao-mysql --network desafio-votacao-network desafio-votacao + +# 7°.4 local onde está o Front-End do projeto e todas as regras para rodar o Front-End +https://github.com/josewalter/desafio-votacao-front-end-angular + \ No newline at end of file diff --git a/votacao/mvnw b/votacao/mvnw new file mode 100644 index 000000000..19529ddf8 --- /dev/null +++ b/votacao/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/votacao/mvnw.cmd b/votacao/mvnw.cmd new file mode 100644 index 000000000..249bdf382 --- /dev/null +++ b/votacao/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/votacao/mysql-docker-compose.yml b/votacao/mysql-docker-compose.yml new file mode 100644 index 000000000..2fb85e25b --- /dev/null +++ b/votacao/mysql-docker-compose.yml @@ -0,0 +1,21 @@ +version: '3.1' + +services: + + db: + image: mysql:8.0.39 + volumes: + - dbbase:/var/lib/mysql + ports: + - "3306:3306" + environment: + MYSQL_ROOT_PASSWORD: 12345 + MYSQL_DATABASE: db_votacao + + phpmyadmin: + image: phpmyadmin + ports: + - 8000:80 + +volumes: + dbbase: \ No newline at end of file diff --git a/votacao/pom.xml b/votacao/pom.xml new file mode 100644 index 000000000..b7cf7b16a --- /dev/null +++ b/votacao/pom.xml @@ -0,0 +1,99 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.0 + + + com.dbserver.votacao + votacao + 0.0.1-SNAPSHOT + votacao + Votação project for Spring Boot + + + + + + + + + + + + + + + 23 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.mysql + mysql-connector-j + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-validation + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java b/votacao/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java new file mode 100644 index 000000000..67e28bd25 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java @@ -0,0 +1,12 @@ +package com.dbserver.votacao.votacao; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VotacaoApplication { + + public static void main(String[] args) { + SpringApplication.run(VotacaoApplication.class, args); + } +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java new file mode 100644 index 000000000..1bee67b82 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java @@ -0,0 +1,39 @@ +package com.dbserver.votacao.votacao.controller; + +import com.dbserver.votacao.votacao.model.Cliente; +import com.dbserver.votacao.votacao.service.ClienteService; +import com.dbserver.votacao.votacao.util.ValidacaoCpf; +import jakarta.validation.Valid; +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 +@CrossOrigin(origins = "http://localhost:4200") +public class ClienteController { + @Autowired + private ClienteService clienteService; + + @ResponseBody + @PostMapping("/clientes") + public ResponseEntity salvaCliente(@RequestBody @Valid Cliente cliente) throws Exception { + + if (ValidacaoCpf.isCPF(cliente.getCpf())) { + cliente = clienteService.salvarCliente(cliente); + //throw new Exception("CPF: " + cliente.getCpf() + "status: ABLE_TO_VOTE" ); + return ResponseEntity.status(HttpStatus.OK).body("CPF: " + cliente.getCpf() + " status: ABLE_TO_VOTE" ); + }else { + // throw new Exception("CPF: " + cliente.getCpf() + "status: ABLE_TO_VOTE" ); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(" status: UNABLE_TO_VOTE "); + } + } + + @GetMapping("/clientes") + public ResponseEntity> getAllCliente() { + return ResponseEntity.status(HttpStatus.OK).body(clienteService.getAll()); + } +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java new file mode 100644 index 000000000..3f378f6b3 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java @@ -0,0 +1,32 @@ +package com.dbserver.votacao.votacao.controller; + +import com.dbserver.votacao.votacao.model.Sessao; +import com.dbserver.votacao.votacao.service.SessaoService; +import jakarta.validation.Valid; +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 +@CrossOrigin(origins = "http://localhost:4200") +public class SessaoController { + @Autowired + private SessaoService sessaoService; + + @ResponseBody + @PostMapping("/sessoes") + public ResponseEntity salvarSessao(@RequestBody @Valid Sessao sessao) throws Exception { + + sessao = sessaoService.salvarSessao(sessao); + return new ResponseEntity(sessao, HttpStatus.OK); + } + + @GetMapping("/sessoes") + public ResponseEntity> getAllSessao() { + return ResponseEntity.status(HttpStatus.OK).body(sessaoService.getAll()); + } +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/ClienteRecordDto.java b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/ClienteRecordDto.java new file mode 100644 index 000000000..d31f138bf --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/ClienteRecordDto.java @@ -0,0 +1,11 @@ +package com.dbserver.votacao.votacao.dto.recordDto; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +import java.util.UUID; + +public record ClienteRecordDto (@NotBlank String nomeCliente, @NotBlank String cpf){ +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/SessaoRecordDto.java b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/SessaoRecordDto.java new file mode 100644 index 000000000..554d06e69 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/SessaoRecordDto.java @@ -0,0 +1,9 @@ +package com.dbserver.votacao.votacao.dto.recordDto; + +import com.dbserver.votacao.votacao.model.Cliente; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public record SessaoRecordDto(@NotBlank String voto, @NotNull Cliente cliente){ + +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/ClienteRequestDto.java b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/ClienteRequestDto.java new file mode 100644 index 000000000..71c48127c --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/ClienteRequestDto.java @@ -0,0 +1,16 @@ +package com.dbserver.votacao.votacao.dto.requestDto; + +import lombok.*; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class ClienteRequestDto { + + private String nomeCliente; + + private String cpf; + +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/SessaoRequestDto.java b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/SessaoRequestDto.java new file mode 100644 index 000000000..8799d9e87 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/SessaoRequestDto.java @@ -0,0 +1,16 @@ +package com.dbserver.votacao.votacao.dto.requestDto; + +import lombok.*; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class SessaoRequestDto { + + private String voto; + + private String cliente; + +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java new file mode 100644 index 000000000..5434ae010 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java @@ -0,0 +1,29 @@ +package com.dbserver.votacao.votacao.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.io.Serializable; +import java.util.UUID; + +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "tbl_clientes") +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +public class Cliente implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @EqualsAndHashCode.Include + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "cliente_id") + private UUID idCliente; + + @Column(name = "cpf", length = 14, nullable = false) + private String cpf; + + @Column(name = "nome_cliente", length = 40, nullable = false) + private String nomeCliente; +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java new file mode 100644 index 000000000..367777dcb --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java @@ -0,0 +1,31 @@ +package com.dbserver.votacao.votacao.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.io.Serializable; +import java.util.UUID; + +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "tbl_sessao") +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +public class Sessao implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @EqualsAndHashCode.Include + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "sessao_id") + private UUID idSessao; + + @Column(name = "voto", length = 4, nullable = false) + private String voto; + + @ManyToOne + //@JoinColumn(name = "cliente_id") + private Cliente cliente; + +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java new file mode 100644 index 000000000..2d934ba89 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java @@ -0,0 +1,16 @@ +package com.dbserver.votacao.votacao.repository; + +import com.dbserver.votacao.votacao.model.Cliente; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface ClienteRepository extends JpaRepository { + /* + @Query(value = "SELECT c FROM tbl_clientes c WHERE c.cpf = ?") + public Cliente existeCadastroCpf(String cpf); + + */ +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java new file mode 100644 index 000000000..264a6ac4e --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java @@ -0,0 +1,13 @@ +package com.dbserver.votacao.votacao.repository; + +import com.dbserver.votacao.votacao.dto.recordDto.SessaoRecordDto; +import com.dbserver.votacao.votacao.model.Sessao; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface SessaoRepository extends JpaRepository { + +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java b/votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java new file mode 100644 index 000000000..d5e714912 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java @@ -0,0 +1,26 @@ +package com.dbserver.votacao.votacao.service; + +import com.dbserver.votacao.votacao.model.Cliente; +import com.dbserver.votacao.votacao.repository.ClienteRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class ClienteService { + + @Autowired + private ClienteRepository clienteRepository; + + public Cliente salvarCliente(Cliente cliente) { + + clienteRepository.save(cliente); + System.out.println("O cliente" + cliente + ", foi salva com sucesso!!"); + return cliente; + } + + public List getAll(){ + return clienteRepository.findAll(); + } +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java b/votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java new file mode 100644 index 000000000..73e2ce109 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java @@ -0,0 +1,47 @@ +package com.dbserver.votacao.votacao.service; + +import com.dbserver.votacao.votacao.model.Sessao; +import com.dbserver.votacao.votacao.repository.SessaoRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class SessaoService { + + @Autowired + private SessaoRepository sessaoRepository; + + public Sessao salvarSessao(Sessao sessao) { + + sessaoRepository.save(sessao); + System.out.println("O sessao" + sessao + ", foi salva com sucesso!!"); + return sessao; + + /* + for (int i = 0; i < sessao.getCliente().getCpf().equalsIgnoreCase(); i++) { + sessao.getCliente().getCpf(); + sessao.getCliente().getNomeCliente(); + } + + + ValidacaoCpf isCpf = new ValidacaoCpf(610.658.880-58); + if (ValidacaoCpf.isCpf(clienteRepository.getCpf())){ + System.out.println("status: ABLE_TO_VOTE"); + }else { + System.out.println("status: UNABLE_TO_VOTE"); + } + + sessaoRepository.save(sessao); + System.out.println("A sessão, " + sessao + ", foi salva com sucesso!!"); + return sessao; + + */ + } + + public List getAll(){ + + return sessaoRepository.findAll(); + } +} diff --git a/votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java b/votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java new file mode 100644 index 000000000..51d47534f --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java @@ -0,0 +1,71 @@ +package com.dbserver.votacao.votacao.util; + +import java.util.InputMismatchException; + +public class ValidacaoCpf { + + public static boolean isCPF(String CPF) { + + CPF = CPF.replaceAll("\\.", "").replaceAll("\\/", "") + .replaceAll("\\-", ""); + + // considera-se erro CPF"s formados por uma sequencia de numeros iguais + if (CPF.equals("00000000000") || + CPF.equals("11111111111") || + CPF.equals("22222222222") || CPF.equals("33333333333") || + CPF.equals("44444444444") || CPF.equals("55555555555") || + CPF.equals("66666666666") || CPF.equals("77777777777") || + CPF.equals("88888888888") || CPF.equals("99999999999") || + (CPF.length() != 11)) + return(false); + + char dig10, dig11; + int sm, i, r, num, peso; + + // "try" - protege o codigo para eventuais erros de conversao de tipo (int) + try { + // Calculo do 1o. Digito Verificador + sm = 0; + peso = 10; + for (i=0; i<9; i++) { + // converte o i-esimo caractere do CPF em um numero: + // por exemplo, transforma o caractere "0" no inteiro 0 + // (48 eh a posicao de "0" na tabela ASCII) + num = (int)(CPF.charAt(i) - 48); + sm = sm + (num * peso); + peso = peso - 1; + } + + r = 11 - (sm % 11); + if ((r == 10) || (r == 11)) + dig10 = '0'; + else dig10 = (char)(r + 48); // converte no respectivo caractere numerico + + // Calculo do 2o. Digito Verificador + sm = 0; + peso = 11; + for(i=0; i<10; i++) { + num = (int)(CPF.charAt(i) - 48); + sm = sm + (num * peso); + peso = peso - 1; + } + + r = 11 - (sm % 11); + if ((r == 10) || (r == 11)) + dig11 = '0'; + else dig11 = (char)(r + 48); + + // Verifica se os digitos calculados conferem com os digitos informados. + if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10))) + return(true); + else return(false); + } catch (InputMismatchException erro) { + return(false); + } + } + + public static String imprimeCPF(String CPF) { + return(CPF.substring(0, 3) + "." + CPF.substring(3, 6) + "." + + CPF.substring(6, 9) + "-" + CPF.substring(9, 11)); + } +} diff --git a/votacao/src/main/resources/application.properties b/votacao/src/main/resources/application.properties new file mode 100644 index 000000000..acd81f4d7 --- /dev/null +++ b/votacao/src/main/resources/application.properties @@ -0,0 +1,17 @@ +spring.application.name=votacao + +server.port=8080 + +spring.datasource.url=jdbc:mysql://${DB_HOST:localhost}/db_votacao?createDatabaseIfNotExist=true&serverTimezone=UTC +spring.datasource.username=root +spring.datasource.password=12345 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect + +spring.jpa.show-sql=true +spring.jpa.generate-ddl=true + +spring.jpa.hibernate.ddl-auto=update +spring.jpa.open-in-view=false diff --git a/votacao/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java b/votacao/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java new file mode 100644 index 000000000..691f24a59 --- /dev/null +++ b/votacao/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java @@ -0,0 +1,15 @@ +/* + package com.dbserver.votacao.votacao; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class VotacaoApplicationTests { + + @Test + void contextLoads() { + } + +} + */