├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── Procfile
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── nelioalves
│ │ └── cursomc
│ │ ├── CursomcApplication.java
│ │ ├── config
│ │ ├── DevConfig.java
│ │ ├── JacksonConfig.java
│ │ ├── S3Config.java
│ │ ├── SecurityConfig.java
│ │ └── TestConfig.java
│ │ ├── domain
│ │ ├── Categoria.java
│ │ ├── Cidade.java
│ │ ├── Cliente.java
│ │ ├── Endereco.java
│ │ ├── Estado.java
│ │ ├── ItemPedido.java
│ │ ├── ItemPedidoPK.java
│ │ ├── Pagamento.java
│ │ ├── PagamentoComBoleto.java
│ │ ├── PagamentoComCartao.java
│ │ ├── Pedido.java
│ │ ├── Produto.java
│ │ └── enums
│ │ │ ├── EstadoPagamento.java
│ │ │ ├── Perfil.java
│ │ │ └── TipoCliente.java
│ │ ├── dto
│ │ ├── CategoriaDTO.java
│ │ ├── CidadeDTO.java
│ │ ├── ClienteDTO.java
│ │ ├── ClienteNewDTO.java
│ │ ├── CredenciaisDTO.java
│ │ ├── EmailDTO.java
│ │ ├── EstadoDTO.java
│ │ └── ProdutoDTO.java
│ │ ├── filters
│ │ └── HeaderExposureFilter.java
│ │ ├── repositories
│ │ ├── CategoriaRepository.java
│ │ ├── CidadeRepository.java
│ │ ├── ClienteRepository.java
│ │ ├── EnderecoRepository.java
│ │ ├── EstadoRepository.java
│ │ ├── ItemPedidoRepository.java
│ │ ├── PagamentoRepository.java
│ │ ├── PedidoRepository.java
│ │ └── ProdutoRepository.java
│ │ ├── resources
│ │ ├── AuthResource.java
│ │ ├── CategoriaResource.java
│ │ ├── ClienteResource.java
│ │ ├── EstadoResource.java
│ │ ├── PedidoResource.java
│ │ ├── ProdutoResource.java
│ │ ├── exception
│ │ │ ├── FieldMessage.java
│ │ │ ├── ResourceExceptionHandler.java
│ │ │ ├── StandardError.java
│ │ │ └── ValidationError.java
│ │ └── utils
│ │ │ └── URL.java
│ │ ├── security
│ │ ├── JWTAuthenticationFilter.java
│ │ ├── JWTAuthorizationFilter.java
│ │ ├── JWTUtil.java
│ │ └── UserSS.java
│ │ └── services
│ │ ├── AbstractEmailService.java
│ │ ├── AuthService.java
│ │ ├── BoletoService.java
│ │ ├── CategoriaService.java
│ │ ├── CidadeService.java
│ │ ├── ClienteService.java
│ │ ├── DBService.java
│ │ ├── EmailService.java
│ │ ├── EstadoService.java
│ │ ├── ImageService.java
│ │ ├── MockEmailService.java
│ │ ├── PedidoService.java
│ │ ├── ProdutoService.java
│ │ ├── S3Service.java
│ │ ├── SmtpEmailService.java
│ │ ├── UserDetailsServiceImpl.java
│ │ ├── UserService.java
│ │ ├── exceptions
│ │ ├── AuthorizationException.java
│ │ ├── DataIntegrityException.java
│ │ ├── FileException.java
│ │ └── ObjectNotFoundException.java
│ │ └── validation
│ │ ├── ClienteInsert.java
│ │ ├── ClienteInsertValidator.java
│ │ ├── ClienteUpdate.java
│ │ ├── ClienteUpdateValidator.java
│ │ └── utils
│ │ └── BR.java
└── resources
│ ├── application-dev.properties
│ ├── application-prod.properties
│ ├── application-test.properties
│ └── application.properties
└── test
└── java
└── com
└── nelioalves
└── cursomc
└── CursomcApplicationTests.java
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 | .sts4-cache
12 |
13 | ### IntelliJ IDEA ###
14 | .idea
15 | *.iws
16 | *.iml
17 | *.ipr
18 |
19 | ### NetBeans ###
20 | nbproject/private/
21 | build/
22 | nbbuild/
23 | dist/
24 | nbdist/
25 | .nb-gradle/
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acenelio/springboot2-ionic-backend/d5419ee2857db1d672e92c887c3698d3899517c1/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
2 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | web: java -Dserver.port=$PORT -Dspring.profiles.active=prod $JAVA_OPTS -jar target/cursomc-0.0.1-SNAPSHOT.jar
2 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # http://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Migwn, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
204 | echo $MAVEN_PROJECTBASEDIR
205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
206 |
207 | # For Cygwin, switch paths to Windows format before running java
208 | if $cygwin; then
209 | [ -n "$M2_HOME" ] &&
210 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
211 | [ -n "$JAVA_HOME" ] &&
212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
213 | [ -n "$CLASSPATH" ] &&
214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
215 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
217 | fi
218 |
219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
220 |
221 | exec "$JAVACMD" \
222 | $MAVEN_OPTS \
223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
226 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM http://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven2 Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
40 |
41 | @REM set %HOME% to equivalent of $HOME
42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
43 |
44 | @REM Execute a user defined script before this one
45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
49 | :skipRcPre
50 |
51 | @setlocal
52 |
53 | set ERROR_CODE=0
54 |
55 | @REM To isolate internal variables from possible post scripts, we use another setlocal
56 | @setlocal
57 |
58 | @REM ==== START VALIDATION ====
59 | if not "%JAVA_HOME%" == "" goto OkJHome
60 |
61 | echo.
62 | echo Error: JAVA_HOME not found in your environment. >&2
63 | echo Please set the JAVA_HOME variable in your environment to match the >&2
64 | echo location of your Java installation. >&2
65 | echo.
66 | goto error
67 |
68 | :OkJHome
69 | if exist "%JAVA_HOME%\bin\java.exe" goto init
70 |
71 | echo.
72 | echo Error: JAVA_HOME is set to an invalid directory. >&2
73 | echo JAVA_HOME = "%JAVA_HOME%" >&2
74 | echo Please set the JAVA_HOME variable in your environment to match the >&2
75 | echo location of your Java installation. >&2
76 | echo.
77 | goto error
78 |
79 | @REM ==== END VALIDATION ====
80 |
81 | :init
82 |
83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
84 | @REM Fallback to current working directory if not found.
85 |
86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
88 |
89 | set EXEC_DIR=%CD%
90 | set WDIR=%EXEC_DIR%
91 | :findBaseDir
92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
93 | cd ..
94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
95 | set WDIR=%CD%
96 | goto findBaseDir
97 |
98 | :baseDirFound
99 | set MAVEN_PROJECTBASEDIR=%WDIR%
100 | cd "%EXEC_DIR%"
101 | goto endDetectBaseDir
102 |
103 | :baseDirNotFound
104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
105 | cd "%EXEC_DIR%"
106 |
107 | :endDetectBaseDir
108 |
109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
110 |
111 | @setlocal EnableExtensions EnableDelayedExpansion
112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
114 |
115 | :endReadAdditionalConfig
116 |
117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
118 |
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
123 | if ERRORLEVEL 1 goto error
124 | goto end
125 |
126 | :error
127 | set ERROR_CODE=1
128 |
129 | :end
130 | @endlocal & set ERROR_CODE=%ERROR_CODE%
131 |
132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
136 | :skipRcPost
137 |
138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
140 |
141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
142 |
143 | exit /B %ERROR_CODE%
144 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.nelioalves.cursomc
7 | cursomc
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | cursomc
12 | Curso Spring Boot Professor Nelio Alves
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.0.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-starter-data-jpa
42 |
43 |
44 |
45 | com.h2database
46 | h2
47 | runtime
48 |
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-devtools
53 |
54 |
55 |
56 | mysql
57 | mysql-connector-java
58 |
59 |
60 |
61 | org.springframework.boot
62 | spring-boot-starter-mail
63 |
64 |
65 |
66 | org.springframework.boot
67 | spring-boot-starter-security
68 |
69 |
70 |
71 | io.jsonwebtoken
72 | jjwt
73 | 0.7.0
74 |
75 |
76 |
77 | com.amazonaws
78 | aws-java-sdk
79 | LATEST
80 |
81 |
82 |
83 | commons-io
84 | commons-io
85 | LATEST
86 |
87 |
88 |
89 | org.imgscalr
90 | imgscalr-lib
91 | 4.2
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 | org.springframework.boot
100 | spring-boot-maven-plugin
101 |
102 |
103 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/CursomcApplication.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc;
2 |
3 | import org.springframework.boot.CommandLineRunner;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 |
7 | @SpringBootApplication
8 | public class CursomcApplication implements CommandLineRunner {
9 |
10 | public static void main(String[] args) {
11 | SpringApplication.run(CursomcApplication.class, args);
12 | }
13 |
14 | @Override
15 | public void run(String... args) throws Exception {
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/config/DevConfig.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.config;
2 |
3 | import java.text.ParseException;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.beans.factory.annotation.Value;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Configuration;
9 | import org.springframework.context.annotation.Profile;
10 |
11 | import com.nelioalves.cursomc.services.DBService;
12 | import com.nelioalves.cursomc.services.EmailService;
13 | import com.nelioalves.cursomc.services.SmtpEmailService;
14 |
15 | @Configuration
16 | @Profile("dev")
17 | public class DevConfig {
18 |
19 | @Autowired
20 | private DBService dbService;
21 |
22 | @Value("${spring.jpa.hibernate.ddl-auto}")
23 | private String strategy;
24 |
25 | @Bean
26 | public boolean instantiateDatabase() throws ParseException {
27 |
28 | if (!"create".equals(strategy)) {
29 | return false;
30 | }
31 |
32 | dbService.instantiateTestDatabase();
33 | return true;
34 | }
35 |
36 | @Bean
37 | public EmailService emailService() {
38 | return new SmtpEmailService();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/config/JacksonConfig.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
6 |
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 | import com.nelioalves.cursomc.domain.PagamentoComBoleto;
9 | import com.nelioalves.cursomc.domain.PagamentoComCartao;
10 |
11 | @Configuration
12 | public class JacksonConfig {
13 | // https://stackoverflow.com/questions/41452598/overcome-can-not-construct-instance-ofinterfaceclass-without-hinting-the-pare
14 | @Bean
15 | public Jackson2ObjectMapperBuilder objectMapperBuilder() {
16 | Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder() {
17 | public void configure(ObjectMapper objectMapper) {
18 | objectMapper.registerSubtypes(PagamentoComCartao.class);
19 | objectMapper.registerSubtypes(PagamentoComBoleto.class);
20 | super.configure(objectMapper);
21 | }
22 | };
23 | return builder;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/config/S3Config.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.config;
2 |
3 | import org.springframework.beans.factory.annotation.Value;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 |
7 | import com.amazonaws.auth.AWSStaticCredentialsProvider;
8 | import com.amazonaws.auth.BasicAWSCredentials;
9 | import com.amazonaws.regions.Regions;
10 | import com.amazonaws.services.s3.AmazonS3;
11 | import com.amazonaws.services.s3.AmazonS3ClientBuilder;
12 |
13 | @Configuration
14 | public class S3Config {
15 |
16 | @Value("${aws.access_key_id}")
17 | private String awsId;
18 |
19 | @Value("${aws.secret_access_key}")
20 | private String awsKey;
21 |
22 | @Value("${s3.region}")
23 | private String region;
24 |
25 | @Bean
26 | public AmazonS3 s3client() {
27 | BasicAWSCredentials awsCred = new BasicAWSCredentials(awsId, awsKey);
28 | AmazonS3 s3client = AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
29 | .withCredentials(new AWSStaticCredentialsProvider(awsCred)).build();
30 | return s3client;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/config/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.config;
2 |
3 | import java.util.Arrays;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.core.env.Environment;
9 | import org.springframework.http.HttpMethod;
10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
11 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
15 | import org.springframework.security.config.http.SessionCreationPolicy;
16 | import org.springframework.security.core.userdetails.UserDetailsService;
17 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
18 | import org.springframework.web.cors.CorsConfiguration;
19 | import org.springframework.web.cors.CorsConfigurationSource;
20 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
21 |
22 | import com.nelioalves.cursomc.security.JWTAuthenticationFilter;
23 | import com.nelioalves.cursomc.security.JWTAuthorizationFilter;
24 | import com.nelioalves.cursomc.security.JWTUtil;
25 |
26 | @Configuration
27 | @EnableWebSecurity
28 | @EnableGlobalMethodSecurity(prePostEnabled = true)
29 | public class SecurityConfig extends WebSecurityConfigurerAdapter {
30 |
31 | @Autowired
32 | private UserDetailsService userDetailsService;
33 |
34 | @Autowired
35 | private Environment env;
36 |
37 | @Autowired
38 | private JWTUtil jwtUtil;
39 |
40 | private static final String[] PUBLIC_MATCHERS = {
41 | "/h2-console/**"
42 | };
43 |
44 | private static final String[] PUBLIC_MATCHERS_GET = {
45 | "/produtos/**",
46 | "/categorias/**",
47 | "/estados/**"
48 | };
49 |
50 | private static final String[] PUBLIC_MATCHERS_POST = {
51 | "/clientes/**",
52 | "/auth/forgot/**"
53 | };
54 |
55 | @Override
56 | protected void configure(HttpSecurity http) throws Exception {
57 |
58 | if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
59 | http.headers().frameOptions().disable();
60 | }
61 |
62 | http.cors().and().csrf().disable();
63 | http.authorizeRequests()
64 | .antMatchers(HttpMethod.POST, PUBLIC_MATCHERS_POST).permitAll()
65 | .antMatchers(HttpMethod.GET, PUBLIC_MATCHERS_GET).permitAll()
66 | .antMatchers(PUBLIC_MATCHERS).permitAll()
67 | .anyRequest().authenticated();
68 | http.addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtUtil));
69 | http.addFilter(new JWTAuthorizationFilter(authenticationManager(), jwtUtil, userDetailsService));
70 | http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
71 | }
72 |
73 | @Override
74 | public void configure(AuthenticationManagerBuilder auth) throws Exception {
75 | auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
76 | }
77 |
78 | @Bean
79 | CorsConfigurationSource corsConfigurationSource() {
80 | CorsConfiguration configuration = new CorsConfiguration().applyPermitDefaultValues();
81 | configuration.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "DELETE", "OPTIONS"));
82 | final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
83 | source.registerCorsConfiguration("/**", configuration);
84 | return source;
85 | }
86 |
87 | @Bean
88 | public BCryptPasswordEncoder bCryptPasswordEncoder() {
89 | return new BCryptPasswordEncoder();
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/config/TestConfig.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.config;
2 |
3 | import java.text.ParseException;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.context.annotation.Profile;
9 |
10 | import com.nelioalves.cursomc.services.DBService;
11 | import com.nelioalves.cursomc.services.EmailService;
12 | import com.nelioalves.cursomc.services.MockEmailService;
13 |
14 | @Configuration
15 | @Profile("test")
16 | public class TestConfig {
17 |
18 | @Autowired
19 | private DBService dbService;
20 |
21 | @Bean
22 | public boolean instantiateDatabase() throws ParseException {
23 | dbService.instantiateTestDatabase();
24 | return true;
25 | }
26 |
27 | @Bean
28 | public EmailService emailService() {
29 | return new MockEmailService();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Categoria.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.ManyToMany;
12 |
13 | @Entity
14 | public class Categoria implements Serializable {
15 | private static final long serialVersionUID = 1L;
16 |
17 | @Id
18 | @GeneratedValue(strategy=GenerationType.IDENTITY)
19 | private Integer id;
20 | private String nome;
21 |
22 | @ManyToMany(mappedBy="categorias")
23 | private List produtos = new ArrayList<>();
24 |
25 | public Categoria() {
26 | }
27 |
28 | public Categoria(Integer id, String nome) {
29 | super();
30 | this.id = id;
31 | this.nome = nome;
32 | }
33 |
34 | public Integer getId() {
35 | return id;
36 | }
37 |
38 | public void setId(Integer id) {
39 | this.id = id;
40 | }
41 |
42 | public String getNome() {
43 | return nome;
44 | }
45 |
46 | public void setNome(String nome) {
47 | this.nome = nome;
48 | }
49 |
50 | public List getProdutos() {
51 | return produtos;
52 | }
53 |
54 | public void setProdutos(List produtos) {
55 | this.produtos = produtos;
56 | }
57 |
58 | @Override
59 | public int hashCode() {
60 | final int prime = 31;
61 | int result = 1;
62 | result = prime * result + ((id == null) ? 0 : id.hashCode());
63 | return result;
64 | }
65 |
66 | @Override
67 | public boolean equals(Object obj) {
68 | if (this == obj)
69 | return true;
70 | if (obj == null)
71 | return false;
72 | if (getClass() != obj.getClass())
73 | return false;
74 | Categoria other = (Categoria) obj;
75 | if (id == null) {
76 | if (other.id != null)
77 | return false;
78 | } else if (!id.equals(other.id))
79 | return false;
80 | return true;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Cidade.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 | import javax.persistence.JoinColumn;
10 | import javax.persistence.ManyToOne;
11 |
12 | @Entity
13 | public class Cidade implements Serializable {
14 | private static final long serialVersionUID = 1L;
15 |
16 | @Id
17 | @GeneratedValue(strategy=GenerationType.IDENTITY)
18 | private Integer id;
19 | private String nome;
20 |
21 | @ManyToOne
22 | @JoinColumn(name="estado_id")
23 | private Estado estado;
24 |
25 | public Cidade() {
26 | }
27 |
28 | public Cidade(Integer id, String nome, Estado estado) {
29 | super();
30 | this.id = id;
31 | this.nome = nome;
32 | this.estado = estado;
33 | }
34 |
35 | public Integer getId() {
36 | return id;
37 | }
38 |
39 | public void setId(Integer id) {
40 | this.id = id;
41 | }
42 |
43 | public String getNome() {
44 | return nome;
45 | }
46 |
47 | public void setNome(String nome) {
48 | this.nome = nome;
49 | }
50 |
51 | public Estado getEstado() {
52 | return estado;
53 | }
54 |
55 | public void setEstado(Estado estado) {
56 | this.estado = estado;
57 | }
58 |
59 | @Override
60 | public int hashCode() {
61 | final int prime = 31;
62 | int result = 1;
63 | result = prime * result + ((id == null) ? 0 : id.hashCode());
64 | return result;
65 | }
66 |
67 | @Override
68 | public boolean equals(Object obj) {
69 | if (this == obj)
70 | return true;
71 | if (obj == null)
72 | return false;
73 | if (getClass() != obj.getClass())
74 | return false;
75 | Cidade other = (Cidade) obj;
76 | if (id == null) {
77 | if (other.id != null)
78 | return false;
79 | } else if (!id.equals(other.id))
80 | return false;
81 | return true;
82 | }
83 |
84 |
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Cliente.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.HashSet;
6 | import java.util.List;
7 | import java.util.Set;
8 | import java.util.stream.Collectors;
9 |
10 | import javax.persistence.CascadeType;
11 | import javax.persistence.CollectionTable;
12 | import javax.persistence.Column;
13 | import javax.persistence.ElementCollection;
14 | import javax.persistence.Entity;
15 | import javax.persistence.FetchType;
16 | import javax.persistence.GeneratedValue;
17 | import javax.persistence.GenerationType;
18 | import javax.persistence.Id;
19 | import javax.persistence.OneToMany;
20 |
21 | import com.fasterxml.jackson.annotation.JsonIgnore;
22 | import com.nelioalves.cursomc.domain.enums.Perfil;
23 | import com.nelioalves.cursomc.domain.enums.TipoCliente;
24 |
25 | @Entity
26 | public class Cliente implements Serializable {
27 | private static final long serialVersionUID = 1L;
28 |
29 | @Id
30 | @GeneratedValue(strategy=GenerationType.IDENTITY)
31 | private Integer id;
32 | private String nome;
33 |
34 | @Column(unique=true)
35 | private String email;
36 | private String cpfOuCnpj;
37 | private Integer tipo;
38 |
39 | @JsonIgnore
40 | private String senha;
41 |
42 | @OneToMany(mappedBy="cliente", cascade=CascadeType.ALL)
43 | private List enderecos = new ArrayList<>();
44 |
45 | @ElementCollection
46 | @CollectionTable(name="TELEFONE")
47 | private Set telefones = new HashSet<>();
48 |
49 | @ElementCollection(fetch=FetchType.EAGER)
50 | @CollectionTable(name="PERFIS")
51 | private Set perfis = new HashSet<>();
52 |
53 | @JsonIgnore
54 | @OneToMany(mappedBy="cliente")
55 | private List pedidos = new ArrayList<>();
56 |
57 | public Cliente() {
58 | addPerfil(Perfil.CLIENTE);
59 | }
60 |
61 | public Cliente(Integer id, String nome, String email, String cpfOuCnpj, TipoCliente tipo, String senha) {
62 | super();
63 | this.id = id;
64 | this.nome = nome;
65 | this.email = email;
66 | this.cpfOuCnpj = cpfOuCnpj;
67 | this.tipo = (tipo==null) ? null : tipo.getCod();
68 | this.senha = senha;
69 | addPerfil(Perfil.CLIENTE);
70 | }
71 |
72 | public Integer getId() {
73 | return id;
74 | }
75 |
76 | public void setId(Integer id) {
77 | this.id = id;
78 | }
79 |
80 | public String getNome() {
81 | return nome;
82 | }
83 |
84 | public void setNome(String nome) {
85 | this.nome = nome;
86 | }
87 |
88 | public String getEmail() {
89 | return email;
90 | }
91 |
92 | public void setEmail(String email) {
93 | this.email = email;
94 | }
95 |
96 | public String getCpfOuCnpj() {
97 | return cpfOuCnpj;
98 | }
99 |
100 | public void setCpfOuCnpj(String cpfOuCnpj) {
101 | this.cpfOuCnpj = cpfOuCnpj;
102 | }
103 |
104 | public TipoCliente getTipo() {
105 | return TipoCliente.toEnum(tipo);
106 | }
107 |
108 | public void setTipo(TipoCliente tipo) {
109 | this.tipo = tipo.getCod();
110 | }
111 |
112 | public String getSenha() {
113 | return senha;
114 | }
115 |
116 | public void setSenha(String senha) {
117 | this.senha = senha;
118 | }
119 |
120 | public Set getPerfis() {
121 | return perfis.stream().map(x -> Perfil.toEnum(x)).collect(Collectors.toSet());
122 | }
123 |
124 | public void addPerfil(Perfil perfil) {
125 | perfis.add(perfil.getCod());
126 | }
127 |
128 | public List getEnderecos() {
129 | return enderecos;
130 | }
131 |
132 | public void setEnderecos(List enderecos) {
133 | this.enderecos = enderecos;
134 | }
135 |
136 | public Set getTelefones() {
137 | return telefones;
138 | }
139 |
140 | public void setTelefones(Set telefones) {
141 | this.telefones = telefones;
142 | }
143 |
144 | public List getPedidos() {
145 | return pedidos;
146 | }
147 |
148 | public void setPedidos(List pedidos) {
149 | this.pedidos = pedidos;
150 | }
151 |
152 | @Override
153 | public int hashCode() {
154 | final int prime = 31;
155 | int result = 1;
156 | result = prime * result + ((id == null) ? 0 : id.hashCode());
157 | return result;
158 | }
159 |
160 | @Override
161 | public boolean equals(Object obj) {
162 | if (this == obj)
163 | return true;
164 | if (obj == null)
165 | return false;
166 | if (getClass() != obj.getClass())
167 | return false;
168 | Cliente other = (Cliente) obj;
169 | if (id == null) {
170 | if (other.id != null)
171 | return false;
172 | } else if (!id.equals(other.id))
173 | return false;
174 | return true;
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Endereco.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 | import javax.persistence.JoinColumn;
10 | import javax.persistence.ManyToOne;
11 |
12 | import com.fasterxml.jackson.annotation.JsonIgnore;
13 |
14 | @Entity
15 | public class Endereco implements Serializable {
16 | private static final long serialVersionUID = 1L;
17 |
18 | @Id
19 | @GeneratedValue(strategy=GenerationType.IDENTITY)
20 | private Integer id;
21 | private String logradouro;
22 | private String numero;
23 | private String complemento;
24 | private String bairro;
25 | private String cep;
26 |
27 | @JsonIgnore
28 | @ManyToOne
29 | @JoinColumn(name="cliente_id")
30 | private Cliente cliente;
31 |
32 | @ManyToOne
33 | @JoinColumn(name="cidade_id")
34 | private Cidade cidade;
35 |
36 | public Endereco() {
37 | }
38 |
39 | public Endereco(Integer id, String logradouro, String numero, String complemento, String bairro, String cep,
40 | Cliente cliente, Cidade cidade) {
41 | super();
42 | this.id = id;
43 | this.logradouro = logradouro;
44 | this.numero = numero;
45 | this.complemento = complemento;
46 | this.bairro = bairro;
47 | this.cep = cep;
48 | this.cliente = cliente;
49 | this.setCidade(cidade);
50 | }
51 |
52 | public Integer getId() {
53 | return id;
54 | }
55 |
56 | public void setId(Integer id) {
57 | this.id = id;
58 | }
59 |
60 | public String getLogradouro() {
61 | return logradouro;
62 | }
63 |
64 | public void setLogradouro(String logradouro) {
65 | this.logradouro = logradouro;
66 | }
67 |
68 | public String getNumero() {
69 | return numero;
70 | }
71 |
72 | public void setNumero(String numero) {
73 | this.numero = numero;
74 | }
75 |
76 | public String getComplemento() {
77 | return complemento;
78 | }
79 |
80 | public void setComplemento(String complemento) {
81 | this.complemento = complemento;
82 | }
83 |
84 | public String getBairro() {
85 | return bairro;
86 | }
87 |
88 | public void setBairro(String bairro) {
89 | this.bairro = bairro;
90 | }
91 |
92 | public String getCep() {
93 | return cep;
94 | }
95 |
96 | public void setCep(String cep) {
97 | this.cep = cep;
98 | }
99 |
100 | public Cliente getCliente() {
101 | return cliente;
102 | }
103 |
104 | public void setCliente(Cliente cliente) {
105 | this.cliente = cliente;
106 | }
107 |
108 | public Cidade getCidade() {
109 | return cidade;
110 | }
111 |
112 | public void setCidade(Cidade cidade) {
113 | this.cidade = cidade;
114 | }
115 |
116 | @Override
117 | public int hashCode() {
118 | final int prime = 31;
119 | int result = 1;
120 | result = prime * result + ((id == null) ? 0 : id.hashCode());
121 | return result;
122 | }
123 |
124 | @Override
125 | public boolean equals(Object obj) {
126 | if (this == obj)
127 | return true;
128 | if (obj == null)
129 | return false;
130 | if (getClass() != obj.getClass())
131 | return false;
132 | Endereco other = (Endereco) obj;
133 | if (id == null) {
134 | if (other.id != null)
135 | return false;
136 | } else if (!id.equals(other.id))
137 | return false;
138 | return true;
139 | }
140 |
141 |
142 |
143 | }
144 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Estado.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.OneToMany;
12 |
13 | import com.fasterxml.jackson.annotation.JsonIgnore;
14 |
15 | @Entity
16 | public class Estado implements Serializable {
17 | private static final long serialVersionUID = 1L;
18 |
19 | @Id
20 | @GeneratedValue(strategy=GenerationType.IDENTITY)
21 | private Integer id;
22 | private String nome;
23 |
24 | @JsonIgnore
25 | @OneToMany(mappedBy="estado")
26 | private List cidades = new ArrayList<>();
27 |
28 | public Estado() {
29 | }
30 |
31 | public Estado(Integer id, String nome) {
32 | super();
33 | this.id = id;
34 | this.nome = nome;
35 | }
36 |
37 | public Integer getId() {
38 | return id;
39 | }
40 |
41 | public void setId(Integer id) {
42 | this.id = id;
43 | }
44 |
45 | public String getNome() {
46 | return nome;
47 | }
48 |
49 | public void setNome(String nome) {
50 | this.nome = nome;
51 | }
52 |
53 | public List getCidades() {
54 | return cidades;
55 | }
56 |
57 | public void setCidades(List cidades) {
58 | this.cidades = cidades;
59 | }
60 |
61 | @Override
62 | public int hashCode() {
63 | final int prime = 31;
64 | int result = 1;
65 | result = prime * result + ((id == null) ? 0 : id.hashCode());
66 | return result;
67 | }
68 |
69 | @Override
70 | public boolean equals(Object obj) {
71 | if (this == obj)
72 | return true;
73 | if (obj == null)
74 | return false;
75 | if (getClass() != obj.getClass())
76 | return false;
77 | Estado other = (Estado) obj;
78 | if (id == null) {
79 | if (other.id != null)
80 | return false;
81 | } else if (!id.equals(other.id))
82 | return false;
83 | return true;
84 | }
85 |
86 |
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/ItemPedido.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 | import java.text.NumberFormat;
5 | import java.util.Locale;
6 |
7 | import javax.persistence.EmbeddedId;
8 | import javax.persistence.Entity;
9 |
10 | import com.fasterxml.jackson.annotation.JsonIgnore;
11 |
12 | @Entity
13 | public class ItemPedido implements Serializable {
14 | private static final long serialVersionUID = 1L;
15 |
16 | @JsonIgnore
17 | @EmbeddedId
18 | private ItemPedidoPK id = new ItemPedidoPK();
19 |
20 | private Double desconto;
21 | private Integer quantidade;
22 | private Double preco;
23 |
24 | public ItemPedido() {
25 | }
26 |
27 | public ItemPedido(Pedido pedido, Produto produto, Double desconto, Integer quantidade, Double preco) {
28 | super();
29 | id.setPedido(pedido);
30 | id.setProduto(produto);
31 | this.desconto = desconto;
32 | this.quantidade = quantidade;
33 | this.preco = preco;
34 | }
35 |
36 | public double getSubTotal() {
37 | return (preco - desconto) * quantidade;
38 | }
39 |
40 | @JsonIgnore
41 | public Pedido getPedido() {
42 | return id.getPedido();
43 | }
44 |
45 | public void setPedido(Pedido pedido) {
46 | id.setPedido(pedido);
47 | }
48 |
49 | public Produto getProduto() {
50 | return id.getProduto();
51 | }
52 |
53 | public void setProduto(Produto produto) {
54 | id.setProduto(produto);
55 | }
56 |
57 | public ItemPedidoPK getId() {
58 | return id;
59 | }
60 |
61 | public void setId(ItemPedidoPK id) {
62 | this.id = id;
63 | }
64 |
65 | public Double getDesconto() {
66 | return desconto;
67 | }
68 |
69 | public void setDesconto(Double desconto) {
70 | this.desconto = desconto;
71 | }
72 |
73 | public Integer getQuantidade() {
74 | return quantidade;
75 | }
76 |
77 | public void setQuantidade(Integer quantidade) {
78 | this.quantidade = quantidade;
79 | }
80 |
81 | public Double getPreco() {
82 | return preco;
83 | }
84 |
85 | public void setPreco(Double preco) {
86 | this.preco = preco;
87 | }
88 |
89 | @Override
90 | public int hashCode() {
91 | final int prime = 31;
92 | int result = 1;
93 | result = prime * result + ((id == null) ? 0 : id.hashCode());
94 | return result;
95 | }
96 |
97 | @Override
98 | public boolean equals(Object obj) {
99 | if (this == obj)
100 | return true;
101 | if (obj == null)
102 | return false;
103 | if (getClass() != obj.getClass())
104 | return false;
105 | ItemPedido other = (ItemPedido) obj;
106 | if (id == null) {
107 | if (other.id != null)
108 | return false;
109 | } else if (!id.equals(other.id))
110 | return false;
111 | return true;
112 | }
113 |
114 | @Override
115 | public String toString() {
116 | NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
117 | StringBuilder builder = new StringBuilder();
118 | builder.append(getProduto().getNome());
119 | builder.append(", Qte: ");
120 | builder.append(getQuantidade());
121 | builder.append(", Preço unitário: ");
122 | builder.append(nf.format(getPreco()));
123 | builder.append(", Subtotal: ");
124 | builder.append(nf.format(getSubTotal()));
125 | builder.append("\n");
126 | return builder.toString();
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/ItemPedidoPK.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.Embeddable;
6 | import javax.persistence.JoinColumn;
7 | import javax.persistence.ManyToOne;
8 |
9 | @Embeddable
10 | public class ItemPedidoPK implements Serializable {
11 | private static final long serialVersionUID = 1L;
12 |
13 | @ManyToOne
14 | @JoinColumn(name="pedido_id")
15 | private Pedido pedido;
16 |
17 | @ManyToOne
18 | @JoinColumn(name="produto_id")
19 | private Produto produto;
20 |
21 | public Pedido getPedido() {
22 | return pedido;
23 | }
24 | public void setPedido(Pedido pedido) {
25 | this.pedido = pedido;
26 | }
27 | public Produto getProduto() {
28 | return produto;
29 | }
30 | public void setProduto(Produto produto) {
31 | this.produto = produto;
32 | }
33 | @Override
34 | public int hashCode() {
35 | final int prime = 31;
36 | int result = 1;
37 | result = prime * result + ((pedido == null) ? 0 : pedido.hashCode());
38 | result = prime * result + ((produto == null) ? 0 : produto.hashCode());
39 | return result;
40 | }
41 | @Override
42 | public boolean equals(Object obj) {
43 | if (this == obj)
44 | return true;
45 | if (obj == null)
46 | return false;
47 | if (getClass() != obj.getClass())
48 | return false;
49 | ItemPedidoPK other = (ItemPedidoPK) obj;
50 | if (pedido == null) {
51 | if (other.pedido != null)
52 | return false;
53 | } else if (!pedido.equals(other.pedido))
54 | return false;
55 | if (produto == null) {
56 | if (other.produto != null)
57 | return false;
58 | } else if (!produto.equals(other.produto))
59 | return false;
60 | return true;
61 | }
62 |
63 |
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Pagamento.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.Id;
7 | import javax.persistence.Inheritance;
8 | import javax.persistence.InheritanceType;
9 | import javax.persistence.JoinColumn;
10 | import javax.persistence.MapsId;
11 | import javax.persistence.OneToOne;
12 |
13 | import com.fasterxml.jackson.annotation.JsonIgnore;
14 | import com.fasterxml.jackson.annotation.JsonTypeInfo;
15 | import com.nelioalves.cursomc.domain.enums.EstadoPagamento;
16 |
17 | @Entity
18 | @Inheritance(strategy=InheritanceType.JOINED)
19 | @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
20 | public abstract class Pagamento implements Serializable {
21 | private static final long serialVersionUID = 1L;
22 |
23 | @Id
24 | private Integer id;
25 | private Integer estado;
26 |
27 | @JsonIgnore
28 | @OneToOne
29 | @JoinColumn(name="pedido_id")
30 | @MapsId
31 | private Pedido pedido;
32 |
33 | public Pagamento() {
34 | }
35 |
36 | public Pagamento(Integer id, EstadoPagamento estado, Pedido pedido) {
37 | super();
38 | this.id = id;
39 | this.estado = (estado==null) ? null : estado.getCod();
40 | this.pedido = pedido;
41 | }
42 |
43 | public Integer getId() {
44 | return id;
45 | }
46 |
47 | public void setId(Integer id) {
48 | this.id = id;
49 | }
50 |
51 | public EstadoPagamento getEstado() {
52 | return EstadoPagamento.toEnum(estado);
53 | }
54 |
55 | public void setEstado(EstadoPagamento estado) {
56 | this.estado = estado.getCod();
57 | }
58 |
59 | public Pedido getPedido() {
60 | return pedido;
61 | }
62 |
63 | public void setPedido(Pedido pedido) {
64 | this.pedido = pedido;
65 | }
66 |
67 | @Override
68 | public int hashCode() {
69 | final int prime = 31;
70 | int result = 1;
71 | result = prime * result + ((id == null) ? 0 : id.hashCode());
72 | return result;
73 | }
74 |
75 | @Override
76 | public boolean equals(Object obj) {
77 | if (this == obj)
78 | return true;
79 | if (obj == null)
80 | return false;
81 | if (getClass() != obj.getClass())
82 | return false;
83 | Pagamento other = (Pagamento) obj;
84 | if (id == null) {
85 | if (other.id != null)
86 | return false;
87 | } else if (!id.equals(other.id))
88 | return false;
89 | return true;
90 | }
91 |
92 |
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/PagamentoComBoleto.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.util.Date;
4 |
5 | import javax.persistence.Entity;
6 |
7 | import com.fasterxml.jackson.annotation.JsonFormat;
8 | import com.fasterxml.jackson.annotation.JsonTypeName;
9 | import com.nelioalves.cursomc.domain.enums.EstadoPagamento;
10 |
11 | @Entity
12 | @JsonTypeName("pagamentoComBoleto")
13 | public class PagamentoComBoleto extends Pagamento {
14 | private static final long serialVersionUID = 1L;
15 |
16 | @JsonFormat(pattern="dd/MM/yyyy")
17 | private Date dataVencimento;
18 |
19 | @JsonFormat(pattern="dd/MM/yyyy")
20 | private Date dataPagamento;
21 |
22 | public PagamentoComBoleto() {
23 | }
24 |
25 | public PagamentoComBoleto(Integer id, EstadoPagamento estado, Pedido pedido, Date dataVencimento, Date dataPagamento) {
26 | super(id, estado, pedido);
27 | this.dataPagamento = dataPagamento;
28 | this.dataVencimento = dataVencimento;
29 | }
30 |
31 | public Date getDataVencimento() {
32 | return dataVencimento;
33 | }
34 |
35 | public void setDataVencimento(Date dataVencimento) {
36 | this.dataVencimento = dataVencimento;
37 | }
38 |
39 | public Date getDataPagamento() {
40 | return dataPagamento;
41 | }
42 |
43 | public void setDataPagamento(Date dataPagamento) {
44 | this.dataPagamento = dataPagamento;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/PagamentoComCartao.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import javax.persistence.Entity;
4 |
5 | import com.fasterxml.jackson.annotation.JsonTypeName;
6 | import com.nelioalves.cursomc.domain.enums.EstadoPagamento;
7 |
8 | @Entity
9 | @JsonTypeName("pagamentoComCartao")
10 | public class PagamentoComCartao extends Pagamento {
11 | private static final long serialVersionUID = 1L;
12 |
13 | private Integer numeroDeParcelas;
14 |
15 | public PagamentoComCartao() {
16 | }
17 |
18 | public PagamentoComCartao(Integer id, EstadoPagamento estado, Pedido pedido, Integer numeroDeParcelas) {
19 | super(id, estado, pedido);
20 | this.numeroDeParcelas = numeroDeParcelas;
21 | }
22 |
23 | public Integer getNumeroDeParcelas() {
24 | return numeroDeParcelas;
25 | }
26 |
27 | public void setNumeroDeParcelas(Integer numeroDeParcelas) {
28 | this.numeroDeParcelas = numeroDeParcelas;
29 | }
30 |
31 |
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Pedido.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 | import java.text.NumberFormat;
5 | import java.text.SimpleDateFormat;
6 | import java.util.Date;
7 | import java.util.HashSet;
8 | import java.util.Locale;
9 | import java.util.Set;
10 |
11 | import javax.persistence.CascadeType;
12 | import javax.persistence.Entity;
13 | import javax.persistence.GeneratedValue;
14 | import javax.persistence.GenerationType;
15 | import javax.persistence.Id;
16 | import javax.persistence.JoinColumn;
17 | import javax.persistence.ManyToOne;
18 | import javax.persistence.OneToMany;
19 | import javax.persistence.OneToOne;
20 |
21 | import com.fasterxml.jackson.annotation.JsonFormat;
22 |
23 | @Entity
24 | public class Pedido implements Serializable {
25 | private static final long serialVersionUID = 1L;
26 |
27 | @Id
28 | @GeneratedValue(strategy=GenerationType.IDENTITY)
29 | private Integer id;
30 |
31 | @JsonFormat(pattern="dd/MM/yyyy HH:mm")
32 | private Date instante;
33 |
34 | @OneToOne(cascade=CascadeType.ALL, mappedBy="pedido")
35 | private Pagamento pagamento;
36 |
37 | @ManyToOne
38 | @JoinColumn(name="cliente_id")
39 | private Cliente cliente;
40 |
41 | @ManyToOne
42 | @JoinColumn(name="endereco_de_entrega_id")
43 | private Endereco enderecoDeEntrega;
44 |
45 | @OneToMany(mappedBy="id.pedido")
46 | private Set itens = new HashSet<>();
47 |
48 | public Pedido() {
49 | }
50 |
51 | public Pedido(Integer id, Date instante, Cliente cliente, Endereco enderecoDeEntrega) {
52 | super();
53 | this.id = id;
54 | this.instante = instante;
55 | this.cliente = cliente;
56 | this.enderecoDeEntrega = enderecoDeEntrega;
57 | }
58 |
59 | public double getValorTotal() {
60 | double soma = 0.0;
61 | for (ItemPedido ip : itens) {
62 | soma = soma + ip.getSubTotal();
63 | }
64 | return soma;
65 | }
66 |
67 | public Integer getId() {
68 | return id;
69 | }
70 |
71 | public void setId(Integer id) {
72 | this.id = id;
73 | }
74 |
75 | public Date getInstante() {
76 | return instante;
77 | }
78 |
79 | public void setInstante(Date instante) {
80 | this.instante = instante;
81 | }
82 |
83 | public Pagamento getPagamento() {
84 | return pagamento;
85 | }
86 |
87 | public void setPagamento(Pagamento pagamento) {
88 | this.pagamento = pagamento;
89 | }
90 |
91 | public Cliente getCliente() {
92 | return cliente;
93 | }
94 |
95 | public void setCliente(Cliente cliente) {
96 | this.cliente = cliente;
97 | }
98 |
99 | public Endereco getEnderecoDeEntrega() {
100 | return enderecoDeEntrega;
101 | }
102 |
103 | public void setEnderecoDeEntrega(Endereco enderecoDeEntrega) {
104 | this.enderecoDeEntrega = enderecoDeEntrega;
105 | }
106 |
107 | public Set getItens() {
108 | return itens;
109 | }
110 |
111 | public void setItens(Set itens) {
112 | this.itens = itens;
113 | }
114 |
115 | @Override
116 | public int hashCode() {
117 | final int prime = 31;
118 | int result = 1;
119 | result = prime * result + ((id == null) ? 0 : id.hashCode());
120 | return result;
121 | }
122 |
123 | @Override
124 | public boolean equals(Object obj) {
125 | if (this == obj)
126 | return true;
127 | if (obj == null)
128 | return false;
129 | if (getClass() != obj.getClass())
130 | return false;
131 | Pedido other = (Pedido) obj;
132 | if (id == null) {
133 | if (other.id != null)
134 | return false;
135 | } else if (!id.equals(other.id))
136 | return false;
137 | return true;
138 | }
139 |
140 | @Override
141 | public String toString() {
142 | NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
143 | SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
144 | StringBuilder builder = new StringBuilder();
145 | builder.append("Pedido número: ");
146 | builder.append(getId());
147 | builder.append(", Instante: ");
148 | builder.append(sdf.format(getInstante()));
149 | builder.append(", Cliente: ");
150 | builder.append(getCliente().getNome());
151 | builder.append(", Situação do pagamento: ");
152 | builder.append(getPagamento().getEstado().getDescricao());
153 | builder.append("\nDetalhes:\n");
154 | for (ItemPedido ip : getItens()) {
155 | builder.append(ip.toString());
156 | }
157 | builder.append("Valor total: ");
158 | builder.append(nf.format(getValorTotal()));
159 | return builder.toString();
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/Produto.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.HashSet;
6 | import java.util.List;
7 | import java.util.Set;
8 |
9 | import javax.persistence.Entity;
10 | import javax.persistence.GeneratedValue;
11 | import javax.persistence.GenerationType;
12 | import javax.persistence.Id;
13 | import javax.persistence.JoinColumn;
14 | import javax.persistence.JoinTable;
15 | import javax.persistence.ManyToMany;
16 | import javax.persistence.OneToMany;
17 |
18 | import com.fasterxml.jackson.annotation.JsonIgnore;
19 |
20 | @Entity
21 | public class Produto implements Serializable {
22 | private static final long serialVersionUID = 1L;
23 |
24 | @Id
25 | @GeneratedValue(strategy=GenerationType.IDENTITY)
26 | private Integer id;
27 | private String nome;
28 | private Double preco;
29 |
30 | @JsonIgnore
31 | @ManyToMany
32 | @JoinTable(name = "PRODUTO_CATEGORIA",
33 | joinColumns = @JoinColumn(name = "produto_id"),
34 | inverseJoinColumns = @JoinColumn(name = "categoria_id")
35 | )
36 | private List categorias = new ArrayList<>();
37 |
38 | @JsonIgnore
39 | @OneToMany(mappedBy="id.produto")
40 | private Set itens = new HashSet<>();
41 |
42 | public Produto() {
43 | }
44 |
45 | public Produto(Integer id, String nome, Double preco) {
46 | super();
47 | this.id = id;
48 | this.nome = nome;
49 | this.preco = preco;
50 | }
51 |
52 | @JsonIgnore
53 | public List getPedidos() {
54 | List lista = new ArrayList<>();
55 | for (ItemPedido x : itens) {
56 | lista.add(x.getPedido());
57 | }
58 | return lista;
59 | }
60 |
61 |
62 | public Integer getId() {
63 | return id;
64 | }
65 |
66 | public void setId(Integer id) {
67 | this.id = id;
68 | }
69 |
70 | public String getNome() {
71 | return nome;
72 | }
73 |
74 | public void setNome(String nome) {
75 | this.nome = nome;
76 | }
77 |
78 | public Double getPreco() {
79 | return preco;
80 | }
81 |
82 | public void setPreco(Double preco) {
83 | this.preco = preco;
84 | }
85 |
86 | public List getCategorias() {
87 | return categorias;
88 | }
89 |
90 | public void setCategorias(List categorias) {
91 | this.categorias = categorias;
92 | }
93 |
94 | public Set getItens() {
95 | return itens;
96 | }
97 |
98 | public void setItens(Set itens) {
99 | this.itens = itens;
100 | }
101 |
102 | @Override
103 | public int hashCode() {
104 | final int prime = 31;
105 | int result = 1;
106 | result = prime * result + ((id == null) ? 0 : id.hashCode());
107 | return result;
108 | }
109 |
110 | @Override
111 | public boolean equals(Object obj) {
112 | if (this == obj)
113 | return true;
114 | if (obj == null)
115 | return false;
116 | if (getClass() != obj.getClass())
117 | return false;
118 | Produto other = (Produto) obj;
119 | if (id == null) {
120 | if (other.id != null)
121 | return false;
122 | } else if (!id.equals(other.id))
123 | return false;
124 | return true;
125 | }
126 |
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/enums/EstadoPagamento.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain.enums;
2 |
3 | public enum EstadoPagamento {
4 |
5 | PENDENTE(1, "Pendente"),
6 | QUITADO(2, "Quitado"),
7 | CANCELADO(3, "Cancelado");
8 |
9 | private int cod;
10 | private String descricao;
11 |
12 | private EstadoPagamento(int cod, String descricao) {
13 | this.cod = cod;
14 | this.descricao = descricao;
15 | }
16 |
17 | public int getCod() {
18 | return cod;
19 | }
20 |
21 | public String getDescricao () {
22 | return descricao;
23 | }
24 |
25 | public static EstadoPagamento toEnum(Integer cod) {
26 |
27 | if (cod == null) {
28 | return null;
29 | }
30 |
31 | for (EstadoPagamento x : EstadoPagamento.values()) {
32 | if (cod.equals(x.getCod())) {
33 | return x;
34 | }
35 | }
36 |
37 | throw new IllegalArgumentException("Id inválido: " + cod);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/enums/Perfil.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain.enums;
2 |
3 | public enum Perfil {
4 |
5 | ADMIN(1, "ROLE_ADMIN"),
6 | CLIENTE(2, "ROLE_CLIENTE");
7 |
8 | private int cod;
9 | private String descricao;
10 |
11 | private Perfil(int cod, String descricao) {
12 | this.cod = cod;
13 | this.descricao = descricao;
14 | }
15 |
16 | public int getCod() {
17 | return cod;
18 | }
19 |
20 | public String getDescricao () {
21 | return descricao;
22 | }
23 |
24 | public static Perfil toEnum(Integer cod) {
25 |
26 | if (cod == null) {
27 | return null;
28 | }
29 |
30 | for (Perfil x : Perfil.values()) {
31 | if (cod.equals(x.getCod())) {
32 | return x;
33 | }
34 | }
35 |
36 | throw new IllegalArgumentException("Id inválido: " + cod);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/domain/enums/TipoCliente.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.domain.enums;
2 |
3 | public enum TipoCliente {
4 |
5 | PESSOAFISICA(1, "Pessoa Física"),
6 | PESSOAJURIDICA(2, "Pessoa Jurídica");
7 |
8 | private int cod;
9 | private String descricao;
10 |
11 | private TipoCliente(int cod, String descricao) {
12 | this.cod = cod;
13 | this.descricao = descricao;
14 | }
15 |
16 | public int getCod() {
17 | return cod;
18 | }
19 |
20 | public String getDescricao () {
21 | return descricao;
22 | }
23 |
24 | public static TipoCliente toEnum(Integer cod) {
25 |
26 | if (cod == null) {
27 | return null;
28 | }
29 |
30 | for (TipoCliente x : TipoCliente.values()) {
31 | if (cod.equals(x.getCod())) {
32 | return x;
33 | }
34 | }
35 |
36 | throw new IllegalArgumentException("Id inválido: " + cod);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/CategoriaDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.validation.constraints.NotEmpty;
6 |
7 | import org.hibernate.validator.constraints.Length;
8 |
9 | import com.nelioalves.cursomc.domain.Categoria;
10 |
11 | public class CategoriaDTO implements Serializable {
12 | private static final long serialVersionUID = 1L;
13 |
14 | private Integer id;
15 |
16 | @NotEmpty(message="Preenchimento obrigatório")
17 | @Length(min=5, max=80, message="O tamanho deve ser entre 5 e 80 caracteres")
18 | private String nome;
19 |
20 | public CategoriaDTO() {
21 | }
22 |
23 | public CategoriaDTO(Categoria obj) {
24 | id = obj.getId();
25 | nome = obj.getNome();
26 | }
27 |
28 | public Integer getId() {
29 | return id;
30 | }
31 |
32 | public void setId(Integer id) {
33 | this.id = id;
34 | }
35 |
36 | public String getNome() {
37 | return nome;
38 | }
39 |
40 | public void setNome(String nome) {
41 | this.nome = nome;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/CidadeDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import com.nelioalves.cursomc.domain.Cidade;
6 |
7 | public class CidadeDTO implements Serializable {
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Integer id;
11 | private String nome;
12 |
13 | public CidadeDTO() {
14 | }
15 |
16 | public CidadeDTO(Cidade obj) {
17 | id = obj.getId();
18 | nome = obj.getNome();
19 | }
20 |
21 | public Integer getId() {
22 | return id;
23 | }
24 |
25 | public void setId(Integer id) {
26 | this.id = id;
27 | }
28 |
29 | public String getNome() {
30 | return nome;
31 | }
32 |
33 | public void setNome(String nome) {
34 | this.nome = nome;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/ClienteDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.validation.constraints.Email;
6 | import javax.validation.constraints.NotEmpty;
7 |
8 | import org.hibernate.validator.constraints.Length;
9 |
10 | import com.nelioalves.cursomc.domain.Cliente;
11 | import com.nelioalves.cursomc.services.validation.ClienteUpdate;
12 |
13 | @ClienteUpdate
14 | public class ClienteDTO implements Serializable {
15 | private static final long serialVersionUID = 1L;
16 |
17 | private Integer id;
18 |
19 | @NotEmpty(message="Preenchimento obrigatório")
20 | @Length(min=5, max=120, message="O tamanho deve ser entre 5 e 120 caracteres")
21 | private String nome;
22 |
23 | @NotEmpty(message="Preenchimento obrigatório")
24 | @Email(message="Email inválido")
25 | private String email;
26 |
27 | public ClienteDTO() {
28 | }
29 |
30 | public ClienteDTO(Cliente obj) {
31 | id = obj.getId();
32 | nome = obj.getNome();
33 | email = obj.getEmail();
34 | }
35 |
36 | public Integer getId() {
37 | return id;
38 | }
39 |
40 | public void setId(Integer id) {
41 | this.id = id;
42 | }
43 |
44 | public String getNome() {
45 | return nome;
46 | }
47 |
48 | public void setNome(String nome) {
49 | this.nome = nome;
50 | }
51 |
52 | public String getEmail() {
53 | return email;
54 | }
55 |
56 | public void setEmail(String email) {
57 | this.email = email;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/ClienteNewDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.validation.constraints.Email;
6 | import javax.validation.constraints.NotEmpty;
7 |
8 | import org.hibernate.validator.constraints.Length;
9 |
10 | import com.nelioalves.cursomc.services.validation.ClienteInsert;
11 |
12 | @ClienteInsert
13 | public class ClienteNewDTO implements Serializable {
14 | private static final long serialVersionUID = 1L;
15 |
16 | @NotEmpty(message="Preenchimento obrigatório")
17 | @Length(min=5, max=120, message="O tamanho deve ser entre 5 e 120 caracteres")
18 | private String nome;
19 |
20 | @NotEmpty(message="Preenchimento obrigatório")
21 | @Email(message="Email inválido")
22 | private String email;
23 |
24 | @NotEmpty(message="Preenchimento obrigatório")
25 | private String cpfOuCnpj;
26 |
27 | private Integer tipo;
28 |
29 | @NotEmpty(message="Preenchimento obrigatório")
30 | private String senha;
31 |
32 | @NotEmpty(message="Preenchimento obrigatório")
33 | private String logradouro;
34 |
35 | @NotEmpty(message="Preenchimento obrigatório")
36 | private String numero;
37 |
38 | private String complemento;
39 |
40 | private String bairro;
41 |
42 | @NotEmpty(message="Preenchimento obrigatório")
43 | private String cep;
44 |
45 | @NotEmpty(message="Preenchimento obrigatório")
46 | private String telefone1;
47 |
48 | private String telefone2;
49 |
50 | private String telefone3;
51 |
52 | private Integer cidadeId;
53 |
54 | public ClienteNewDTO() {
55 | }
56 |
57 | public String getNome() {
58 | return nome;
59 | }
60 |
61 | public void setNome(String nome) {
62 | this.nome = nome;
63 | }
64 |
65 | public String getEmail() {
66 | return email;
67 | }
68 |
69 | public void setEmail(String email) {
70 | this.email = email;
71 | }
72 |
73 | public String getCpfOuCnpj() {
74 | return cpfOuCnpj;
75 | }
76 |
77 | public void setCpfOuCnpj(String cpfOuCnpj) {
78 | this.cpfOuCnpj = cpfOuCnpj;
79 | }
80 |
81 | public Integer getTipo() {
82 | return tipo;
83 | }
84 |
85 | public void setTipo(Integer tipo) {
86 | this.tipo = tipo;
87 | }
88 |
89 | public String getLogradouro() {
90 | return logradouro;
91 | }
92 |
93 | public void setLogradouro(String logradouro) {
94 | this.logradouro = logradouro;
95 | }
96 |
97 | public String getNumero() {
98 | return numero;
99 | }
100 |
101 | public void setNumero(String numero) {
102 | this.numero = numero;
103 | }
104 |
105 | public String getComplemento() {
106 | return complemento;
107 | }
108 |
109 | public void setComplemento(String complemento) {
110 | this.complemento = complemento;
111 | }
112 |
113 | public String getBairro() {
114 | return bairro;
115 | }
116 |
117 | public void setBairro(String bairro) {
118 | this.bairro = bairro;
119 | }
120 |
121 | public String getCep() {
122 | return cep;
123 | }
124 |
125 | public void setCep(String cep) {
126 | this.cep = cep;
127 | }
128 |
129 | public String getTelefone1() {
130 | return telefone1;
131 | }
132 |
133 | public void setTelefone1(String telefone1) {
134 | this.telefone1 = telefone1;
135 | }
136 |
137 | public String getTelefone2() {
138 | return telefone2;
139 | }
140 |
141 | public void setTelefone2(String telefone2) {
142 | this.telefone2 = telefone2;
143 | }
144 |
145 | public String getTelefone3() {
146 | return telefone3;
147 | }
148 |
149 | public void setTelefone3(String telefone3) {
150 | this.telefone3 = telefone3;
151 | }
152 |
153 | public Integer getCidadeId() {
154 | return cidadeId;
155 | }
156 |
157 | public void setCidadeId(Integer cidadeId) {
158 | this.cidadeId = cidadeId;
159 | }
160 |
161 | public String getSenha() {
162 | return senha;
163 | }
164 |
165 | public void setSenha(String senha) {
166 | this.senha = senha;
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/CredenciaisDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | public class CredenciaisDTO implements Serializable {
6 | private static final long serialVersionUID = 1L;
7 |
8 | private String email;
9 | private String senha;
10 |
11 | public CredenciaisDTO() {
12 | }
13 |
14 | public String getEmail() {
15 | return email;
16 | }
17 | public void setEmail(String email) {
18 | this.email = email;
19 | }
20 | public String getSenha() {
21 | return senha;
22 | }
23 | public void setSenha(String senha) {
24 | this.senha = senha;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/EmailDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.validation.constraints.Email;
6 | import javax.validation.constraints.NotEmpty;
7 |
8 |
9 | public class EmailDTO implements Serializable {
10 | private static final long serialVersionUID = 1L;
11 |
12 | @NotEmpty(message="Preenchimento obrigatório")
13 | @Email(message="Email inválido")
14 | private String email;
15 |
16 | public EmailDTO() {
17 | }
18 |
19 | public String getEmail() {
20 | return email;
21 | }
22 |
23 | public void setEmail(String email) {
24 | this.email = email;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/EstadoDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import com.nelioalves.cursomc.domain.Estado;
6 |
7 | public class EstadoDTO implements Serializable {
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Integer id;
11 | private String nome;
12 |
13 | public EstadoDTO() {
14 | }
15 |
16 | public EstadoDTO(Estado obj) {
17 | id = obj.getId();
18 | nome = obj.getNome();
19 | }
20 |
21 | public Integer getId() {
22 | return id;
23 | }
24 |
25 | public void setId(Integer id) {
26 | this.id = id;
27 | }
28 |
29 | public String getNome() {
30 | return nome;
31 | }
32 |
33 | public void setNome(String nome) {
34 | this.nome = nome;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/dto/ProdutoDTO.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import com.nelioalves.cursomc.domain.Produto;
6 |
7 | public class ProdutoDTO implements Serializable {
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Integer id;
11 | private String nome;
12 | private Double preco;
13 |
14 | public ProdutoDTO() {
15 | }
16 |
17 | public ProdutoDTO(Produto obj) {
18 | id = obj.getId();
19 | nome = obj.getNome();
20 | preco = obj.getPreco();
21 | }
22 |
23 | public Integer getId() {
24 | return id;
25 | }
26 |
27 | public void setId(Integer id) {
28 | this.id = id;
29 | }
30 |
31 | public String getNome() {
32 | return nome;
33 | }
34 |
35 | public void setNome(String nome) {
36 | this.nome = nome;
37 | }
38 |
39 | public Double getPreco() {
40 | return preco;
41 | }
42 |
43 | public void setPreco(Double preco) {
44 | this.preco = preco;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/filters/HeaderExposureFilter.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.filters;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.Filter;
6 | import javax.servlet.FilterChain;
7 | import javax.servlet.FilterConfig;
8 | import javax.servlet.ServletException;
9 | import javax.servlet.ServletRequest;
10 | import javax.servlet.ServletResponse;
11 | import javax.servlet.http.HttpServletResponse;
12 |
13 | import org.springframework.stereotype.Component;
14 |
15 | @Component
16 | public class HeaderExposureFilter implements Filter {
17 |
18 | @Override
19 | public void init(FilterConfig filterConfig) throws ServletException {
20 | }
21 |
22 | @Override
23 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
24 | throws IOException, ServletException {
25 |
26 | HttpServletResponse res = (HttpServletResponse) response;
27 | res.addHeader("access-control-expose-headers", "location");
28 | chain.doFilter(request, response);
29 | }
30 |
31 | @Override
32 | public void destroy() {
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/CategoriaRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import com.nelioalves.cursomc.domain.Categoria;
7 |
8 | @Repository
9 | public interface CategoriaRepository extends JpaRepository {
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/CidadeRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.data.repository.query.Param;
8 | import org.springframework.stereotype.Repository;
9 | import org.springframework.transaction.annotation.Transactional;
10 |
11 | import com.nelioalves.cursomc.domain.Cidade;
12 |
13 | @Repository
14 | public interface CidadeRepository extends JpaRepository {
15 |
16 | @Transactional(readOnly=true)
17 | @Query("SELECT obj FROM Cidade obj WHERE obj.estado.id = :estadoId ORDER BY obj.nome")
18 | public List findCidades(@Param("estadoId") Integer estado_id);
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/ClienteRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 | import org.springframework.transaction.annotation.Transactional;
6 |
7 | import com.nelioalves.cursomc.domain.Cliente;
8 |
9 | @Repository
10 | public interface ClienteRepository extends JpaRepository {
11 |
12 | @Transactional(readOnly=true)
13 | Cliente findByEmail(String email);
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/EnderecoRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import com.nelioalves.cursomc.domain.Endereco;
7 |
8 | @Repository
9 | public interface EnderecoRepository extends JpaRepository {
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/EstadoRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.stereotype.Repository;
7 | import org.springframework.transaction.annotation.Transactional;
8 |
9 | import com.nelioalves.cursomc.domain.Estado;
10 |
11 | @Repository
12 | public interface EstadoRepository extends JpaRepository {
13 |
14 | @Transactional(readOnly=true)
15 | public List findAllByOrderByNome();
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/ItemPedidoRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import com.nelioalves.cursomc.domain.ItemPedido;
7 |
8 | @Repository
9 | public interface ItemPedidoRepository extends JpaRepository {
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/PagamentoRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import com.nelioalves.cursomc.domain.Pagamento;
7 |
8 | @Repository
9 | public interface PagamentoRepository extends JpaRepository {
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/PedidoRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.domain.Pageable;
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.stereotype.Repository;
7 | import org.springframework.transaction.annotation.Transactional;
8 |
9 | import com.nelioalves.cursomc.domain.Cliente;
10 | import com.nelioalves.cursomc.domain.Pedido;
11 |
12 | @Repository
13 | public interface PedidoRepository extends JpaRepository {
14 |
15 | @Transactional(readOnly=true)
16 | Page findByCliente(Cliente cliente, Pageable pageRequest);
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/repositories/ProdutoRepository.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.repositories;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Pageable;
7 | import org.springframework.data.jpa.repository.JpaRepository;
8 | import org.springframework.data.jpa.repository.Query;
9 | import org.springframework.data.repository.query.Param;
10 | import org.springframework.stereotype.Repository;
11 | import org.springframework.transaction.annotation.Transactional;
12 |
13 | import com.nelioalves.cursomc.domain.Categoria;
14 | import com.nelioalves.cursomc.domain.Produto;
15 |
16 | @Repository
17 | public interface ProdutoRepository extends JpaRepository {
18 |
19 | @Transactional(readOnly=true)
20 | @Query("SELECT DISTINCT obj FROM Produto obj INNER JOIN obj.categorias cat WHERE obj.nome LIKE %:nome% AND cat IN :categorias")
21 | Page findDistinctByNomeContainingAndCategoriasIn(@Param("nome") String nome, @Param("categorias") List categorias, Pageable pageRequest);
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/AuthResource.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources;
2 |
3 | import javax.servlet.http.HttpServletResponse;
4 | import javax.validation.Valid;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.RequestBody;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | import com.nelioalves.cursomc.dto.EmailDTO;
14 | import com.nelioalves.cursomc.security.JWTUtil;
15 | import com.nelioalves.cursomc.security.UserSS;
16 | import com.nelioalves.cursomc.services.AuthService;
17 | import com.nelioalves.cursomc.services.UserService;
18 |
19 | @RestController
20 | @RequestMapping(value = "/auth")
21 | public class AuthResource {
22 |
23 | @Autowired
24 | private JWTUtil jwtUtil;
25 |
26 | @Autowired
27 | private AuthService service;
28 |
29 | @RequestMapping(value = "/refresh_token", method = RequestMethod.POST)
30 | public ResponseEntity refreshToken(HttpServletResponse response) {
31 | UserSS user = UserService.authenticated();
32 | String token = jwtUtil.generateToken(user.getUsername());
33 | response.addHeader("Authorization", "Bearer " + token);
34 | response.addHeader("access-control-expose-headers", "Authorization");
35 | return ResponseEntity.noContent().build();
36 | }
37 |
38 | @RequestMapping(value = "/forgot", method = RequestMethod.POST)
39 | public ResponseEntity forgot(@Valid @RequestBody EmailDTO objDto) {
40 | service.sendNewPassword(objDto.getEmail());
41 | return ResponseEntity.noContent().build();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/CategoriaResource.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources;
2 |
3 | import java.net.URI;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | import javax.validation.Valid;
8 |
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.security.access.prepost.PreAuthorize;
13 | import org.springframework.web.bind.annotation.PathVariable;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RequestMapping;
16 | import org.springframework.web.bind.annotation.RequestMethod;
17 | import org.springframework.web.bind.annotation.RequestParam;
18 | import org.springframework.web.bind.annotation.RestController;
19 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
20 |
21 | import com.nelioalves.cursomc.domain.Categoria;
22 | import com.nelioalves.cursomc.dto.CategoriaDTO;
23 | import com.nelioalves.cursomc.services.CategoriaService;
24 |
25 | @RestController
26 | @RequestMapping(value="/categorias")
27 | public class CategoriaResource {
28 |
29 | @Autowired
30 | private CategoriaService service;
31 |
32 | @RequestMapping(value="/{id}", method=RequestMethod.GET)
33 | public ResponseEntity find(@PathVariable Integer id) {
34 | Categoria obj = service.find(id);
35 | return ResponseEntity.ok().body(obj);
36 | }
37 |
38 | @PreAuthorize("hasAnyRole('ADMIN')")
39 | @RequestMapping(method=RequestMethod.POST)
40 | public ResponseEntity insert(@Valid @RequestBody CategoriaDTO objDto) {
41 | Categoria obj = service.fromDTO(objDto);
42 | obj = service.insert(obj);
43 | URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
44 | .path("/{id}").buildAndExpand(obj.getId()).toUri();
45 | return ResponseEntity.created(uri).build();
46 | }
47 |
48 | @PreAuthorize("hasAnyRole('ADMIN')")
49 | @RequestMapping(value="/{id}", method=RequestMethod.PUT)
50 | public ResponseEntity update(@Valid @RequestBody CategoriaDTO objDto, @PathVariable Integer id) {
51 | Categoria obj = service.fromDTO(objDto);
52 | obj.setId(id);
53 | obj = service.update(obj);
54 | return ResponseEntity.noContent().build();
55 | }
56 |
57 | @PreAuthorize("hasAnyRole('ADMIN')")
58 | @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
59 | public ResponseEntity delete(@PathVariable Integer id) {
60 | service.delete(id);
61 | return ResponseEntity.noContent().build();
62 | }
63 |
64 | @RequestMapping(method=RequestMethod.GET)
65 | public ResponseEntity> findAll() {
66 | List list = service.findAll();
67 | List listDto = list.stream().map(obj -> new CategoriaDTO(obj)).collect(Collectors.toList());
68 | return ResponseEntity.ok().body(listDto);
69 | }
70 |
71 | @RequestMapping(value="/page", method=RequestMethod.GET)
72 | public ResponseEntity> findPage(
73 | @RequestParam(value="page", defaultValue="0") Integer page,
74 | @RequestParam(value="linesPerPage", defaultValue="24") Integer linesPerPage,
75 | @RequestParam(value="orderBy", defaultValue="nome") String orderBy,
76 | @RequestParam(value="direction", defaultValue="ASC") String direction) {
77 | Page list = service.findPage(page, linesPerPage, orderBy, direction);
78 | Page listDto = list.map(obj -> new CategoriaDTO(obj));
79 | return ResponseEntity.ok().body(listDto);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/ClienteResource.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources;
2 |
3 | import java.net.URI;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | import javax.validation.Valid;
8 |
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.security.access.prepost.PreAuthorize;
13 | import org.springframework.web.bind.annotation.PathVariable;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RequestMapping;
16 | import org.springframework.web.bind.annotation.RequestMethod;
17 | import org.springframework.web.bind.annotation.RequestParam;
18 | import org.springframework.web.bind.annotation.RestController;
19 | import org.springframework.web.multipart.MultipartFile;
20 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
21 |
22 | import com.nelioalves.cursomc.domain.Cliente;
23 | import com.nelioalves.cursomc.dto.ClienteDTO;
24 | import com.nelioalves.cursomc.dto.ClienteNewDTO;
25 | import com.nelioalves.cursomc.services.ClienteService;
26 |
27 | @RestController
28 | @RequestMapping(value="/clientes")
29 | public class ClienteResource {
30 |
31 | @Autowired
32 | private ClienteService service;
33 |
34 | @RequestMapping(value="/{id}", method=RequestMethod.GET)
35 | public ResponseEntity find(@PathVariable Integer id) {
36 | Cliente obj = service.find(id);
37 | return ResponseEntity.ok().body(obj);
38 | }
39 |
40 | @RequestMapping(value="/email", method=RequestMethod.GET)
41 | public ResponseEntity find(@RequestParam(value="value") String email) {
42 | Cliente obj = service.findByEmail(email);
43 | return ResponseEntity.ok().body(obj);
44 | }
45 |
46 | @RequestMapping(method=RequestMethod.POST)
47 | public ResponseEntity insert(@Valid @RequestBody ClienteNewDTO objDto) {
48 | Cliente obj = service.fromDTO(objDto);
49 | obj = service.insert(obj);
50 | URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
51 | .path("/{id}").buildAndExpand(obj.getId()).toUri();
52 | return ResponseEntity.created(uri).build();
53 | }
54 |
55 | @RequestMapping(value="/{id}", method=RequestMethod.PUT)
56 | public ResponseEntity update(@Valid @RequestBody ClienteDTO objDto, @PathVariable Integer id) {
57 | Cliente obj = service.fromDTO(objDto);
58 | obj.setId(id);
59 | obj = service.update(obj);
60 | return ResponseEntity.noContent().build();
61 | }
62 |
63 | @PreAuthorize("hasAnyRole('ADMIN')")
64 | @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
65 | public ResponseEntity delete(@PathVariable Integer id) {
66 | service.delete(id);
67 | return ResponseEntity.noContent().build();
68 | }
69 |
70 | @PreAuthorize("hasAnyRole('ADMIN')")
71 | @RequestMapping(method=RequestMethod.GET)
72 | public ResponseEntity> findAll() {
73 | List list = service.findAll();
74 | List listDto = list.stream().map(obj -> new ClienteDTO(obj)).collect(Collectors.toList());
75 | return ResponseEntity.ok().body(listDto);
76 | }
77 |
78 | @PreAuthorize("hasAnyRole('ADMIN')")
79 | @RequestMapping(value="/page", method=RequestMethod.GET)
80 | public ResponseEntity> findPage(
81 | @RequestParam(value="page", defaultValue="0") Integer page,
82 | @RequestParam(value="linesPerPage", defaultValue="24") Integer linesPerPage,
83 | @RequestParam(value="orderBy", defaultValue="nome") String orderBy,
84 | @RequestParam(value="direction", defaultValue="ASC") String direction) {
85 | Page list = service.findPage(page, linesPerPage, orderBy, direction);
86 | Page listDto = list.map(obj -> new ClienteDTO(obj));
87 | return ResponseEntity.ok().body(listDto);
88 | }
89 |
90 | @RequestMapping(value="/picture", method=RequestMethod.POST)
91 | public ResponseEntity uploadProfilePicture(@RequestParam(name="file") MultipartFile file) {
92 | URI uri = service.uploadProfilePicture(file);
93 | return ResponseEntity.created(uri).build();
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/EstadoResource.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources;
2 |
3 | import java.util.List;
4 | import java.util.stream.Collectors;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.PathVariable;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | import com.nelioalves.cursomc.domain.Cidade;
14 | import com.nelioalves.cursomc.domain.Estado;
15 | import com.nelioalves.cursomc.dto.CidadeDTO;
16 | import com.nelioalves.cursomc.dto.EstadoDTO;
17 | import com.nelioalves.cursomc.services.CidadeService;
18 | import com.nelioalves.cursomc.services.EstadoService;
19 |
20 | @RestController
21 | @RequestMapping(value="/estados")
22 | public class EstadoResource {
23 |
24 | @Autowired
25 | private EstadoService service;
26 |
27 | @Autowired
28 | private CidadeService cidadeService;
29 |
30 | @RequestMapping(method=RequestMethod.GET)
31 | public ResponseEntity> findAll() {
32 | List list = service.findAll();
33 | List listDto = list.stream().map(obj -> new EstadoDTO(obj)).collect(Collectors.toList());
34 | return ResponseEntity.ok().body(listDto);
35 | }
36 |
37 | @RequestMapping(value="/{estadoId}/cidades", method=RequestMethod.GET)
38 | public ResponseEntity> findCidades(@PathVariable Integer estadoId) {
39 | List list = cidadeService.findByEstado(estadoId);
40 | List listDto = list.stream().map(obj -> new CidadeDTO(obj)).collect(Collectors.toList());
41 | return ResponseEntity.ok().body(listDto);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/PedidoResource.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources;
2 |
3 | import java.net.URI;
4 |
5 | import javax.validation.Valid;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.data.domain.Page;
9 | import org.springframework.http.ResponseEntity;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.RequestBody;
12 | import org.springframework.web.bind.annotation.RequestMapping;
13 | import org.springframework.web.bind.annotation.RequestMethod;
14 | import org.springframework.web.bind.annotation.RequestParam;
15 | import org.springframework.web.bind.annotation.RestController;
16 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
17 |
18 | import com.nelioalves.cursomc.domain.Pedido;
19 | import com.nelioalves.cursomc.services.PedidoService;
20 |
21 | @RestController
22 | @RequestMapping(value="/pedidos")
23 | public class PedidoResource {
24 |
25 | @Autowired
26 | private PedidoService service;
27 |
28 | @RequestMapping(value="/{id}", method=RequestMethod.GET)
29 | public ResponseEntity find(@PathVariable Integer id) {
30 | Pedido obj = service.find(id);
31 | return ResponseEntity.ok().body(obj);
32 | }
33 |
34 | @RequestMapping(method=RequestMethod.POST)
35 | public ResponseEntity insert(@Valid @RequestBody Pedido obj) {
36 | obj = service.insert(obj);
37 | URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
38 | .path("/{id}").buildAndExpand(obj.getId()).toUri();
39 | return ResponseEntity.created(uri).build();
40 | }
41 |
42 | @RequestMapping(method=RequestMethod.GET)
43 | public ResponseEntity> findPage(
44 | @RequestParam(value="page", defaultValue="0") Integer page,
45 | @RequestParam(value="linesPerPage", defaultValue="24") Integer linesPerPage,
46 | @RequestParam(value="orderBy", defaultValue="instante") String orderBy,
47 | @RequestParam(value="direction", defaultValue="DESC") String direction) {
48 | Page list = service.findPage(page, linesPerPage, orderBy, direction);
49 | return ResponseEntity.ok().body(list);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/ProdutoResource.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.data.domain.Page;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.PathVariable;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 | import org.springframework.web.bind.annotation.RequestParam;
12 | import org.springframework.web.bind.annotation.RestController;
13 |
14 | import com.nelioalves.cursomc.domain.Produto;
15 | import com.nelioalves.cursomc.dto.ProdutoDTO;
16 | import com.nelioalves.cursomc.resources.utils.URL;
17 | import com.nelioalves.cursomc.services.ProdutoService;
18 |
19 | @RestController
20 | @RequestMapping(value="/produtos")
21 | public class ProdutoResource {
22 |
23 | @Autowired
24 | private ProdutoService service;
25 |
26 | @RequestMapping(value="/{id}", method=RequestMethod.GET)
27 | public ResponseEntity find(@PathVariable Integer id) {
28 | Produto obj = service.find(id);
29 | return ResponseEntity.ok().body(obj);
30 | }
31 |
32 | @RequestMapping(method=RequestMethod.GET)
33 | public ResponseEntity> findPage(
34 | @RequestParam(value="nome", defaultValue="") String nome,
35 | @RequestParam(value="categorias", defaultValue="") String categorias,
36 | @RequestParam(value="page", defaultValue="0") Integer page,
37 | @RequestParam(value="linesPerPage", defaultValue="24") Integer linesPerPage,
38 | @RequestParam(value="orderBy", defaultValue="nome") String orderBy,
39 | @RequestParam(value="direction", defaultValue="ASC") String direction) {
40 | String nomeDecoded = URL.decodeParam(nome);
41 | List ids = URL.decodeIntList(categorias);
42 | Page list = service.search(nomeDecoded, ids, page, linesPerPage, orderBy, direction);
43 | Page listDto = list.map(obj -> new ProdutoDTO(obj));
44 | return ResponseEntity.ok().body(listDto);
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/exception/FieldMessage.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources.exception;
2 |
3 | import java.io.Serializable;
4 |
5 | public class FieldMessage implements Serializable {
6 | private static final long serialVersionUID = 1L;
7 |
8 | private String fieldName;
9 | private String message;
10 |
11 | public FieldMessage() {
12 | }
13 |
14 | public FieldMessage(String fieldName, String message) {
15 | super();
16 | this.fieldName = fieldName;
17 | this.message = message;
18 | }
19 |
20 | public String getFieldName() {
21 | return fieldName;
22 | }
23 |
24 | public void setFieldName(String fieldName) {
25 | this.fieldName = fieldName;
26 | }
27 |
28 | public String getMessage() {
29 | return message;
30 | }
31 |
32 | public void setMessage(String message) {
33 | this.message = message;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/exception/ResourceExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources.exception;
2 |
3 | import javax.servlet.http.HttpServletRequest;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.validation.FieldError;
8 | import org.springframework.web.bind.MethodArgumentNotValidException;
9 | import org.springframework.web.bind.annotation.ControllerAdvice;
10 | import org.springframework.web.bind.annotation.ExceptionHandler;
11 |
12 | import com.amazonaws.AmazonClientException;
13 | import com.amazonaws.AmazonServiceException;
14 | import com.amazonaws.services.s3.model.AmazonS3Exception;
15 | import com.nelioalves.cursomc.services.exceptions.AuthorizationException;
16 | import com.nelioalves.cursomc.services.exceptions.DataIntegrityException;
17 | import com.nelioalves.cursomc.services.exceptions.FileException;
18 | import com.nelioalves.cursomc.services.exceptions.ObjectNotFoundException;
19 |
20 | @ControllerAdvice
21 | public class ResourceExceptionHandler {
22 |
23 | @ExceptionHandler(ObjectNotFoundException.class)
24 | public ResponseEntity objectNotFound(ObjectNotFoundException e, HttpServletRequest request) {
25 |
26 | StandardError err = new StandardError(System.currentTimeMillis(), HttpStatus.NOT_FOUND.value(), "Não encontrado", e.getMessage(), request.getRequestURI());
27 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
28 | }
29 |
30 | @ExceptionHandler(DataIntegrityException.class)
31 | public ResponseEntity dataIntegrity(DataIntegrityException e, HttpServletRequest request) {
32 |
33 | StandardError err = new StandardError(System.currentTimeMillis(), HttpStatus.BAD_REQUEST.value(), "Integridade de dados", e.getMessage(), request.getRequestURI());
34 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
35 | }
36 |
37 | @ExceptionHandler(MethodArgumentNotValidException.class)
38 | public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest request) {
39 |
40 | ValidationError err = new ValidationError(System.currentTimeMillis(), HttpStatus.UNPROCESSABLE_ENTITY.value(), "Erro de validação", e.getMessage(), request.getRequestURI());
41 | for (FieldError x : e.getBindingResult().getFieldErrors()) {
42 | err.addError(x.getField(), x.getDefaultMessage());
43 | }
44 | return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(err);
45 | }
46 |
47 | @ExceptionHandler(AuthorizationException.class)
48 | public ResponseEntity authorization(AuthorizationException e, HttpServletRequest request) {
49 |
50 | StandardError err = new StandardError(System.currentTimeMillis(), HttpStatus.FORBIDDEN.value(), "Acesso negado", e.getMessage(), request.getRequestURI());
51 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(err);
52 | }
53 |
54 | @ExceptionHandler(FileException.class)
55 | public ResponseEntity file(FileException e, HttpServletRequest request) {
56 |
57 | StandardError err = new StandardError(System.currentTimeMillis(), HttpStatus.BAD_REQUEST.value(), "Erro de arquivo", e.getMessage(), request.getRequestURI());
58 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
59 | }
60 |
61 | @ExceptionHandler(AmazonServiceException.class)
62 | public ResponseEntity amazonService(AmazonServiceException e, HttpServletRequest request) {
63 |
64 | HttpStatus code = HttpStatus.valueOf(e.getErrorCode());
65 | StandardError err = new StandardError(System.currentTimeMillis(), code.value(), "Erro Amazon Service", e.getMessage(), request.getRequestURI());
66 | return ResponseEntity.status(code).body(err);
67 | }
68 |
69 | @ExceptionHandler(AmazonClientException.class)
70 | public ResponseEntity amazonClient(AmazonClientException e, HttpServletRequest request) {
71 |
72 | StandardError err = new StandardError(System.currentTimeMillis(), HttpStatus.BAD_REQUEST.value(), "Erro Amazon Client", e.getMessage(), request.getRequestURI());
73 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
74 | }
75 |
76 | @ExceptionHandler(AmazonS3Exception.class)
77 | public ResponseEntity amazonS3(AmazonS3Exception e, HttpServletRequest request) {
78 |
79 | StandardError err = new StandardError(System.currentTimeMillis(), HttpStatus.BAD_REQUEST.value(), "Erro S3", e.getMessage(), request.getRequestURI());
80 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/exception/StandardError.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources.exception;
2 |
3 | import java.io.Serializable;
4 |
5 | public class StandardError implements Serializable {
6 | private static final long serialVersionUID = 1L;
7 |
8 | private Long timestamp;
9 | private Integer status;
10 | private String error;
11 | private String message;
12 | private String path;
13 |
14 | public StandardError(Long timestamp, Integer status, String error, String message, String path) {
15 | super();
16 | this.timestamp = timestamp;
17 | this.status = status;
18 | this.error = error;
19 | this.message = message;
20 | this.path = path;
21 | }
22 |
23 | public Long getTimestamp() {
24 | return timestamp;
25 | }
26 |
27 | public void setTimestamp(Long timestamp) {
28 | this.timestamp = timestamp;
29 | }
30 |
31 | public Integer getStatus() {
32 | return status;
33 | }
34 |
35 | public void setStatus(Integer status) {
36 | this.status = status;
37 | }
38 |
39 | public String getError() {
40 | return error;
41 | }
42 |
43 | public void setError(String error) {
44 | this.error = error;
45 | }
46 |
47 | public String getMessage() {
48 | return message;
49 | }
50 |
51 | public void setMessage(String message) {
52 | this.message = message;
53 | }
54 |
55 | public String getPath() {
56 | return path;
57 | }
58 |
59 | public void setPath(String path) {
60 | this.path = path;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/exception/ValidationError.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources.exception;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class ValidationError extends StandardError {
7 | private static final long serialVersionUID = 1L;
8 |
9 | private List errors = new ArrayList<>();
10 |
11 | public ValidationError(Long timestamp, Integer status, String error, String message, String path) {
12 | super(timestamp, status, error, message, path);
13 | }
14 |
15 | public List getErrors() {
16 | return errors;
17 | }
18 |
19 | public void addError(String fieldName, String messagem) {
20 | errors.add(new FieldMessage(fieldName, messagem));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/resources/utils/URL.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.resources.utils;
2 |
3 | import java.io.UnsupportedEncodingException;
4 | import java.net.URLDecoder;
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | public class URL {
9 |
10 | public static String decodeParam(String s) {
11 | try {
12 | return URLDecoder.decode(s, "UTF-8");
13 | }
14 | catch (UnsupportedEncodingException e) {
15 | return "";
16 | }
17 | }
18 |
19 | public static List decodeIntList(String s) {
20 | String[] vet = s.split(",");
21 | List list = new ArrayList<>();
22 | for (int i=0; i Integer.parseInt(x)).collect(Collectors.toList());
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/security/JWTAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.security;
2 |
3 | import java.io.IOException;
4 | import java.util.ArrayList;
5 | import java.util.Date;
6 |
7 | import javax.servlet.FilterChain;
8 | import javax.servlet.ServletException;
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 |
12 | import org.springframework.security.authentication.AuthenticationManager;
13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
14 | import org.springframework.security.core.Authentication;
15 | import org.springframework.security.core.AuthenticationException;
16 | import org.springframework.security.web.authentication.AuthenticationFailureHandler;
17 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
18 |
19 | import com.fasterxml.jackson.databind.ObjectMapper;
20 | import com.nelioalves.cursomc.dto.CredenciaisDTO;
21 |
22 | public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
23 |
24 | private AuthenticationManager authenticationManager;
25 |
26 | private JWTUtil jwtUtil;
27 |
28 | public JWTAuthenticationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) {
29 | setAuthenticationFailureHandler(new JWTAuthenticationFailureHandler());
30 | this.authenticationManager = authenticationManager;
31 | this.jwtUtil = jwtUtil;
32 | }
33 |
34 | @Override
35 | public Authentication attemptAuthentication(HttpServletRequest req,
36 | HttpServletResponse res) throws AuthenticationException {
37 |
38 | try {
39 | CredenciaisDTO creds = new ObjectMapper()
40 | .readValue(req.getInputStream(), CredenciaisDTO.class);
41 |
42 | UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getSenha(), new ArrayList<>());
43 |
44 | Authentication auth = authenticationManager.authenticate(authToken);
45 | return auth;
46 | }
47 | catch (IOException e) {
48 | throw new RuntimeException(e);
49 | }
50 | }
51 |
52 | @Override
53 | protected void successfulAuthentication(HttpServletRequest req,
54 | HttpServletResponse res,
55 | FilterChain chain,
56 | Authentication auth) throws IOException, ServletException {
57 |
58 | String username = ((UserSS) auth.getPrincipal()).getUsername();
59 | String token = jwtUtil.generateToken(username);
60 | res.addHeader("Authorization", "Bearer " + token);
61 | res.addHeader("access-control-expose-headers", "Authorization");
62 | }
63 |
64 | private class JWTAuthenticationFailureHandler implements AuthenticationFailureHandler {
65 |
66 | @Override
67 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
68 | throws IOException, ServletException {
69 | response.setStatus(401);
70 | response.setContentType("application/json");
71 | response.getWriter().append(json());
72 | }
73 |
74 | private String json() {
75 | long date = new Date().getTime();
76 | return "{\"timestamp\": " + date + ", "
77 | + "\"status\": 401, "
78 | + "\"error\": \"Não autorizado\", "
79 | + "\"message\": \"Email ou senha inválidos\", "
80 | + "\"path\": \"/login\"}";
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/security/JWTAuthorizationFilter.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.security;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.FilterChain;
6 | import javax.servlet.ServletException;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import org.springframework.security.authentication.AuthenticationManager;
11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
12 | import org.springframework.security.core.context.SecurityContextHolder;
13 | import org.springframework.security.core.userdetails.UserDetails;
14 | import org.springframework.security.core.userdetails.UserDetailsService;
15 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
16 |
17 | public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
18 |
19 | private JWTUtil jwtUtil;
20 |
21 | private UserDetailsService userDetailsService;
22 |
23 | public JWTAuthorizationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil, UserDetailsService userDetailsService) {
24 | super(authenticationManager);
25 | this.jwtUtil = jwtUtil;
26 | this.userDetailsService = userDetailsService;
27 | }
28 |
29 | @Override
30 | protected void doFilterInternal(HttpServletRequest request,
31 | HttpServletResponse response,
32 | FilterChain chain) throws IOException, ServletException {
33 |
34 | String header = request.getHeader("Authorization");
35 | if (header != null && header.startsWith("Bearer ")) {
36 | UsernamePasswordAuthenticationToken auth = getAuthentication(header.substring(7));
37 | if (auth != null) {
38 | SecurityContextHolder.getContext().setAuthentication(auth);
39 | }
40 | }
41 | chain.doFilter(request, response);
42 | }
43 |
44 | private UsernamePasswordAuthenticationToken getAuthentication(String token) {
45 | if (jwtUtil.tokenValido(token)) {
46 | String username = jwtUtil.getUsername(token);
47 | UserDetails user = userDetailsService.loadUserByUsername(username);
48 | return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
49 | }
50 | return null;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/security/JWTUtil.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.security;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.beans.factory.annotation.Value;
6 | import org.springframework.stereotype.Component;
7 |
8 | import io.jsonwebtoken.Claims;
9 | import io.jsonwebtoken.Jwts;
10 | import io.jsonwebtoken.SignatureAlgorithm;
11 |
12 | @Component
13 | public class JWTUtil {
14 |
15 | @Value("${jwt.secret}")
16 | private String secret;
17 |
18 | @Value("${jwt.expiration}")
19 | private Long expiration;
20 |
21 | public String generateToken(String username) {
22 | return Jwts.builder()
23 | .setSubject(username)
24 | .setExpiration(new Date(System.currentTimeMillis() + expiration))
25 | .signWith(SignatureAlgorithm.HS512, secret.getBytes())
26 | .compact();
27 | }
28 |
29 | public boolean tokenValido(String token) {
30 | Claims claims = getClaims(token);
31 | if (claims != null) {
32 | String username = claims.getSubject();
33 | Date expirationDate = claims.getExpiration();
34 | Date now = new Date(System.currentTimeMillis());
35 | if (username != null && expirationDate != null && now.before(expirationDate)) {
36 | return true;
37 | }
38 | }
39 | return false;
40 | }
41 |
42 | public String getUsername(String token) {
43 | Claims claims = getClaims(token);
44 | if (claims != null) {
45 | return claims.getSubject();
46 | }
47 | return null;
48 | }
49 |
50 | private Claims getClaims(String token) {
51 | try {
52 | return Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(token).getBody();
53 | }
54 | catch (Exception e) {
55 | return null;
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/security/UserSS.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.security;
2 |
3 | import java.util.Collection;
4 | import java.util.Set;
5 | import java.util.stream.Collectors;
6 |
7 | import org.springframework.security.core.GrantedAuthority;
8 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
9 | import org.springframework.security.core.userdetails.UserDetails;
10 |
11 | import com.nelioalves.cursomc.domain.enums.Perfil;
12 |
13 | public class UserSS implements UserDetails {
14 | private static final long serialVersionUID = 1L;
15 |
16 | private Integer id;
17 | private String email;
18 | private String senha;
19 | private Collection extends GrantedAuthority> authorities;
20 |
21 | public UserSS() {
22 | }
23 |
24 | public UserSS(Integer id, String email, String senha, Set perfis) {
25 | super();
26 | this.id = id;
27 | this.email = email;
28 | this.senha = senha;
29 | this.authorities = perfis.stream().map(x -> new SimpleGrantedAuthority(x.getDescricao())).collect(Collectors.toList());
30 | }
31 |
32 | public Integer getId() {
33 | return id;
34 | }
35 |
36 | @Override
37 | public Collection extends GrantedAuthority> getAuthorities() {
38 | return authorities;
39 | }
40 |
41 | @Override
42 | public String getPassword() {
43 | return senha;
44 | }
45 |
46 | @Override
47 | public String getUsername() {
48 | return email;
49 | }
50 |
51 | @Override
52 | public boolean isAccountNonExpired() {
53 | return true;
54 | }
55 |
56 | @Override
57 | public boolean isAccountNonLocked() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public boolean isCredentialsNonExpired() {
63 | return true;
64 | }
65 |
66 | @Override
67 | public boolean isEnabled() {
68 | return true;
69 | }
70 |
71 | public boolean hasRole(Perfil perfil) {
72 | return getAuthorities().contains(new SimpleGrantedAuthority(perfil.getDescricao()));
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/AbstractEmailService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.beans.factory.annotation.Value;
6 | import org.springframework.mail.SimpleMailMessage;
7 |
8 | import com.nelioalves.cursomc.domain.Cliente;
9 | import com.nelioalves.cursomc.domain.Pedido;
10 |
11 | public abstract class AbstractEmailService implements EmailService {
12 |
13 | @Value("${default.sender}")
14 | private String sender;
15 |
16 | @Override
17 | public void sendOrderConfirmationEmail(Pedido obj) {
18 | SimpleMailMessage sm = prepareSimpleMailMessageFromPedido(obj);
19 | sendEmail(sm);
20 | }
21 |
22 | protected SimpleMailMessage prepareSimpleMailMessageFromPedido(Pedido obj) {
23 | SimpleMailMessage sm = new SimpleMailMessage();
24 | sm.setTo(obj.getCliente().getEmail());
25 | sm.setFrom(sender);
26 | sm.setSubject("Pedido confirmado! Código: " + obj.getId());
27 | sm.setSentDate(new Date(System.currentTimeMillis()));
28 | sm.setText(obj.toString());
29 | return sm;
30 | }
31 |
32 | @Override
33 | public void sendNewPasswordEmail(Cliente cliente, String newPass) {
34 | SimpleMailMessage sm = prepareNewPasswordEmail(cliente, newPass);
35 | sendEmail(sm);
36 | }
37 |
38 | protected SimpleMailMessage prepareNewPasswordEmail(Cliente cliente, String newPass) {
39 | SimpleMailMessage sm = new SimpleMailMessage();
40 | sm.setTo(cliente.getEmail());
41 | sm.setFrom(sender);
42 | sm.setSubject("Solicitação de nova senha");
43 | sm.setSentDate(new Date(System.currentTimeMillis()));
44 | sm.setText("Nova senha: " + newPass);
45 | return sm;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/AuthService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.Random;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
7 | import org.springframework.stereotype.Service;
8 |
9 | import com.nelioalves.cursomc.domain.Cliente;
10 | import com.nelioalves.cursomc.repositories.ClienteRepository;
11 | import com.nelioalves.cursomc.services.exceptions.ObjectNotFoundException;
12 |
13 | @Service
14 | public class AuthService {
15 |
16 | @Autowired
17 | private ClienteRepository clienteRepository;
18 |
19 | @Autowired
20 | private BCryptPasswordEncoder pe;
21 |
22 | @Autowired
23 | private EmailService emailService;
24 |
25 | private Random rand = new Random();
26 |
27 | public void sendNewPassword(String email) {
28 |
29 | Cliente cliente = clienteRepository.findByEmail(email);
30 | if (cliente == null) {
31 | throw new ObjectNotFoundException("Email não encontrado");
32 | }
33 |
34 | String newPass = newPassword();
35 | cliente.setSenha(pe.encode(newPass));
36 |
37 | clienteRepository.save(cliente);
38 | emailService.sendNewPasswordEmail(cliente, newPass);
39 | }
40 |
41 | private String newPassword() {
42 | char[] vet = new char[10];
43 | for (int i=0; i<10; i++) {
44 | vet[i] = randomChar();
45 | }
46 | return new String(vet);
47 | }
48 |
49 | private char randomChar() {
50 | int opt = rand.nextInt(3);
51 | if (opt == 0) { // gera um digito
52 | return (char) (rand.nextInt(10) + 48);
53 | }
54 | else if (opt == 1) { // gera letra maiuscula
55 | return (char) (rand.nextInt(26) + 65);
56 | }
57 | else { // gera letra minuscula
58 | return (char) (rand.nextInt(26) + 97);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/BoletoService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.Calendar;
4 | import java.util.Date;
5 |
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.nelioalves.cursomc.domain.PagamentoComBoleto;
9 |
10 | @Service
11 | public class BoletoService {
12 |
13 | public void preencherPagamentoComBoleto(PagamentoComBoleto pagto, Date instanteDoPedido) {
14 | Calendar cal = Calendar.getInstance();
15 | cal.setTime(instanteDoPedido);
16 | cal.add(Calendar.DAY_OF_MONTH, 7);
17 | pagto.setDataVencimento(cal.getTime());
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/CategoriaService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.dao.DataIntegrityViolationException;
8 | import org.springframework.data.domain.Page;
9 | import org.springframework.data.domain.PageRequest;
10 | import org.springframework.data.domain.Sort.Direction;
11 | import org.springframework.stereotype.Service;
12 |
13 | import com.nelioalves.cursomc.domain.Categoria;
14 | import com.nelioalves.cursomc.dto.CategoriaDTO;
15 | import com.nelioalves.cursomc.repositories.CategoriaRepository;
16 | import com.nelioalves.cursomc.services.exceptions.DataIntegrityException;
17 | import com.nelioalves.cursomc.services.exceptions.ObjectNotFoundException;
18 |
19 | @Service
20 | public class CategoriaService {
21 |
22 | @Autowired
23 | private CategoriaRepository repo;
24 |
25 | public Categoria find(Integer id) {
26 | Optional obj = repo.findById(id);
27 | return obj.orElseThrow(() -> new ObjectNotFoundException(
28 | "Objeto não encontrado! Id: " + id + ", Tipo: " + Categoria.class.getName()));
29 | }
30 |
31 | public Categoria insert(Categoria obj) {
32 | obj.setId(null);
33 | return repo.save(obj);
34 | }
35 |
36 | public Categoria update(Categoria obj) {
37 | Categoria newObj = find(obj.getId());
38 | updateData(newObj, obj);
39 | return repo.save(newObj);
40 | }
41 |
42 | public void delete(Integer id) {
43 | find(id);
44 | try {
45 | repo.deleteById(id);
46 | }
47 | catch (DataIntegrityViolationException e) {
48 | throw new DataIntegrityException("Não é possível excluir uma categoria que possui produtos");
49 | }
50 | }
51 |
52 | public List findAll() {
53 | return repo.findAll();
54 | }
55 |
56 | public Page findPage(Integer page, Integer linesPerPage, String orderBy, String direction) {
57 | PageRequest pageRequest = PageRequest.of(page, linesPerPage, Direction.valueOf(direction), orderBy);
58 | return repo.findAll(pageRequest);
59 | }
60 |
61 | public Categoria fromDTO(CategoriaDTO objDto) {
62 | return new Categoria(objDto.getId(), objDto.getNome());
63 | }
64 |
65 | private void updateData(Categoria newObj, Categoria obj) {
66 | newObj.setNome(obj.getNome());
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/CidadeService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.nelioalves.cursomc.domain.Cidade;
9 | import com.nelioalves.cursomc.repositories.CidadeRepository;
10 |
11 | @Service
12 | public class CidadeService {
13 |
14 | @Autowired
15 | private CidadeRepository repo;
16 |
17 | public List findByEstado(Integer estadoId) {
18 | return repo.findCidades(estadoId);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/ClienteService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.awt.image.BufferedImage;
4 | import java.net.URI;
5 | import java.util.List;
6 | import java.util.Optional;
7 |
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.beans.factory.annotation.Value;
10 | import org.springframework.dao.DataIntegrityViolationException;
11 | import org.springframework.data.domain.Page;
12 | import org.springframework.data.domain.PageRequest;
13 | import org.springframework.data.domain.Sort.Direction;
14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
15 | import org.springframework.stereotype.Service;
16 | import org.springframework.transaction.annotation.Transactional;
17 | import org.springframework.web.multipart.MultipartFile;
18 |
19 | import com.nelioalves.cursomc.domain.Cidade;
20 | import com.nelioalves.cursomc.domain.Cliente;
21 | import com.nelioalves.cursomc.domain.Endereco;
22 | import com.nelioalves.cursomc.domain.enums.Perfil;
23 | import com.nelioalves.cursomc.domain.enums.TipoCliente;
24 | import com.nelioalves.cursomc.dto.ClienteDTO;
25 | import com.nelioalves.cursomc.dto.ClienteNewDTO;
26 | import com.nelioalves.cursomc.repositories.ClienteRepository;
27 | import com.nelioalves.cursomc.repositories.EnderecoRepository;
28 | import com.nelioalves.cursomc.security.UserSS;
29 | import com.nelioalves.cursomc.services.exceptions.AuthorizationException;
30 | import com.nelioalves.cursomc.services.exceptions.DataIntegrityException;
31 | import com.nelioalves.cursomc.services.exceptions.ObjectNotFoundException;
32 |
33 | @Service
34 | public class ClienteService {
35 |
36 | @Autowired
37 | private ClienteRepository repo;
38 |
39 | @Autowired
40 | private EnderecoRepository enderecoRepository;
41 |
42 | @Autowired
43 | private BCryptPasswordEncoder pe;
44 |
45 | @Autowired
46 | private S3Service s3Service;
47 |
48 | @Autowired
49 | private ImageService imageService;
50 |
51 | @Value("${img.prefix.client.profile}")
52 | private String prefix;
53 |
54 | @Value("${img.profile.size}")
55 | private Integer size;
56 |
57 | public Cliente find(Integer id) {
58 |
59 | UserSS user = UserService.authenticated();
60 | if (user==null || !user.hasRole(Perfil.ADMIN) && !id.equals(user.getId())) {
61 | throw new AuthorizationException("Acesso negado");
62 | }
63 |
64 | Optional obj = repo.findById(id);
65 | return obj.orElseThrow(() -> new ObjectNotFoundException(
66 | "Objeto não encontrado! Id: " + id + ", Tipo: " + Cliente.class.getName()));
67 | }
68 |
69 | @Transactional
70 | public Cliente insert(Cliente obj) {
71 | obj.setId(null);
72 | obj = repo.save(obj);
73 | enderecoRepository.saveAll(obj.getEnderecos());
74 | return obj;
75 | }
76 |
77 | public Cliente update(Cliente obj) {
78 | Cliente newObj = find(obj.getId());
79 | updateData(newObj, obj);
80 | return repo.save(newObj);
81 | }
82 |
83 | public void delete(Integer id) {
84 | find(id);
85 | try {
86 | repo.deleteById(id);
87 | }
88 | catch (DataIntegrityViolationException e) {
89 | throw new DataIntegrityException("Não é possível excluir porque há pedidos relacionados");
90 | }
91 | }
92 |
93 | public List findAll() {
94 | return repo.findAll();
95 | }
96 |
97 | public Cliente findByEmail(String email) {
98 | UserSS user = UserService.authenticated();
99 | if (user == null || !user.hasRole(Perfil.ADMIN) && !email.equals(user.getUsername())) {
100 | throw new AuthorizationException("Acesso negado");
101 | }
102 |
103 | Cliente obj = repo.findByEmail(email);
104 | if (obj == null) {
105 | throw new ObjectNotFoundException(
106 | "Objeto não encontrado! Id: " + user.getId() + ", Tipo: " + Cliente.class.getName());
107 | }
108 | return obj;
109 | }
110 |
111 | public Page findPage(Integer page, Integer linesPerPage, String orderBy, String direction) {
112 | PageRequest pageRequest = PageRequest.of(page, linesPerPage, Direction.valueOf(direction), orderBy);
113 | return repo.findAll(pageRequest);
114 | }
115 |
116 | public Cliente fromDTO(ClienteDTO objDto) {
117 | return new Cliente(objDto.getId(), objDto.getNome(), objDto.getEmail(), null, null, null);
118 | }
119 |
120 | public Cliente fromDTO(ClienteNewDTO objDto) {
121 | Cliente cli = new Cliente(null, objDto.getNome(), objDto.getEmail(), objDto.getCpfOuCnpj(), TipoCliente.toEnum(objDto.getTipo()), pe.encode(objDto.getSenha()));
122 | Cidade cid = new Cidade(objDto.getCidadeId(), null, null);
123 | Endereco end = new Endereco(null, objDto.getLogradouro(), objDto.getNumero(), objDto.getComplemento(), objDto.getBairro(), objDto.getCep(), cli, cid);
124 | cli.getEnderecos().add(end);
125 | cli.getTelefones().add(objDto.getTelefone1());
126 | if (objDto.getTelefone2()!=null) {
127 | cli.getTelefones().add(objDto.getTelefone2());
128 | }
129 | if (objDto.getTelefone3()!=null) {
130 | cli.getTelefones().add(objDto.getTelefone3());
131 | }
132 | return cli;
133 | }
134 |
135 | private void updateData(Cliente newObj, Cliente obj) {
136 | newObj.setNome(obj.getNome());
137 | newObj.setEmail(obj.getEmail());
138 | }
139 |
140 | public URI uploadProfilePicture(MultipartFile multipartFile) {
141 | UserSS user = UserService.authenticated();
142 | if (user == null) {
143 | throw new AuthorizationException("Acesso negado");
144 | }
145 |
146 | BufferedImage jpgImage = imageService.getJpgImageFromFile(multipartFile);
147 | jpgImage = imageService.cropSquare(jpgImage);
148 | jpgImage = imageService.resize(jpgImage, size);
149 |
150 | String fileName = prefix + user.getId() + ".jpg";
151 |
152 | return s3Service.uploadFile(imageService.getInputStream(jpgImage, "jpg"), fileName, "image");
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/DBService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.text.ParseException;
4 | import java.text.SimpleDateFormat;
5 | import java.util.Arrays;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 | import org.springframework.stereotype.Service;
10 |
11 | import com.nelioalves.cursomc.domain.Categoria;
12 | import com.nelioalves.cursomc.domain.Cidade;
13 | import com.nelioalves.cursomc.domain.Cliente;
14 | import com.nelioalves.cursomc.domain.Endereco;
15 | import com.nelioalves.cursomc.domain.Estado;
16 | import com.nelioalves.cursomc.domain.ItemPedido;
17 | import com.nelioalves.cursomc.domain.Pagamento;
18 | import com.nelioalves.cursomc.domain.PagamentoComBoleto;
19 | import com.nelioalves.cursomc.domain.PagamentoComCartao;
20 | import com.nelioalves.cursomc.domain.Pedido;
21 | import com.nelioalves.cursomc.domain.Produto;
22 | import com.nelioalves.cursomc.domain.enums.EstadoPagamento;
23 | import com.nelioalves.cursomc.domain.enums.Perfil;
24 | import com.nelioalves.cursomc.domain.enums.TipoCliente;
25 | import com.nelioalves.cursomc.repositories.CategoriaRepository;
26 | import com.nelioalves.cursomc.repositories.CidadeRepository;
27 | import com.nelioalves.cursomc.repositories.ClienteRepository;
28 | import com.nelioalves.cursomc.repositories.EnderecoRepository;
29 | import com.nelioalves.cursomc.repositories.EstadoRepository;
30 | import com.nelioalves.cursomc.repositories.ItemPedidoRepository;
31 | import com.nelioalves.cursomc.repositories.PagamentoRepository;
32 | import com.nelioalves.cursomc.repositories.PedidoRepository;
33 | import com.nelioalves.cursomc.repositories.ProdutoRepository;
34 |
35 | @Service
36 | public class DBService {
37 |
38 | @Autowired
39 | private BCryptPasswordEncoder pe;
40 | @Autowired
41 | private CategoriaRepository categoriaRepository;
42 | @Autowired
43 | private ProdutoRepository produtoRepository;
44 | @Autowired
45 | private EstadoRepository estadoRepository;
46 | @Autowired
47 | private CidadeRepository cidadeRepository;
48 | @Autowired
49 | private ClienteRepository clienteRepository;
50 | @Autowired
51 | private EnderecoRepository enderecoRepository;
52 | @Autowired
53 | private PedidoRepository pedidoRepository;
54 | @Autowired
55 | private PagamentoRepository pagamentoRepository;
56 | @Autowired
57 | private ItemPedidoRepository itemPedidoRepository;
58 |
59 | public void instantiateTestDatabase() throws ParseException {
60 |
61 | Categoria cat1 = new Categoria(null, "Informática");
62 | Categoria cat2 = new Categoria(null, "Escritório");
63 | Categoria cat3 = new Categoria(null, "Cama mesa e banho");
64 | Categoria cat4 = new Categoria(null, "Eletrônicos");
65 | Categoria cat5 = new Categoria(null, "Jardinagem");
66 | Categoria cat6 = new Categoria(null, "Decoração");
67 | Categoria cat7 = new Categoria(null, "Perfumaria");
68 |
69 | Produto p1 = new Produto(null, "Computador", 2000.00);
70 | Produto p2 = new Produto(null, "Impressora", 800.00);
71 | Produto p3 = new Produto(null, "Mouse", 80.00);
72 | Produto p4 = new Produto(null, "Mesa de escritório", 300.00);
73 | Produto p5 = new Produto(null, "Toalha", 50.00);
74 | Produto p6 = new Produto(null, "Colcha", 200.00);
75 | Produto p7 = new Produto(null, "TV true color", 1200.00);
76 | Produto p8 = new Produto(null, "Roçadeira", 800.00);
77 | Produto p9 = new Produto(null, "Abajour", 100.00);
78 | Produto p10 = new Produto(null, "Pendente", 180.00);
79 | Produto p11 = new Produto(null, "Shampoo", 90.00);
80 |
81 | Produto p12 = new Produto(null, "Produto 12", 10.00);
82 | Produto p13 = new Produto(null, "Produto 13", 10.00);
83 | Produto p14 = new Produto(null, "Produto 14", 10.00);
84 | Produto p15 = new Produto(null, "Produto 15", 10.00);
85 | Produto p16 = new Produto(null, "Produto 16", 10.00);
86 | Produto p17 = new Produto(null, "Produto 17", 10.00);
87 | Produto p18 = new Produto(null, "Produto 18", 10.00);
88 | Produto p19 = new Produto(null, "Produto 19", 10.00);
89 | Produto p20 = new Produto(null, "Produto 20", 10.00);
90 | Produto p21 = new Produto(null, "Produto 21", 10.00);
91 | Produto p22 = new Produto(null, "Produto 22", 10.00);
92 | Produto p23 = new Produto(null, "Produto 23", 10.00);
93 | Produto p24 = new Produto(null, "Produto 24", 10.00);
94 | Produto p25 = new Produto(null, "Produto 25", 10.00);
95 | Produto p26 = new Produto(null, "Produto 26", 10.00);
96 | Produto p27 = new Produto(null, "Produto 27", 10.00);
97 | Produto p28 = new Produto(null, "Produto 28", 10.00);
98 | Produto p29 = new Produto(null, "Produto 29", 10.00);
99 | Produto p30 = new Produto(null, "Produto 30", 10.00);
100 | Produto p31 = new Produto(null, "Produto 31", 10.00);
101 | Produto p32 = new Produto(null, "Produto 32", 10.00);
102 | Produto p33 = new Produto(null, "Produto 33", 10.00);
103 | Produto p34 = new Produto(null, "Produto 34", 10.00);
104 | Produto p35 = new Produto(null, "Produto 35", 10.00);
105 | Produto p36 = new Produto(null, "Produto 36", 10.00);
106 | Produto p37 = new Produto(null, "Produto 37", 10.00);
107 | Produto p38 = new Produto(null, "Produto 38", 10.00);
108 | Produto p39 = new Produto(null, "Produto 39", 10.00);
109 | Produto p40 = new Produto(null, "Produto 40", 10.00);
110 | Produto p41 = new Produto(null, "Produto 41", 10.00);
111 | Produto p42 = new Produto(null, "Produto 42", 10.00);
112 | Produto p43 = new Produto(null, "Produto 43", 10.00);
113 | Produto p44 = new Produto(null, "Produto 44", 10.00);
114 | Produto p45 = new Produto(null, "Produto 45", 10.00);
115 | Produto p46 = new Produto(null, "Produto 46", 10.00);
116 | Produto p47 = new Produto(null, "Produto 47", 10.00);
117 | Produto p48 = new Produto(null, "Produto 48", 10.00);
118 | Produto p49 = new Produto(null, "Produto 49", 10.00);
119 | Produto p50 = new Produto(null, "Produto 50", 10.00);
120 |
121 | cat1.getProdutos().addAll(Arrays.asList(p12, p13, p14, p15, p16, p17, p18, p19, p20,
122 | p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p34, p35, p36, p37, p38,
123 | p39, p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50));
124 |
125 | p12.getCategorias().add(cat1);
126 | p13.getCategorias().add(cat1);
127 | p14.getCategorias().add(cat1);
128 | p15.getCategorias().add(cat1);
129 | p16.getCategorias().add(cat1);
130 | p17.getCategorias().add(cat1);
131 | p18.getCategorias().add(cat1);
132 | p19.getCategorias().add(cat1);
133 | p20.getCategorias().add(cat1);
134 | p21.getCategorias().add(cat1);
135 | p22.getCategorias().add(cat1);
136 | p23.getCategorias().add(cat1);
137 | p24.getCategorias().add(cat1);
138 | p25.getCategorias().add(cat1);
139 | p26.getCategorias().add(cat1);
140 | p27.getCategorias().add(cat1);
141 | p28.getCategorias().add(cat1);
142 | p29.getCategorias().add(cat1);
143 | p30.getCategorias().add(cat1);
144 | p31.getCategorias().add(cat1);
145 | p32.getCategorias().add(cat1);
146 | p33.getCategorias().add(cat1);
147 | p34.getCategorias().add(cat1);
148 | p35.getCategorias().add(cat1);
149 | p36.getCategorias().add(cat1);
150 | p37.getCategorias().add(cat1);
151 | p38.getCategorias().add(cat1);
152 | p39.getCategorias().add(cat1);
153 | p40.getCategorias().add(cat1);
154 | p41.getCategorias().add(cat1);
155 | p42.getCategorias().add(cat1);
156 | p43.getCategorias().add(cat1);
157 | p44.getCategorias().add(cat1);
158 | p45.getCategorias().add(cat1);
159 | p46.getCategorias().add(cat1);
160 | p47.getCategorias().add(cat1);
161 | p48.getCategorias().add(cat1);
162 | p49.getCategorias().add(cat1);
163 | p50.getCategorias().add(cat1);
164 |
165 | cat1.getProdutos().addAll(Arrays.asList(p1, p2, p3));
166 | cat2.getProdutos().addAll(Arrays.asList(p2, p4));
167 | cat3.getProdutos().addAll(Arrays.asList(p5, p6));
168 | cat4.getProdutos().addAll(Arrays.asList(p1, p2, p3, p7));
169 | cat5.getProdutos().addAll(Arrays.asList(p8));
170 | cat6.getProdutos().addAll(Arrays.asList(p9, p10));
171 | cat7.getProdutos().addAll(Arrays.asList(p11));
172 |
173 | p1.getCategorias().addAll(Arrays.asList(cat1, cat4));
174 | p2.getCategorias().addAll(Arrays.asList(cat1, cat2, cat4));
175 | p3.getCategorias().addAll(Arrays.asList(cat1, cat4));
176 | p4.getCategorias().addAll(Arrays.asList(cat2));
177 | p5.getCategorias().addAll(Arrays.asList(cat3));
178 | p6.getCategorias().addAll(Arrays.asList(cat3));
179 | p7.getCategorias().addAll(Arrays.asList(cat4));
180 | p8.getCategorias().addAll(Arrays.asList(cat5));
181 | p9.getCategorias().addAll(Arrays.asList(cat6));
182 | p10.getCategorias().addAll(Arrays.asList(cat6));
183 | p11.getCategorias().addAll(Arrays.asList(cat7));
184 |
185 | categoriaRepository.saveAll(Arrays.asList(cat1, cat2, cat3, cat4, cat5, cat6, cat7));
186 | produtoRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11));
187 |
188 | produtoRepository.saveAll(Arrays.asList(p12, p13, p14, p15, p16, p17, p18, p19, p20,
189 | p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38,
190 | p39, p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50));
191 |
192 | Estado est1 = new Estado(null, "Minas Gerais");
193 | Estado est2 = new Estado(null, "São Paulo");
194 |
195 | Cidade c1 = new Cidade(null, "Uberlândia", est1);
196 | Cidade c2 = new Cidade(null, "São Paulo", est2);
197 | Cidade c3 = new Cidade(null, "Campinas", est2);
198 |
199 | est1.getCidades().addAll(Arrays.asList(c1));
200 | est2.getCidades().addAll(Arrays.asList(c2, c3));
201 |
202 | estadoRepository.saveAll(Arrays.asList(est1, est2));
203 | cidadeRepository.saveAll(Arrays.asList(c1, c2, c3));
204 |
205 | Cliente cli1 = new Cliente(null, "Maria Silva", "nelio.cursos@gmail.com", "36378912377", TipoCliente.PESSOAFISICA, pe.encode("123"));
206 |
207 | cli1.getTelefones().addAll(Arrays.asList("27363323", "93838393"));
208 |
209 | Cliente cli2 = new Cliente(null, "Ana Costa", "nelio.iftm@gmail.com", "31628382740", TipoCliente.PESSOAFISICA, pe.encode("123"));
210 | cli2.getTelefones().addAll(Arrays.asList("93883321", "34252625"));
211 | cli2.addPerfil(Perfil.ADMIN);
212 |
213 | Endereco e1 = new Endereco(null, "Rua Flores", "300", "Apto 303", "Jardim", "38220834", cli1, c1);
214 | Endereco e2 = new Endereco(null, "Avenida Matos", "105", "Sala 800", "Centro", "38777012", cli1, c2);
215 | Endereco e3 = new Endereco(null, "Avenida Floriano", "2106", null, "Centro", "281777012", cli2, c2);
216 |
217 | cli1.getEnderecos().addAll(Arrays.asList(e1, e2));
218 | cli2.getEnderecos().addAll(Arrays.asList(e3));
219 |
220 | clienteRepository.saveAll(Arrays.asList(cli1, cli2));
221 | enderecoRepository.saveAll(Arrays.asList(e1, e2, e3));
222 |
223 | SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
224 |
225 | Pedido ped1 = new Pedido(null, sdf.parse("30/09/2017 10:32"), cli1, e1);
226 | Pedido ped2 = new Pedido(null, sdf.parse("10/10/2017 19:35"), cli1, e2);
227 |
228 | Pagamento pagto1 = new PagamentoComCartao(null, EstadoPagamento.QUITADO, ped1, 6);
229 | ped1.setPagamento(pagto1);
230 |
231 | Pagamento pagto2 = new PagamentoComBoleto(null, EstadoPagamento.PENDENTE, ped2, sdf.parse("20/10/2017 00:00"), null);
232 | ped2.setPagamento(pagto2);
233 |
234 | cli1.getPedidos().addAll(Arrays.asList(ped1, ped2));
235 |
236 | pedidoRepository.saveAll(Arrays.asList(ped1, ped2));
237 | pagamentoRepository.saveAll(Arrays.asList(pagto1, pagto2));
238 |
239 | ItemPedido ip1 = new ItemPedido(ped1, p1, 0.00, 1, 2000.00);
240 | ItemPedido ip2 = new ItemPedido(ped1, p3, 0.00, 2, 80.00);
241 | ItemPedido ip3 = new ItemPedido(ped2, p2, 100.00, 1, 800.00);
242 |
243 | ped1.getItens().addAll(Arrays.asList(ip1, ip2));
244 | ped2.getItens().addAll(Arrays.asList(ip3));
245 |
246 | p1.getItens().addAll(Arrays.asList(ip1));
247 | p2.getItens().addAll(Arrays.asList(ip3));
248 | p3.getItens().addAll(Arrays.asList(ip2));
249 |
250 | itemPedidoRepository.saveAll(Arrays.asList(ip1, ip2, ip3));
251 | }
252 | }
253 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/EmailService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import org.springframework.mail.SimpleMailMessage;
4 |
5 | import com.nelioalves.cursomc.domain.Cliente;
6 | import com.nelioalves.cursomc.domain.Pedido;
7 |
8 | public interface EmailService {
9 |
10 | void sendOrderConfirmationEmail(Pedido obj);
11 |
12 | void sendEmail(SimpleMailMessage msg);
13 |
14 | void sendNewPasswordEmail(Cliente cliente, String newPass);
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/EstadoService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.nelioalves.cursomc.domain.Estado;
9 | import com.nelioalves.cursomc.repositories.EstadoRepository;
10 |
11 | @Service
12 | public class EstadoService {
13 |
14 | @Autowired
15 | private EstadoRepository repo;
16 |
17 | public List findAll() {
18 | return repo.findAllByOrderByNome();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/ImageService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.awt.Color;
4 | import java.awt.image.BufferedImage;
5 | import java.io.ByteArrayInputStream;
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 |
10 | import javax.imageio.ImageIO;
11 |
12 | import org.apache.commons.io.FilenameUtils;
13 | import org.imgscalr.Scalr;
14 | import org.springframework.stereotype.Service;
15 | import org.springframework.web.multipart.MultipartFile;
16 |
17 | import com.nelioalves.cursomc.services.exceptions.FileException;
18 |
19 | @Service
20 | public class ImageService {
21 |
22 | public BufferedImage getJpgImageFromFile(MultipartFile uploadedFile) {
23 | String ext = FilenameUtils.getExtension(uploadedFile.getOriginalFilename());
24 | if (!"png".equals(ext) && !"jpg".equals(ext)) {
25 | throw new FileException("Somente imagens PNG e JPG são permitidas");
26 | }
27 |
28 | try {
29 | BufferedImage img = ImageIO.read(uploadedFile.getInputStream());
30 | if ("png".equals(ext)) {
31 | img = pngToJpg(img);
32 | }
33 | return img;
34 | } catch (IOException e) {
35 | throw new FileException("Erro ao ler arquivo");
36 | }
37 | }
38 |
39 | public BufferedImage pngToJpg(BufferedImage img) {
40 | BufferedImage jpgImage = new BufferedImage(img.getWidth(), img.getHeight(),
41 | BufferedImage.TYPE_INT_RGB);
42 | jpgImage.createGraphics().drawImage(img, 0, 0, Color.WHITE, null);
43 | return jpgImage;
44 | }
45 |
46 | public InputStream getInputStream(BufferedImage img, String extension) {
47 | try {
48 | ByteArrayOutputStream os = new ByteArrayOutputStream();
49 | ImageIO.write(img, extension, os);
50 | return new ByteArrayInputStream(os.toByteArray());
51 | } catch (IOException e) {
52 | throw new FileException("Erro ao ler arquivo");
53 | }
54 | }
55 |
56 | public BufferedImage cropSquare(BufferedImage sourceImg) {
57 | int min = (sourceImg.getHeight() <= sourceImg.getWidth()) ? sourceImg.getHeight() : sourceImg.getWidth();
58 | return Scalr.crop(
59 | sourceImg,
60 | (sourceImg.getWidth()/2) - (min/2),
61 | (sourceImg.getHeight()/2) - (min/2),
62 | min,
63 | min);
64 | }
65 |
66 | public BufferedImage resize(BufferedImage sourceImg, int size) {
67 | return Scalr.resize(sourceImg, Scalr.Method.ULTRA_QUALITY, size);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/MockEmailService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.mail.SimpleMailMessage;
6 |
7 | public class MockEmailService extends AbstractEmailService {
8 |
9 | private static final Logger LOG = LoggerFactory.getLogger(MockEmailService.class);
10 |
11 | @Override
12 | public void sendEmail(SimpleMailMessage msg) {
13 | LOG.info("Simulando envio de email...");
14 | LOG.info(msg.toString());
15 | LOG.info("Email enviado");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/PedidoService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.Date;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.PageRequest;
9 | import org.springframework.data.domain.Sort.Direction;
10 | import org.springframework.stereotype.Service;
11 |
12 | import com.nelioalves.cursomc.domain.Cliente;
13 | import com.nelioalves.cursomc.domain.ItemPedido;
14 | import com.nelioalves.cursomc.domain.PagamentoComBoleto;
15 | import com.nelioalves.cursomc.domain.Pedido;
16 | import com.nelioalves.cursomc.domain.enums.EstadoPagamento;
17 | import com.nelioalves.cursomc.repositories.ItemPedidoRepository;
18 | import com.nelioalves.cursomc.repositories.PagamentoRepository;
19 | import com.nelioalves.cursomc.repositories.PedidoRepository;
20 | import com.nelioalves.cursomc.security.UserSS;
21 | import com.nelioalves.cursomc.services.exceptions.AuthorizationException;
22 | import com.nelioalves.cursomc.services.exceptions.ObjectNotFoundException;
23 |
24 | @Service
25 | public class PedidoService {
26 |
27 | @Autowired
28 | private PedidoRepository repo;
29 |
30 | @Autowired
31 | private BoletoService boletoService;
32 |
33 | @Autowired
34 | private PagamentoRepository pagamentoRepository;
35 |
36 | @Autowired
37 | private ItemPedidoRepository itemPedidoRepository;
38 |
39 | @Autowired
40 | private ProdutoService produtoService;
41 |
42 | @Autowired
43 | private ClienteService clienteService;
44 |
45 | @Autowired
46 | private EmailService emailService;
47 |
48 | public Pedido find(Integer id) {
49 | Optional obj = repo.findById(id);
50 | return obj.orElseThrow(() -> new ObjectNotFoundException(
51 | "Objeto não encontrado! Id: " + id + ", Tipo: " + Pedido.class.getName()));
52 | }
53 |
54 | public Pedido insert(Pedido obj) {
55 | obj.setId(null);
56 | obj.setInstante(new Date());
57 | obj.setCliente(clienteService.find(obj.getCliente().getId()));
58 | obj.getPagamento().setEstado(EstadoPagamento.PENDENTE);
59 | obj.getPagamento().setPedido(obj);
60 | if (obj.getPagamento() instanceof PagamentoComBoleto) {
61 | PagamentoComBoleto pagto = (PagamentoComBoleto) obj.getPagamento();
62 | boletoService.preencherPagamentoComBoleto(pagto, obj.getInstante());
63 | }
64 | obj = repo.save(obj);
65 | pagamentoRepository.save(obj.getPagamento());
66 | for (ItemPedido ip : obj.getItens()) {
67 | ip.setDesconto(0.0);
68 | ip.setProduto(produtoService.find(ip.getProduto().getId()));
69 | ip.setPreco(ip.getProduto().getPreco());
70 | ip.setPedido(obj);
71 | }
72 | itemPedidoRepository.saveAll(obj.getItens());
73 | emailService.sendOrderConfirmationEmail(obj);
74 | return obj;
75 | }
76 |
77 | public Page findPage(Integer page, Integer linesPerPage, String orderBy, String direction) {
78 | UserSS user = UserService.authenticated();
79 | if (user == null) {
80 | throw new AuthorizationException("Acesso negado");
81 | }
82 | PageRequest pageRequest = PageRequest.of(page, linesPerPage, Direction.valueOf(direction), orderBy);
83 | Cliente cliente = clienteService.find(user.getId());
84 | return repo.findByCliente(cliente, pageRequest);
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/ProdutoService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.PageRequest;
9 | import org.springframework.data.domain.Sort.Direction;
10 | import org.springframework.stereotype.Service;
11 |
12 | import com.nelioalves.cursomc.domain.Categoria;
13 | import com.nelioalves.cursomc.domain.Produto;
14 | import com.nelioalves.cursomc.repositories.CategoriaRepository;
15 | import com.nelioalves.cursomc.repositories.ProdutoRepository;
16 | import com.nelioalves.cursomc.services.exceptions.ObjectNotFoundException;
17 |
18 | @Service
19 | public class ProdutoService {
20 |
21 | @Autowired
22 | private ProdutoRepository repo;
23 |
24 | @Autowired
25 | private CategoriaRepository categoriaRepository;
26 |
27 | public Produto find(Integer id) {
28 | Optional obj = repo.findById(id);
29 | return obj.orElseThrow(() -> new ObjectNotFoundException(
30 | "Objeto não encontrado! Id: " + id + ", Tipo: " + Produto.class.getName()));
31 | }
32 |
33 | public Page search(String nome, List ids, Integer page, Integer linesPerPage, String orderBy, String direction) {
34 | PageRequest pageRequest = PageRequest.of(page, linesPerPage, Direction.valueOf(direction), orderBy);
35 | List categorias = categoriaRepository.findAllById(ids);
36 | return repo.findDistinctByNomeContainingAndCategoriasIn(nome, categorias, pageRequest);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/S3Service.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.net.URI;
6 | import java.net.URISyntaxException;
7 |
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.beans.factory.annotation.Value;
12 | import org.springframework.stereotype.Service;
13 | import org.springframework.web.multipart.MultipartFile;
14 |
15 | import com.amazonaws.services.s3.AmazonS3;
16 | import com.amazonaws.services.s3.model.ObjectMetadata;
17 | import com.nelioalves.cursomc.services.exceptions.FileException;
18 |
19 | @Service
20 | public class S3Service {
21 |
22 | private Logger LOG = LoggerFactory.getLogger(S3Service.class);
23 |
24 | @Autowired
25 | private AmazonS3 s3client;
26 |
27 | @Value("${s3.bucket}")
28 | private String bucketName;
29 |
30 | public URI uploadFile(MultipartFile multipartFile) {
31 | try {
32 | String fileName = multipartFile.getOriginalFilename();
33 | InputStream is = multipartFile.getInputStream();
34 | String contentType = multipartFile.getContentType();
35 | return uploadFile(is, fileName, contentType);
36 | } catch (IOException e) {
37 | throw new FileException("Erro de IO: " + e.getMessage());
38 | }
39 | }
40 |
41 | public URI uploadFile(InputStream is, String fileName, String contentType) {
42 | try {
43 | ObjectMetadata meta = new ObjectMetadata();
44 | meta.setContentType(contentType);
45 | LOG.info("Iniciando upload");
46 | s3client.putObject(bucketName, fileName, is, meta);
47 | LOG.info("Upload finalizado");
48 | return s3client.getUrl(bucketName, fileName).toURI();
49 | } catch (URISyntaxException e) {
50 | throw new FileException("Erro ao converter URL para URI");
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/SmtpEmailService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.mail.MailSender;
7 | import org.springframework.mail.SimpleMailMessage;
8 |
9 | public class SmtpEmailService extends AbstractEmailService {
10 |
11 | @Autowired
12 | private MailSender mailSender;
13 |
14 | private static final Logger LOG = LoggerFactory.getLogger(SmtpEmailService.class);
15 |
16 | @Override
17 | public void sendEmail(SimpleMailMessage msg) {
18 | LOG.info("Enviando email...");
19 | mailSender.send(msg);
20 | LOG.info("Email enviado");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/UserDetailsServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.core.userdetails.UserDetails;
5 | import org.springframework.security.core.userdetails.UserDetailsService;
6 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
7 | import org.springframework.stereotype.Service;
8 |
9 | import com.nelioalves.cursomc.domain.Cliente;
10 | import com.nelioalves.cursomc.repositories.ClienteRepository;
11 | import com.nelioalves.cursomc.security.UserSS;
12 |
13 | @Service
14 | public class UserDetailsServiceImpl implements UserDetailsService {
15 |
16 | @Autowired
17 | private ClienteRepository repo;
18 |
19 | @Override
20 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
21 | Cliente cli = repo.findByEmail(email);
22 | if (cli == null) {
23 | throw new UsernameNotFoundException(email);
24 | }
25 | return new UserSS(cli.getId(), cli.getEmail(), cli.getSenha(), cli.getPerfis());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/UserService.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services;
2 |
3 | import org.springframework.security.core.context.SecurityContextHolder;
4 |
5 | import com.nelioalves.cursomc.security.UserSS;
6 |
7 | public class UserService {
8 |
9 | public static UserSS authenticated() {
10 | try {
11 | return (UserSS) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
12 | }
13 | catch (Exception e) {
14 | return null;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/exceptions/AuthorizationException.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.exceptions;
2 |
3 | public class AuthorizationException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 1L;
6 |
7 | public AuthorizationException(String msg) {
8 | super(msg);
9 | }
10 |
11 | public AuthorizationException(String msg, Throwable cause) {
12 | super(msg, cause);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/exceptions/DataIntegrityException.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.exceptions;
2 |
3 | public class DataIntegrityException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 1L;
6 |
7 | public DataIntegrityException(String msg) {
8 | super(msg);
9 | }
10 |
11 | public DataIntegrityException(String msg, Throwable cause) {
12 | super(msg, cause);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/exceptions/FileException.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.exceptions;
2 |
3 | public class FileException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 1L;
6 |
7 | public FileException(String msg) {
8 | super(msg);
9 | }
10 |
11 | public FileException(String msg, Throwable cause) {
12 | super(msg, cause);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/exceptions/ObjectNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.exceptions;
2 |
3 | public class ObjectNotFoundException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 1L;
6 |
7 | public ObjectNotFoundException(String msg) {
8 | super(msg);
9 | }
10 |
11 | public ObjectNotFoundException(String msg, Throwable cause) {
12 | super(msg, cause);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/validation/ClienteInsert.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.validation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | import javax.validation.Constraint;
9 | import javax.validation.Payload;
10 |
11 | @Constraint(validatedBy = ClienteInsertValidator.class)
12 | @Target({ ElementType.TYPE })
13 | @Retention(RetentionPolicy.RUNTIME)
14 |
15 | public @interface ClienteInsert {
16 | String message() default "Erro de validação";
17 |
18 | Class>[] groups() default {};
19 |
20 | Class extends Payload>[] payload() default {};
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/validation/ClienteInsertValidator.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.validation;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import javax.validation.ConstraintValidator;
7 | import javax.validation.ConstraintValidatorContext;
8 |
9 | import org.springframework.beans.factory.annotation.Autowired;
10 |
11 | import com.nelioalves.cursomc.domain.Cliente;
12 | import com.nelioalves.cursomc.domain.enums.TipoCliente;
13 | import com.nelioalves.cursomc.dto.ClienteNewDTO;
14 | import com.nelioalves.cursomc.repositories.ClienteRepository;
15 | import com.nelioalves.cursomc.resources.exception.FieldMessage;
16 | import com.nelioalves.cursomc.services.validation.utils.BR;
17 |
18 | public class ClienteInsertValidator implements ConstraintValidator {
19 |
20 | @Autowired
21 | private ClienteRepository repo;
22 |
23 | @Override
24 | public void initialize(ClienteInsert ann) {
25 | }
26 |
27 | @Override
28 | public boolean isValid(ClienteNewDTO objDto, ConstraintValidatorContext context) {
29 |
30 | List list = new ArrayList<>();
31 |
32 | if (objDto.getTipo().equals(TipoCliente.PESSOAFISICA.getCod()) && !BR.isValidCPF(objDto.getCpfOuCnpj())) {
33 | list.add(new FieldMessage("cpfOuCnpj", "CPF inválido"));
34 | }
35 |
36 | if (objDto.getTipo().equals(TipoCliente.PESSOAJURIDICA.getCod()) && !BR.isValidCNPJ(objDto.getCpfOuCnpj())) {
37 | list.add(new FieldMessage("cpfOuCnpj", "CNPJ inválido"));
38 | }
39 |
40 | Cliente aux = repo.findByEmail(objDto.getEmail());
41 | if (aux != null) {
42 | list.add(new FieldMessage("email", "Email já existente"));
43 | }
44 |
45 | for (FieldMessage e : list) {
46 | context.disableDefaultConstraintViolation();
47 | context.buildConstraintViolationWithTemplate(e.getMessage()).addPropertyNode(e.getFieldName())
48 | .addConstraintViolation();
49 | }
50 | return list.isEmpty();
51 | }
52 | }
53 |
54 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/validation/ClienteUpdate.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.validation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | import javax.validation.Constraint;
9 | import javax.validation.Payload;
10 |
11 | @Constraint(validatedBy = ClienteUpdateValidator.class)
12 | @Target({ ElementType.TYPE })
13 | @Retention(RetentionPolicy.RUNTIME)
14 |
15 | public @interface ClienteUpdate {
16 | String message() default "Erro de validação";
17 |
18 | Class>[] groups() default {};
19 |
20 | Class extends Payload>[] payload() default {};
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/validation/ClienteUpdateValidator.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.validation;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.validation.ConstraintValidator;
9 | import javax.validation.ConstraintValidatorContext;
10 |
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.web.servlet.HandlerMapping;
13 |
14 | import com.nelioalves.cursomc.domain.Cliente;
15 | import com.nelioalves.cursomc.dto.ClienteDTO;
16 | import com.nelioalves.cursomc.repositories.ClienteRepository;
17 | import com.nelioalves.cursomc.resources.exception.FieldMessage;
18 |
19 | public class ClienteUpdateValidator implements ConstraintValidator {
20 |
21 | @Autowired
22 | private HttpServletRequest request;
23 |
24 | @Autowired
25 | private ClienteRepository repo;
26 |
27 | @Override
28 | public void initialize(ClienteUpdate ann) {
29 | }
30 |
31 | @Override
32 | public boolean isValid(ClienteDTO objDto, ConstraintValidatorContext context) {
33 |
34 | @SuppressWarnings("unchecked")
35 | Map map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
36 | Integer uriId = Integer.parseInt(map.get("id"));
37 |
38 | List list = new ArrayList<>();
39 |
40 | Cliente aux = repo.findByEmail(objDto.getEmail());
41 | if (aux != null && !aux.getId().equals(uriId)) {
42 | list.add(new FieldMessage("email", "Email já existente"));
43 | }
44 |
45 | for (FieldMessage e : list) {
46 | context.disableDefaultConstraintViolation();
47 | context.buildConstraintViolationWithTemplate(e.getMessage()).addPropertyNode(e.getFieldName())
48 | .addConstraintViolation();
49 | }
50 | return list.isEmpty();
51 | }
52 | }
53 |
54 |
--------------------------------------------------------------------------------
/src/main/java/com/nelioalves/cursomc/services/validation/utils/BR.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc.services.validation.utils;
2 |
3 | // Fonte: https://gist.github.com/adrianoluis/5043397d378ae506d87366abb0ab4e30
4 | public class BR {
5 | // CPF
6 | private static final int[] weightSsn = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2};
7 |
8 | // CNPJ
9 | private static final int[] weightTin = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};
10 |
11 | private static int calculate(final String str, final int[] weight) {
12 | int sum = 0;
13 | for (int i = str.length() - 1, digit; i >= 0; i--) {
14 | digit = Integer.parseInt(str.substring(i, i + 1));
15 | sum += digit * weight[weight.length - str.length() + i];
16 | }
17 | sum = 11 - sum % 11;
18 | return sum > 9 ? 0 : sum;
19 | }
20 |
21 | /**
22 | * Valida CPF
23 | *
24 | * @param ssn
25 | * @return
26 | */
27 | public static boolean isValidCPF(final String ssn) {
28 | if ((ssn == null) || (ssn.length() != 11) || ssn.matches(ssn.charAt(0) + "{11}")) return false;
29 |
30 | final Integer digit1 = calculate(ssn.substring(0, 9), weightSsn);
31 | final Integer digit2 = calculate(ssn.substring(0, 9) + digit1, weightSsn);
32 | return ssn.equals(ssn.substring(0, 9) + digit1.toString() + digit2.toString());
33 | }
34 |
35 | /**
36 | * Valida CNPJ
37 | *
38 | * @param tin
39 | * @return
40 | */
41 | public static boolean isValidCNPJ(final String tin) {
42 | if ((tin == null) || (tin.length() != 14) || tin.matches(tin.charAt(0) + "{14}")) return false;
43 |
44 | final Integer digit1 = calculate(tin.substring(0, 12), weightTin);
45 | final Integer digit2 = calculate(tin.substring(0, 12) + digit1, weightTin);
46 | return tin.equals(tin.substring(0, 12) + digit1.toString() + digit2.toString());
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/resources/application-dev.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=jdbc:mysql://localhost:3306/curso_spring
2 | spring.datasource.username=root
3 | spring.datasource.password=
4 |
5 | spring.jpa.hibernate.ddl-auto=create
6 | spring.jpa.show-sql=true
7 | spring.jpa.properties.hibernate.format_sql=true
8 |
9 | spring.mail.host=smtp.gmail.com
10 | spring.mail.username=
11 | spring.mail.password=
12 | spring.mail.properties.mail.smtp.auth = true
13 | spring.mail.properties.mail.smtp.socketFactory.port = 465
14 | spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
15 | spring.mail.properties.mail.smtp.socketFactory.fallback = false
16 | spring.mail.properties.mail.smtp.starttls.enable = true
17 | spring.mail.properties.mail.smtp.ssl.enable = true
18 |
--------------------------------------------------------------------------------
/src/main/resources/application-prod.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=
2 |
3 | spring.jpa.hibernate.ddl-auto=none
4 | spring.jpa.show-sql=false
5 | spring.jpa.properties.hibernate.format_sql=false
6 |
7 | spring.mail.host=smtp.gmail.com
8 | spring.mail.username=
9 | spring.mail.password=
10 | spring.mail.properties.mail.smtp.auth = true
11 | spring.mail.properties.mail.smtp.socketFactory.port = 465
12 | spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
13 | spring.mail.properties.mail.smtp.socketFactory.fallback = false
14 | spring.mail.properties.mail.smtp.starttls.enable = true
15 | spring.mail.properties.mail.smtp.ssl.enable = true
16 |
--------------------------------------------------------------------------------
/src/main/resources/application-test.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=jdbc:h2:mem:testdb
2 | spring.datasource.username=sa
3 | spring.datasource.password=
4 |
5 | spring.jpa.show-sql=true
6 | spring.jpa.properties.hibernate.format_sql=true
7 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.profiles.active=test
2 |
3 | default.sender=
4 | default.recipient=
5 |
6 | jwt.secret=SequenciaDeCaracteresParaAssinarToken
7 | jwt.expiration=86400000
8 |
9 | aws.access_key_id=
10 | aws.secret_access_key=
11 | s3.bucket=curso-spring-ionic
12 | s3.region=sa-east-1
13 |
14 | img.prefix.client.profile=cp
15 | img.profile.size=200
16 |
17 | spring.servlet.multipart.max-file-size=10MB
18 | spring.servlet.multipart.max-request-size=10MB
19 |
--------------------------------------------------------------------------------
/src/test/java/com/nelioalves/cursomc/CursomcApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.nelioalves.cursomc;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class CursomcApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------