From 383b6b0df45113139c9eae2bf7b9480192a07cec Mon Sep 17 00:00:00 2001 From: josewalter Date: Tue, 24 Dec 2024 16:30:56 -0300 Subject: [PATCH 1/6] =?UTF-8?q?Primeiro=20commit=20com=20as=20classes=20cl?= =?UTF-8?q?iente,=20e=20sess=C3=A3o=20etc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- votacao/.gitattributes | 2 + votacao/.gitignore | 33 +++ votacao/.mvn/wrapper/maven-wrapper.properties | 19 ++ votacao/mvnw | 259 ++++++++++++++++++ votacao/mvnw.cmd | 149 ++++++++++ votacao/pom.xml | 99 +++++++ .../votacao/votacao/VotacaoApplication.java | 12 + .../votacao/controller/ClienteController.java | 55 ++++ .../votacao/controller/SessaoController.java | 46 ++++ .../dto/recordDto/ClienteRecordDto.java | 8 + .../dto/recordDto/SessaoRecordDto.java | 8 + .../dto/requestDto/ClienteRequestDto.java | 16 ++ .../dto/requestDto/SessaoRequestDto.java | 16 ++ .../votacao/votacao/model/Cliente.java | 29 ++ .../votacao/votacao/model/Sessao.java | 31 +++ .../votacao/repository/ClienteRepository.java | 17 ++ .../votacao/repository/SessaoRepository.java | 12 + .../votacao/service/ClienteService.java | 36 +++ .../votacao/service/SessaoService.java | 43 +++ .../src/main/resources/application.properties | 17 ++ .../votacao/VotacaoApplicationTests.java | 15 + 21 files changed, 922 insertions(+) create mode 100644 votacao/.gitattributes create mode 100644 votacao/.gitignore create mode 100644 votacao/.mvn/wrapper/maven-wrapper.properties create mode 100644 votacao/mvnw create mode 100644 votacao/mvnw.cmd create mode 100644 votacao/pom.xml create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/ClienteRecordDto.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/SessaoRecordDto.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/ClienteRequestDto.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/dto/requestDto/SessaoRequestDto.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java create mode 100644 votacao/src/main/resources/application.properties create mode 100644 votacao/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java diff --git a/votacao/.gitattributes b/votacao/.gitattributes new file mode 100644 index 00000000..3b41682a --- /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 00000000..549e00a2 --- /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 00000000..d58dfb70 --- /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/mvnw b/votacao/mvnw new file mode 100644 index 00000000..19529ddf --- /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 00000000..249bdf38 --- /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/pom.xml b/votacao/pom.xml new file mode 100644 index 00000000..b7cf7b16 --- /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 00000000..67e28bd2 --- /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 00000000..11a493ea --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java @@ -0,0 +1,55 @@ +package com.dbserver.votacao.votacao.controller; + +import com.dbserver.votacao.votacao.model.Cliente; +import com.dbserver.votacao.votacao.repository.ClienteRepository; +import com.dbserver.votacao.votacao.service.ClienteService; +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 +public class ClienteController { + @Autowired + private ClienteService clienteService; + + /* + @Autowired + private ClienteRepository clienteRepository; + + @Autowired + private ValidacaoCpf validacaoCpf; + */ + + @ResponseBody + @PostMapping("/clientes") + public ResponseEntity salvaCliente(@RequestBody @Valid Cliente cliente) throws Exception { + /* + if (cliente == null) { + throw new Exception("Cliente não pode ser NULL"); + } + + if (cliente.getIdCliente() == null && clienteRepository.existeCadastroCpf(cliente.getCpf()) != null) { + throw new Exception("Já existe um CPF cadastrado com esse número! " + cliente.getCpf()); + } + + if (!validacaoCpf.isCPF()) { + throw new Exception("CPF: " + cliente.getCpf() + "status: UNABLE_TO_VOTE" ); + }else { + throw new Exception("CPF: " + cliente.getCpf() + "status: ABLE_TO_VOTE" ); + } + */ + cliente = clienteService.salvarCliente(cliente); + + return new ResponseEntity(cliente, HttpStatus.OK); + } + + @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 00000000..1755c7cd --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java @@ -0,0 +1,46 @@ +//package com.dbserver.votacao.votacao.controller; +// +//import com.dbserver.votacao.votacao.model.Cliente; +//import com.dbserver.votacao.votacao.model.Sessao; +//import com.dbserver.votacao.votacao.service.SessaoService; +//import com.dbserver.votacao.votacaoutil.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 +//public class SessaoController { +// @Autowired +// private SessaoService sessaoService; +// +// @ResponseBody +// @PostMapping("/sessoes") +// public ResponseEntity salvarSessao(@RequestBody @Valid Cliente cliente) throws Exception { +// +// if (cliente == null) { +// throw new Exception("Cliente não pode ser NULL"); +// } +// +// if (cliente.getIdCliente() == null && sessaoService.salvarSessao(cliente.getCpf()) != null){ +// throw new Exception("status: UNABLE_TO_VOTE" + cliente.getCpf()); +// } +// +// if (!ValidacaoCpf.isCPF(cliente.getCpf())) { +// throw new Exception("CPF : " + cliente.getCpf() + "status: UNABLE_TO_VOTE"); +// return new ResponseEntity(cliente, HttpStatus.NOT_FOUND); +// }else { +// cliente = sessaoService.salvarSessao(); +// return new ResponseEntity(cliente, 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 00000000..1032e123 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/ClienteRecordDto.java @@ -0,0 +1,8 @@ +package com.dbserver.votacao.votacao.dto.recordDto; + +import jakarta.validation.constraints.NotBlank; + +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 00000000..f3873835 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/dto/recordDto/SessaoRecordDto.java @@ -0,0 +1,8 @@ +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 00000000..71c48127 --- /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 00000000..8799d9e8 --- /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 00000000..46aab0d2 --- /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 = 11, 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 00000000..8cbe9b66 --- /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 00000000..3f85b5fb --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java @@ -0,0 +1,17 @@ +package com.dbserver.votacao.votacao.repository; + +import com.dbserver.votacao.votacao.model.Cliente; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface ClienteRepository extends JpaRepository { + /* + @Query(value = "SELECT c FROM db_votacao.tbl_clientes c WHERE c.cpf = ?1") + 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 00000000..0e4a4890 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java @@ -0,0 +1,12 @@ +package com.dbserver.votacao.votacao.repository; + +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 00000000..e1776437 --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java @@ -0,0 +1,36 @@ +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.io.UnsupportedEncodingException; +import java.util.List; + +@Service +public class ClienteService { + + @Autowired + private ClienteRepository clienteRepository; + + public Cliente salvarCliente(Cliente cliente) { + /* + for (int i = 0; i < cliente.getCpf().length(); i++) { + try { + cliente.getCpf().getBytes(String.valueOf(i)).toString(); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + cliente.getNomeCliente().chars().toString(); + } + */ + 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 00000000..d3c7e39b --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java @@ -0,0 +1,43 @@ +//package com.dbserver.votacao.votacao.service; +// +//import com.dbserver.votacao.votacao.model.Sessao; +//import com.dbserver.votacao.votacao.repository.ClienteRepository; +//import com.dbserver.votacao.votacao.repository.SessaoRepository; +//import com.dbserver.votacao.votacaoutil.ValidacaoCpf; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.stereotype.Service; +// +//import java.util.List; +// +//@Service +//public class SessaoService { +// +// @Autowired +// private SessaoRepository sessaoRepository; +// private ClienteRepository clienteRepository +// +// public Sessao salvarSessao(String 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/resources/application.properties b/votacao/src/main/resources/application.properties new file mode 100644 index 00000000..72ef5238 --- /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://localhost:3306/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=create +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 00000000..691f24a5 --- /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() { + } + +} + */ From bcf9985cab4da144294ab54bd133df907d330c17 Mon Sep 17 00:00:00 2001 From: josewalter Date: Tue, 24 Dec 2024 16:54:17 -0300 Subject: [PATCH 2/6] =?UTF-8?q?=20Subindo=20a=20classe=20de=20Valida=C3=A7?= =?UTF-8?q?=C3=A3o=20de=20CPF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../votacao/votacao/util/ValidacaoCpf.java | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java 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 00000000..436706ba --- /dev/null +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java @@ -0,0 +1,93 @@ +package com.dbserver.votacao.votacao.util; + +import javax.swing.text.DefaultFormatterFactory; +import javax.swing.text.MaskFormatter; + +public class ValidacaoCpf { + + private String cpf; + private static final String Formato = "###.###.###-##"; + + public ValidacaoCpf(String C) { + this.cpf = this.Format(C,false); + } + + public boolean isCPF(){ + + if (this.cpf.equals("00000000000") || + this.cpf.equals("11111111111") || + this.cpf.equals("22222222222") || + this.cpf.equals("33333333333") || + this.cpf.equals("44444444444") || + this.cpf.equals("55555555555") || + this.cpf.equals("66666666666") || + this.cpf.equals("77777777777") || + this.cpf.equals("88888888888") || + this.cpf.equals("99999999999") || + this.cpf.length() != 11) + return(false); + + char dig10, dig11; + int sm, i, r, num, peso; + + try { + // Calculo do primeiro Digito Verificador + sm = 0; + peso = 10; + for (i=0; i<9; i++) { + num = (int)(this.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); + + // Calculo do segundo Digito Verificador + sm = 0; + peso = 11; + for(i=0; i<10; i++) { + num = (int)(this.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); + + if ((dig10 == this.cpf.charAt(9)) && (dig11 == this.cpf.charAt(10))) + return(true); + else return(false); + } catch(Exception e) { + return(false); + } + } + + public String getCPF(boolean Mascara) { + return Format(this.cpf,Mascara); + } + + private String Format(String C, boolean Mascara){ + if(Mascara){ + return(C.substring(0, 3) + "." + C.substring(3, 6) + "." + + C.substring(6, 9) + "-" + C.substring(9, 11)); + }else{ + C = C.replace(".",""); + C = C.replace("-",""); + return C; + } + } + + + public static DefaultFormatterFactory getFormat(){ + try { + return new DefaultFormatterFactory(new MaskFormatter(Formato)); + } catch (Exception e) { + return null; + } + } +} From 196b32610c4e6cd5118274307bd697999e790f9b Mon Sep 17 00:00:00 2001 From: josewalter Date: Mon, 30 Dec 2024 15:10:25 -0300 Subject: [PATCH 3/6] =?UTF-8?q?Atualiza=C3=A7=C3=A3o=20de=20arquivos=20que?= =?UTF-8?q?=20estavam=20dando=20erro=20no=20teste?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 11 ++ votacao/Dockerfile | 5 + votacao/README.md | 177 ++++++++++++++++++ votacao/mysql-docker-compose.yml | 21 +++ .../votacao/controller/ClienteController.java | 33 +--- .../votacao/controller/SessaoController.java | 81 ++++---- .../dto/recordDto/ClienteRecordDto.java | 3 + .../dto/recordDto/SessaoRecordDto.java | 1 + .../votacao/votacao/model/Cliente.java | 2 +- .../votacao/votacao/model/Sessao.java | 2 +- .../votacao/repository/ClienteRepository.java | 3 +- .../votacao/repository/SessaoRepository.java | 1 + .../votacao/service/ClienteService.java | 12 +- .../votacao/service/SessaoService.java | 90 ++++----- .../votacao/votacao/util/ValidacaoCpf.java | 82 +++----- .../src/main/resources/application.properties | 4 +- 16 files changed, 346 insertions(+), 182 deletions(-) create mode 100644 votacao/Dockerfile create mode 100644 votacao/README.md create mode 100644 votacao/mysql-docker-compose.yml diff --git a/README.md b/README.md index 9af96c3d..bf45271d 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/Dockerfile b/votacao/Dockerfile new file mode 100644 index 00000000..ed5d502a --- /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 00000000..f2e7ecaa --- /dev/null +++ b/votacao/README.md @@ -0,0 +1,177 @@ +# 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 aplicação back-end docker image build -t votacao-projeto-reserva . + +Comando para subir o container do MySQL: +docker container run -d -p 3307:3307 -e MYSQL_ROOT_PASSWORD=12345 --network votacao-projeto-reserva-network --name +votacao-projeto-reserva-mysql mysql:8.0 + +Comando para subir a aplicação back-end: +docker container run -d -p 8080:8080 -e DB_HOST=votacao-projeto-reserva-mysql --network votacao-projeto-reserva-network +votacao-projeto-reserva + + + + + \ No newline at end of file diff --git a/votacao/mysql-docker-compose.yml b/votacao/mysql-docker-compose.yml new file mode 100644 index 00000000..83555b0c --- /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: + - "3307:3307" + 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/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java index 11a493ea..2867a4d1 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java @@ -1,8 +1,8 @@ package com.dbserver.votacao.votacao.controller; import com.dbserver.votacao.votacao.model.Cliente; -import com.dbserver.votacao.votacao.repository.ClienteRepository; 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; @@ -17,35 +17,20 @@ public class ClienteController { @Autowired private ClienteService clienteService; - /* - @Autowired - private ClienteRepository clienteRepository; - - @Autowired - private ValidacaoCpf validacaoCpf; - */ - @ResponseBody @PostMapping("/clientes") - public ResponseEntity salvaCliente(@RequestBody @Valid Cliente cliente) throws Exception { - /* - if (cliente == null) { - throw new Exception("Cliente não pode ser NULL"); - } - - if (cliente.getIdCliente() == null && clienteRepository.existeCadastroCpf(cliente.getCpf()) != null) { - throw new Exception("Já existe um CPF cadastrado com esse número! " + cliente.getCpf()); - } + public ResponseEntity salvaCliente(@RequestBody @Valid Cliente cliente) throws Exception { - if (!validacaoCpf.isCPF()) { - throw new Exception("CPF: " + cliente.getCpf() + "status: UNABLE_TO_VOTE" ); + 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" ); + // throw new Exception("CPF: " + cliente.getCpf() + "status: ABLE_TO_VOTE" ); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(" status: UNABLE_TO_VOTE "); } - */ - cliente = clienteService.salvarCliente(cliente); - return new ResponseEntity(cliente, HttpStatus.OK); + // return ResponseEntity.status(HttpStatus.OK).body(clienteService.salvarCliente(cliente)); } @GetMapping("/clientes") 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 index 1755c7cd..8b7b8dcd 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java @@ -1,46 +1,35 @@ -//package com.dbserver.votacao.votacao.controller; -// -//import com.dbserver.votacao.votacao.model.Cliente; -//import com.dbserver.votacao.votacao.model.Sessao; -//import com.dbserver.votacao.votacao.service.SessaoService; -//import com.dbserver.votacao.votacaoutil.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 -//public class SessaoController { -// @Autowired -// private SessaoService sessaoService; -// -// @ResponseBody -// @PostMapping("/sessoes") -// public ResponseEntity salvarSessao(@RequestBody @Valid Cliente cliente) throws Exception { -// -// if (cliente == null) { -// throw new Exception("Cliente não pode ser NULL"); -// } -// -// if (cliente.getIdCliente() == null && sessaoService.salvarSessao(cliente.getCpf()) != null){ -// throw new Exception("status: UNABLE_TO_VOTE" + cliente.getCpf()); -// } -// -// if (!ValidacaoCpf.isCPF(cliente.getCpf())) { -// throw new Exception("CPF : " + cliente.getCpf() + "status: UNABLE_TO_VOTE"); -// return new ResponseEntity(cliente, HttpStatus.NOT_FOUND); -// }else { -// cliente = sessaoService.salvarSessao(); -// return new ResponseEntity(cliente, HttpStatus.OK); -// } -// } -// -// @GetMapping("/sessoes") -// public ResponseEntity> getAllSessao() { -// return ResponseEntity.status(HttpStatus.OK).body(sessaoService.getAll()); -// } -//} +package com.dbserver.votacao.votacao.controller; + +import com.dbserver.votacao.votacao.model.Sessao; +import com.dbserver.votacao.votacao.service.SessaoService; +import jakarta.servlet.http.HttpSession; +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 +public class SessaoController { + @Autowired + private SessaoService sessaoService; + + @ResponseBody + @PostMapping("/sessoes") + public ResponseEntity salvarSessao(@RequestBody @Valid Sessao sessao) throws Exception { + /* + HttpSession session = sessao.se; + session.setMaxInactiveInterval(60); + */ + 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 index 1032e123..d31f138b 100644 --- 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 @@ -1,6 +1,9 @@ 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; 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 index f3873835..554d06e6 100644 --- 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 @@ -5,4 +5,5 @@ 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/model/Cliente.java b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java index 46aab0d2..5434ae01 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java @@ -21,7 +21,7 @@ public class Cliente implements Serializable { @Column(name = "cliente_id") private UUID idCliente; - @Column(name = "cpf", length = 11, nullable = false) + @Column(name = "cpf", length = 14, nullable = false) private String cpf; @Column(name = "nome_cliente", length = 40, nullable = false) 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 index 8cbe9b66..367777dc 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java @@ -25,7 +25,7 @@ public class Sessao implements Serializable { private String voto; @ManyToOne - @JoinColumn(name = "cliente_id") + //@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 index 3f85b5fb..2d934ba8 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java @@ -2,7 +2,6 @@ import com.dbserver.votacao.votacao.model.Cliente; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.UUID; @@ -10,7 +9,7 @@ @Repository public interface ClienteRepository extends JpaRepository { /* - @Query(value = "SELECT c FROM db_votacao.tbl_clientes c WHERE c.cpf = ?1") + @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 index 0e4a4890..264a6ac4 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/repository/SessaoRepository.java @@ -1,5 +1,6 @@ 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; 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 index e1776437..d5e71491 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java @@ -5,7 +5,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.io.UnsupportedEncodingException; import java.util.List; @Service @@ -15,16 +14,7 @@ public class ClienteService { private ClienteRepository clienteRepository; public Cliente salvarCliente(Cliente cliente) { - /* - for (int i = 0; i < cliente.getCpf().length(); i++) { - try { - cliente.getCpf().getBytes(String.valueOf(i)).toString(); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - cliente.getNomeCliente().chars().toString(); - } - */ + clienteRepository.save(cliente); System.out.println("O cliente" + cliente + ", foi salva com sucesso!!"); return cliente; 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 index d3c7e39b..73e2ce10 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/service/SessaoService.java @@ -1,43 +1,47 @@ -//package com.dbserver.votacao.votacao.service; -// -//import com.dbserver.votacao.votacao.model.Sessao; -//import com.dbserver.votacao.votacao.repository.ClienteRepository; -//import com.dbserver.votacao.votacao.repository.SessaoRepository; -//import com.dbserver.votacao.votacaoutil.ValidacaoCpf; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Service; -// -//import java.util.List; -// -//@Service -//public class SessaoService { -// -// @Autowired -// private SessaoRepository sessaoRepository; -// private ClienteRepository clienteRepository -// -// public Sessao salvarSessao(String 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(); -// } -//} +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 index 436706ba..51d47534 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/util/ValidacaoCpf.java @@ -1,93 +1,71 @@ package com.dbserver.votacao.votacao.util; -import javax.swing.text.DefaultFormatterFactory; -import javax.swing.text.MaskFormatter; +import java.util.InputMismatchException; public class ValidacaoCpf { - private String cpf; - private static final String Formato = "###.###.###-##"; + public static boolean isCPF(String CPF) { - public ValidacaoCpf(String C) { - this.cpf = this.Format(C,false); - } - - public boolean isCPF(){ + CPF = CPF.replaceAll("\\.", "").replaceAll("\\/", "") + .replaceAll("\\-", ""); - if (this.cpf.equals("00000000000") || - this.cpf.equals("11111111111") || - this.cpf.equals("22222222222") || - this.cpf.equals("33333333333") || - this.cpf.equals("44444444444") || - this.cpf.equals("55555555555") || - this.cpf.equals("66666666666") || - this.cpf.equals("77777777777") || - this.cpf.equals("88888888888") || - this.cpf.equals("99999999999") || - this.cpf.length() != 11) + // 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 primeiro Digito Verificador + // Calculo do 1o. Digito Verificador sm = 0; peso = 10; for (i=0; i<9; i++) { - num = (int)(this.cpf.charAt(i) - 48); + // 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); + else dig10 = (char)(r + 48); // converte no respectivo caractere numerico - // Calculo do segundo Digito Verificador + // Calculo do 2o. Digito Verificador sm = 0; peso = 11; for(i=0; i<10; i++) { - num = (int)(this.cpf.charAt(i) - 48); + 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); + else dig11 = (char)(r + 48); - if ((dig10 == this.cpf.charAt(9)) && (dig11 == this.cpf.charAt(10))) + // 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(Exception e) { + } catch (InputMismatchException erro) { return(false); } } - public String getCPF(boolean Mascara) { - return Format(this.cpf,Mascara); - } - - private String Format(String C, boolean Mascara){ - if(Mascara){ - return(C.substring(0, 3) + "." + C.substring(3, 6) + "." + - C.substring(6, 9) + "-" + C.substring(9, 11)); - }else{ - C = C.replace(".",""); - C = C.replace("-",""); - return C; - } - } - - - public static DefaultFormatterFactory getFormat(){ - try { - return new DefaultFormatterFactory(new MaskFormatter(Formato)); - } catch (Exception e) { - return null; - } + 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 index 72ef5238..acd81f4d 100644 --- a/votacao/src/main/resources/application.properties +++ b/votacao/src/main/resources/application.properties @@ -2,7 +2,7 @@ spring.application.name=votacao server.port=8080 -spring.datasource.url=jdbc:mysql://localhost:3306/db_votacao?createDatabaseIfNotExist=true&serverTimezone=UTC +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 @@ -13,5 +13,5 @@ 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.hibernate.ddl-auto=update spring.jpa.open-in-view=false From 6001f8b077a0063a709547a6b70904a453e3eed5 Mon Sep 17 00:00:00 2001 From: josewalter Date: Mon, 30 Dec 2024 17:13:10 -0300 Subject: [PATCH 4/6] =?UTF-8?q?Atualiza=C3=A7=C3=A3o=20do=20README=20com?= =?UTF-8?q?=20as=20regras=20para=20gerar=20os=20containers=20e=20da=20clas?= =?UTF-8?q?se=20ClienteController=20que=20estava=20dando=20erro.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- votacao-old/.gitattributes | 2 + votacao-old/.gitignore | 33 +++ .../.mvn/wrapper/maven-wrapper.properties | 19 ++ votacao-old/mvnw | 259 ++++++++++++++++++ votacao-old/mvnw.cmd | 149 ++++++++++ votacao-old/pom.xml | 109 ++++++++ .../votacao/votacao/VotacaoApplication.java | 13 + .../votacao/controller/ClienteController.java | 65 +++++ .../votacao/votacao/dto/ClienteRecordDto.java | 6 + .../votacao/dto/ClienteRequestDto.java | 16 ++ .../votacao/votacao/model/Cliente.java | 31 +++ .../votacao/votacao/model/Sessao.java | 13 + .../votacao/repository/ClienteRepository.java | 14 + .../votacao/service/ClienteService.java | 55 ++++ .../src/main/resources/application.properties | 16 ++ .../votacao/VotacaoApplicationTests.java | 15 + votacao.zip | Bin 0 -> 16208 bytes votacao/README.md | 14 +- .../votacao/controller/ClienteController.java | 2 +- 19 files changed, 824 insertions(+), 7 deletions(-) create mode 100644 votacao-old/.gitattributes create mode 100644 votacao-old/.gitignore create mode 100644 votacao-old/.mvn/wrapper/maven-wrapper.properties create mode 100644 votacao-old/mvnw create mode 100644 votacao-old/mvnw.cmd create mode 100644 votacao-old/pom.xml create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/VotacaoApplication.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRecordDto.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/dto/ClienteRequestDto.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Cliente.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/model/Sessao.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/repository/ClienteRepository.java create mode 100644 votacao-old/src/main/java/com/dbserver/votacao/votacao/service/ClienteService.java create mode 100644 votacao-old/src/main/resources/application.properties create mode 100644 votacao-old/src/test/java/com/dbserver/votacao/votacao/VotacaoApplicationTests.java create mode 100644 votacao.zip diff --git a/votacao-old/.gitattributes b/votacao-old/.gitattributes new file mode 100644 index 00000000..3b41682a --- /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 00000000..549e00a2 --- /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 00000000..d58dfb70 --- /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 00000000..19529ddf --- /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 00000000..249bdf38 --- /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 00000000..5a028338 --- /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 00000000..1c795037 --- /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 00000000..8d6b7be9 --- /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 00000000..67e5b354 --- /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 00000000..e323b3b7 --- /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 00000000..08ac41fc --- /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 00000000..128233fb --- /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 00000000..1e3d6d98 --- /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 00000000..1ec68d83 --- /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 00000000..02d86a08 --- /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 00000000..2ab70c51 --- /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 0000000000000000000000000000000000000000..be3292e4e5065e1b4f15d543356d0e65fcbc56d5 GIT binary patch literal 16208 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 literal 0 HcmV?d00001 diff --git a/votacao/README.md b/votacao/README.md index f2e7ecaa..57746454 100644 --- a/votacao/README.md +++ b/votacao/README.md @@ -161,15 +161,17 @@ para subir a imagem e manter a imagem no ar: docker container run -p 8080:8080 v 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 aplicação back-end docker image build -t votacao-projeto-reserva . +Comando para fazer o build da imagem da API: +docker image build -t votacao . -Comando para subir o container do MySQL: -docker container run -d -p 3307:3307 -e MYSQL_ROOT_PASSWORD=12345 --network votacao-projeto-reserva-network --name -votacao-projeto-reserva-mysql mysql:8.0 +Comando para fazer a imagem subir: +docker container run --rm -p 8080:8080 votacao + +Comando para subir o container do MySQL para dentro da rede: +docker container run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=12345 --network votacao-network --name votacao-mysql mysql:8.0 Comando para subir a aplicação back-end: -docker container run -d -p 8080:8080 -e DB_HOST=votacao-projeto-reserva-mysql --network votacao-projeto-reserva-network -votacao-projeto-reserva +docker container run -d -p 8080:8080 -e DB_HOST=votacao-projeto-reserva-mysql --network votacao-network votacao 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 index 2867a4d1..a7b2082c 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java @@ -30,7 +30,7 @@ public ResponseEntity salvaCliente(@RequestBody @Valid Cliente cliente) return ResponseEntity.status(HttpStatus.NOT_FOUND).body(" status: UNABLE_TO_VOTE "); } - // return ResponseEntity.status(HttpStatus.OK).body(clienteService.salvarCliente(cliente)); + //return ResponseEntity.status(HttpStatus.OK).body(clienteService.salvarCliente(cliente)); } @GetMapping("/clientes") From a2054e3058dc27393956ee2c7488bf3c49d4c8f9 Mon Sep 17 00:00:00 2001 From: josewalter Date: Sun, 5 Jan 2025 23:43:21 -0300 Subject: [PATCH 5/6] =?UTF-8?q?Atualiza=C3=A7=C3=A3o=20de=20alguns=20arqui?= =?UTF-8?q?vos=20e=20classes=20que=20precisaram=20ser=20atualizados.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- votacao/README.md | 39 ++++++++++++------- votacao/mysql-docker-compose.yml | 2 +- .../votacao/controller/ClienteController.java | 3 +- .../votacao/controller/SessaoController.java | 7 +--- 4 files changed, 28 insertions(+), 23 deletions(-) diff --git a/votacao/README.md b/votacao/README.md index 57746454..0e36ff92 100644 --- a/votacao/README.md +++ b/votacao/README.md @@ -119,7 +119,7 @@ O aplicativo envia uma requisição POST para a url informada e com o body defin # 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 +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. @@ -128,11 +128,11 @@ Oracle. 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 +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 +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 @@ -146,34 +146,43 @@ 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/ +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, +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 +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 da API: -docker image build -t votacao . +docker build -t desafio-votacao/desafio-votacao-josewalter:v1 . Comando para fazer a imagem subir: -docker container run --rm -p 8080:8080 votacao +docker container run --rm -p 8080:8080 desafio-votacao/desafio-votacao-josewalter:v1 -Comando para subir o container do MySQL para dentro da rede: -docker container run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=12345 --network votacao-network --name votacao-mysql mysql:8.0 - -Comando para subir a aplicação back-end: -docker container run -d -p 8080:8080 -e DB_HOST=votacao-projeto-reserva-mysql --network votacao-network votacao +Comando para criar a rede onde os containers irão ficar e se comunicar. +docker network create desafio-votacao-network +Comando para criar o volume para a aplicação. +docker volume create desafio-votacao-volume +Comando para criar o container do MySQL e subir dentro da rede. +docker container run -d -p 3306:3306 --name desafio_votacao_db -e MYSQL_USER=root +-e MYSQL_DATABASE=desafiovotacaoDb --network desafio-votacao-network --mount +type=volume,source=desafio-votacao-volume,target=/var/lib/mysql/data mysql:8.0 +Comando para subir a aplicação back-end dentro da rede: +docker container run -d -p 8080:8080 -e MYSQL_DATABASE=desafiovotacaoDb -e MYSQL_USER=root +MYSQL_PASSWORD=12345 -e DB_HOST= desafio_votacao_db --network desafio-votacao-network +desafio-votacao/votacao:v1 +# 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/mysql-docker-compose.yml b/votacao/mysql-docker-compose.yml index 83555b0c..2fb85e25 100644 --- a/votacao/mysql-docker-compose.yml +++ b/votacao/mysql-docker-compose.yml @@ -7,7 +7,7 @@ services: volumes: - dbbase:/var/lib/mysql ports: - - "3307:3307" + - "3306:3306" environment: MYSQL_ROOT_PASSWORD: 12345 MYSQL_DATABASE: db_votacao 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 index a7b2082c..1bee67b8 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/ClienteController.java @@ -13,6 +13,7 @@ @RestController @RequestMapping +@CrossOrigin(origins = "http://localhost:4200") public class ClienteController { @Autowired private ClienteService clienteService; @@ -29,8 +30,6 @@ public ResponseEntity salvaCliente(@RequestBody @Valid Cliente cliente) // throw new Exception("CPF: " + cliente.getCpf() + "status: ABLE_TO_VOTE" ); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(" status: UNABLE_TO_VOTE "); } - - //return ResponseEntity.status(HttpStatus.OK).body(clienteService.salvarCliente(cliente)); } @GetMapping("/clientes") 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 index 8b7b8dcd..3f378f6b 100644 --- a/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java +++ b/votacao/src/main/java/com/dbserver/votacao/votacao/controller/SessaoController.java @@ -2,7 +2,6 @@ import com.dbserver.votacao.votacao.model.Sessao; import com.dbserver.votacao.votacao.service.SessaoService; -import jakarta.servlet.http.HttpSession; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -13,6 +12,7 @@ @RestController @RequestMapping +@CrossOrigin(origins = "http://localhost:4200") public class SessaoController { @Autowired private SessaoService sessaoService; @@ -20,10 +20,7 @@ public class SessaoController { @ResponseBody @PostMapping("/sessoes") public ResponseEntity salvarSessao(@RequestBody @Valid Sessao sessao) throws Exception { - /* - HttpSession session = sessao.se; - session.setMaxInactiveInterval(60); - */ + sessao = sessaoService.salvarSessao(sessao); return new ResponseEntity(sessao, HttpStatus.OK); } From ad8309a4bdd543900456ba48607e6bff66cbf225 Mon Sep 17 00:00:00 2001 From: josewalter Date: Sun, 5 Jan 2025 23:50:51 -0300 Subject: [PATCH 6/6] =?UTF-8?q?Subindo=20atualiza=C3=A7=C3=A3o=20do=20READ?= =?UTF-8?q?ME.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- votacao/README.md | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/votacao/README.md b/votacao/README.md index 0e36ff92..64954f0e 100644 --- a/votacao/README.md +++ b/votacao/README.md @@ -161,27 +161,28 @@ para subir a imagem e manter a imagem no ar: docker container run -p 8080:8080 v 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 da API: -docker build -t desafio-votacao/desafio-votacao-josewalter:v1 . +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 fazer a imagem subir: -docker container run --rm -p 8080:8080 desafio-votacao/desafio-votacao-josewalter:v1 +Comando para subir a imagem da API: +docker container run --rm -p 8080:8080 desafio-votacao +Nome da imagem desafio-votacao -Comando para criar a rede onde os containers irão ficar e se comunicar. -docker network create desafio-votacao-network +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 o volume para a aplicação. -docker volume create desafio-votacao-volume +Comando para criar a network para acolocar os container criados: +docker network create desafio-votacao-network -Comando para criar o container do MySQL e subir dentro da rede. -docker container run -d -p 3306:3306 --name desafio_votacao_db -e MYSQL_USER=root --e MYSQL_DATABASE=desafiovotacaoDb --network desafio-votacao-network --mount -type=volume,source=desafio-votacao-volume,target=/var/lib/mysql/data mysql:8.0 +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 subir a aplicação back-end dentro da rede: -docker container run -d -p 8080:8080 -e MYSQL_DATABASE=desafiovotacaoDb -e MYSQL_USER=root -MYSQL_PASSWORD=12345 -e DB_HOST= desafio_votacao_db --network desafio-votacao-network -desafio-votacao/votacao:v1 +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