From 608e1c688cae9851359edd649530297f290ba2f6 Mon Sep 17 00:00:00 2001 From: StewenAscari Date: Sat, 16 May 2020 23:32:35 -0300 Subject: [PATCH 1/5] =?UTF-8?q?Finalizando=20o=20CRUD=20de=20User,=20retor?= =?UTF-8?q?no=20das=20informa=C3=A7=C3=B5es=20por=20sigla,=20importa=C3=A7?= =?UTF-8?q?=C3=A3o=20de=20arquivo=20csv.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api-selecaojava/.classpath | 49 +++ api-selecaojava/.directory | 3 + api-selecaojava/.gitignore | 25 ++ api-selecaojava/.project | 28 ++ .../org.eclipse.core.resources.prefs | 5 + .../.settings/org.eclipse.jdt.apt.core.prefs | 2 + .../.settings/org.eclipse.jdt.core.prefs | 10 + .../.settings/org.eclipse.m2e.core.prefs | 4 + .../org.springframework.ide.eclipse.prefs | 2 + api-selecaojava/HELP.md | 19 ++ api-selecaojava/bin/.gitignore | 23 ++ api-selecaojava/bin/.project | 23 ++ .../org.eclipse.core.resources.prefs | 2 + api-selecaojava/bin/HELP.md | 19 ++ api-selecaojava/bin/README.md | 1 + api-selecaojava/bin/mvnw | 286 ++++++++++++++++++ api-selecaojava/bin/mvnw.cmd | 161 ++++++++++ api-selecaojava/bin/pom.xml | 86 ++++++ .../src/main/resources/application.properties | 1 + .../bin/target/classes/META-INF/MANIFEST.MF | 10 + .../api-nano/pom.properties | 6 + .../br.com.nanoimobiliaria/api-nano/pom.xml | 86 ++++++ .../bin/target/classes/application.properties | 1 + api-selecaojava/mvnw | 286 ++++++++++++++++++ api-selecaojava/mvnw.cmd | 161 ++++++++++ api-selecaojava/pom.xml | 139 +++++++++ .../ApiSelecaojavaApplication.java | 19 ++ .../br/com/selecaojava/config/DevConfig.java | 40 +++ .../selecaojava/config/SecurityConfig.java | 121 ++++++++ .../com/selecaojava/config/SwaggerConfig.java | 44 +++ .../br/com/selecaojava/config/TestConfig.java | 34 +++ .../java/br/com/selecaojava/domain/Useer.java | 114 +++++++ .../br/com/selecaojava/domain/Vendas.java | 174 +++++++++++ .../br/com/selecaojava/domain/initial.txt | 0 .../com/selecaojava/dto/CredenciaisDTO.java | 29 ++ .../java/br/com/selecaojava/dto/EmailDTO.java | 26 ++ .../java/br/com/selecaojava/dto/NomeDTO.java | 36 +++ .../br/com/selecaojava/dto/PasswordDTO.java | 39 +++ .../java/br/com/selecaojava/dto/UserDTO.java | 68 +++++ .../br/com/selecaojava/dto/VendasDTO.java | 131 ++++++++ .../java/br/com/selecaojava/dto/initial.txt | 0 .../java/br/com/selecaojava/enums/Perfil.java | 38 +++ .../filters/HeaderExposureFilter.java | 35 +++ .../repositories/UserRepository.java | 16 + .../repositories/VendasRepository.java | 26 ++ .../com/selecaojava/repositories/initial.txt | 0 .../selecaojava/resources/AuthResource.java | 43 +++ .../selecaojava/resources/UserResouces.java | 111 +++++++ .../selecaojava/resources/VendasResource.java | 84 +++++ .../resources/exceptions/FieldMassage.java | 39 +++ .../exceptions/ResourceExceptionHandler.java | 55 ++++ .../resources/exceptions/StandardError.java | 43 +++ .../resources/exceptions/ValidationError.java | 24 ++ .../br/com/selecaojava/resources/initial.txt | 0 .../security/JWTAuthenticationFilter.java | 80 +++++ .../security/JWTAuthorizationFilter.java | 53 ++++ .../br/com/selecaojava/security/JWTUtil.java | 58 ++++ .../br/com/selecaojava/security/UserSS.java | 77 +++++ .../services/AbstractEmailService.java | 34 +++ .../com/selecaojava/services/AuthService.java | 62 ++++ .../com/selecaojava/services/DBService.java | 34 +++ .../selecaojava/services/EmailService.java | 14 + .../services/MockEmailService.java | 17 ++ .../services/SmtpEmailService.java | 22 ++ .../services/UserDetailsServiceImpl.java | 30 ++ .../com/selecaojava/services/UserService.java | 130 ++++++++ .../services/UserServiceService.java | 17 ++ .../selecaojava/services/VendasServices.java | 33 ++ .../exceptions/ObjectNotFoundException.java | 18 ++ .../exceptions/PropertyNotFoundException.java | 22 ++ .../br/com/selecaojava/services/initial.txt | 0 .../exceptions/AuthorizationException.java | 15 + .../exceptions/DataIntegrityException.java | 15 + .../exceptions/ObjectNotFoundException.java | 15 + .../src/main/java/utils/FileSaver.java | 48 +++ .../main/resources/application-dev.properties | 6 + .../resources/application-test.properties | 6 + .../src/main/resources/application.properties | 20 ++ .../selecaojava/ApiNanoApplicationTests.java | 13 + .../api-selecaojava/pom.xml | 139 +++++++++ .../target/classes/application-dev.properties | 6 + .../classes/application-test.properties | 6 + .../target/classes/application.properties | 20 ++ .../br/com/selecaojava/domain/initial.txt | 0 .../br/com/selecaojava/dto/initial.txt | 0 .../com/selecaojava/repositories/initial.txt | 0 .../br/com/selecaojava/resources/initial.txt | 0 .../br/com/selecaojava/services/initial.txt | 0 88 files changed, 3837 insertions(+) create mode 100644 api-selecaojava/.classpath create mode 100644 api-selecaojava/.directory create mode 100644 api-selecaojava/.gitignore create mode 100644 api-selecaojava/.project create mode 100644 api-selecaojava/.settings/org.eclipse.core.resources.prefs create mode 100644 api-selecaojava/.settings/org.eclipse.jdt.apt.core.prefs create mode 100644 api-selecaojava/.settings/org.eclipse.jdt.core.prefs create mode 100644 api-selecaojava/.settings/org.eclipse.m2e.core.prefs create mode 100644 api-selecaojava/.settings/org.springframework.ide.eclipse.prefs create mode 100644 api-selecaojava/HELP.md create mode 100644 api-selecaojava/bin/.gitignore create mode 100644 api-selecaojava/bin/.project create mode 100644 api-selecaojava/bin/.settings/org.eclipse.core.resources.prefs create mode 100644 api-selecaojava/bin/HELP.md create mode 100644 api-selecaojava/bin/README.md create mode 100755 api-selecaojava/bin/mvnw create mode 100644 api-selecaojava/bin/mvnw.cmd create mode 100644 api-selecaojava/bin/pom.xml create mode 100644 api-selecaojava/bin/src/main/resources/application.properties create mode 100644 api-selecaojava/bin/target/classes/META-INF/MANIFEST.MF create mode 100644 api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.properties create mode 100644 api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.xml create mode 100644 api-selecaojava/bin/target/classes/application.properties create mode 100755 api-selecaojava/mvnw create mode 100644 api-selecaojava/mvnw.cmd create mode 100644 api-selecaojava/pom.xml create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/ApiSelecaojavaApplication.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/config/DevConfig.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/config/SwaggerConfig.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/config/TestConfig.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/domain/initial.txt create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/CredenciaisDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/EmailDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/NomeDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/PasswordDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/initial.txt create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/enums/Perfil.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/filters/HeaderExposureFilter.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/repositories/initial.txt create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/AuthResource.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/FieldMassage.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ResourceExceptionHandler.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/StandardError.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ValidationError.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/initial.txt create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthenticationFilter.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthorizationFilter.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/security/JWTUtil.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/security/UserSS.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/MockEmailService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/SmtpEmailService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/UserServiceService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/ObjectNotFoundException.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/initial.txt create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/AuthorizationException.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/DataIntegrityException.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/ObjectNotFoundException.java create mode 100644 api-selecaojava/src/main/java/utils/FileSaver.java create mode 100644 api-selecaojava/src/main/resources/application-dev.properties create mode 100644 api-selecaojava/src/main/resources/application-test.properties create mode 100644 api-selecaojava/src/main/resources/application.properties create mode 100644 api-selecaojava/src/test/java/br/com/selecaojava/ApiNanoApplicationTests.java create mode 100644 api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml create mode 100644 api-selecaojava/target/classes/application-dev.properties create mode 100644 api-selecaojava/target/classes/application-test.properties create mode 100644 api-selecaojava/target/classes/application.properties create mode 100644 api-selecaojava/target/classes/br/com/selecaojava/domain/initial.txt create mode 100644 api-selecaojava/target/classes/br/com/selecaojava/dto/initial.txt create mode 100644 api-selecaojava/target/classes/br/com/selecaojava/repositories/initial.txt create mode 100644 api-selecaojava/target/classes/br/com/selecaojava/resources/initial.txt create mode 100644 api-selecaojava/target/classes/br/com/selecaojava/services/initial.txt diff --git a/api-selecaojava/.classpath b/api-selecaojava/.classpath new file mode 100644 index 0000000..39abf1c --- /dev/null +++ b/api-selecaojava/.classpath @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/api-selecaojava/.directory b/api-selecaojava/.directory new file mode 100644 index 0000000..031ef52 --- /dev/null +++ b/api-selecaojava/.directory @@ -0,0 +1,3 @@ +[Dolphin] +Timestamp=2019,11,14,0,12,10 +Version=4 diff --git a/api-selecaojava/.gitignore b/api-selecaojava/.gitignore new file mode 100644 index 0000000..fc2eff4 --- /dev/null +++ b/api-selecaojava/.gitignore @@ -0,0 +1,25 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +target/classes/META-INF/MANIFEST.MF +target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.properties diff --git a/api-selecaojava/.project b/api-selecaojava/.project new file mode 100644 index 0000000..be17531 --- /dev/null +++ b/api-selecaojava/.project @@ -0,0 +1,28 @@ + + + api-selecaojava + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.springframework.ide.eclipse.boot.validation.springbootbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/api-selecaojava/.settings/org.eclipse.core.resources.prefs b/api-selecaojava/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..839d647 --- /dev/null +++ b/api-selecaojava/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/api-selecaojava/.settings/org.eclipse.jdt.apt.core.prefs b/api-selecaojava/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000..d4313d4 --- /dev/null +++ b/api-selecaojava/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/api-selecaojava/.settings/org.eclipse.jdt.core.prefs b/api-selecaojava/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..951833c --- /dev/null +++ b/api-selecaojava/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,10 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.methodParameters=generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/api-selecaojava/.settings/org.eclipse.m2e.core.prefs b/api-selecaojava/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/api-selecaojava/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/api-selecaojava/.settings/org.springframework.ide.eclipse.prefs b/api-selecaojava/.settings/org.springframework.ide.eclipse.prefs new file mode 100644 index 0000000..a12794d --- /dev/null +++ b/api-selecaojava/.settings/org.springframework.ide.eclipse.prefs @@ -0,0 +1,2 @@ +boot.validation.initialized=true +eclipse.preferences.version=1 diff --git a/api-selecaojava/HELP.md b/api-selecaojava/HELP.md new file mode 100644 index 0000000..d029bd3 --- /dev/null +++ b/api-selecaojava/HELP.md @@ -0,0 +1,19 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.0.M6/maven-plugin/) +* [Spring Boot DevTools](https://docs.spring.io/spring-boot/docs/{bootVersion}/reference/htmlsingle/#using-boot-devtools) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/{bootVersion}/reference/htmlsingle/#boot-features-jpa-and-spring-data) +* [Spring Web](https://docs.spring.io/spring-boot/docs/{bootVersion}/reference/htmlsingle/#boot-features-developing-web-applications) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) + diff --git a/api-selecaojava/bin/.gitignore b/api-selecaojava/bin/.gitignore new file mode 100644 index 0000000..a1c2a23 --- /dev/null +++ b/api-selecaojava/bin/.gitignore @@ -0,0 +1,23 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/api-selecaojava/bin/.project b/api-selecaojava/bin/.project new file mode 100644 index 0000000..e912e8c --- /dev/null +++ b/api-selecaojava/bin/.project @@ -0,0 +1,23 @@ + + + api-selecaojava + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/api-selecaojava/bin/.settings/org.eclipse.core.resources.prefs b/api-selecaojava/bin/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..99f26c0 --- /dev/null +++ b/api-selecaojava/bin/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/api-selecaojava/bin/HELP.md b/api-selecaojava/bin/HELP.md new file mode 100644 index 0000000..d029bd3 --- /dev/null +++ b/api-selecaojava/bin/HELP.md @@ -0,0 +1,19 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.0.M6/maven-plugin/) +* [Spring Boot DevTools](https://docs.spring.io/spring-boot/docs/{bootVersion}/reference/htmlsingle/#using-boot-devtools) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/{bootVersion}/reference/htmlsingle/#boot-features-jpa-and-spring-data) +* [Spring Web](https://docs.spring.io/spring-boot/docs/{bootVersion}/reference/htmlsingle/#boot-features-developing-web-applications) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) + diff --git a/api-selecaojava/bin/README.md b/api-selecaojava/bin/README.md new file mode 100644 index 0000000..ae31b82 --- /dev/null +++ b/api-selecaojava/bin/README.md @@ -0,0 +1 @@ +# api-selecaojava \ No newline at end of file diff --git a/api-selecaojava/bin/mvnw b/api-selecaojava/bin/mvnw new file mode 100755 index 0000000..8b9da3b --- /dev/null +++ b/api-selecaojava/bin/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/api-selecaojava/bin/mvnw.cmd b/api-selecaojava/bin/mvnw.cmd new file mode 100644 index 0000000..fef5a8f --- /dev/null +++ b/api-selecaojava/bin/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/api-selecaojava/bin/pom.xml b/api-selecaojava/bin/pom.xml new file mode 100644 index 0000000..bf87b2d --- /dev/null +++ b/api-selecaojava/bin/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.M6 + + + br.com.selecaojavaa + api-selecaojava + 0.0.1-SNAPSHOT + api-selecaojava + + + + 3.1.1 + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.h2database + h2 + runtime + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/api-selecaojava/bin/src/main/resources/application.properties b/api-selecaojava/bin/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/api-selecaojava/bin/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/api-selecaojava/bin/target/classes/META-INF/MANIFEST.MF b/api-selecaojava/bin/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..6391ce1 --- /dev/null +++ b/api-selecaojava/bin/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,10 @@ +Manifest-Version: 1.0 +Implementation-Title: api-selecaojava +Implementation-Version: 0.0.1-SNAPSHOT +Built-By: stewen +Implementation-Vendor-Id: br.com.selecaojava +Build-Jdk: 1.8.0_201 +Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo + ot-starter-parent/api-selecaojava +Created-By: Maven Integration for Eclipse + diff --git a/api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.properties b/api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.properties new file mode 100644 index 0000000..67980b2 --- /dev/null +++ b/api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.properties @@ -0,0 +1,6 @@ +#Generated by Maven Integration for Eclipse +#Tue Sep 10 19:03:54 BRT 2019 +version=0.0.1-SNAPSHOT +groupId=br.com.selecaojava +m2e.projectName=api-selecaojava +artifactId=api-selecaojava-selecaojava \ No newline at end of file diff --git a/api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.xml b/api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.xml new file mode 100644 index 0000000..c2c96cf --- /dev/null +++ b/api-selecaojava/bin/target/classes/META-INF/maven/br.com.nanoimobiliaria/api-nano/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.M6 + + + br.com.selecaojava + api-selecaojava + 0.0.1-SNAPSHOT + api-selecaojava + + + + 3.1.1 + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.h2database + h2 + runtime + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/api-selecaojava/bin/target/classes/application.properties b/api-selecaojava/bin/target/classes/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/api-selecaojava/bin/target/classes/application.properties @@ -0,0 +1 @@ + diff --git a/api-selecaojava/mvnw b/api-selecaojava/mvnw new file mode 100755 index 0000000..8b9da3b --- /dev/null +++ b/api-selecaojava/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/api-selecaojava/mvnw.cmd b/api-selecaojava/mvnw.cmd new file mode 100644 index 0000000..fef5a8f --- /dev/null +++ b/api-selecaojava/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/api-selecaojava/pom.xml b/api-selecaojava/pom.xml new file mode 100644 index 0000000..d5a88d5 --- /dev/null +++ b/api-selecaojava/pom.xml @@ -0,0 +1,139 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + + br.com.selecaojava + api-selecaojava + 0.0.1-SNAPSHOT + api-selecaojava + + + + + 3.1.1 + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + + + + com.h2database + h2 + runtime + + + + org.apache.commons + commons-lang3 + 3.7 + + + + org.postgresql + postgresql + runtime + + + + com.opencsv + opencsv + 5.0 + + + + org.springframework.boot + spring-boot-starter-security + + + + io.jsonwebtoken + jjwt + 0.7.0 + + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/ApiSelecaojavaApplication.java b/api-selecaojava/src/main/java/br/com/selecaojava/ApiSelecaojavaApplication.java new file mode 100644 index 0000000..234e823 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/ApiSelecaojavaApplication.java @@ -0,0 +1,19 @@ +package br.com.selecaojava; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApiSelecaojavaApplication implements CommandLineRunner{ + + public static void main(String[] args) { + SpringApplication.run(ApiSelecaojavaApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + // TODO Auto-generated method stub + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/config/DevConfig.java b/api-selecaojava/src/main/java/br/com/selecaojava/config/DevConfig.java new file mode 100644 index 0000000..b0f1af4 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/config/DevConfig.java @@ -0,0 +1,40 @@ +package br.com.selecaojava.config; + +import java.text.ParseException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import br.com.selecaojava.services.DBService; +import br.com.selecaojava.services.EmailService; +import br.com.selecaojava.services.SmtpEmailService; + + +@Configuration +@Profile("dev") +public class DevConfig { + + @Autowired + private DBService dbService; + + @Value("$(spring.jpa.hibernate.ddl-auto)") + private String strategy; + + @Bean + public boolean instantiateDatabase() throws ParseException { + if (!"create".equals(strategy)) { + return false; + } + dbService.instantiateTestDatabase(); + return true; + } + + @Bean + public EmailService emailService() { + return new SmtpEmailService(); + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java b/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java new file mode 100644 index 0000000..c13ee63 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java @@ -0,0 +1,121 @@ +package br.com.selecaojava.config; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +import br.com.selecaojava.security.JWTAuthenticationFilter; +import br.com.selecaojava.security.JWTAuthorizationFilter; +import br.com.selecaojava.security.JWTUtil; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter{ + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private Environment env; + + @Autowired + private JWTUtil jwtUtil; + + private static final String[] PUBLIC_MATCHERS = { //Arraay dos endpoint que vão ser permitidos os acessos + "/h2-console/**", + "/property/**", + "/property/1/**" + + }; + + private static final String[] PUBLIC_SWAGGER_TEST= { + "/v2/api-docs", + "/configuration/ui", + "/swagger-resources/**", + "/configuration/security", + "/swagger-ui.html", + "/webjars/**" + }; + + private static final String[] PUBLIC_MATCHERS_GET = { //dpoint array that a non-logged in user can only retrieve data from + "/user/**" + + //Aqui pode colocar os endpoints separados por virgula + }; + private static final String[] PUBLIC_MATCHERS_POST = { //Endpoint array that a non-logged in user can only add data to + "/user/**", + "/auth/forgot/**", + "/vendas/**" + }; + @Override + protected void configure(HttpSecurity http) throws Exception{ + + if(Arrays.asList(env.getActiveProfiles()).contains("test")) { + http.headers().frameOptions().disable(); + http.authorizeRequests() + .antMatchers(HttpMethod.GET,PUBLIC_SWAGGER_TEST).permitAll(); + } + + http.cors().and().csrf().disable(); //desativa função que protege contra ataque de armazenamento de em seção + http.authorizeRequests() + .antMatchers(HttpMethod.GET, PUBLIC_MATCHERS_POST).permitAll() + .antMatchers(HttpMethod.GET, PUBLIC_MATCHERS_GET).permitAll() + .antMatchers(PUBLIC_MATCHERS).permitAll() + .anyRequest().authenticated(); //Request authentication for remaining endpoints + http.addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtUtil)); + http.addFilter(new JWTAuthorizationFilter(authenticationManager(), jwtUtil, userDetailsService)); + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + } + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception{ + auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { //Allows access to endpoints with basic settings + final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); + return source; + } + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { //Causes password when saving password to encrypted database + return new BCryptPasswordEncoder(); + } + + @Bean + public CorsFilter corsFilter() { + final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + final CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("*"); + config.addAllowedHeader("*"); + config.addAllowedMethod("OPTIONS"); + config.addAllowedMethod("HEAD"); + config.addAllowedMethod("GET"); + config.addAllowedMethod("PUT"); + config.addAllowedMethod("POST"); + config.addAllowedMethod("DELETE"); + config.addAllowedMethod("PATCH"); + source.registerCorsConfiguration("/**", config); + return new CorsFilter(source); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/config/SwaggerConfig.java b/api-selecaojava/src/main/java/br/com/selecaojava/config/SwaggerConfig.java new file mode 100644 index 0000000..7957361 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/config/SwaggerConfig.java @@ -0,0 +1,44 @@ +package br.com.selecaojava.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@EnableSwagger2 +@Configuration +public class SwaggerConfig { + + @Bean + public Docket detalheApi() { + + Docket docket = new Docket(DocumentationType.SWAGGER_2); + + docket + .select() + .apis(RequestHandlerSelectors.basePackage("br.com.selecaojava")) + .paths(PathSelectors.any()) + .build() + .apiInfo(this.informacoesApi().build()); + + return docket; + } + + private ApiInfoBuilder informacoesApi() { + + ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder(); + + apiInfoBuilder.title("Seleção Java"); + apiInfoBuilder.description("Api para realização de um CRUD."); + apiInfoBuilder.version("1.0"); + + return apiInfoBuilder; + + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/config/TestConfig.java b/api-selecaojava/src/main/java/br/com/selecaojava/config/TestConfig.java new file mode 100644 index 0000000..c36b6bc --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/config/TestConfig.java @@ -0,0 +1,34 @@ +package br.com.selecaojava.config; + +import java.text.ParseException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import br.com.selecaojava.services.DBService; +import br.com.selecaojava.services.EmailService; +import br.com.selecaojava.services.MockEmailService; + + +@Configuration +@Profile("test") +public class TestConfig { + + @Autowired + private DBService dbService; + @Bean + public boolean instantiateDatabase() throws ParseException { + + dbService.instantiateTestDatabase(); + + return true; + } + + @Bean + public EmailService emailService() { + return new MockEmailService(); + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java new file mode 100644 index 0000000..dc283b3 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java @@ -0,0 +1,114 @@ +package br.com.selecaojava.domain; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.persistence.CollectionTable; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import br.com.selecaojava.enums.Perfil; + +@Entity +public class Useer implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Integer id; + private String nome; + private String email; + + @JsonIgnore //Do not show password when retrieving data + private String senha; + + @ElementCollection(fetch=FetchType.EAGER) + @CollectionTable(name="PERFIS") + private Set perfis = new HashSet<>(); + + + public Useer() { + addPerfil(Perfil.ADMIN); + } + public Useer(Integer id, String nome, String email, String senha) { + super(); + this.id = id; + this.nome = nome; + this.email = email; + this.senha = senha; + addPerfil(Perfil.ADMIN); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + public String getSenha() { + return senha; + } + + public void setSenha(String senha) { + this.senha = senha; + } + + + public Set getPerfis() { + return perfis.stream().map(x -> Perfil.toEnum(x)).collect(Collectors.toSet()); + } + + public void addPerfil(Perfil perfil) { + this.perfis.add(perfil.getCod()); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Useer other = (Useer) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java new file mode 100644 index 0000000..8f85e49 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java @@ -0,0 +1,174 @@ +package br.com.selecaojava.domain; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.OrderBy; + +import com.opencsv.bean.CsvBindByName; +import com.opencsv.bean.CsvBindByPosition; + +@Entity +public class Vendas { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Integer id; + + @CsvBindByName(column = "Região - Sigla") + @Column(columnDefinition = "VARCHAR(1000)") + @CsvBindByPosition(position = 0) + private String regiaoSigla; + + @CsvBindByName(column = "Estado - Sigla") + @CsvBindByPosition(position = 1) + private String estadoSigla; + + @CsvBindByName(column = "Município") + @CsvBindByPosition(position = 2) + private String municipio; + + @CsvBindByName(column = "Revenda") + @CsvBindByPosition(position = 3) + private String revenda; + + @CsvBindByName(column = "CNPJ da Revenda") + @CsvBindByPosition(position = 4) + private String cnpjdaRevenda; + + @CsvBindByName(column = "Produto") + @CsvBindByPosition(position = 5) + private String produto; + + @CsvBindByName(column = "Data da Coleta") + @CsvBindByPosition(position = 6) + private String datadaColeta; + + @CsvBindByName(column = "Valor de Venda") + @CsvBindByPosition(position = 7) + private String valordeVenda; + + @CsvBindByName(column = "Valor de Compra") + @CsvBindByPosition(position = 8) + private String valordeCompra; + + @CsvBindByName(column = "Unidade de Medida") + @CsvBindByPosition(position = 9) + private String unidadedeMedida; + + @CsvBindByName(column = "Bandeira") + @CsvBindByPosition(position = 10) + private String bandeira; + + + public Vendas() { + + } + public Vendas(Integer id, String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, + String valorVenda, String valorCompra, String unidadeMedida, String bandeira) { + this.id = id; + this.regiaoSigla = regiaoSigla; + this.estadoSigla = stadoSigla; + this.municipio = municipio; + this.revenda = revenda; + this.cnpjdaRevenda = revendaCNPJ; + this.produto = produto; + this.datadaColeta = dataColeta; + this.valordeVenda = valorVenda; + this.valordeCompra = valorCompra; + this.unidadedeMedida = unidadeMedida; + this.bandeira = bandeira; + } + + + + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getRegiaoSigla() { + return regiaoSigla; + } + public void setRegiaoSigla(String regiaoSigla) { + this.regiaoSigla = regiaoSigla; + } + public String getEstadoSigla() { + return estadoSigla; + } + public void setEstadoSigla(String estadoSigla) { + this.estadoSigla = estadoSigla; + } + public String getMunicipio() { + return municipio; + } + public void setMunicipio(String municipio) { + this.municipio = municipio; + } + public String getRevenda() { + return revenda; + } + public void setRevenda(String revenda) { + this.revenda = revenda; + } + public String getCnpjdaRevenda() { + return cnpjdaRevenda; + } + public void setCnpjdaRevenda(String cnpjdaRevenda) { + this.cnpjdaRevenda = cnpjdaRevenda; + } + public String getProduto() { + return produto; + } + public void setProduto(String produto) { + this.produto = produto; + } + public String getDatadaColeta() { + return datadaColeta; + } + public void setDatadaColeta(String datadaColeta) { + datadaColeta = datadaColeta; + } + public String getValordeVenda() { + return valordeVenda; + } + public void setValordeVenda(String valordeVenda) { + this.valordeVenda = valordeVenda; + } + public String getValordeCompra() { + return valordeCompra; + } + public void setValordeCompra(String valordeCompra) { + this.valordeCompra = valordeCompra; + } + public String getUnidadedeMedida() { + return unidadedeMedida; + } + public void setUnidadedeMedida(String unidadedeMedida) { + this.unidadedeMedida = unidadedeMedida; + } + public String getBandeira() { + return bandeira; + } + public void setBandeira(String bandeira) { + this.bandeira = bandeira; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public String toString(){ + return regiaoSigla+estadoSigla+municipio+revenda+cnpjdaRevenda+produto+datadaColeta+valordeVenda+valordeCompra+unidadedeMedida+bandeira; + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/initial.txt b/api-selecaojava/src/main/java/br/com/selecaojava/domain/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/CredenciaisDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/CredenciaisDTO.java new file mode 100644 index 0000000..436b287 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/CredenciaisDTO.java @@ -0,0 +1,29 @@ +package br.com.selecaojava.dto; + +import java.io.Serializable; + +public class CredenciaisDTO implements Serializable{ + private static final long serialVersionUID = 1L; + + private String Email; + private String senha; + + public CredenciaisDTO() { + + } + + public String getEmail() { + return Email; + } + public void setEmail(String email) { + Email = email; + } + public String getSenha() { + return senha; + } + public void setSenha(String senha) { + this.senha = senha; + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/EmailDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/EmailDTO.java new file mode 100644 index 0000000..5eece64 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/EmailDTO.java @@ -0,0 +1,26 @@ +package br.com.selecaojava.dto; + +import java.io.Serializable; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; + + +public class EmailDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @NotEmpty(message="Preenchimento obrigatório") + @Email(message="Email inválido") + private String email; + + public EmailDTO() { + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/NomeDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/NomeDTO.java new file mode 100644 index 0000000..4da2240 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/NomeDTO.java @@ -0,0 +1,36 @@ +package br.com.selecaojava.dto; + +import javax.validation.constraints.NotEmpty; + +public class NomeDTO { + + private Integer id; + + @NotEmpty(message = "Preenchimento obrigatório") + private String nome; + + public NomeDTO() { + + } + + public NomeDTO(Integer id, String nome) { + this.id = id; + this.nome = nome; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/PasswordDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/PasswordDTO.java new file mode 100644 index 0000000..29f8992 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/PasswordDTO.java @@ -0,0 +1,39 @@ +package br.com.selecaojava.dto; + +import java.io.Serializable; + +import javax.validation.constraints.NotEmpty; + +public class PasswordDTO implements Serializable { + private static final long serialVersionUID = 1L; + + private Integer id; + + @NotEmpty(message = "Preenchimento obrigatório") + private String senha; + + public PasswordDTO() { + + } + + public PasswordDTO(Integer id, String senha) { + this.id = id; + this.senha = senha; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getSenha() { + return senha; + } + + public void setSenha(String senha) { + this.senha = senha; + } +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java new file mode 100644 index 0000000..4ec63a6 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java @@ -0,0 +1,68 @@ +package br.com.selecaojava.dto; + +import java.io.Serializable; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; + +import br.com.selecaojava.domain.Useer; + +public class UserDTO implements Serializable{ + private static final long serialVersionUID = 1L; + + private Integer id; + + @NotEmpty(message="Preenchimento obrigatório") + @Email(message="Email inválido") + private String email; + + @NotEmpty(message="Preenchimento obrigatório") + private String nome; + + @NotEmpty(message="Preenchimento obrigatório") + private String senha; + + public UserDTO() { + + } + + public UserDTO(Useer user) { + id = user.getId(); + nome = user.getNome(); + email = user.getEmail(); + senha = user.getSenha(); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getSenha() { + return senha; + } + + public void setSenha(String senha) { + this.senha = senha; + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java new file mode 100644 index 0000000..ac09598 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java @@ -0,0 +1,131 @@ +package br.com.selecaojava.dto; + +import javax.persistence.Column; + +import com.opencsv.bean.CsvBindByName; +import com.opencsv.bean.CsvBindByPosition; + +import br.com.selecaojava.domain.Vendas; + +public class VendasDTO { + + @CsvBindByName(column = "Região - Sigla") + @Column(columnDefinition = "VARCHAR(1000)") + private String regiaoSigla; + + @CsvBindByName(column = "Estado - Sigla") + private String estadoSigla; + + @CsvBindByName(column = "Município") + private String municipio; + + @CsvBindByName(column = "Revenda") + private String revenda; + + @CsvBindByName(column = "CNPJ da Revenda") + private String cnpjdaRevenda; + + @CsvBindByName(column = "Produto") + private String produto; + + @CsvBindByName(column = "Data da Coleta") + private String datadaColeta; + + @CsvBindByName(column = "Valor de Venda") + private String valordeVenda; + + @CsvBindByName(column = "Valor de Compra") + private String valordeCompra; + + @CsvBindByName(column = "Unidade de Medida") + private String unidadedeMedida; + + @CsvBindByName(column = "Bandeira") + private String bandeira; + + + public VendasDTO() { + + } + public VendasDTO(Vendas vendas) { + regiaoSigla = vendas.getRegiaoSigla(); + estadoSigla = vendas.getEstadoSigla(); + municipio = vendas.getMunicipio(); + revenda = vendas.getRevenda(); + cnpjdaRevenda = vendas.getCnpjdaRevenda(); + produto = vendas.getProduto(); + datadaColeta = vendas.getDatadaColeta(); + valordeVenda = vendas.getValordeVenda(); + valordeCompra = vendas.getValordeCompra(); + unidadedeMedida = vendas.getUnidadedeMedida(); + bandeira = vendas.getBandeira(); + } + public String getRegiaoSigla() { + return regiaoSigla; + } + public void setRegiaoSigla(String regiaoSigla) { + this.regiaoSigla = regiaoSigla; + } + public String getEstadoSigla() { + return estadoSigla; + } + public void setEstadoSigla(String estadoSigla) { + this.estadoSigla = estadoSigla; + } + public String getMunicipio() { + return municipio; + } + public void setMunicipio(String municipio) { + this.municipio = municipio; + } + public String getRevenda() { + return revenda; + } + public void setRevenda(String revenda) { + this.revenda = revenda; + } + public String getCnpjdaRevenda() { + return cnpjdaRevenda; + } + public void setCnpjdaRevenda(String cnpjdaRevenda) { + this.cnpjdaRevenda = cnpjdaRevenda; + } + public String getProduto() { + return produto; + } + public void setProduto(String produto) { + this.produto = produto; + } + public String getDatadaColeta() { + return datadaColeta; + } + public void setDatadaColeta(String datadaColeta) { + this.datadaColeta = datadaColeta; + } + public String getValordeVenda() { + return valordeVenda; + } + public void setValordeVenda(String valordeVenda) { + this.valordeVenda = valordeVenda; + } + public String getValordeCompra() { + return valordeCompra; + } + public void setValordeCompra(String valordeCompra) { + this.valordeCompra = valordeCompra; + } + public String getUnidadedeMedida() { + return unidadedeMedida; + } + public void setUnidadedeMedida(String unidadedeMedida) { + this.unidadedeMedida = unidadedeMedida; + } + public String getBandeira() { + return bandeira; + } + public void setBandeira(String bandeira) { + this.bandeira = bandeira; + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/initial.txt b/api-selecaojava/src/main/java/br/com/selecaojava/dto/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/enums/Perfil.java b/api-selecaojava/src/main/java/br/com/selecaojava/enums/Perfil.java new file mode 100644 index 0000000..8182a54 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/enums/Perfil.java @@ -0,0 +1,38 @@ +package br.com.selecaojava.enums; + +public enum Perfil { + + ADMIN(1,"ROLE_ADMIN"), + USER(2,"ROLE_USER"); + + private int cod; + private String descricao; + + private Perfil(int cod, String descricao) { + this.cod = cod; + this.descricao = descricao; + } + + public static Perfil toEnum(Integer cod) { + + if(cod == null) { + return null; + } + + for(Perfil x: Perfil.values()) { + if(cod.equals(x.getCod())) { + return x; + } + } + + throw new IllegalArgumentException("Id invalido: "+cod); + } + + public int getCod() { + return cod; + } + + public String getDescricao() { + return descricao; + } +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/filters/HeaderExposureFilter.java b/api-selecaojava/src/main/java/br/com/selecaojava/filters/HeaderExposureFilter.java new file mode 100644 index 0000000..15215c2 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/filters/HeaderExposureFilter.java @@ -0,0 +1,35 @@ +package br.com.selecaojava.filters; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Component; + +@Component +public class HeaderExposureFilter implements Filter{ + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("access-control-expose-headers", "location"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java new file mode 100644 index 0000000..c4994c7 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java @@ -0,0 +1,16 @@ +package br.com.selecaojava.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import br.com.selecaojava.domain.Useer; + + +@Repository +public interface UserRepository extends JpaRepository{ + + @Transactional(readOnly=true) + Useer findByEmail(String email); + +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java new file mode 100644 index 0000000..21965c3 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java @@ -0,0 +1,26 @@ +package br.com.selecaojava.repositories; +import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.dto.VendasDTO; + +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.OrderBy; +import javax.transaction.Transactional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import com.google.common.base.Strings; +import com.opencsv.bean.CsvBindByName; +import com.opencsv.bean.CsvBindByPosition; + +@Repository +public interface VendasRepository extends JpaRepository { + + List findByregiaoSigla(String regiaoSigla); + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/initial.txt b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/AuthResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/AuthResource.java new file mode 100644 index 0000000..ca5be5b --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/AuthResource.java @@ -0,0 +1,43 @@ +package br.com.selecaojava.resources; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import br.com.selecaojava.dto.EmailDTO; +import br.com.selecaojava.security.JWTUtil; +import br.com.selecaojava.security.UserSS; +import br.com.selecaojava.services.AuthService; +import br.com.selecaojava.services.UserServiceService; + +@RestController +@RequestMapping(value = "/auth") +public class AuthResource { //This class renews the token so you don't have to log in multiple times. + + @Autowired + private JWTUtil jwtUtil; + + @Autowired + private AuthService service; + + @RequestMapping(value = "/refresh_token", method = RequestMethod.POST) + public ResponseEntity refreshToken(HttpServletResponse response) { + UserSS user = UserServiceService.authenticated(); + String token = jwtUtil.generateToken(user.getUsername()); + response.addHeader("Authorization", "Bearer " + token); + response.addHeader("access-control-expose-headers", "Authorization"); + return ResponseEntity.noContent().build(); + } + + @RequestMapping(value = "/forgot", method = RequestMethod.POST) + public ResponseEntity forgot(@Valid @RequestBody EmailDTO objDto) { + service.sendNewPassword(objDto.getEmail()); + return ResponseEntity.noContent().build(); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java new file mode 100644 index 0000000..14c8dbe --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java @@ -0,0 +1,111 @@ +package br.com.selecaojava.resources; + +import java.net.URI; +import java.util.List; +import java.util.stream.Collectors; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.dto.NomeDTO; +import br.com.selecaojava.dto.PasswordDTO; +import br.com.selecaojava.dto.UserDTO; +import br.com.selecaojava.services.UserService; +import javassist.tools.rmi.ObjectNotFoundException; + +@RestController +@RequestMapping(value="/user") +public class UserResouces { + + @Autowired + private UserService service; + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(value="/{id}", method = RequestMethod.GET) + public ResponseEntity find(@PathVariable Integer id){ + Useer obj = service.find(id); + return ResponseEntity.ok().body(obj); + } + + @RequestMapping(value="/email", method=RequestMethod.GET) + public ResponseEntity find(@RequestParam(value="value") String email) { + Useer obj = service.findByEmail(email); + return ResponseEntity.ok().body(obj); + } + + @PreAuthorize("hasAnyRole('ADMIN')") //Forces a user is logged in to access this endpoint + @RequestMapping(method=RequestMethod.POST) //add a new admin + public ResponseEntity insert(@Valid @RequestBody UserDTO objDto){ + Useer obj = service.fromDTO(objDto); + obj = service.insert(obj); + URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"). + buildAndExpand(obj.getId()).toUri(); + return ResponseEntity.created(uri).build(); + } + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(value="/{id}",method=RequestMethod.PUT) //update an entire ADM + public ResponseEntity update(@Valid @RequestBody UserDTO objDto,@PathVariable Integer id) throws ObjectNotFoundException{ + Useer obj = service.fromDTO(objDto); + obj = service.update(obj); + return ResponseEntity.noContent().build(); + } + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(value="/password/{id}",method=RequestMethod.PATCH) //update a password ADM + public ResponseEntity update(@Valid @RequestBody PasswordDTO passwordDto, @PathVariable Integer id) throws ObjectNotFoundException{ + PasswordDTO objDTO = service.passwordDTO(passwordDto); + service.update(objDTO); + return ResponseEntity.noContent().build(); + } + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(value="/name/{id}",method=RequestMethod.PATCH) //update name ADM + public ResponseEntity update(@Valid @RequestBody NomeDTO nomeDto, @PathVariable Integer id) throws ObjectNotFoundException{ + NomeDTO objDTO = service.nomeDTO(nomeDto); + service.update(objDTO); + return ResponseEntity.noContent().build(); + } + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(value="/{id}", method = RequestMethod.DELETE) //Delete ADM + public ResponseEntity delete(@PathVariable Integer id) throws ObjectNotFoundException { + service.delete(id); + return ResponseEntity.noContent().build(); + } + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(method = RequestMethod.GET) //list all ADM + public ResponseEntity> findPage() { + List list = service.findAll(); + List listDTO = list.stream().map(obj -> new UserDTO(obj)).collect(Collectors.toList()); + return ResponseEntity.ok().body(listDTO); + } + + @PreAuthorize("hasAnyRole('ADMIN')") + @RequestMapping(value = "/page", method = RequestMethod.GET) //lists all paged ADMs + public ResponseEntity> findAll( + @RequestParam(value="page", defaultValue="0") Integer page, + @RequestParam(value="linesPerPage", defaultValue="24") Integer linesPerPage, + @RequestParam(value="orderBy", defaultValue="nome") String orderBy, + @RequestParam(value="direction", defaultValue="ASC") String direction){ + Page list = service.findPage(page, linesPerPage, orderBy, direction); + Page listDTO = list.map(obj -> new UserDTO(obj)); + return ResponseEntity.ok().body(listDTO); + } + + +} + diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java new file mode 100644 index 0000000..d3c2582 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java @@ -0,0 +1,84 @@ +package br.com.selecaojava.resources; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.hibernate.hql.spi.PositionalParameterInformation; +import org.hibernate.loader.custom.sql.PositionalParamBinder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import com.opencsv.bean.ColumnPositionMappingStrategy; +import com.opencsv.bean.CsvToBean; +import com.opencsv.bean.CsvToBeanBuilder; + +import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.dto.VendasDTO; +import br.com.selecaojava.repositories.VendasRepository; +import br.com.selecaojava.services.VendasServices; + +@RestController +@RequestMapping(value="/vendas") +public class VendasResource { + + @Autowired + private VendasServices vendasServices; + @Autowired + private VendasRepository vendasRepository; + + @RequestMapping(value="/upload-csv-file", method = RequestMethod.POST) + public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model model) { + + // validate file + if (file.isEmpty()) { + model.addAttribute("message", "Please select a CSV file to upload."); + model.addAttribute("status", false); + } else { + + // parse CSV file to create a list of `Vendas` objects + try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()), '\t')) { + + // create csv bean reader + CsvToBean csvToBean = new CsvToBeanBuilder(reader) + .withType(Vendas.class) + .withSkipLines(1) + .withIgnoreLeadingWhiteSpace(true) + .build(); + + // convert `CsvToBean` object to list of users + List vendas = csvToBean.parse(); + + // TODO: save users in DB? + vendasServices.insert(vendas); + // save users list on model + model.addAttribute("users", vendas); + model.addAttribute("status", true); + + } catch (Exception ex) { + model.addAttribute("message", "An error occurred while processing the CSV file."); + model.addAttribute("status", false); + } + } + + + return "file-upload-status"; + } + + @RequestMapping(value = "/{sigla}", method = RequestMethod.GET) //lists all paged ADMs + public ResponseEntity> findPage(@PathVariable String sigla) { + List list = vendasServices.findAll(sigla); + List listDTO = list.stream().map(obj -> new VendasDTO(obj)).collect(Collectors.toList()); + return ResponseEntity.ok().body(listDTO); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/FieldMassage.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/FieldMassage.java new file mode 100644 index 0000000..a4427b9 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/FieldMassage.java @@ -0,0 +1,39 @@ +package br.com.selecaojava.resources.exceptions; + +import java.io.Serializable; + +public class FieldMassage implements Serializable{ + private static final long serialVersionUID = 1L; + + private String fielName; + private String message; + + public FieldMassage() { + + } + + public FieldMassage(String fielName, String message) { + super(); + this.fielName = fielName; + this.message = message; + } + + public String getFielName() { + return fielName; + } + + public void setFielName(String fielName) { + this.fielName = fielName; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ResourceExceptionHandler.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ResourceExceptionHandler.java new file mode 100644 index 0000000..8df7226 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ResourceExceptionHandler.java @@ -0,0 +1,55 @@ +package br.com.selecaojava.resources.exceptions; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import br.com.selecaojava.servives.exceptions.AuthorizationException; +import br.com.selecaojava.servives.exceptions.DataIntegrityException; +import br.com.selecaojava.servives.exceptions.ObjectNotFoundException; + +@ControllerAdvice +public class ResourceExceptionHandler { + + @ExceptionHandler(ObjectNotFoundException.class) + public ResponseEntity objectNotfound(ObjectNotFoundException e, HttpServletRequest request){ + + StandardError err = new StandardError(HttpStatus.NOT_FOUND.value(),e.getMessage(),System.currentTimeMillis()); + + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err); + } + + @ExceptionHandler(DataIntegrityException.class) + public ResponseEntity objectNotfound(DataIntegrityException e, HttpServletRequest request){ + + StandardError err = new StandardError(HttpStatus.BAD_REQUEST.value(),e.getMessage(),System.currentTimeMillis()); + + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest request){ + + ValidationError err = new ValidationError(HttpStatus.BAD_REQUEST.value(),"Erro de Validação",System.currentTimeMillis()); + + for(FieldError x : e.getBindingResult().getFieldErrors()) { + err.addError(x.getField(), x.getDefaultMessage()); + } + + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err); + } + + @ExceptionHandler(AuthorizationException.class) + public ResponseEntity authorization(AuthorizationException e, HttpServletRequest request) { + + StandardError err = new StandardError(HttpStatus.FORBIDDEN.value(), e.getMessage(), System.currentTimeMillis()); + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(err); + } + + +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/StandardError.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/StandardError.java new file mode 100644 index 0000000..9e90f5a --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/StandardError.java @@ -0,0 +1,43 @@ +package br.com.selecaojava.resources.exceptions; + +import java.io.Serializable; + +public class StandardError implements Serializable { + private static final long serialVersionUID = 1L; + + private Integer status; + private String msg; + private Long timeStamp; + + public StandardError(Integer status, String msg, Long timeStamp) { + super(); + this.status = status; + this.msg = msg; + this.timeStamp = timeStamp; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Long getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(Long timeStamp) { + this.timeStamp = timeStamp; + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ValidationError.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ValidationError.java new file mode 100644 index 0000000..9750419 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/exceptions/ValidationError.java @@ -0,0 +1,24 @@ +package br.com.selecaojava.resources.exceptions; + +import java.util.ArrayList; +import java.util.List; + +public class ValidationError extends StandardError { + private static final long serialVersionUID = 1L; + + private List errors = new ArrayList<>(); + + public ValidationError(Integer status, String msg, Long timeStamp) { + super(status, msg, timeStamp); + // TODO Auto-generated constructor stub + } + + public List getErrors() { + return errors; + } + public void addError(String fieldName, String messagem) { + errors.add(new FieldMassage(fieldName,messagem)); + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/initial.txt b/api-selecaojava/src/main/java/br/com/selecaojava/resources/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthenticationFilter.java b/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthenticationFilter.java new file mode 100644 index 0000000..026d131 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthenticationFilter.java @@ -0,0 +1,80 @@ +package br.com.selecaojava.security; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + + +import com.fasterxml.jackson.databind.ObjectMapper; + +import br.com.selecaojava.dto.CredenciaisDTO; + +public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { + + private AuthenticationManager authenticationManager; + + private JWTUtil jwtUtil; + + public JWTAuthenticationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) { + setAuthenticationFailureHandler(new JWTAuthenticationFailureHandler()); + this.authenticationManager = authenticationManager; + this.jwtUtil = jwtUtil; + } + + @Override + public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException{ + + try { + CredenciaisDTO creds = new ObjectMapper() + .readValue(req.getInputStream(), CredenciaisDTO.class); + + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getSenha(), new ArrayList<>()); + + Authentication auth = authenticationManager.authenticate(authToken); + + return auth; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth){ + String username = ((UserSS) auth.getPrincipal()).getUsername(); + String token = jwtUtil.generateToken(username); + res.addHeader("Authorization", "Bearer "+ token); + res.addHeader("access-control-expose-headers", "Authorization"); + } + + private class JWTAuthenticationFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) + throws IOException, ServletException { + response.setStatus(401); + response.setContentType("application/json"); + response.getWriter().append(json()); + } + + private String json() { + long date = new Date().getTime(); + return "{\"timestamp\": " + date + ", " + + "\"status\": 401, " + + "\"error\": \"Não autorizado\", " + + "\"message\": \"Email ou senha inválidos\", " + + "\"path\": \"/login\"}"; + } + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthorizationFilter.java b/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthorizationFilter.java new file mode 100644 index 0000000..4fde030 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTAuthorizationFilter.java @@ -0,0 +1,53 @@ +package br.com.selecaojava.security; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +public class JWTAuthorizationFilter extends BasicAuthenticationFilter{ + + private JWTUtil jwtUtil; + + private UserDetailsService userDetailsService; + + public JWTAuthorizationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil, UserDetailsService userDetailsService) { + super(authenticationManager); + this.jwtUtil = jwtUtil; + this.userDetailsService = userDetailsService; + } + + @Override + public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain chain) throws IOException, ServletException{ + + String header = request.getHeader("Authorization"); + + if(header != null && header.startsWith("Bearer ")) { + UsernamePasswordAuthenticationToken auth = getAuthentication(header.substring(7)); + if(auth != null) { + SecurityContextHolder.getContext().setAuthentication(auth); + } + } + chain.doFilter(request, response); + } + + private UsernamePasswordAuthenticationToken getAuthentication(String token) { + if(jwtUtil.tokenValido(token)) { + String username = jwtUtil.getUsername(token); + UserDetails user = userDetailsService.loadUserByUsername(username); + return new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities()); + } + return null; + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTUtil.java b/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTUtil.java new file mode 100644 index 0000000..03f3004 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/security/JWTUtil.java @@ -0,0 +1,58 @@ +package br.com.selecaojava.security; + +import java.util.Date; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +@Component +public class JWTUtil { + + @Value("${jwt.secret}") + private String secret; + + @Value("${jwt.expiration}") + private Long expiration; + + public String generateToken(String username) { + return Jwts.builder() + .setSubject(username) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(SignatureAlgorithm.HS512, secret.getBytes()) + .compact(); + } + + public boolean tokenValido(String token) { + Claims claims = getClaims(token); + if (claims != null) { + String username = claims.getSubject(); + Date expirationDate = claims.getExpiration(); + Date now = new Date(System.currentTimeMillis()); + if (username != null && expirationDate != null && now.before(expirationDate)) { + return true; + } + } + return false; + } + + public String getUsername(String token) { + Claims claims = getClaims(token); + if (claims != null) { + return claims.getSubject(); + } + return null; + } + + private Claims getClaims(String token) { + try { + return Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(token).getBody(); + } + catch (Exception e) { + return null; + } + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/security/UserSS.java b/api-selecaojava/src/main/java/br/com/selecaojava/security/UserSS.java new file mode 100644 index 0000000..2cd463d --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/security/UserSS.java @@ -0,0 +1,77 @@ +package br.com.selecaojava.security; + +import java.util.Collection; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import br.com.selecaojava.enums.Perfil; + + +public class UserSS implements UserDetails{ + private static final long serialVersionUID = 1L; + + private Integer id; + private String email; + private String senha; + private Collection authorities; + + public UserSS() { + + } + + public UserSS(Integer id, String email, String senha, Set perfis) { + super(); + this.id = id; + this.email = email; + this.senha = senha; + this.authorities = perfis.stream().map(x -> new SimpleGrantedAuthority(x.getDescricao())).collect(Collectors.toList()); + + } + + public Integer getId() { + return id; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return senha; + } + + @Override + public String getUsername() { + return email; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + public boolean hasRole(Perfil perfil) { + return getAuthorities().contains(new SimpleGrantedAuthority(perfil.getDescricao())); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java new file mode 100644 index 0000000..8b54753 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java @@ -0,0 +1,34 @@ +package br.com.selecaojava.services; + +import java.util.Date; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.stereotype.Service; + +import br.com.selecaojava.domain.Useer; + +@Service +public abstract class AbstractEmailService implements EmailService{ + + @Value("${default.sender}") + private String sender; + + @Override + public void sendNewPasswordEmail(Useer user, String newPass) { + SimpleMailMessage sm = prepareNewPasswordEmail(user, newPass); + sendEmail(sm); + } + + + protected SimpleMailMessage prepareNewPasswordEmail(Useer user, String newPass) { + SimpleMailMessage sm = new SimpleMailMessage(); + sm.setTo(user.getEmail()); + sm.setFrom(sender); + sm.setSubject("Solicitação de nova senha"); + sm.setSentDate(new Date(System.currentTimeMillis())); + sm.setText("Nova senha: " + newPass); + return sm; + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java new file mode 100644 index 0000000..12511f2 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java @@ -0,0 +1,62 @@ +package br.com.selecaojava.services; + +import java.util.Random; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; + +import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.repositories.UserRepository; +import br.com.selecaojava.servives.exceptions.ObjectNotFoundException; + +@Service +public class AuthService { + + @Autowired + private UserRepository userRepository; + + @Autowired + private BCryptPasswordEncoder pe; + + @Autowired + private EmailService emailService; + + private Random rand = new Random(); + + public void sendNewPassword(String email) { + + Useer user = userRepository.findByEmail(email); + + if (user == null) { + throw new ObjectNotFoundException("Email não encontrado"); + } + + String newPass = newPassword(); + user.setSenha(pe.encode(newPass)); + + userRepository.save(user); + emailService.sendNewPasswordEmail(user, newPass); + } + + private String newPassword() { + char[] vet = new char[10]; + for (int i=0; i<10; i++) { + vet[i] = randomChar(); + } + return new String(vet); + } + + private char randomChar() { + int opt = rand.nextInt(3); + if (opt == 0) { //generate a digit + return (char) (rand.nextInt(10) + 48); + } + else if (opt == 1) { //generate capital letter + return (char) (rand.nextInt(26) + 65); + } + else { //generate lowercase letter + return (char) (rand.nextInt(26) + 97); + } + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java new file mode 100644 index 0000000..82c9b15 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java @@ -0,0 +1,34 @@ +package br.com.selecaojava.services; + +import java.text.ParseException; +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; + + +import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.enums.Perfil; +import br.com.selecaojava.repositories.UserRepository; + +@Service +public class DBService { + + @Autowired + private BCryptPasswordEncoder pe; + + @Autowired + private UserRepository userRepository; + + + public void instantiateTestDatabase() throws ParseException{ + + Useer userAdmin = new Useer(null,"MainAdmin","admin@gmail.com",pe.encode("admin")); + userAdmin.addPerfil(Perfil.ADMIN); + + userRepository.saveAll(Arrays.asList(userAdmin)); + + } +} + diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java new file mode 100644 index 0000000..30993cf --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java @@ -0,0 +1,14 @@ +package br.com.selecaojava.services; + +import org.springframework.mail.SimpleMailMessage; +import org.springframework.stereotype.Service; + +import br.com.selecaojava.domain.Useer; + +@Service +public interface EmailService { + + void sendEmail(SimpleMailMessage msg); + + void sendNewPasswordEmail(Useer user, String newPass); +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/MockEmailService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/MockEmailService.java new file mode 100644 index 0000000..80e8dfe --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/MockEmailService.java @@ -0,0 +1,17 @@ +package br.com.selecaojava.services; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.mail.SimpleMailMessage; + +public class MockEmailService extends AbstractEmailService { + + private static final Logger LOG = LoggerFactory.getLogger(MockEmailService.class); + + @Override + public void sendEmail(SimpleMailMessage msg) { + LOG.info("Simulando envio de email..."); + LOG.info(msg.toString()); + LOG.info("Email enviado"); + } +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/SmtpEmailService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/SmtpEmailService.java new file mode 100644 index 0000000..4023bb0 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/SmtpEmailService.java @@ -0,0 +1,22 @@ +package br.com.selecaojava.services; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mail.MailSender; +import org.springframework.mail.SimpleMailMessage; + +public class SmtpEmailService extends AbstractEmailService { + + @Autowired + private MailSender mailSender; + + private static final Logger LOG = LoggerFactory.getLogger(SmtpEmailService.class); + + @Override + public void sendEmail(SimpleMailMessage msg) { + LOG.info("Enviando email..."); + mailSender.send(msg); + LOG.info("Email enviado"); + } +} \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java new file mode 100644 index 0000000..d3624f5 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java @@ -0,0 +1,30 @@ +package br.com.selecaojava.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.repositories.UserRepository; +import br.com.selecaojava.security.UserSS; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService{ + @Autowired + private UserRepository repo; + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + Useer user = repo.findByEmail(email); //Search email database + + if(user == null) { //If imail does not exist throw exception + throw new UsernameNotFoundException("Email não existe: "+email); + } + + return new UserSS(user.getId(),user.getEmail(),user.getSenha(), user.getPerfis()); + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java new file mode 100644 index 0000000..2797b90 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java @@ -0,0 +1,130 @@ + +package br.com.selecaojava.services; + +import java.util.List; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.dto.NomeDTO; +import br.com.selecaojava.dto.PasswordDTO; +import br.com.selecaojava.dto.UserDTO; +import br.com.selecaojava.enums.Perfil; +import br.com.selecaojava.repositories.UserRepository; +import br.com.selecaojava.security.UserSS; +import br.com.selecaojava.servives.exceptions.AuthorizationException; +import br.com.selecaojava.servives.exceptions.ObjectNotFoundException; + + +@Service +public class UserService { + + @Autowired + private BCryptPasswordEncoder pe; + + @Autowired + private UserRepository repo; + + public Useer find(Integer id) throws ObjectNotFoundException { + UserSS user = UserServiceService.authenticated(); + if (user==null || !user.hasRole(Perfil.ADMIN) && !id.equals(user.getId())) { + throw new AuthorizationException("Acesso negado"); + } + Optional obj = repo.findById(id); + return obj.orElseThrow(() -> new ObjectNotFoundException( + "Objeto não encontrado! Id: " + id + ", Tipo: " + Useer.class.getName())); + } + + @Transactional + public Useer insert(Useer obj) { + obj.setId(null); + return repo.save(obj); + } + + public Useer update(Useer obj) throws ObjectNotFoundException { + Useer newObj = find(obj.getId()); + updateData(newObj,obj); + return repo.save(obj); + } + + public Useer update(PasswordDTO obj) throws ObjectNotFoundException { + Useer newObj = find(obj.getId()); + updatePassword(newObj,obj); + return repo.save(newObj); + } + + public Useer update(NomeDTO obj) throws ObjectNotFoundException { + Useer newObj = find(obj.getId()); + updateNome(newObj,obj); + return repo.save(newObj); + } + + private void updateNome(Useer newObj, NomeDTO obj) { + newObj.setId(obj.getId()); + newObj.setNome(obj.getNome()); + } + + public NomeDTO nomeDTO(NomeDTO nomeDto) { + return new NomeDTO(nomeDto.getId(), nomeDto.getNome()); + } + + public PasswordDTO passwordDTO(PasswordDTO objDto) { + return new PasswordDTO(objDto.getId(), pe.encode(objDto.getSenha())); + } + + private void updatePassword(Useer newObj,PasswordDTO obj) { + newObj.setId(obj.getId()); + newObj.setSenha(obj.getSenha()); + } + + public void delete(Integer id) throws ObjectNotFoundException { + find(id); + try { + repo.deleteById(id); + } + catch (DataIntegrityViolationException e) { + throw new DataIntegrityViolationException("Não é possivevel excluir um User"); + } + } + + public List findAll() { + return repo.findAll(); + } + + public Page findPage(Integer page, Integer linesPerPage, String orderBy, String direction){ + PageRequest pageRequest = PageRequest.of(page, linesPerPage , Direction.valueOf(direction), orderBy); + return repo.findAll(pageRequest); + } + + public Useer fromDTO(UserDTO objDto) { + return new Useer(objDto.getId(),objDto.getNome(), objDto.getEmail(), pe.encode(objDto.getSenha())); + } + + private void updateData(Useer newObj,Useer obj) { + newObj.setNome(obj.getNome()); + } + + public Useer findByEmail(String email){ + + UserSS user = UserServiceService.authenticated(); + if (user == null || !user.hasRole(Perfil.ADMIN) && !email.equals(user.getUsername())) { + throw new AuthorizationException("Acesso negado"); + } + Useer obj = repo.findByEmail(email); + if (obj == null) { + throw new ObjectNotFoundException( + "Objeto não encontrado! Id: " + user.getId() + ", Tipo: " + Useer.class.getName()); + } + return obj; + } + +} + diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserServiceService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserServiceService.java new file mode 100644 index 0000000..33f5026 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserServiceService.java @@ -0,0 +1,17 @@ +package br.com.selecaojava.services; + +import org.springframework.security.core.context.SecurityContextHolder; + +import br.com.selecaojava.security.UserSS; + +public class UserServiceService { + + public static UserSS authenticated() { + try { + return (UserSS) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + } + catch (Exception e) { + return null; + } + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java new file mode 100644 index 0000000..2ac1769 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java @@ -0,0 +1,33 @@ +package br.com.selecaojava.services; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.dataformat.csv.CsvMapper; +import com.fasterxml.jackson.dataformat.csv.CsvSchema; + +import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.dto.VendasDTO; +import br.com.selecaojava.repositories.VendasRepository; + +@Service +public class VendasServices { + + @Autowired + private VendasRepository vendasRepository; + + public void insert(List vendas) { + //obj.setId(null); + vendasRepository.saveAll(vendas); + } +// private static final CsvMapper mapper = new CsvMapper(); + + public List findAll(String sigla) { + return vendasRepository.findByregiaoSigla(sigla); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/ObjectNotFoundException.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/ObjectNotFoundException.java new file mode 100644 index 0000000..38887a9 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/ObjectNotFoundException.java @@ -0,0 +1,18 @@ +package br.com.selecaojava.services.exceptions; + +import org.springframework.http.HttpStatus; + +public class ObjectNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 1L; + private HttpStatus httpStatus; + + public ObjectNotFoundException(String msg,HttpStatus httpStatus) { + super(msg); + this.httpStatus = httpStatus; + } + + public ObjectNotFoundException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java new file mode 100644 index 0000000..38f96d2 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java @@ -0,0 +1,22 @@ +package br.com.selecaojava.services.exceptions; + +import org.springframework.http.HttpStatus; + +public class PropertyNotFoundException extends Exception{ + /** + * + */ + private static final long serialVersionUID = 1L; + private HttpStatus httpStatus; + + public PropertyNotFoundException (String mensagem, HttpStatus httpStatus){ + super (mensagem); + this.httpStatus = httpStatus; + } + + public HttpStatus getHttpStatus() { + return httpStatus; + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/initial.txt b/api-selecaojava/src/main/java/br/com/selecaojava/services/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/AuthorizationException.java b/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/AuthorizationException.java new file mode 100644 index 0000000..f106164 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/AuthorizationException.java @@ -0,0 +1,15 @@ +package br.com.selecaojava.servives.exceptions; + +public class AuthorizationException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public AuthorizationException(String mgs) { + super(mgs); + } + + public AuthorizationException(String mgs,Throwable cause) { + super(mgs,cause); + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/DataIntegrityException.java b/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/DataIntegrityException.java new file mode 100644 index 0000000..86af5fe --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/DataIntegrityException.java @@ -0,0 +1,15 @@ +package br.com.selecaojava.servives.exceptions; + +public class DataIntegrityException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public DataIntegrityException(String mgs) { + super(mgs); + } + + public DataIntegrityException(String mgs,Throwable cause) { + super(mgs,cause); + } + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/ObjectNotFoundException.java b/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/ObjectNotFoundException.java new file mode 100644 index 0000000..0166bd5 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/servives/exceptions/ObjectNotFoundException.java @@ -0,0 +1,15 @@ +package br.com.selecaojava.servives.exceptions; + +public class ObjectNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ObjectNotFoundException(String mgs) { + super(mgs); + } + + public ObjectNotFoundException(String mgs,Throwable cause) { + super(mgs,cause); + } + +} diff --git a/api-selecaojava/src/main/java/utils/FileSaver.java b/api-selecaojava/src/main/java/utils/FileSaver.java new file mode 100644 index 0000000..97d8724 --- /dev/null +++ b/api-selecaojava/src/main/java/utils/FileSaver.java @@ -0,0 +1,48 @@ +package utils; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +@Component +public class FileSaver { + + @Value("${contato.disco.raiz}") + private String raiz = "/home/alvaro/Documents/projetos"; + + @Value("${contato.disco.diretorio-fotos}") + private String diretorioFotos = "imagensdoprojeto"; + + public String salvarFoto(MultipartFile foto) { + return this.salvar(this.diretorioFotos, foto); + } + + public String salvar(String diretorio, MultipartFile arquivo) { + + + Path diretorioPath = Paths.get(this.raiz, diretorio); + Path arquivoPath = diretorioPath.resolve(arquivo.getOriginalFilename()); + + try { + Files.createDirectories(diretorioPath); + + arquivo.transferTo(arquivoPath.toFile()); + + return arquivoPath.toString(); + } catch (IOException e) { + + throw new RuntimeException("Problemas na tentativa de salvar arquivo.", e); + } + } + + public Boolean deletar(String url) { + File file = new File(url); + return file.delete(); + } +} \ No newline at end of file diff --git a/api-selecaojava/src/main/resources/application-dev.properties b/api-selecaojava/src/main/resources/application-dev.properties new file mode 100644 index 0000000..4f9852c --- /dev/null +++ b/api-selecaojava/src/main/resources/application-dev.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:h2:mem:selecaodb +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true \ No newline at end of file diff --git a/api-selecaojava/src/main/resources/application-test.properties b/api-selecaojava/src/main/resources/application-test.properties new file mode 100644 index 0000000..e7f65d2 --- /dev/null +++ b/api-selecaojava/src/main/resources/application-test.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:h2:mem:selecaodb +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true diff --git a/api-selecaojava/src/main/resources/application.properties b/api-selecaojava/src/main/resources/application.properties new file mode 100644 index 0000000..56d2cad --- /dev/null +++ b/api-selecaojava/src/main/resources/application.properties @@ -0,0 +1,20 @@ +## MULTIPART (MultipartProperties) +# Enable multipart uploads +spring.servlet.multipart.enabled=true +# Threshold after which files are written to disk. +spring.servlet.multipart.file-size-threshold=2KB +# Max file size. +spring.servlet.multipart.max-file-size=200MB +# Max Request Size +contato.disco.raiz=/home/alvaro/Documents/projetos +contato.disco.diretorio-fotos=imagensdoprojeto + +spring.servlet.multipart.max-request-size=215MB + +spring.profiles.active=test + +default.sender= +default.recipient= + +jwt.secret=SequenciaCaracterireParaAssinarToken +jwt.expiration=86400000 \ No newline at end of file diff --git a/api-selecaojava/src/test/java/br/com/selecaojava/ApiNanoApplicationTests.java b/api-selecaojava/src/test/java/br/com/selecaojava/ApiNanoApplicationTests.java new file mode 100644 index 0000000..b2f6b72 --- /dev/null +++ b/api-selecaojava/src/test/java/br/com/selecaojava/ApiNanoApplicationTests.java @@ -0,0 +1,13 @@ +package br.com.selecaojava; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApiselecaojavaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml b/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml new file mode 100644 index 0000000..d5a88d5 --- /dev/null +++ b/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml @@ -0,0 +1,139 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + + br.com.selecaojava + api-selecaojava + 0.0.1-SNAPSHOT + api-selecaojava + + + + + 3.1.1 + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + + + + com.h2database + h2 + runtime + + + + org.apache.commons + commons-lang3 + 3.7 + + + + org.postgresql + postgresql + runtime + + + + com.opencsv + opencsv + 5.0 + + + + org.springframework.boot + spring-boot-starter-security + + + + io.jsonwebtoken + jjwt + 0.7.0 + + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/api-selecaojava/target/classes/application-dev.properties b/api-selecaojava/target/classes/application-dev.properties new file mode 100644 index 0000000..4f9852c --- /dev/null +++ b/api-selecaojava/target/classes/application-dev.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:h2:mem:selecaodb +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true \ No newline at end of file diff --git a/api-selecaojava/target/classes/application-test.properties b/api-selecaojava/target/classes/application-test.properties new file mode 100644 index 0000000..e7f65d2 --- /dev/null +++ b/api-selecaojava/target/classes/application-test.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:h2:mem:selecaodb +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true diff --git a/api-selecaojava/target/classes/application.properties b/api-selecaojava/target/classes/application.properties new file mode 100644 index 0000000..56d2cad --- /dev/null +++ b/api-selecaojava/target/classes/application.properties @@ -0,0 +1,20 @@ +## MULTIPART (MultipartProperties) +# Enable multipart uploads +spring.servlet.multipart.enabled=true +# Threshold after which files are written to disk. +spring.servlet.multipart.file-size-threshold=2KB +# Max file size. +spring.servlet.multipart.max-file-size=200MB +# Max Request Size +contato.disco.raiz=/home/alvaro/Documents/projetos +contato.disco.diretorio-fotos=imagensdoprojeto + +spring.servlet.multipart.max-request-size=215MB + +spring.profiles.active=test + +default.sender= +default.recipient= + +jwt.secret=SequenciaCaracterireParaAssinarToken +jwt.expiration=86400000 \ No newline at end of file diff --git a/api-selecaojava/target/classes/br/com/selecaojava/domain/initial.txt b/api-selecaojava/target/classes/br/com/selecaojava/domain/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/target/classes/br/com/selecaojava/dto/initial.txt b/api-selecaojava/target/classes/br/com/selecaojava/dto/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/target/classes/br/com/selecaojava/repositories/initial.txt b/api-selecaojava/target/classes/br/com/selecaojava/repositories/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/target/classes/br/com/selecaojava/resources/initial.txt b/api-selecaojava/target/classes/br/com/selecaojava/resources/initial.txt new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/target/classes/br/com/selecaojava/services/initial.txt b/api-selecaojava/target/classes/br/com/selecaojava/services/initial.txt new file mode 100644 index 0000000..e69de29 From 00c5071bfe43359113f6a9c861c0b3b5048fed73 Mon Sep 17 00:00:00 2001 From: StewenAscari Date: Thu, 21 May 2020 16:12:04 -0300 Subject: [PATCH 2/5] finalizando o import de arquivo csv --- api-selecaojava/pom.xml | 6 ++++++ .../main/java/br/com/selecaojava/domain/Vendas.java | 11 ----------- .../main/java/br/com/selecaojava/dto/VendasDTO.java | 7 +++++++ .../selecaojava/repositories/VendasRepository.java | 1 + .../br/com/selecaojava/resources/VendasResource.java | 9 ++++++--- .../br/com/selecaojava/services/VendasServices.java | 3 +++ .../maven/br.com.selecaojava/api-selecaojava/pom.xml | 6 ++++++ 7 files changed, 29 insertions(+), 14 deletions(-) diff --git a/api-selecaojava/pom.xml b/api-selecaojava/pom.xml index d5a88d5..8a0bd92 100644 --- a/api-selecaojava/pom.xml +++ b/api-selecaojava/pom.xml @@ -81,6 +81,12 @@ 0.7.0 + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + 2.5.3 + + org.springframework.boot diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java index 8f85e49..a079075 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java @@ -20,48 +20,37 @@ public class Vendas { @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; - @CsvBindByName(column = "Região - Sigla") @Column(columnDefinition = "VARCHAR(1000)") @CsvBindByPosition(position = 0) private String regiaoSigla; - @CsvBindByName(column = "Estado - Sigla") @CsvBindByPosition(position = 1) private String estadoSigla; - @CsvBindByName(column = "Município") @CsvBindByPosition(position = 2) private String municipio; - @CsvBindByName(column = "Revenda") @CsvBindByPosition(position = 3) private String revenda; - @CsvBindByName(column = "CNPJ da Revenda") @CsvBindByPosition(position = 4) private String cnpjdaRevenda; - @CsvBindByName(column = "Produto") @CsvBindByPosition(position = 5) private String produto; - @CsvBindByName(column = "Data da Coleta") @CsvBindByPosition(position = 6) private String datadaColeta; - @CsvBindByName(column = "Valor de Venda") @CsvBindByPosition(position = 7) private String valordeVenda; - @CsvBindByName(column = "Valor de Compra") @CsvBindByPosition(position = 8) private String valordeCompra; - @CsvBindByName(column = "Unidade de Medida") @CsvBindByPosition(position = 9) private String unidadedeMedida; - @CsvBindByName(column = "Bandeira") @CsvBindByPosition(position = 10) private String bandeira; diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java index ac09598..ae99621 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java @@ -43,6 +43,7 @@ public class VendasDTO { @CsvBindByName(column = "Bandeira") private String bandeira; + private Integer id; public VendasDTO() { @@ -126,6 +127,12 @@ public String getBandeira() { public void setBandeira(String bandeira) { this.bandeira = bandeira; } + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java index 21965c3..fed0ac7 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java @@ -21,6 +21,7 @@ public interface VendasRepository extends JpaRepository { List findByregiaoSigla(String regiaoSigla); + } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java index d3c2582..cc3339b 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java @@ -3,6 +3,7 @@ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -20,6 +21,7 @@ import org.springframework.web.multipart.MultipartFile; import com.opencsv.bean.ColumnPositionMappingStrategy; +import com.opencsv.bean.CsvBindByName; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; @@ -47,18 +49,19 @@ public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model mode } else { // parse CSV file to create a list of `Vendas` objects - try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()), '\t')) { + try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) { // create csv bean reader CsvToBean csvToBean = new CsvToBeanBuilder(reader) .withType(Vendas.class) .withSkipLines(1) +// .withSeparator(',') + .withSeparator('\t') .withIgnoreLeadingWhiteSpace(true) .build(); - + // convert `CsvToBean` object to list of users List vendas = csvToBean.parse(); - // TODO: save users in DB? vendasServices.insert(vendas); // save users list on model diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java index 2ac1769..145b15a 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java @@ -24,6 +24,9 @@ public class VendasServices { public void insert(List vendas) { //obj.setId(null); vendasRepository.saveAll(vendas); + while (vendas.remove(null)) { + System.out.println("remove null"); + } } // private static final CsvMapper mapper = new CsvMapper(); diff --git a/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml b/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml index d5a88d5..8a0bd92 100644 --- a/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml +++ b/api-selecaojava/target/classes/META-INF/maven/br.com.selecaojava/api-selecaojava/pom.xml @@ -81,6 +81,12 @@ 0.7.0 + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + 2.5.3 + + org.springframework.boot From 8bfdbba70bed0ce8fa7827e02820d4ea4089f71f Mon Sep 17 00:00:00 2001 From: StewenAscari Date: Fri, 22 May 2020 18:04:05 -0300 Subject: [PATCH 3/5] implementando a relacao das entidades --- api-selecaojava/.attach_pid9292 | 0 .../selecaojava/config/SecurityConfig.java | 2 - .../domain/{Vendas.java => Sales.java} | 29 +++++++-- .../domain/{Useer.java => User.java} | 27 ++++++-- .../java/br/com/selecaojava/dto/UserDTO.java | 7 +- .../br/com/selecaojava/dto/VendasDTO.java | 4 +- .../repositories/UserRepository.java | 9 ++- .../repositories/VendasRepository.java | 6 +- .../selecaojava/resources/UserResouces.java | 20 +++--- .../selecaojava/resources/VendasResource.java | 65 +++++++++++++++---- .../services/AbstractEmailService.java | 8 +-- .../com/selecaojava/services/AuthService.java | 6 +- .../com/selecaojava/services/DBService.java | 7 +- .../selecaojava/services/EmailService.java | 7 +- .../services/UserDetailsServiceImpl.java | 6 +- .../com/selecaojava/services/UserService.java | 44 ++++++------- .../selecaojava/services/VendasServices.java | 20 +++--- ...ption.java => SalesNotFoundException.java} | 4 +- 18 files changed, 171 insertions(+), 100 deletions(-) create mode 100644 api-selecaojava/.attach_pid9292 rename api-selecaojava/src/main/java/br/com/selecaojava/domain/{Vendas.java => Sales.java} (85%) rename api-selecaojava/src/main/java/br/com/selecaojava/domain/{Useer.java => User.java} (80%) rename api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/{PropertyNotFoundException.java => SalesNotFoundException.java} (72%) diff --git a/api-selecaojava/.attach_pid9292 b/api-selecaojava/.attach_pid9292 new file mode 100644 index 0000000..e69de29 diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java b/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java index c13ee63..14426f4 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java @@ -40,8 +40,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter{ private static final String[] PUBLIC_MATCHERS = { //Arraay dos endpoint que vão ser permitidos os acessos "/h2-console/**", - "/property/**", - "/property/1/**" }; diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java similarity index 85% rename from api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java rename to api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java index a079075..b081c84 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Vendas.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java @@ -1,20 +1,25 @@ package br.com.selecaojava.domain; -import java.util.Set; +import java.io.Serializable; +import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; import javax.persistence.OrderBy; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.opencsv.bean.CsvBindByName; import com.opencsv.bean.CsvBindByPosition; @Entity -public class Vendas { +public class Sales implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -53,13 +58,15 @@ public class Vendas { @CsvBindByPosition(position = 10) private String bandeira; - - - public Vendas() { + + @ManyToOne(fetch = FetchType.EAGER) + @JsonIgnore + private User user; + public Sales() { } - public Vendas(Integer id, String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, - String valorVenda, String valorCompra, String unidadeMedida, String bandeira) { + public Sales(Integer id, String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, + String valorVenda, String valorCompra, String unidadeMedida, String bandeira, User user) { this.id = id; this.regiaoSigla = regiaoSigla; this.estadoSigla = stadoSigla; @@ -72,6 +79,7 @@ public Vendas(Integer id, String regiaoSigla, String stadoSigla, String municipi this.valordeCompra = valorCompra; this.unidadedeMedida = unidadeMedida; this.bandeira = bandeira; + this.user = user; } @@ -148,6 +156,13 @@ public String getBandeira() { public void setBandeira(String bandeira) { this.bandeira = bandeira; } + + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } @Override public int hashCode() { final int prime = 31; diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/User.java similarity index 80% rename from api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java rename to api-selecaojava/src/main/java/br/com/selecaojava/domain/User.java index dc283b3..3d562b5 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Useer.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/User.java @@ -1,10 +1,13 @@ package br.com.selecaojava.domain; import java.io.Serializable; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; +import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; @@ -12,13 +15,13 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonIgnore; - import br.com.selecaojava.enums.Perfil; @Entity -public class Useer implements Serializable { +public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @@ -30,15 +33,20 @@ public class Useer implements Serializable { @JsonIgnore //Do not show password when retrieving data private String senha; + @OneToMany(fetch = FetchType.EAGER) + @JsonIgnore + private List sales = new ArrayList<>(); + + @ElementCollection(fetch=FetchType.EAGER) @CollectionTable(name="PERFIS") private Set perfis = new HashSet<>(); - public Useer() { + public User() { addPerfil(Perfil.ADMIN); } - public Useer(Integer id, String nome, String email, String senha) { + public User(Integer id, String nome, String email, String senha) { super(); this.id = id; this.nome = nome; @@ -86,7 +94,14 @@ public Set getPerfis() { public void addPerfil(Perfil perfil) { this.perfis.add(perfil.getCod()); } - + + + public List getSales() { + return sales; + } + public void setSales(List sales) { + this.sales = sales; + } @Override public int hashCode() { final int prime = 31; @@ -102,7 +117,7 @@ public boolean equals(Object obj) { return false; if (getClass() != obj.getClass()) return false; - Useer other = (Useer) obj; + User other = (User) obj; if (id == null) { if (other.id != null) return false; diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java index 4ec63a6..ac298d8 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/UserDTO.java @@ -1,11 +1,10 @@ package br.com.selecaojava.dto; -import java.io.Serializable; +import java.io.Serializable; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; - -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; public class UserDTO implements Serializable{ private static final long serialVersionUID = 1L; @@ -26,7 +25,7 @@ public UserDTO() { } - public UserDTO(Useer user) { + public UserDTO(User user) { id = user.getId(); nome = user.getNome(); email = user.getEmail(); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java index ae99621..d633761 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java @@ -5,7 +5,7 @@ import com.opencsv.bean.CsvBindByName; import com.opencsv.bean.CsvBindByPosition; -import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.domain.Sales; public class VendasDTO { @@ -48,7 +48,7 @@ public class VendasDTO { public VendasDTO() { } - public VendasDTO(Vendas vendas) { + public VendasDTO(Sales vendas) { regiaoSigla = vendas.getRegiaoSigla(); estadoSigla = vendas.getEstadoSigla(); municipio = vendas.getMunicipio(); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java index c4994c7..a20d347 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/UserRepository.java @@ -1,16 +1,15 @@ package br.com.selecaojava.repositories; -import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; - -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; @Repository -public interface UserRepository extends JpaRepository{ +public interface UserRepository extends JpaRepository{ @Transactional(readOnly=true) - Useer findByEmail(String email); + User findByEmail(String email); } \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java index fed0ac7..fbed5cc 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java @@ -1,5 +1,5 @@ package br.com.selecaojava.repositories; -import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.domain.Sales; import br.com.selecaojava.dto.VendasDTO; import java.util.List; @@ -18,9 +18,9 @@ import com.opencsv.bean.CsvBindByPosition; @Repository -public interface VendasRepository extends JpaRepository { +public interface VendasRepository extends JpaRepository { - List findByregiaoSigla(String regiaoSigla); + List findByregiaoSigla(String regiaoSigla); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java index 14c8dbe..32b0eaf 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/UserResouces.java @@ -1,6 +1,6 @@ package br.com.selecaojava.resources; -import java.net.URI; +import java.net.URI; import java.util.List; import java.util.stream.Collectors; @@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; import br.com.selecaojava.dto.NomeDTO; import br.com.selecaojava.dto.PasswordDTO; import br.com.selecaojava.dto.UserDTO; @@ -34,21 +34,21 @@ public class UserResouces { @PreAuthorize("hasAnyRole('ADMIN')") @RequestMapping(value="/{id}", method = RequestMethod.GET) - public ResponseEntity find(@PathVariable Integer id){ - Useer obj = service.find(id); + public ResponseEntity find(@PathVariable Integer id){ + User obj = service.find(id); return ResponseEntity.ok().body(obj); } @RequestMapping(value="/email", method=RequestMethod.GET) - public ResponseEntity find(@RequestParam(value="value") String email) { - Useer obj = service.findByEmail(email); + public ResponseEntity find(@RequestParam(value="value") String email) { + User obj = service.findByEmail(email); return ResponseEntity.ok().body(obj); } @PreAuthorize("hasAnyRole('ADMIN')") //Forces a user is logged in to access this endpoint @RequestMapping(method=RequestMethod.POST) //add a new admin public ResponseEntity insert(@Valid @RequestBody UserDTO objDto){ - Useer obj = service.fromDTO(objDto); + User obj = service.fromDTO(objDto); obj = service.insert(obj); URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"). buildAndExpand(obj.getId()).toUri(); @@ -58,7 +58,7 @@ public ResponseEntity insert(@Valid @RequestBody UserDTO objDto){ @PreAuthorize("hasAnyRole('ADMIN')") @RequestMapping(value="/{id}",method=RequestMethod.PUT) //update an entire ADM public ResponseEntity update(@Valid @RequestBody UserDTO objDto,@PathVariable Integer id) throws ObjectNotFoundException{ - Useer obj = service.fromDTO(objDto); + User obj = service.fromDTO(objDto); obj = service.update(obj); return ResponseEntity.noContent().build(); } @@ -89,7 +89,7 @@ public ResponseEntity delete(@PathVariable Integer id) throws ObjectNotFou @PreAuthorize("hasAnyRole('ADMIN')") @RequestMapping(method = RequestMethod.GET) //list all ADM public ResponseEntity> findPage() { - List list = service.findAll(); + List list = service.findAll(); List listDTO = list.stream().map(obj -> new UserDTO(obj)).collect(Collectors.toList()); return ResponseEntity.ok().body(listDTO); } @@ -101,7 +101,7 @@ public ResponseEntity> findAll( @RequestParam(value="linesPerPage", defaultValue="24") Integer linesPerPage, @RequestParam(value="orderBy", defaultValue="nome") String orderBy, @RequestParam(value="direction", defaultValue="ASC") String direction){ - Page list = service.findPage(page, linesPerPage, orderBy, direction); + Page list = service.findPage(page, linesPerPage, orderBy, direction); Page listDTO = list.map(obj -> new UserDTO(obj)); return ResponseEntity.ok().body(listDTO); } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java index cc3339b..66f3c2e 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java @@ -1,6 +1,6 @@ package br.com.selecaojava.resources; -import java.io.BufferedReader; +import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; @@ -8,15 +8,19 @@ import java.util.List; import java.util.stream.Collectors; +import javax.validation.Valid; + import org.hibernate.hql.spi.PositionalParameterInformation; import org.hibernate.loader.custom.sql.PositionalParamBinder; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @@ -25,23 +29,40 @@ import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; -import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.domain.User; import br.com.selecaojava.dto.VendasDTO; import br.com.selecaojava.repositories.VendasRepository; +import br.com.selecaojava.services.UserService; import br.com.selecaojava.services.VendasServices; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; @RestController -@RequestMapping(value="/vendas") +@RequestMapping(value="/user/{id}/sales") public class VendasResource { @Autowired private VendasServices vendasServices; @Autowired - private VendasRepository vendasRepository; + private UserService userService; - @RequestMapping(value="/upload-csv-file", method = RequestMethod.POST) - public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model model) { + /* + * Operação PUT + */ + @ApiOperation(value = "Insere s", response = Sales.class, + notes = "Essa operação Edita um novo registro propriedades") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Retorna um ResponseEntity com o objeto e o status", response = Sales.class), + @ApiResponse(code = 406, message = "Caso as imagens não sejam aceitas retorna um erro") + }) + @RequestMapping(value="/upload-csv-file", method = RequestMethod.PUT) + public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model model, + @Valid @RequestPart @RequestParam("id") @PathVariable Integer id) { + User user = userService.find(id); + // validate file if (file.isEmpty()) { model.addAttribute("message", "Please select a CSV file to upload."); @@ -52,8 +73,8 @@ public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model mode try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) { // create csv bean reader - CsvToBean csvToBean = new CsvToBeanBuilder(reader) - .withType(Vendas.class) + CsvToBean csvToBean = new CsvToBeanBuilder(reader) + .withType(Sales.class) .withSkipLines(1) // .withSeparator(',') .withSeparator('\t') @@ -61,12 +82,15 @@ public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model mode .build(); // convert `CsvToBean` object to list of users - List vendas = csvToBean.parse(); + List sales = csvToBean.parse(); // TODO: save users in DB? - vendasServices.insert(vendas); + vendasServices.insert(sales); + user.setSales(sales);; // save users list on model - model.addAttribute("users", vendas); + model.addAttribute("sales", sales); model.addAttribute("status", true); + + userService.update(user); } catch (Exception ex) { model.addAttribute("message", "An error occurred while processing the CSV file."); @@ -80,8 +104,25 @@ public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model mode @RequestMapping(value = "/{sigla}", method = RequestMethod.GET) //lists all paged ADMs public ResponseEntity> findPage(@PathVariable String sigla) { - List list = vendasServices.findAll(sigla); + List list = vendasServices.findAll(sigla); List listDTO = list.stream().map(obj -> new VendasDTO(obj)).collect(Collectors.toList()); return ResponseEntity.ok().body(listDTO); } + + @ApiOperation(value = "Buscar uma Imagem por ID", response = Sales.class, notes = "Essa operação Busca um novo registro com as informações de uma Propriedade.") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Retorna um ResponseEntity com o objeto", response = Sales.class), + @ApiResponse(code = 404, message = "Caso tenhamos algum erro vamos retornar uma mensagem e um código http") + + }) + @RequestMapping(value = "/consulta/{id}", method = RequestMethod.GET) + public ResponseEntity listar(@PathVariable Integer id) { + Sales obj = vendasServices.find(id); + + if (obj == null) { + return new ResponseEntity("Imagem não encotrada!", HttpStatus.NOT_FOUND); + } + + return ResponseEntity.ok(obj); + } } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java index 8b54753..c8c3e43 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/AbstractEmailService.java @@ -1,12 +1,12 @@ package br.com.selecaojava.services; -import java.util.Date; +import java.util.Date; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Service; -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; @Service public abstract class AbstractEmailService implements EmailService{ @@ -15,13 +15,13 @@ public abstract class AbstractEmailService implements EmailService{ private String sender; @Override - public void sendNewPasswordEmail(Useer user, String newPass) { + public void sendNewPasswordEmail(User user, String newPass) { SimpleMailMessage sm = prepareNewPasswordEmail(user, newPass); sendEmail(sm); } - protected SimpleMailMessage prepareNewPasswordEmail(Useer user, String newPass) { + protected SimpleMailMessage prepareNewPasswordEmail(User user, String newPass) { SimpleMailMessage sm = new SimpleMailMessage(); sm.setTo(user.getEmail()); sm.setFrom(sender); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java index 12511f2..d36e135 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/AuthService.java @@ -1,12 +1,12 @@ package br.com.selecaojava.services; -import java.util.Random; +import java.util.Random; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; import br.com.selecaojava.repositories.UserRepository; import br.com.selecaojava.servives.exceptions.ObjectNotFoundException; @@ -26,7 +26,7 @@ public class AuthService { public void sendNewPassword(String email) { - Useer user = userRepository.findByEmail(email); + User user = userRepository.findByEmail(email); if (user == null) { throw new ObjectNotFoundException("Email não encontrado"); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java index 82c9b15..235f88d 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/DBService.java @@ -1,14 +1,13 @@ package br.com.selecaojava.services; -import java.text.ParseException; +import java.text.ParseException; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; - -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; import br.com.selecaojava.enums.Perfil; import br.com.selecaojava.repositories.UserRepository; @@ -24,7 +23,7 @@ public class DBService { public void instantiateTestDatabase() throws ParseException{ - Useer userAdmin = new Useer(null,"MainAdmin","admin@gmail.com",pe.encode("admin")); + User userAdmin = new User(null,"MainAdmin","admin@gmail.com",pe.encode("admin")); userAdmin.addPerfil(Perfil.ADMIN); userRepository.saveAll(Arrays.asList(userAdmin)); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java index 30993cf..0161def 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/EmailService.java @@ -1,14 +1,15 @@ package br.com.selecaojava.services; -import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Service; -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; + @Service public interface EmailService { void sendEmail(SimpleMailMessage msg); - void sendNewPasswordEmail(Useer user, String newPass); + void sendNewPasswordEmail(User user, String newPass); } \ No newline at end of file diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java index d3624f5..fb90ff1 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserDetailsServiceImpl.java @@ -1,12 +1,12 @@ package br.com.selecaojava.services; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; import br.com.selecaojava.repositories.UserRepository; import br.com.selecaojava.security.UserSS; @@ -17,7 +17,7 @@ public class UserDetailsServiceImpl implements UserDetailsService{ @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { - Useer user = repo.findByEmail(email); //Search email database + User user = repo.findByEmail(email); //Search email database if(user == null) { //If imail does not exist throw exception throw new UsernameNotFoundException("Email não existe: "+email); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java index 2797b90..2eb91bb 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/UserService.java @@ -1,7 +1,7 @@ package br.com.selecaojava.services; -import java.util.List; +import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; @@ -13,7 +13,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import br.com.selecaojava.domain.Useer; +import br.com.selecaojava.domain.User; import br.com.selecaojava.dto.NomeDTO; import br.com.selecaojava.dto.PasswordDTO; import br.com.selecaojava.dto.UserDTO; @@ -33,41 +33,41 @@ public class UserService { @Autowired private UserRepository repo; - public Useer find(Integer id) throws ObjectNotFoundException { + public User find(Integer id) throws ObjectNotFoundException { UserSS user = UserServiceService.authenticated(); if (user==null || !user.hasRole(Perfil.ADMIN) && !id.equals(user.getId())) { throw new AuthorizationException("Acesso negado"); } - Optional obj = repo.findById(id); + Optional obj = repo.findById(id); return obj.orElseThrow(() -> new ObjectNotFoundException( - "Objeto não encontrado! Id: " + id + ", Tipo: " + Useer.class.getName())); + "Objeto não encontrado! Id: " + id + ", Tipo: " + User.class.getName())); } @Transactional - public Useer insert(Useer obj) { + public User insert(User obj) { obj.setId(null); return repo.save(obj); } - public Useer update(Useer obj) throws ObjectNotFoundException { - Useer newObj = find(obj.getId()); + public User update(User obj) throws ObjectNotFoundException { + User newObj = find(obj.getId()); updateData(newObj,obj); return repo.save(obj); } - public Useer update(PasswordDTO obj) throws ObjectNotFoundException { - Useer newObj = find(obj.getId()); + public User update(PasswordDTO obj) throws ObjectNotFoundException { + User newObj = find(obj.getId()); updatePassword(newObj,obj); return repo.save(newObj); } - public Useer update(NomeDTO obj) throws ObjectNotFoundException { - Useer newObj = find(obj.getId()); + public User update(NomeDTO obj) throws ObjectNotFoundException { + User newObj = find(obj.getId()); updateNome(newObj,obj); return repo.save(newObj); } - private void updateNome(Useer newObj, NomeDTO obj) { + private void updateNome(User newObj, NomeDTO obj) { newObj.setId(obj.getId()); newObj.setNome(obj.getNome()); } @@ -80,7 +80,7 @@ public PasswordDTO passwordDTO(PasswordDTO objDto) { return new PasswordDTO(objDto.getId(), pe.encode(objDto.getSenha())); } - private void updatePassword(Useer newObj,PasswordDTO obj) { + private void updatePassword(User newObj,PasswordDTO obj) { newObj.setId(obj.getId()); newObj.setSenha(obj.getSenha()); } @@ -95,33 +95,33 @@ public void delete(Integer id) throws ObjectNotFoundException { } } - public List findAll() { + public List findAll() { return repo.findAll(); } - public Page findPage(Integer page, Integer linesPerPage, String orderBy, String direction){ + public Page findPage(Integer page, Integer linesPerPage, String orderBy, String direction){ PageRequest pageRequest = PageRequest.of(page, linesPerPage , Direction.valueOf(direction), orderBy); return repo.findAll(pageRequest); } - public Useer fromDTO(UserDTO objDto) { - return new Useer(objDto.getId(),objDto.getNome(), objDto.getEmail(), pe.encode(objDto.getSenha())); + public User fromDTO(UserDTO objDto) { + return new User(objDto.getId(),objDto.getNome(), objDto.getEmail(), pe.encode(objDto.getSenha())); } - private void updateData(Useer newObj,Useer obj) { + private void updateData(User newObj,User obj) { newObj.setNome(obj.getNome()); } - public Useer findByEmail(String email){ + public User findByEmail(String email){ UserSS user = UserServiceService.authenticated(); if (user == null || !user.hasRole(Perfil.ADMIN) && !email.equals(user.getUsername())) { throw new AuthorizationException("Acesso negado"); } - Useer obj = repo.findByEmail(email); + User obj = repo.findByEmail(email); if (obj == null) { throw new ObjectNotFoundException( - "Objeto não encontrado! Id: " + user.getId() + ", Tipo: " + Useer.class.getName()); + "Objeto não encontrado! Id: " + user.getId() + ", Tipo: " + User.class.getName()); } return obj; } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java index 145b15a..a32fcec 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java @@ -1,7 +1,8 @@ package br.com.selecaojava.services; -import java.io.IOException; +import java.io.IOException; import java.io.InputStream; +import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; @@ -10,8 +11,8 @@ import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; - -import br.com.selecaojava.domain.Vendas; +import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.domain.User; import br.com.selecaojava.dto.VendasDTO; import br.com.selecaojava.repositories.VendasRepository; @@ -21,16 +22,19 @@ public class VendasServices { @Autowired private VendasRepository vendasRepository; - public void insert(List vendas) { - //obj.setId(null); - vendasRepository.saveAll(vendas); + public void insert(List vendas) { while (vendas.remove(null)) { - System.out.println("remove null"); } + vendasRepository.saveAll(vendas); } // private static final CsvMapper mapper = new CsvMapper(); - public List findAll(String sigla) { + public List findAll(String sigla) { return vendasRepository.findByregiaoSigla(sigla); } + + public Sales find(Integer id) { + Sales imageModel = vendasRepository.findById(id).orElse(null); + return imageModel; + } } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/SalesNotFoundException.java similarity index 72% rename from api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java rename to api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/SalesNotFoundException.java index 38f96d2..09b954a 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/PropertyNotFoundException.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/exceptions/SalesNotFoundException.java @@ -2,14 +2,14 @@ import org.springframework.http.HttpStatus; -public class PropertyNotFoundException extends Exception{ +public class SalesNotFoundException extends Exception{ /** * */ private static final long serialVersionUID = 1L; private HttpStatus httpStatus; - public PropertyNotFoundException (String mensagem, HttpStatus httpStatus){ + public SalesNotFoundException (String mensagem, HttpStatus httpStatus){ super (mensagem); this.httpStatus = httpStatus; } From 6b1f2077560003ed6ef1c5cbb5d10ca6fa392274 Mon Sep 17 00:00:00 2001 From: StewenAscari Date: Sun, 24 May 2020 23:43:24 -0300 Subject: [PATCH 4/5] =?UTF-8?q?ajuste=20na=20aplica=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../selecaojava/config/SecurityConfig.java | 3 +- .../com/selecaojava/domain/PriceHistoric.java | 75 ++++++++ .../java/br/com/selecaojava/domain/Sales.java | 39 ++-- .../br/com/selecaojava/dto/ModelCSVDTO.java | 134 +++++++++++++ .../com/selecaojava/dto/PriceHistoricDTO.java | 60 ++++++ .../dto/{VendasDTO.java => SalesDTO.java} | 70 +++---- .../repositories/PriceHistoricRepository.java | 11 ++ ...asRepository.java => SalesRepository.java} | 4 +- .../resources/PriceHistoricResource.java | 70 +++++++ .../selecaojava/resources/SalesResource.java | 182 ++++++++++++++++++ .../selecaojava/resources/VendasResource.java | 128 ------------ .../services/PriceHistoricService.java | 73 +++++++ .../selecaojava/services/SalesServices.java | 93 +++++++++ .../selecaojava/services/VendasServices.java | 40 ---- 14 files changed, 755 insertions(+), 227 deletions(-) create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/domain/PriceHistoric.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/ModelCSVDTO.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/dto/PriceHistoricDTO.java rename api-selecaojava/src/main/java/br/com/selecaojava/dto/{VendasDTO.java => SalesDTO.java} (68%) create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/repositories/PriceHistoricRepository.java rename api-selecaojava/src/main/java/br/com/selecaojava/repositories/{VendasRepository.java => SalesRepository.java} (84%) create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/PriceHistoricResource.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/SalesResource.java delete mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/PriceHistoricService.java create mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/SalesServices.java delete mode 100644 api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java b/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java index 14426f4..baf5633 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/config/SecurityConfig.java @@ -60,7 +60,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter{ private static final String[] PUBLIC_MATCHERS_POST = { //Endpoint array that a non-logged in user can only add data to "/user/**", "/auth/forgot/**", - "/vendas/**" + "/vendas/**", + "/priceHistoric/**" }; @Override protected void configure(HttpSecurity http) throws Exception{ diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/PriceHistoric.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/PriceHistoric.java new file mode 100644 index 0000000..1d8a334 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/PriceHistoric.java @@ -0,0 +1,75 @@ +package br.com.selecaojava.domain; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@Entity +public class PriceHistoric implements Serializable{ + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Integer id; + + private String valor; + + private String revenda; + + public PriceHistoric() { + + } + + public PriceHistoric(Integer id, String revenda, String valor) { + this.id = id; + this.revenda = revenda; + this.valor = valor; + } + + public PriceHistoric(String revenda, String valor) { + this.revenda = revenda; + this.valor = valor; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + + public String getValor() { + return valor; + } + + public void setValor(String valor) { + this.valor = valor; + } + + public String getRevenda() { + return revenda; + } + + public void setRevenda(String revenda) { + this.revenda = revenda; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java index b081c84..20b43f5 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/domain/Sales.java @@ -1,6 +1,8 @@ package br.com.selecaojava.domain; import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; import java.util.Set; import javax.persistence.Column; @@ -12,6 +14,7 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; import javax.persistence.OrderBy; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -26,37 +29,26 @@ public class Sales implements Serializable{ private Integer id; @Column(columnDefinition = "VARCHAR(1000)") - @CsvBindByPosition(position = 0) private String regiaoSigla; - @CsvBindByPosition(position = 1) private String estadoSigla; - @CsvBindByPosition(position = 2) private String municipio; - @CsvBindByPosition(position = 3) private String revenda; - @CsvBindByPosition(position = 4) private String cnpjdaRevenda; - @CsvBindByPosition(position = 5) private String produto; - @CsvBindByPosition(position = 6) private String datadaColeta; - @CsvBindByPosition(position = 7) private String valordeVenda; - @CsvBindByPosition(position = 8) private String valordeCompra; - @CsvBindByPosition(position = 9) private String unidadedeMedida; - @CsvBindByPosition(position = 10) private String bandeira; @ManyToOne(fetch = FetchType.EAGER) @@ -65,9 +57,9 @@ public class Sales implements Serializable{ public Sales() { } - public Sales(Integer id, String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, + public Sales(String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, String valorVenda, String valorCompra, String unidadeMedida, String bandeira, User user) { - this.id = id; + this.regiaoSigla = regiaoSigla; this.estadoSigla = stadoSigla; this.municipio = municipio; @@ -82,6 +74,22 @@ public Sales(Integer id, String regiaoSigla, String stadoSigla, String municipio this.user = user; } + public Sales(Integer id, String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, + String valorVenda, String valorCompra, String unidadeMedida, String bandeira) { + this.id = id; + this.regiaoSigla = regiaoSigla; + this.estadoSigla = stadoSigla; + this.municipio = municipio; + this.revenda = revenda; + this.cnpjdaRevenda = revendaCNPJ; + this.produto = produto; + this.datadaColeta = dataColeta; + this.valordeVenda = valorVenda; + this.valordeCompra = valorCompra; + this.unidadedeMedida = unidadeMedida; + this.bandeira = bandeira; + this.user = user; + } public Integer getId() { @@ -170,9 +178,4 @@ public int hashCode() { result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } - - @Override - public String toString(){ - return regiaoSigla+estadoSigla+municipio+revenda+cnpjdaRevenda+produto+datadaColeta+valordeVenda+valordeCompra+unidadedeMedida+bandeira; - } } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/ModelCSVDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/ModelCSVDTO.java new file mode 100644 index 0000000..6cec8fe --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/ModelCSVDTO.java @@ -0,0 +1,134 @@ +package br.com.selecaojava.dto; + +import javax.persistence.Column; + +import com.opencsv.bean.CsvBindByName; +import com.opencsv.bean.CsvBindByPosition; + +import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.domain.User; + +public class ModelCSVDTO { + + @Column(columnDefinition = "VARCHAR(1000)") + @CsvBindByPosition(position = 0) + private String regiaoSigla; + + @CsvBindByPosition(position = 1) + private String estadoSigla; + + @CsvBindByPosition(position = 2) + private String municipio; + + @CsvBindByPosition(position = 3) + private String revenda; + + @CsvBindByPosition(position = 4) + private String cnpjdaRevenda; + + @CsvBindByPosition(position = 5) + private String produto; + + @CsvBindByPosition(position = 6) + private String datadaColeta; + + @CsvBindByPosition(position = 7) + private String valordeVenda; + + @CsvBindByPosition(position = 8) + private String valordeCompra; + + @CsvBindByPosition(position = 9) + private String unidadedeMedida; + + @CsvBindByPosition(position = 10) + private String bandeira; + + public ModelCSVDTO() { + + } + public ModelCSVDTO(String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, + String valorVenda, String valorCompra, String unidadeMedida, String bandeira, User user) { + + this.regiaoSigla = regiaoSigla; + this.estadoSigla = stadoSigla; + this.municipio = municipio; + this.revenda = revenda; + this.cnpjdaRevenda = revendaCNPJ; + this.produto = produto; + this.datadaColeta = dataColeta; + this.valordeVenda = valorVenda; + this.valordeCompra = valorCompra; + this.unidadedeMedida = unidadeMedida; + this.bandeira = bandeira; + + } + public String getRegiaoSigla() { + return regiaoSigla; + } + public void setRegiaoSigla(String regiaoSigla) { + this.regiaoSigla = regiaoSigla; + } + public String getEstadoSigla() { + return estadoSigla; + } + public void setEstadoSigla(String estadoSigla) { + this.estadoSigla = estadoSigla; + } + public String getMunicipio() { + return municipio; + } + public void setMunicipio(String municipio) { + this.municipio = municipio; + } + public String getRevenda() { + return revenda; + } + public void setRevenda(String revenda) { + this.revenda = revenda; + } + public String getCnpjdaRevenda() { + return cnpjdaRevenda; + } + public void setCnpjdaRevenda(String cnpjdaRevenda) { + this.cnpjdaRevenda = cnpjdaRevenda; + } + public String getProduto() { + return produto; + } + public void setProduto(String produto) { + this.produto = produto; + } + public String getDatadaColeta() { + return datadaColeta; + } + public void setDatadaColeta(String datadaColeta) { + this.datadaColeta = datadaColeta; + } + public String getValordeVenda() { + return valordeVenda; + } + public void setValordeVenda(String valordeVenda) { + this.valordeVenda = valordeVenda; + } + public String getValordeCompra() { + return valordeCompra; + } + public void setValordeCompra(String valordeCompra) { + this.valordeCompra = valordeCompra; + } + public String getUnidadedeMedida() { + return unidadedeMedida; + } + public void setUnidadedeMedida(String unidadedeMedida) { + this.unidadedeMedida = unidadedeMedida; + } + public String getBandeira() { + return bandeira; + } + public void setBandeira(String bandeira) { + this.bandeira = bandeira; + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/PriceHistoricDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/PriceHistoricDTO.java new file mode 100644 index 0000000..b4e5408 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/PriceHistoricDTO.java @@ -0,0 +1,60 @@ +package br.com.selecaojava.dto; + +import java.io.Serializable; + +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import br.com.selecaojava.domain.PriceHistoric; + +public class PriceHistoricDTO implements Serializable{ + private static final long serialVersionUID = 1L; + + private Integer id; + private String valor; + private String revenda; + + public PriceHistoricDTO() { + + } + + + public PriceHistoricDTO(PriceHistoric priceHistoric) { + this.valor = valor; + } + + + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + public String getValue() { + return valor; + } + + + public void setValue(String value) { + this.valor = value; + } + + + public String getRevenda() { + return revenda; + } + + + public void setRevenda(String revenda) { + this.revenda = revenda; + } + + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java b/api-selecaojava/src/main/java/br/com/selecaojava/dto/SalesDTO.java similarity index 68% rename from api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java rename to api-selecaojava/src/main/java/br/com/selecaojava/dto/SalesDTO.java index d633761..d0728a2 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/dto/VendasDTO.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/dto/SalesDTO.java @@ -1,65 +1,67 @@ package br.com.selecaojava.dto; import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; -import com.opencsv.bean.CsvBindByName; import com.opencsv.bean.CsvBindByPosition; import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.domain.User; -public class VendasDTO { - - @CsvBindByName(column = "Região - Sigla") +public class SalesDTO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Integer id; @Column(columnDefinition = "VARCHAR(1000)") private String regiaoSigla; - @CsvBindByName(column = "Estado - Sigla") private String estadoSigla; - @CsvBindByName(column = "Município") private String municipio; - @CsvBindByName(column = "Revenda") private String revenda; - @CsvBindByName(column = "CNPJ da Revenda") private String cnpjdaRevenda; - @CsvBindByName(column = "Produto") private String produto; - @CsvBindByName(column = "Data da Coleta") private String datadaColeta; - - @CsvBindByName(column = "Valor de Venda") + private String valordeVenda; - @CsvBindByName(column = "Valor de Compra") private String valordeCompra; - @CsvBindByName(column = "Unidade de Medida") private String unidadedeMedida; - @CsvBindByName(column = "Bandeira") private String bandeira; - private Integer id; - - public VendasDTO() { + public SalesDTO(Sales obj) { + + } + public SalesDTO(String regiaoSigla, String stadoSigla, String municipio, String revenda, String revendaCNPJ, String produto, String dataColeta, + String valorVenda, String valorCompra, String unidadeMedida, String bandeira) { + this.regiaoSigla = regiaoSigla; + this.estadoSigla = stadoSigla; + this.municipio = municipio; + this.revenda = revenda; + this.cnpjdaRevenda = revendaCNPJ; + this.produto = produto; + this.datadaColeta = dataColeta; + this.valordeVenda = valorVenda; + this.valordeCompra = valorCompra; + this.unidadedeMedida = unidadeMedida; + this.bandeira = bandeira; + } - public VendasDTO(Sales vendas) { - regiaoSigla = vendas.getRegiaoSigla(); - estadoSigla = vendas.getEstadoSigla(); - municipio = vendas.getMunicipio(); - revenda = vendas.getRevenda(); - cnpjdaRevenda = vendas.getCnpjdaRevenda(); - produto = vendas.getProduto(); - datadaColeta = vendas.getDatadaColeta(); - valordeVenda = vendas.getValordeVenda(); - valordeCompra = vendas.getValordeCompra(); - unidadedeMedida = vendas.getUnidadedeMedida(); - bandeira = vendas.getBandeira(); + + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; } public String getRegiaoSigla() { return regiaoSigla; @@ -127,12 +129,4 @@ public String getBandeira() { public void setBandeira(String bandeira) { this.bandeira = bandeira; } - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } - - } diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/PriceHistoricRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/PriceHistoricRepository.java new file mode 100644 index 0000000..6d0f7cc --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/PriceHistoricRepository.java @@ -0,0 +1,11 @@ +package br.com.selecaojava.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import br.com.selecaojava.domain.PriceHistoric; + +@Repository +public interface PriceHistoricRepository extends JpaRepository { + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/SalesRepository.java similarity index 84% rename from api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java rename to api-selecaojava/src/main/java/br/com/selecaojava/repositories/SalesRepository.java index fbed5cc..1d411cb 100644 --- a/api-selecaojava/src/main/java/br/com/selecaojava/repositories/VendasRepository.java +++ b/api-selecaojava/src/main/java/br/com/selecaojava/repositories/SalesRepository.java @@ -1,6 +1,6 @@ package br.com.selecaojava.repositories; import br.com.selecaojava.domain.Sales; -import br.com.selecaojava.dto.VendasDTO; +import br.com.selecaojava.dto.ModelCSVDTO; import java.util.List; @@ -18,7 +18,7 @@ import com.opencsv.bean.CsvBindByPosition; @Repository -public interface VendasRepository extends JpaRepository { +public interface SalesRepository extends JpaRepository { List findByregiaoSigla(String regiaoSigla); diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/PriceHistoricResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/PriceHistoricResource.java new file mode 100644 index 0000000..f00dcf9 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/PriceHistoricResource.java @@ -0,0 +1,70 @@ +package br.com.selecaojava.resources; + +import java.util.List; +import java.util.stream.Collectors; + +import javax.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.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import br.com.selecaojava.domain.PriceHistoric; +import br.com.selecaojava.domain.User; +import br.com.selecaojava.dto.PriceHistoricDTO; +import br.com.selecaojava.dto.UserDTO; +import br.com.selecaojava.services.PriceHistoricService; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import javassist.tools.rmi.ObjectNotFoundException; + +@RestController +@RequestMapping(value="/priceHistoric") +public class PriceHistoricResource { + + @Autowired + private PriceHistoricService priceHistoricService; + + @ApiOperation(value = "Buscar um historico de preço por id", response = PriceHistoric.class, notes = "Essa operação Busca um registro do histórico de preco.") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Retorna um ResponseEntity com o objeto", response = PriceHistoric.class), + @ApiResponse(code = 404, message = "Caso tenhamos algum erro vamos retornar uma mensagem e um código http") + + }) + @RequestMapping(value = "/consulta/{id}", method = RequestMethod.GET) + public ResponseEntity listar(@PathVariable Integer id) { + PriceHistoric obj = priceHistoricService.find(id); + + if (obj == null) { + return new ResponseEntity("Venda não encotrada!", HttpStatus.NOT_FOUND); + } + + return ResponseEntity.ok(obj); + } + + @RequestMapping(value="/{id}",method=RequestMethod.PUT) //update + public ResponseEntity update(@Valid @RequestBody PriceHistoricDTO objDto,@PathVariable Integer id) throws ObjectNotFoundException{ + PriceHistoric obj = priceHistoricService.fromDTO(objDto); + obj = priceHistoricService.update(obj); + return ResponseEntity.noContent().build(); + } + + @RequestMapping(value="/{id}", method = RequestMethod.DELETE) //Delete ADM + public ResponseEntity delete(@PathVariable Integer id) throws ObjectNotFoundException { + priceHistoricService.delete(id); + return ResponseEntity.noContent().build(); + } + + @RequestMapping(method = RequestMethod.GET) //list all + public ResponseEntity> find() { + List list = priceHistoricService.findAll(); + List listDTO = list.stream().map(obj -> new PriceHistoricDTO(obj)).collect(Collectors.toList()); + return ResponseEntity.ok().body(listDTO); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/SalesResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/SalesResource.java new file mode 100644 index 0000000..50b0ea5 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/resources/SalesResource.java @@ -0,0 +1,182 @@ +package br.com.selecaojava.resources; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import javax.validation.Valid; + +import org.hibernate.hql.spi.PositionalParameterInformation; +import org.hibernate.loader.custom.sql.PositionalParamBinder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import com.opencsv.CSVParser; +import com.opencsv.bean.ColumnPositionMappingStrategy; +import com.opencsv.bean.CsvBindByName; +import com.opencsv.bean.CsvToBean; +import com.opencsv.bean.CsvToBeanBuilder; + +import br.com.selecaojava.domain.PriceHistoric; +import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.domain.User; +import br.com.selecaojava.dto.ModelCSVDTO; +import br.com.selecaojava.dto.PriceHistoricDTO; +import br.com.selecaojava.dto.SalesDTO; +import br.com.selecaojava.repositories.SalesRepository; +import br.com.selecaojava.services.UserService; +import br.com.selecaojava.services.PriceHistoricService; +import br.com.selecaojava.services.SalesServices; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import javassist.tools.rmi.ObjectNotFoundException; + +@RestController +@RequestMapping(value="/user/{id}/sales") +public class SalesResource { + + @Autowired + private SalesServices vendasServices; + @Autowired + private UserService userService; + private PriceHistoricService priceHistoricService; + + /* + * Operação PUT + */ + @ApiOperation(value = "importar arquivo csv", response = Sales.class, + notes = "Essa operação Edita um novo registro propriedades") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Retorna um ResponseEntity com o objeto e o status", response = Sales.class), + @ApiResponse(code = 406, message = "Caso o arquivo não sejam aceita retorna um erro") + + }) + @RequestMapping(value="/upload-csv-file", method = RequestMethod.PUT) + public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model model, + @Valid @RequestPart @RequestParam("id") @PathVariable Integer id) { + User user = userService.find(id); + + // validate file + if (file.isEmpty()) { + model.addAttribute("message", "Please select a CSV file to upload."); + model.addAttribute("status", false); + } else { + + // parse CSV file to create a list of `Vendas` objects + try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_16))) { + + // create csv bean reader + CsvToBean csvToBean = new CsvToBeanBuilder(reader) + .withType(ModelCSVDTO.class) + .withSkipLines(1) + .withSeparator(' ') + .withSeparator('\t') + .build(); + // convert `CsvToBean` object to list of users + List sales = csvToBean.parse(); + List salesDB = new ArrayList(); + + for (ModelCSVDTO s: sales) { + if(s.getRegiaoSigla() != null && s.getEstadoSigla()!= null && + s.getMunicipio()!= null && + s.getRevenda()!= null && s.getCnpjdaRevenda()!= null && + s.getProduto()!= null && s.getDatadaColeta()!= null && + s.getValordeVenda()!= null && s.getValordeCompra()!= null && + s.getUnidadedeMedida()!= null && s.getBandeira()!= null) { + PriceHistoric priceHistoric = new PriceHistoric(s.getRevenda(), s.getValordeVenda()); + Sales r = new Sales(s.getRegiaoSigla().toLowerCase(), s.getEstadoSigla().toLowerCase(), + s.getMunicipio().toLowerCase(), s.getRevenda().toLowerCase(), s.getCnpjdaRevenda(), + s.getProduto().toLowerCase(), s.getDatadaColeta(), s.getValordeVenda() ,s.getValordeCompra(), + s.getUnidadedeMedida(), s.getBandeira(), user); + salesDB.add(r); + + } + + + } + vendasServices.insert(salesDB); + priceHistoricService.insertAll(salesDB); + + // TODO: save users in DB? +// vendasServices.insert(sales); +// user.setSales(sales);; + // save users list on model + model.addAttribute("sales", sales); + model.addAttribute("status", true); + +// priceHistoricService.insert(p); + userService.update(user); + + } catch (Exception ex) { + model.addAttribute("message", "An error occurred while processing the CSV file."); + model.addAttribute("status", false); + } + } + + + return "file-upload-status"; + } + + @RequestMapping(value = "/find/{sigla}", method = RequestMethod.GET) //lists all + public List sigla(@PathVariable String sigla) { + List obj = vendasServices.findBysigla(sigla); + if (obj == null) { + return (List) new ResponseEntity("Venda não encotrada!", HttpStatus.NOT_FOUND); + } + return obj; + } + @ApiOperation(value = "Buscar uma venda por id", response = Sales.class, notes = "Essa operação Busca um registro com as informações de uma venda.") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Retorna um ResponseEntity com o objeto", response = Sales.class), + @ApiResponse(code = 404, message = "Caso tenhamos algum erro vamos retornar uma mensagem e um código http") + + }) + @RequestMapping(value = "/consulta/{id}", method = RequestMethod.GET) + public ResponseEntity listar(@PathVariable Integer id) { + Sales obj = vendasServices.find(id); + + if (obj == null) { + return new ResponseEntity("Venda não encotrada!", HttpStatus.NOT_FOUND); + } + + return ResponseEntity.ok(obj); + } + + @RequestMapping(value="/{id}",method=RequestMethod.PUT) //update + public ResponseEntity update(@Valid @RequestBody SalesDTO objDto,@PathVariable Integer id) throws ObjectNotFoundException{ + Sales obj = vendasServices.fromDTO(objDto); + obj = vendasServices.update(obj); + return ResponseEntity.noContent().build(); + } + + @RequestMapping(value="/{id}", method = RequestMethod.DELETE) //Delete + public ResponseEntity delete(@PathVariable Integer id) throws ObjectNotFoundException { + vendasServices.delete(id); + return ResponseEntity.noContent().build(); + } + + @RequestMapping(method = RequestMethod.GET) //list all + public ResponseEntity> find() { + List list = vendasServices.findAll(); + List listDTO = list.stream().map(obj -> new SalesDTO(obj)).collect(Collectors.toList()); + return ResponseEntity.ok().body(listDTO); + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java b/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java deleted file mode 100644 index 66f3c2e..0000000 --- a/api-selecaojava/src/main/java/br/com/selecaojava/resources/VendasResource.java +++ /dev/null @@ -1,128 +0,0 @@ -package br.com.selecaojava.resources; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import javax.validation.Valid; - -import org.hibernate.hql.spi.PositionalParameterInformation; -import org.hibernate.loader.custom.sql.PositionalParamBinder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import com.opencsv.bean.ColumnPositionMappingStrategy; -import com.opencsv.bean.CsvBindByName; -import com.opencsv.bean.CsvToBean; -import com.opencsv.bean.CsvToBeanBuilder; - -import br.com.selecaojava.domain.Sales; -import br.com.selecaojava.domain.User; -import br.com.selecaojava.dto.VendasDTO; -import br.com.selecaojava.repositories.VendasRepository; -import br.com.selecaojava.services.UserService; -import br.com.selecaojava.services.VendasServices; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -@RestController -@RequestMapping(value="/user/{id}/sales") -public class VendasResource { - - @Autowired - private VendasServices vendasServices; - @Autowired - private UserService userService; - - /* - * Operação PUT - */ - @ApiOperation(value = "Insere s", response = Sales.class, - notes = "Essa operação Edita um novo registro propriedades") - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Retorna um ResponseEntity com o objeto e o status", response = Sales.class), - @ApiResponse(code = 406, message = "Caso as imagens não sejam aceitas retorna um erro") - - }) - @RequestMapping(value="/upload-csv-file", method = RequestMethod.PUT) - public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model model, - @Valid @RequestPart @RequestParam("id") @PathVariable Integer id) { - User user = userService.find(id); - - // validate file - if (file.isEmpty()) { - model.addAttribute("message", "Please select a CSV file to upload."); - model.addAttribute("status", false); - } else { - - // parse CSV file to create a list of `Vendas` objects - try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) { - - // create csv bean reader - CsvToBean csvToBean = new CsvToBeanBuilder(reader) - .withType(Sales.class) - .withSkipLines(1) -// .withSeparator(',') - .withSeparator('\t') - .withIgnoreLeadingWhiteSpace(true) - .build(); - - // convert `CsvToBean` object to list of users - List sales = csvToBean.parse(); - // TODO: save users in DB? - vendasServices.insert(sales); - user.setSales(sales);; - // save users list on model - model.addAttribute("sales", sales); - model.addAttribute("status", true); - - userService.update(user); - - } catch (Exception ex) { - model.addAttribute("message", "An error occurred while processing the CSV file."); - model.addAttribute("status", false); - } - } - - - return "file-upload-status"; - } - - @RequestMapping(value = "/{sigla}", method = RequestMethod.GET) //lists all paged ADMs - public ResponseEntity> findPage(@PathVariable String sigla) { - List list = vendasServices.findAll(sigla); - List listDTO = list.stream().map(obj -> new VendasDTO(obj)).collect(Collectors.toList()); - return ResponseEntity.ok().body(listDTO); - } - - @ApiOperation(value = "Buscar uma Imagem por ID", response = Sales.class, notes = "Essa operação Busca um novo registro com as informações de uma Propriedade.") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Retorna um ResponseEntity com o objeto", response = Sales.class), - @ApiResponse(code = 404, message = "Caso tenhamos algum erro vamos retornar uma mensagem e um código http") - - }) - @RequestMapping(value = "/consulta/{id}", method = RequestMethod.GET) - public ResponseEntity listar(@PathVariable Integer id) { - Sales obj = vendasServices.find(id); - - if (obj == null) { - return new ResponseEntity("Imagem não encotrada!", HttpStatus.NOT_FOUND); - } - - return ResponseEntity.ok(obj); - } -} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/PriceHistoricService.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/PriceHistoricService.java new file mode 100644 index 0000000..4162426 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/PriceHistoricService.java @@ -0,0 +1,73 @@ +package br.com.selecaojava.services; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import br.com.selecaojava.domain.PriceHistoric; +import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.dto.PriceHistoricDTO; +import br.com.selecaojava.repositories.PriceHistoricRepository; +import br.com.selecaojava.servives.exceptions.ObjectNotFoundException; + +@Service +public class PriceHistoricService { + + private PriceHistoricRepository priceHistoricRepository; + + public PriceHistoric find(Integer id) { + PriceHistoric imageModel = priceHistoricRepository.findById(id).orElse(null); + return imageModel; + } + + public void insert(List historic) { + priceHistoricRepository.saveAll(historic); + } + + public PriceHistoric fromDTO(PriceHistoricDTO objDto) { + return new PriceHistoric(objDto.getRevenda(), objDto.getValue()); + } + + public PriceHistoric update(PriceHistoric obj) throws ObjectNotFoundException { + PriceHistoric newObj = find(obj.getId()); + updateData(newObj,obj); + return priceHistoricRepository.save(obj); + } + + private void updateData(PriceHistoric newObj,PriceHistoric obj) { + newObj.setRevenda(obj.getRevenda()); + newObj.setValor(obj.getValor()); + } + + public void delete(Integer id) throws ObjectNotFoundException { + find(id); + try { + priceHistoricRepository.deleteById(id); + } + catch (DataIntegrityViolationException e) { + throw new DataIntegrityViolationException("Não é possivevel excluir um User"); + } + } + + public List findAll() { + return priceHistoricRepository.findAll(); + } + + public void insertAll(List salesDB) { + Listhistoric = new ArrayList(); + for (Sales s: salesDB) { + PriceHistoric p = new PriceHistoric(s.getRevenda(), s.getValordeVenda()); + historic.add(p); + } + this.insert(historic); + + } + + +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/SalesServices.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/SalesServices.java new file mode 100644 index 0000000..4be3c72 --- /dev/null +++ b/api-selecaojava/src/main/java/br/com/selecaojava/services/SalesServices.java @@ -0,0 +1,93 @@ +package br.com.selecaojava.services; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.dataformat.csv.CsvMapper; +import com.fasterxml.jackson.dataformat.csv.CsvSchema; + +import br.com.selecaojava.domain.PriceHistoric; +import br.com.selecaojava.domain.Sales; +import br.com.selecaojava.domain.User; +import br.com.selecaojava.dto.PriceHistoricDTO; +import br.com.selecaojava.dto.SalesDTO; +import br.com.selecaojava.dto.ModelCSVDTO; +import br.com.selecaojava.repositories.PriceHistoricRepository; +import br.com.selecaojava.repositories.SalesRepository; +import br.com.selecaojava.servives.exceptions.ObjectNotFoundException; + +@Service +public class SalesServices { + + @Autowired + private SalesRepository vendasRepository; + private PriceHistoricService re; + + public void insert(List vendas) { + vendasRepository.saveAll(vendas); + List p = new ArrayList(); + for(Sales s: vendas) { + + PriceHistoric price = new PriceHistoric(s.getRevenda(), s.getValordeVenda()); + p.add(price); + } + re.insert(p); + + + } + public void delete(Integer id) throws ObjectNotFoundException { + find(id); + try { + vendasRepository.deleteById(id); + } + catch (DataIntegrityViolationException e) { + throw new DataIntegrityViolationException("Não é possivevel excluir um User"); + } + } + public List findAll() { + return vendasRepository.findAll(); + } + + public Sales fromDTO(SalesDTO objDto) { + return new Sales(objDto.getId(), objDto.getRegiaoSigla(),objDto.getEstadoSigla(), objDto.getMunicipio(), objDto.getRevenda(), objDto.getCnpjdaRevenda(), + objDto.getProduto(), objDto.getDatadaColeta(), objDto.getValordeVenda(), objDto.getValordeCompra(), objDto.getUnidadedeMedida(), + objDto.getBandeira()); + } + + public Sales update(Sales obj) throws ObjectNotFoundException { + Sales newObj = find(obj.getId()); + updateData(newObj,obj); + return vendasRepository.save(obj); + } + private void updateData(Sales newObj,Sales obj) { + newObj.setRegiaoSigla(obj.getRegiaoSigla()); + newObj.setEstadoSigla(obj.getEstadoSigla()); + newObj.setMunicipio(obj.getMunicipio()); + newObj.setRevenda(obj.getRevenda()); + newObj.setCnpjdaRevenda(obj.getCnpjdaRevenda()); + newObj.setProduto(obj.getProduto()); + newObj.setDatadaColeta(obj.getDatadaColeta()); + newObj.setValordeVenda(obj.getValordeVenda()); + newObj.setValordeCompra(obj.getValordeCompra()); + newObj.setUnidadedeMedida(obj.getUnidadedeMedida()); + newObj.setBandeira(obj.getBandeira()); + } +// private static final CsvMapper mapper = new CsvMapper(); + + public List findBysigla(String sigla) { + return vendasRepository.findByregiaoSigla(sigla); + } + + public Sales find(Integer id) { + Sales imageModel = vendasRepository.findById(id).orElse(null); + return imageModel; + } +} diff --git a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java b/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java deleted file mode 100644 index a32fcec..0000000 --- a/api-selecaojava/src/main/java/br/com/selecaojava/services/VendasServices.java +++ /dev/null @@ -1,40 +0,0 @@ -package br.com.selecaojava.services; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.dataformat.csv.CsvMapper; -import com.fasterxml.jackson.dataformat.csv.CsvSchema; -import br.com.selecaojava.domain.Sales; -import br.com.selecaojava.domain.User; -import br.com.selecaojava.dto.VendasDTO; -import br.com.selecaojava.repositories.VendasRepository; - -@Service -public class VendasServices { - - @Autowired - private VendasRepository vendasRepository; - - public void insert(List vendas) { - while (vendas.remove(null)) { - } - vendasRepository.saveAll(vendas); - } -// private static final CsvMapper mapper = new CsvMapper(); - - public List findAll(String sigla) { - return vendasRepository.findByregiaoSigla(sigla); - } - - public Sales find(Integer id) { - Sales imageModel = vendasRepository.findById(id).orElse(null); - return imageModel; - } -} From f87b0a2edd81de25e88e6e3b5d798b1aa67fae50 Mon Sep 17 00:00:00 2001 From: StewenAscari Date: Sun, 24 May 2020 23:56:24 -0300 Subject: [PATCH 5/5] adicionando o script do postman --- api-selecaojava/script do postman | 71 +++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 api-selecaojava/script do postman diff --git a/api-selecaojava/script do postman b/api-selecaojava/script do postman new file mode 100644 index 0000000..4051694 --- /dev/null +++ b/api-selecaojava/script do postman @@ -0,0 +1,71 @@ +-- fazer login -- + +curl --request POST \ + --url http://localhost:8080/login \ + --header 'content-type: application/json' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D \ + --data '{ + "email": "admin@gmail.com", + "senha": "admin" +}' + +-- import csv -- + +curl --request PUT \ + --url http://localhost:8080/user/1/sales/upload-csv-file \ + --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBnbWFpbC5jb20iLCJleHAiOjE1OTA0MTcyMTh9.iwoS-LpHujpSppgGLmKzrpCT1MgA1n_Tx9nOrw2eFxcJk9a5zct4IhWcMPBBIrM6LZ242M69s0dYXJo8X-8T6A' \ + --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ + --header 'content-typeype: application/json' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D \ + --form id=1 \ + --form file= + + +-- listar todos os dados do csv importado -- + +curl --request GET \ + --url http://localhost:8080/user/1/sales \ + --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBnbWFpbC5jb20iLCJleHAiOjE1OTA0MzQzMTd9.c5qhLZC6F-nzvI9JLrCqGjWT5PYFYWYrsokmIcw8iJ1qBrEkTodMq77v38Dns2nwPYfq5OukFf6y-g42fdKI2w' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D + +-- update de um dos dados do csv importado -- + +curl --request PUT \ + --url http://localhost:8080/user/1/sales/2 \ + --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBnbWFpbC5jb20iLCJleHAiOjE1OTA0MzQzMTd9.c5qhLZC6F-nzvI9JLrCqGjWT5PYFYWYrsokmIcw8iJ1qBrEkTodMq77v38Dns2nwPYfq5OukFf6y-g42fdKI2w' \ + --header 'content-type: application/json' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D \ + --data '{ + "id":"2", + "regiaoSigla": "pe", + "estadoSigla":"pe", + "municipio":"eee", + "revenda":"eee", + "cnpjdaRevenda":"eeeeeeeee", + "produto":"eeeeee", + "dataColeta":"eeeeeeee", + "valorVenda":"eeeeee", + "valorCompra":"eeeeeee", + "unidadeMedida":"eeee", + "bandeira":"eeee" +}' + +-- deletar um dos dados do csv importado -- + +curl --request DELETE \ + --url http://localhost:8080/user/1/sales/1 \ + --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBnbWFpbC5jb20iLCJleHAiOjE1OTA0MzQzMTd9.c5qhLZC6F-nzvI9JLrCqGjWT5PYFYWYrsokmIcw8iJ1qBrEkTodMq77v38Dns2nwPYfq5OukFf6y-g42fdKI2w' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D + +-- buscar por sigla do estado -- +curl --request GET \ + --url http://localhost:8080/user/1/sales/find/co \ + --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBnbWFpbC5jb20iLCJleHAiOjE1OTAzMzA0ODZ9.Ayqfj0Z-WQ7VXRshOOUTfq537OnU-HhZH7L8SuIfR6tLGQbg1h7lF3KRptTOdvhsdGQ7-_kkzfkAVH7SNSN3Fw' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D + +-- buscar por um dos dados do csv importado pelo id -- + +curl --request GET \ + --url http://localhost:8080/user/1/sales/consulta/1 \ + --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBnbWFpbC5jb20iLCJleHAiOjE1OTAzMzA0ODZ9.Ayqfj0Z-WQ7VXRshOOUTfq537OnU-HhZH7L8SuIfR6tLGQbg1h7lF3KRptTOdvhsdGQ7-_kkzfkAVH7SNSN3Fw' \ + --cookie JSESSIONID=7C281E49BC8E185E595B6A647727910D