├── .gitignore
├── .mvn
└── wrapper
│ ├── MavenWrapperDownloader.java
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── resources
├── db.sql
└── db_postgres.sql
└── src
├── main
├── java
│ └── com
│ │ └── kdmeubichinho
│ │ ├── KdMeuBichinhoApplication.java
│ │ ├── config
│ │ ├── JwtAuthenticationEntryPoint.java
│ │ ├── JwtRequestFilter.java
│ │ ├── JwtTokenUtil.java
│ │ └── WebSecurityConfig.java
│ │ ├── controllers
│ │ ├── AnimalController.java
│ │ ├── AnuncioController.java
│ │ ├── CategoriaController.java
│ │ ├── EspecieController.java
│ │ ├── FotoController.java
│ │ ├── JwtAuthenticationController.java
│ │ ├── MensagemController.java
│ │ ├── PessoaController.java
│ │ └── generics
│ │ │ └── RestBasicController.java
│ │ ├── converters
│ │ ├── AnimalClassificacaoEtariaConverter.java
│ │ ├── AnimalPorteConverter.java
│ │ ├── AnimalSexoConverter.java
│ │ ├── AnimalTipoConverter.java
│ │ └── AnuncioStatusConverter.java
│ │ ├── dto
│ │ ├── CategoriaRequestDTO.java
│ │ ├── CredenciaisDTO.java
│ │ ├── CustomExceptionDTO.java
│ │ ├── EspecieRequestDTO.java
│ │ ├── MensagemDTO.java
│ │ ├── PessoaDTO.java
│ │ ├── TokenDTO.java
│ │ └── generics
│ │ │ └── ObjectDTO.java
│ │ ├── entities
│ │ ├── Animal.java
│ │ ├── Anuncio.java
│ │ ├── Categoria.java
│ │ ├── Especie.java
│ │ ├── Foto.java
│ │ ├── Mensagem.java
│ │ ├── Pessoa.java
│ │ └── generics
│ │ │ └── BaseEntity.java
│ │ ├── enums
│ │ ├── AnimalClassificacaoEtaria.java
│ │ ├── AnimalPorte.java
│ │ ├── AnimalSexo.java
│ │ ├── AnimalTipo.java
│ │ ├── AnuncioStatus.java
│ │ └── EnumException.java
│ │ ├── exception
│ │ ├── GlobalControllerExceptionHandler.java
│ │ └── ValidationException.java
│ │ ├── model
│ │ ├── JwtRequest.java
│ │ └── JwtResponse.java
│ │ ├── repositories
│ │ ├── AnimalRepository.java
│ │ ├── AnuncioRepository.java
│ │ ├── CategoriaRepository.java
│ │ ├── EspecieRepository.java
│ │ ├── FotoRepository.java
│ │ ├── MensagemRepository.java
│ │ └── PessoaRepository.java
│ │ ├── security
│ │ └── AutenticacaoService.java
│ │ ├── services
│ │ ├── AnimalService.java
│ │ ├── AnuncioService.java
│ │ ├── CategoriaService.java
│ │ ├── EspecieService.java
│ │ ├── JwtService.java
│ │ ├── MensagemService.java
│ │ ├── PessoaService.java
│ │ └── generics
│ │ │ └── RestBasicService.java
│ │ ├── specification
│ │ └── AnuncioSpecification.java
│ │ └── util
│ │ └── FileUploadUtil.java
└── resources
│ ├── application-integrationtest.properties
│ └── application.properties
└── test
└── java
└── com
└── kdmeubichinho
├── config
└── JwtRequestFilterTest.java
├── controllers
├── AnimalControllerTest.java
├── CategoriaControllerTest.java
├── EspecieControllerTest.java
├── FotoControllerTest.java
└── JwtAuthenticationControllerTest.java
├── converters
├── AnimalClassificacaoEtariaConverterTest.java
├── AnimalPorteConverterTest.java
├── AnimalSexoConverterTest.java
├── AnimalTipoConverterTest.java
└── AnuncioStatusConverterTest.java
├── dto
├── CategoriaRequestDTOTest.java
├── CredenciaisDTOTest.java
├── CustomExceptionDTOTest.java
├── EspecieRequestDTOTest.java
├── MensagemDTOTest.java
├── PessoaDTOTest.java
└── TokenDTOTest.java
├── entities
├── AnimalTest.java
├── AnuncioTest.java
├── CategoriaTest.java
├── EspecieTest.java
├── FotoTest.java
├── MensagemTest.java
└── PessoaTest.java
├── enums
├── AnimalClassificacaoEtariaTest.java
├── AnimalPorteTest.java
├── AnimalSexoTest.java
├── AnimalTipoTest.java
├── AnuncioStatusTest.java
└── EnumExceptionTest.java
├── exception
├── GlobalControllerExceptionHandlerTest.java
└── ValidationExceptionTest.java
├── model
├── JwtRequestTest.java
└── JwtResponseTest.java
├── security
└── AutenticacaoServiceTest.java
├── services
├── AnimalServiceTest.java
├── AnuncioServiceTest.java
├── JwtServiceTest.java
├── MensagemServiceTest.java
└── PessoaServiceTest.java
└── specification
└── AnuncioSpecificationTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2007-present the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | import java.net.*;
17 | import java.io.*;
18 | import java.nio.channels.*;
19 | import java.util.Properties;
20 |
21 | public class MavenWrapperDownloader {
22 |
23 | private static final String WRAPPER_VERSION = "0.5.6";
24 | /**
25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
26 | */
27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
29 |
30 | /**
31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
32 | * use instead of the default one.
33 | */
34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
35 | ".mvn/wrapper/maven-wrapper.properties";
36 |
37 | /**
38 | * Path where the maven-wrapper.jar will be saved to.
39 | */
40 | private static final String MAVEN_WRAPPER_JAR_PATH =
41 | ".mvn/wrapper/maven-wrapper.jar";
42 |
43 | /**
44 | * Name of the property which should be used to override the default download url for the wrapper.
45 | */
46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
47 |
48 | public static void main(String args[]) {
49 | System.out.println("- Downloader started");
50 | File baseDirectory = new File(args[0]);
51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
52 |
53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
54 | // wrapperUrl parameter.
55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
56 | String url = DEFAULT_DOWNLOAD_URL;
57 | if(mavenWrapperPropertyFile.exists()) {
58 | FileInputStream mavenWrapperPropertyFileInputStream = null;
59 | try {
60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
61 | Properties mavenWrapperProperties = new Properties();
62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
64 | } catch (IOException e) {
65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
66 | } finally {
67 | try {
68 | if(mavenWrapperPropertyFileInputStream != null) {
69 | mavenWrapperPropertyFileInputStream.close();
70 | }
71 | } catch (IOException e) {
72 | // Ignore ...
73 | }
74 | }
75 | }
76 | System.out.println("- Downloading from: " + url);
77 |
78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
79 | if(!outputFile.getParentFile().exists()) {
80 | if(!outputFile.getParentFile().mkdirs()) {
81 | System.out.println(
82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
83 | }
84 | }
85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
86 | try {
87 | downloadFileFromURL(url, outputFile);
88 | System.out.println("Done");
89 | System.exit(0);
90 | } catch (Throwable e) {
91 | System.out.println("- Error downloading");
92 | e.printStackTrace();
93 | System.exit(1);
94 | }
95 | }
96 |
97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
99 | String username = System.getenv("MVNW_USERNAME");
100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
101 | Authenticator.setDefault(new Authenticator() {
102 | @Override
103 | protected PasswordAuthentication getPasswordAuthentication() {
104 | return new PasswordAuthentication(username, password);
105 | }
106 | });
107 | }
108 | URL website = new URL(urlString);
109 | ReadableByteChannel rbc;
110 | rbc = Channels.newChannel(website.openStream());
111 | FileOutputStream fos = new FileOutputStream(destination);
112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
113 | fos.close();
114 | rbc.close();
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teteusAraujo/KdMeuBichinho-BackEnd/99f365c2967f5999e8fe782756ee13a48bf614a5/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 🚧 Kd meu bichinho? A plataforna ainda se encontra em fase de construção ✔️ 🚧
3 |
4 |
5 | ## 💻 Sobre o projeto
6 |
7 | :shipit: KdMeuBichinho? - O projeto surgiu com a missão de ajudar as pessoas que querem encontrar seu melhor amigo :dog: :cat: :rabbit: que foi perdido ou encontrar alguém que está doando.
8 |
9 | ## :bulb: Ideia do Projeto
10 |
11 | ```bash
12 | Realizar conexão entre interesses comuns das pessoas e os animais através de suas localizações.
13 |
14 | -Pessoas que perderam seus animais e querem encontrá-los.
15 | -Pessoas que encontraram animais perdidos e querem devolvê-los.
16 | -Pessoas que têm animais para doar e adotar.
17 |
18 | ```
19 | ## 🤔 Como contribuir
20 |
21 | - Faça um fork desse repositório;
22 | - Cria uma branch com a sua feature: `git checkout -b minha-feature`;
23 | - Faça commit das suas alterações: `git commit -m 'feat: Minha nova feature'`;
24 | - Faça push para a sua branch: `git push origin minha-feature`.
25 |
26 | Depois que o merge da sua pull request for feito, você pode deletar a sua branch.
27 |
28 |
29 | ## :mortar_board: Autores
30 |
31 |
42 |
45 |
--------------------------------------------------------------------------------
/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 | # https://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 | # Maven 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 Mingw, 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 | fi
118 |
119 | if [ -z "$JAVA_HOME" ]; then
120 | javaExecutable="`which javac`"
121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
122 | # readlink(1) is not available as standard on Solaris 10.
123 | readLink=`which readlink`
124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
125 | if $darwin ; then
126 | javaHome="`dirname \"$javaExecutable\"`"
127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
128 | else
129 | javaExecutable="`readlink -f \"$javaExecutable\"`"
130 | fi
131 | javaHome="`dirname \"$javaExecutable\"`"
132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
133 | JAVA_HOME="$javaHome"
134 | export JAVA_HOME
135 | fi
136 | fi
137 | fi
138 |
139 | if [ -z "$JAVACMD" ] ; then
140 | if [ -n "$JAVA_HOME" ] ; then
141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
142 | # IBM's JDK on AIX uses strange locations for the executables
143 | JAVACMD="$JAVA_HOME/jre/sh/java"
144 | else
145 | JAVACMD="$JAVA_HOME/bin/java"
146 | fi
147 | else
148 | JAVACMD="`which java`"
149 | fi
150 | fi
151 |
152 | if [ ! -x "$JAVACMD" ] ; then
153 | echo "Error: JAVA_HOME is not defined correctly." >&2
154 | echo " We cannot execute $JAVACMD" >&2
155 | exit 1
156 | fi
157 |
158 | if [ -z "$JAVA_HOME" ] ; then
159 | echo "Warning: JAVA_HOME environment variable is not set."
160 | fi
161 |
162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
163 |
164 | # traverses directory structure from process work directory to filesystem root
165 | # first directory with .mvn subdirectory is considered project base directory
166 | find_maven_basedir() {
167 |
168 | if [ -z "$1" ]
169 | then
170 | echo "Path not specified to find_maven_basedir"
171 | return 1
172 | fi
173 |
174 | basedir="$1"
175 | wdir="$1"
176 | while [ "$wdir" != '/' ] ; do
177 | if [ -d "$wdir"/.mvn ] ; then
178 | basedir=$wdir
179 | break
180 | fi
181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
182 | if [ -d "${wdir}" ]; then
183 | wdir=`cd "$wdir/.."; pwd`
184 | fi
185 | # end of workaround
186 | done
187 | echo "${basedir}"
188 | }
189 |
190 | # concatenates all lines of a file
191 | concat_lines() {
192 | if [ -f "$1" ]; then
193 | echo "$(tr -s '\n' ' ' < "$1")"
194 | fi
195 | }
196 |
197 | BASE_DIR=`find_maven_basedir "$(pwd)"`
198 | if [ -z "$BASE_DIR" ]; then
199 | exit 1;
200 | fi
201 |
202 | ##########################################################################################
203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
204 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
205 | ##########################################################################################
206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
207 | if [ "$MVNW_VERBOSE" = true ]; then
208 | echo "Found .mvn/wrapper/maven-wrapper.jar"
209 | fi
210 | else
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
213 | fi
214 | if [ -n "$MVNW_REPOURL" ]; then
215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
216 | else
217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
218 | fi
219 | while IFS="=" read key value; do
220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
221 | esac
222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
223 | if [ "$MVNW_VERBOSE" = true ]; then
224 | echo "Downloading from: $jarUrl"
225 | fi
226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
227 | if $cygwin; then
228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
229 | fi
230 |
231 | if command -v wget > /dev/null; then
232 | if [ "$MVNW_VERBOSE" = true ]; then
233 | echo "Found wget ... using wget"
234 | fi
235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
236 | wget "$jarUrl" -O "$wrapperJarPath"
237 | else
238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
239 | fi
240 | elif command -v curl > /dev/null; then
241 | if [ "$MVNW_VERBOSE" = true ]; then
242 | echo "Found curl ... using curl"
243 | fi
244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
245 | curl -o "$wrapperJarPath" "$jarUrl" -f
246 | else
247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
248 | fi
249 |
250 | else
251 | if [ "$MVNW_VERBOSE" = true ]; then
252 | echo "Falling back to using Java to download"
253 | fi
254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
255 | # For Cygwin, switch paths to Windows format before running javac
256 | if $cygwin; then
257 | javaClass=`cygpath --path --windows "$javaClass"`
258 | fi
259 | if [ -e "$javaClass" ]; then
260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
261 | if [ "$MVNW_VERBOSE" = true ]; then
262 | echo " - Compiling MavenWrapperDownloader.java ..."
263 | fi
264 | # Compiling the Java class
265 | ("$JAVA_HOME/bin/javac" "$javaClass")
266 | fi
267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
268 | # Running the downloader
269 | if [ "$MVNW_VERBOSE" = true ]; then
270 | echo " - Running MavenWrapperDownloader.java ..."
271 | fi
272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
273 | fi
274 | fi
275 | fi
276 | fi
277 | ##########################################################################################
278 | # End of extension
279 | ##########################################################################################
280 |
281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
282 | if [ "$MVNW_VERBOSE" = true ]; then
283 | echo $MAVEN_PROJECTBASEDIR
284 | fi
285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
286 |
287 | # For Cygwin, switch paths to Windows format before running java
288 | if $cygwin; then
289 | [ -n "$M2_HOME" ] &&
290 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
291 | [ -n "$JAVA_HOME" ] &&
292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
293 | [ -n "$CLASSPATH" ] &&
294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
295 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
297 | fi
298 |
299 | # Provide a "standardized" way to retrieve the CLI args that will
300 | # work with both Windows and non-Windows executions.
301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
302 | export MAVEN_CMD_LINE_ARGS
303 |
304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
305 |
306 | exec "$JAVACMD" \
307 | $MAVEN_OPTS \
308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
311 |
--------------------------------------------------------------------------------
/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 https://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 Maven 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 keystroke 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 set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
124 |
125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
162 | if ERRORLEVEL 1 goto error
163 | goto end
164 |
165 | :error
166 | set ERROR_CODE=1
167 |
168 | :end
169 | @endlocal & set ERROR_CODE=%ERROR_CODE%
170 |
171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
175 | :skipRcPost
176 |
177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
179 |
180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
181 |
182 | exit /B %ERROR_CODE%
183 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.4.5
9 |
10 |
11 | com.kdmeubichinho
12 | KdMeuBichinho
13 | 1.0.0-SNAPSHOT
14 | KdMeuBichinho
15 | website que surgiu com a missão de ajudar as pessoas que querem encontrar seu melhor amigo(pet) que foi perdido ou encontrar alguém que está doando.
16 |
17 |
18 | 0.8.6
19 | jacoco
20 | reuseReports
21 | ${project.basedir}/../target/jacoco.exec
22 | java
23 |
24 |
25 |
26 |
27 | sonar
28 |
29 | true
30 |
31 |
32 |
33 |
34 | org.sonarsource.scanner.maven
35 | sonar-maven-plugin
36 | 3.4.0.905
37 |
38 |
39 | org.jacoco
40 | jacoco-maven-plugin
41 | ${jacoco.version}
42 |
43 |
44 | jacoco-initialize
45 |
46 | prepare-agent
47 |
48 |
49 |
50 | jacoco-site
51 | package
52 |
53 | report
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 | http://localhost:9000
64 |
65 | 47d31b6e31ec3a09ecf80724a018142d7ad9213c
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 | org.springframework.boot
74 | spring-boot-starter-security
75 |
76 |
77 |
78 | io.jsonwebtoken
79 | jjwt
80 | 0.9.1
81 |
82 |
83 |
84 | org.jacoco
85 | jacoco-maven-plugin
86 | 0.8.6
87 |
88 |
89 |
90 | org.springframework.boot
91 | spring-boot-starter-web
92 |
93 |
94 |
95 | org.springframework.boot
96 | spring-boot-starter-data-jpa
97 |
98 |
99 |
100 | org.springframework.boot
101 | spring-boot-devtools
102 | runtime
103 | true
104 |
105 |
106 | org.springframework.boot
107 | spring-boot-starter-test
108 | test
109 |
110 |
111 | org.projectlombok
112 | lombok
113 | true
114 |
115 |
116 |
117 | org.postgresql
118 | postgresql
119 | runtime
120 |
121 |
122 |
123 | org.springframework.boot
124 | spring-boot-starter-test
125 | test
126 |
127 |
128 |
129 | com.h2database
130 | h2
131 | test
132 |
133 |
134 |
135 | org.junit.vintage
136 | junit-vintage-engine
137 | test
138 |
139 |
140 | org.hamcrest
141 | hamcrest-core
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 | org.springframework.boot
152 | spring-boot-maven-plugin
153 |
154 |
155 |
156 |
157 |
158 |
--------------------------------------------------------------------------------
/resources/db.sql:
--------------------------------------------------------------------------------
1 | CREATE SCHEMA kdmeubichinho;
2 | USE kdmeubichinho;
3 |
4 | CREATE TABLE especie(
5 | id_especie INT PRIMARY KEY AUTO_INCREMENT,
6 | nome VARCHAR(20) NOT NULL UNIQUE
7 | ) ENGINE = InnoDB;
8 |
9 | CREATE TABLE foto (
10 | id_foto INT PRIMARY KEY AUTO_INCREMENT,
11 | caminho VARCHAR(255)
12 | )ENGINE = InnoDB;
13 |
14 | CREATE TABLE pessoa (
15 | id_pessoa INT PRIMARY KEY AUTO_INCREMENT,
16 | nome VARCHAR(120) NOT NULL,
17 | email VARCHAR(80) NOT NULL UNIQUE,
18 | cep VARCHAR(10) NOT NULL,
19 | logradouro VARCHAR(255),
20 | complemento VARCHAR(255),
21 | bairro VARCHAR(255),
22 | localidade VARCHAR(150),
23 | uf VARCHAR(2),
24 | ibge VARCHAR(50),
25 | ddd VARCHAR(5),
26 | numero_residencial VARCHAR(10),
27 | celular VARCHAR(16) NOT NULL,
28 | senha VARCHAR(70) NOT NULL,
29 | admin BOOL NOT NULL DEFAULT false
30 | )ENGINE = InnoDB;
31 |
32 | CREATE TABLE animal (
33 | id_animal INT PRIMARY KEY AUTO_INCREMENT,
34 | sexo ENUM("Macho", "Fêmea", "Não identificado") NOT NULL,
35 | classificacao_etaria ENUM("Filhote", "Adulto") NOT NULL,
36 | porte ENUM("Pequeno","Médio", "Grande") NOT NULL,
37 | castrado BOOL NOT NULL DEFAULT false,
38 | vacinado BOOL NOT NULL DEFAULT false,
39 | nome VARCHAR(120),
40 | cep VARCHAR(10) NOT NULL,
41 | logradouro VARCHAR(255),
42 | complemento VARCHAR(255),
43 | bairro VARCHAR(255),
44 | localidade VARCHAR(150),
45 | uf VARCHAR(2),
46 | ibge VARCHAR(50),
47 | ddd VARCHAR(5),
48 | numero_residencial VARCHAR(10),
49 | fk_id_especie INT NOT NULL,
50 | fk_id_foto INT NOT NULL,
51 | FOREIGN KEY (`fk_id_especie`) REFERENCES `especie`(`id_especie`),
52 | FOREIGN KEY (`fk_id_foto`) REFERENCES `foto`(`id_foto`)
53 | )ENGINE = InnoDB;
54 |
55 | CREATE TABLE categoria(
56 | id_categoria INT PRIMARY KEY AUTO_INCREMENT,
57 | classificacao VARCHAR(100) NOT NULL
58 | )ENGINE = InnoDB;
59 |
60 | CREATE TABLE anuncio (
61 | id_anuncio INT PRIMARY KEY AUTO_INCREMENT,
62 | status_anuncio ENUM("Ativo", "Inativo"),
63 | data_criacao DATETIME NOT NULL,
64 | data_encerramento DATETIME,
65 | fk_id_pessoa INT NOT NULL,
66 | fk_id_animal INT NOT NULL,
67 | fk_id_categoria INT NOT NULL,
68 | FOREIGN KEY (`fk_id_pessoa`) REFERENCES `pessoa`(`id_pessoa`),
69 | FOREIGN KEY (`fk_id_animal`) REFERENCES `animal`(`id_animal`),
70 | FOREIGN KEY (`fk_id_categoria`) REFERENCES `categoria`(`id_categoria`)
71 | )ENGINE = InnoDB;
72 |
73 | CREATE TABLE mensagem (
74 | id_mensagem INT PRIMARY KEY AUTO_INCREMENT,
75 | data_mensagem DATETIME NOT NULL,
76 | mensagem VARCHAR(255),
77 | fk_id_pessoa INT,
78 | fk_id_anuncio INT,
79 | FOREIGN KEY (`fk_id_pessoa`) REFERENCES `pessoa`(`id_pessoa`),
80 | FOREIGN KEY (`fk_id_anuncio`) REFERENCES `anuncio`(`id_anuncio`)
81 | )ENGINE = InnoDB;
82 |
83 | -- ALTER TABLE `foto` ADD CONSTRAINT `fk_id_animal` FOREIGN KEY (`fk_id_animal`) REFERENCES `animal`(`id_animal`);
84 | -- ALTER TABLE `animal` ADD CONSTRAINT `fk_id_especie` FOREIGN KEY (`fk_id_especie`) REFERENCES `especie`(`id_especie`);
85 | -- ALTER TABLE `anuncio` ADD CONSTRAINT `fk_id_pessoa` FOREIGN KEY (`fk_id_pessoa`) REFERENCES `pessoa`(`id_pessoa`);
86 | -- ALTER TABLE `anuncio` ADD CONSTRAINT `fk_id_animal` FOREIGN KEY (`fk_id_animal`) REFERENCES `animal`(`id_animal`);
87 | -- ALTER TABLE `anuncio` ADD CONSTRAINT `fk_id_categoria` FOREIGN KEY (`fk_id_categoria`) REFERENCES `categoria`(`id_categoria`);
88 | -- ALTER TABLE `mensagem` ADD CONSTRAINT `fk_id_pessoa` FOREIGN KEY (`fk_id_pessoa`) REFERENCES `pessoa`(`id_pessoa`);
89 | -- ALTER TABLE `mensagem` ADD CONSTRAINT `fk_id_anuncio` FOREIGN KEY (`fk_id_anuncio`) REFERENCES `anuncio`(`id_anuncio`);
90 |
91 | INSERT INTO `kdmeubichinho`.`especie` (`nome`) VALUES ('Cachorro'), ('Gato'), ('Pássaro'), ('Roedor');
92 | INSERT INTO `kdmeubichinho`.`categoria` (`classificacao`) VALUES ('Fugiu de casa'), ('Encontrado na rua'), ('Procurando um lar');
--------------------------------------------------------------------------------
/resources/db_postgres.sql:
--------------------------------------------------------------------------------
1 | CREATE DATABASE kdmeubichinho;
2 | --CREATE SCHEMA kdmeubichinho;
3 |
4 | CREATE TABLE especie(
5 | id_especie SERIAL PRIMARY KEY,
6 | nome VARCHAR(20) NOT NULL UNIQUE
7 | );
8 |
9 | CREATE TABLE foto (
10 | id_foto SERIAL PRIMARY KEY,
11 | caminho VARCHAR(255)
12 | );
13 |
14 | CREATE TABLE pessoa (
15 | id_pessoa SERIAL PRIMARY KEY,
16 | nome VARCHAR(120) NOT NULL,
17 | email VARCHAR(80) NOT NULL UNIQUE,
18 | cep VARCHAR(10) NOT NULL,
19 | logradouro VARCHAR(255),
20 | complemento VARCHAR(255),
21 | bairro VARCHAR(255),
22 | localidade VARCHAR(150),
23 | uf VARCHAR(2),
24 | ibge VARCHAR(50),
25 | ddd VARCHAR(5),
26 | numero_residencial VARCHAR(10),
27 | celular VARCHAR(16) NOT NULL,
28 | senha VARCHAR(70) NOT NULL,
29 | admin BOOL NOT NULL DEFAULT false
30 | );
31 |
32 | CREATE TYPE sexo AS ENUM ('Macho', 'Fêmea', 'Não identificado');
33 | CREATE TYPE classificacao_etaria AS ENUM ('Filhote', 'Adulto');
34 | CREATE TYPE porte AS ENUM ('Pequeno','Médio', 'Grande');
35 |
36 | CREATE TABLE animal (
37 | id_animal SERIAL PRIMARY KEY,
38 | sexo sexo NOT NULL,
39 | classificacao_etaria classificacao_etaria NOT NULL,
40 | porte porte NOT NULL,
41 | castrado BOOL NOT NULL DEFAULT false,
42 | vacinado BOOL NOT NULL DEFAULT false,
43 | nome VARCHAR(120),
44 | cep VARCHAR(10) NOT NULL,
45 | logradouro VARCHAR(255),
46 | complemento VARCHAR(255),
47 | bairro VARCHAR(255),
48 | localidade VARCHAR(150),
49 | uf VARCHAR(2),
50 | ibge VARCHAR(50),
51 | ddd VARCHAR(5),
52 | numero_residencial VARCHAR(10),
53 | fk_id_especie INT NOT NULL,
54 | fk_id_foto INT NOT NULL,
55 | FOREIGN KEY ("fk_id_especie") REFERENCES especie("id_especie"),
56 | FOREIGN KEY ("fk_id_foto") REFERENCES foto("id_foto")
57 | );
58 |
59 | CREATE TABLE categoria(
60 | id_categoria SERIAL PRIMARY KEY,
61 | classificacao VARCHAR(100) NOT NULL
62 | );
63 |
64 | CREATE TYPE status_anuncio AS ENUM ('Ativo','Inativo');
65 |
66 | CREATE TABLE anuncio (
67 | id_anuncio SERIAL PRIMARY KEY,
68 | status_anuncio status_anuncio,
69 | data_criacao DATE NOT NULL,
70 | data_encerramento DATE,
71 | fk_id_pessoa INT NOT NULL,
72 | fk_id_animal INT NOT NULL,
73 | fk_id_categoria INT NOT NULL,
74 | FOREIGN KEY ("fk_id_pessoa") REFERENCES pessoa("id_pessoa"),
75 | FOREIGN KEY ("fk_id_animal") REFERENCES animal("id_animal"),
76 | FOREIGN KEY ("fk_id_categoria") REFERENCES categoria("id_categoria")
77 | );
78 |
79 | CREATE TABLE mensagem (
80 | id_mensagem SERIAL PRIMARY KEY,
81 | data_mensagem DATE NOT NULL,
82 | mensagem VARCHAR(255),
83 | fk_id_pessoa INT,
84 | fk_id_anuncio INT,
85 | FOREIGN KEY ("fk_id_pessoa") REFERENCES pessoa("id_pessoa"),
86 | FOREIGN KEY ("fk_id_anuncio") REFERENCES anuncio("id_anuncio")
87 | );
88 |
89 | -- ALTER TABLE `foto` ADD CONSTRAINT `fk_id_animal` FOREIGN KEY (`fk_id_animal`) REFERENCES `animal`(`id_animal`);
90 | -- ALTER TABLE `animal` ADD CONSTRAINT `fk_id_especie` FOREIGN KEY (`fk_id_especie`) REFERENCES `especie`(`id_especie`);
91 | -- ALTER TABLE `anuncio` ADD CONSTRAINT `fk_id_pessoa` FOREIGN KEY (`fk_id_pessoa`) REFERENCES `pessoa`(`id_pessoa`);
92 | -- ALTER TABLE `anuncio` ADD CONSTRAINT `fk_id_animal` FOREIGN KEY (`fk_id_animal`) REFERENCES `animal`(`id_animal`);
93 | -- ALTER TABLE `anuncio` ADD CONSTRAINT `fk_id_categoria` FOREIGN KEY (`fk_id_categoria`) REFERENCES `categoria`(`id_categoria`);
94 | -- ALTER TABLE `mensagem` ADD CONSTRAINT `fk_id_pessoa` FOREIGN KEY (`fk_id_pessoa`) REFERENCES `pessoa`(`id_pessoa`);
95 | -- ALTER TABLE `mensagem` ADD CONSTRAINT `fk_id_anuncio` FOREIGN KEY (`fk_id_anuncio`) REFERENCES `anuncio`(`id_anuncio`);
96 |
97 | INSERT INTO especie ("nome") VALUES ('Cachorro'), ('Gato'), ('Pássaro'), ('Roedor');
98 | INSERT INTO categoria ("classificacao") VALUES ('Fugiu de casa'), ('Encontrado na rua'), ('Procurando um lar');
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/KdMeuBichinhoApplication.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class KdMeuBichinhoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(KdMeuBichinhoApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/config/JwtAuthenticationEntryPoint.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.config;
2 |
3 | import org.springframework.security.core.AuthenticationException;
4 | import org.springframework.security.web.AuthenticationEntryPoint;
5 | import org.springframework.stereotype.Component;
6 |
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 | import java.io.IOException;
10 | import java.io.Serializable;
11 |
12 | @Component
13 | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
14 |
15 | private static final long serialVersionUID = -7858869558953243875L;
16 |
17 | @Override
18 | public void commence(HttpServletRequest request, HttpServletResponse response,
19 | AuthenticationException authException) throws IOException {
20 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/config/JwtRequestFilter.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.config;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import com.kdmeubichinho.services.PessoaService;
5 | import io.jsonwebtoken.ExpiredJwtException;
6 | import io.jsonwebtoken.MalformedJwtException;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
9 | import org.springframework.security.core.context.SecurityContextHolder;
10 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
11 | import org.springframework.stereotype.Component;
12 | import org.springframework.web.bind.annotation.CrossOrigin;
13 | import org.springframework.web.filter.OncePerRequestFilter;
14 |
15 | import javax.servlet.FilterChain;
16 | import javax.servlet.ServletException;
17 | import javax.servlet.http.HttpServletRequest;
18 | import javax.servlet.http.HttpServletResponse;
19 | import java.io.IOException;
20 |
21 | @Component
22 | @CrossOrigin(origins = "*")
23 | public class JwtRequestFilter extends OncePerRequestFilter {
24 |
25 | @Autowired
26 | private PessoaService service;
27 |
28 | @Autowired
29 | private JwtTokenUtil jwtTokenUtil;
30 |
31 | @Override
32 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
33 | throws ServletException, IOException {
34 |
35 | final String requestTokenHeader = request.getHeader("Authorization");
36 |
37 | String username = null;
38 | String jwtToken = null;
39 |
40 | if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
41 | jwtToken = requestTokenHeader.substring(7);
42 |
43 | if (jwtToken.indexOf(".") >= 0) {
44 | try {
45 | username = jwtTokenUtil.getUsernameFromToken(jwtToken);
46 | } catch (MalformedJwtException e) {
47 | logger.error("Unable to get JWT Token");
48 | } catch (ExpiredJwtException e) {
49 | logger.error("JWT Token has expired");
50 | }
51 | }
52 | } else {
53 | logger.warn("JWT Token does not begin with Bearer String");
54 | }
55 |
56 | if (username != null && SecurityContextHolder.getContext() == null
57 | || SecurityContextHolder.getContext().getAuthentication() == null) {
58 | Pessoa userDetails = this.service.getPersonByEmail(username).orElse(null);
59 |
60 | if ((userDetails != null) && (jwtTokenUtil.validateToken(jwtToken, userDetails))) {
61 | UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
62 | userDetails, null, userDetails.getAuthorities());
63 | usernamePasswordAuthenticationToken
64 | .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
65 |
66 | SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
67 | }
68 | }
69 | chain.doFilter(request, response);
70 | }
71 |
72 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/config/JwtTokenUtil.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.config;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import io.jsonwebtoken.Claims;
5 | import io.jsonwebtoken.Jwts;
6 | import io.jsonwebtoken.SignatureAlgorithm;
7 | import org.springframework.beans.factory.annotation.Value;
8 | import org.springframework.stereotype.Component;
9 |
10 | import java.io.Serializable;
11 | import java.util.Date;
12 | import java.util.HashMap;
13 | import java.util.Map;
14 | import java.util.function.Function;
15 |
16 | @Component
17 | public class JwtTokenUtil implements Serializable {
18 |
19 | private static final long serialVersionUID = -2550185165626007488L;
20 | public static final long JWT_TOKEN_VALIDITY = (long) 5 * 60 * 60;
21 |
22 | @Value("${security.jwt.chave-assinatura}")
23 | private String secret;
24 |
25 | public String getUsernameFromToken(String token) {
26 | return getClaimFromToken(token, Claims::getSubject);
27 | }
28 |
29 | public String getValueFromClaim(String token, String claim) {
30 | Claims allClaimsFromToken = this.getAllClaimsFromToken(token);
31 | Object object = allClaimsFromToken.get(claim);
32 | return object.toString();
33 | }
34 |
35 | public Date getExpirationDateFromToken(String token) {
36 | return getClaimFromToken(token, Claims::getExpiration);
37 | }
38 |
39 | public T getClaimFromToken(String token, Function claimsResolver) {
40 | final Claims claims = getAllClaimsFromToken(token);
41 | return claimsResolver.apply(claims);
42 | }
43 |
44 | private Claims getAllClaimsFromToken(String token) {
45 | return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
46 | }
47 |
48 | private Boolean isTokenExpired(String token) {
49 | final Date expiration = getExpirationDateFromToken(token);
50 | return expiration.before(new Date());
51 | }
52 |
53 | public String generateToken(Pessoa userDetails, Object specificClaim) {
54 | Map claims = new HashMap<>();
55 | if(null != userDetails.getAuthorities()){
56 | claims.put("authority_list", userDetails.getAuthorities().toArray());
57 | }
58 |
59 | claims.put("specific_claim", specificClaim);
60 |
61 | return doGenerateToken(claims, userDetails.getUsername());
62 | }
63 |
64 | private String doGenerateToken(Map claims, String subject) {
65 | return Jwts.builder()
66 | .setClaims(claims)
67 | .setSubject(subject)
68 | .setIssuedAt(new Date(System.currentTimeMillis()))
69 | .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
70 | .signWith(SignatureAlgorithm.HS512, secret)
71 | .compact();
72 | }
73 |
74 | public boolean validateToken(String token, Pessoa userDetails) {
75 | final String username = getUsernameFromToken(token);
76 | return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)
77 | && (this.getAllClaimsFromToken(token) != null));
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/config/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.config;
2 |
3 |
4 | import com.kdmeubichinho.security.AutenticacaoService;
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.security.authentication.AuthenticationManager;
9 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
10 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
12 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
13 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
14 | import org.springframework.security.config.http.SessionCreationPolicy;
15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
16 | import org.springframework.security.crypto.password.PasswordEncoder;
17 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
18 | import org.springframework.web.bind.annotation.CrossOrigin;
19 |
20 | @Configuration
21 | @EnableWebSecurity
22 | @EnableGlobalMethodSecurity(prePostEnabled = true)
23 | @CrossOrigin(origins = "*")
24 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
25 |
26 | @Autowired
27 | private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
28 |
29 | @Autowired
30 | private AutenticacaoService autenticacaoService;
31 |
32 | @Autowired
33 | private JwtRequestFilter jwtRequestFilter;
34 |
35 | @Autowired
36 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
37 | auth.userDetailsService(autenticacaoService).passwordEncoder(passwordEncoder());
38 | }
39 |
40 | @Bean
41 | public PasswordEncoder passwordEncoder() {
42 | return new BCryptPasswordEncoder();
43 | }
44 |
45 | @Bean
46 | @Override
47 | public AuthenticationManager authenticationManagerBean() throws Exception {
48 | return super.authenticationManagerBean();
49 | }
50 |
51 | @Override
52 | protected void configure(HttpSecurity httpSecurity) throws Exception {
53 | httpSecurity
54 | .csrf()
55 | .disable()
56 | .authorizeRequests()
57 |
58 | .antMatchers("/**")
59 | .permitAll()
60 |
61 | .anyRequest()
62 | .authenticated()
63 | .and()
64 | .exceptionHandling()
65 | .authenticationEntryPoint(jwtAuthenticationEntryPoint)
66 | .and()
67 | .sessionManagement()
68 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
69 |
70 | httpSecurity.cors();
71 |
72 | httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
73 |
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/AnimalController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.entities.Animal;
4 | import com.kdmeubichinho.services.AnimalService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.*;
7 |
8 | import java.util.Optional;
9 |
10 | @RestController
11 | @RequestMapping(path = "animal")
12 | public class AnimalController {
13 |
14 | @Autowired
15 | AnimalService animalService;
16 |
17 | @GetMapping()
18 | public Iterable getAllAnimais() {
19 | return animalService.getAllAnimals();
20 | }
21 |
22 | @GetMapping("/{id}")
23 | public Optional getById(@PathVariable Integer id) {
24 | return animalService.getById(id);
25 | }
26 |
27 | /*
28 | FIXME Fazer este metodo retonar a representacao mais atualida deste objeto
29 | */
30 | @PostMapping("/cadastrar")
31 | public Animal addAnimal(@RequestBody Animal animal) {
32 | animalService.save(animal);
33 | return animal;
34 | }
35 |
36 | @PutMapping("/{idAnimal}")
37 | public Animal updateAnimal(@PathVariable Integer idAnimal, @RequestBody Animal dadosAnimal) {
38 | return animalService.updateAnimal(idAnimal, dadosAnimal);
39 | }
40 |
41 | @DeleteMapping("/{id}")
42 | public void deleteAnimal(@PathVariable Integer id) {
43 | animalService.deleteAnimal(id);
44 | }
45 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/AnuncioController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.entities.Anuncio;
4 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
5 | import com.kdmeubichinho.enums.AnimalPorte;
6 | import com.kdmeubichinho.enums.AnimalSexo;
7 | import com.kdmeubichinho.enums.AnuncioStatus;
8 | import com.kdmeubichinho.services.AnuncioService;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.data.domain.Pageable;
12 | import org.springframework.http.HttpStatus;
13 | import org.springframework.web.bind.annotation.*;
14 |
15 | import java.util.Optional;
16 |
17 | @RestController
18 | @RequestMapping(path = "/anuncio")
19 | @CrossOrigin
20 | public class AnuncioController {
21 |
22 | @Autowired
23 | private AnuncioService anuncioService;
24 |
25 | @GetMapping("/busca")
26 | public Iterable getFilteredAnnounce(Pageable pageable, String cep, AnuncioStatus status, AnimalSexo sexo,
27 | AnimalPorte porte, AnimalClassificacaoEtaria classificacaoEtaria, Integer idCategoria, Integer idEspecie,
28 | Boolean castrado, Boolean vacinado) {
29 | return anuncioService.getFilteredAnnounce(pageable, cep, status, sexo, porte, classificacaoEtaria, idCategoria,
30 | idEspecie, castrado, vacinado);
31 | }
32 |
33 | @GetMapping("/{id}")
34 | public Optional getAnnounceById(@PathVariable Integer id) {
35 | return anuncioService.getAnnounceById(id);
36 | }
37 |
38 | @GetMapping("/pessoa")
39 | public Page getAnnounceByEmailPessoa(@RequestParam String email, Pageable pageable) {
40 | return anuncioService.getAnnounceByEmailPessoa(email, pageable);
41 | }
42 |
43 | @PostMapping()
44 | @ResponseStatus(HttpStatus.CREATED)
45 | public Anuncio addAnnounce(@RequestBody Anuncio anuncio) {
46 | return anuncioService.save(anuncio);
47 | }
48 |
49 | @PutMapping("atualizastatus/{idAnuncio}")
50 | public Anuncio updateStatusAnnounce(@PathVariable Integer idAnuncio) {
51 | return anuncioService.updateStatusAnnounce(idAnuncio);
52 | }
53 |
54 | @DeleteMapping("/{id}")
55 | public void deleteAnnounce(@PathVariable Integer id) {
56 | anuncioService.deleteAnnounce(id);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/CategoriaController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.controllers.generics.RestBasicController;
4 | import com.kdmeubichinho.dto.CategoriaRequestDTO;
5 | import com.kdmeubichinho.entities.Categoria;
6 | import com.kdmeubichinho.services.CategoriaService;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 |
12 | @RestController
13 | @RequestMapping(path = "categoria")
14 | public class CategoriaController extends RestBasicController {
15 |
16 | CategoriaService categoriaService;
17 |
18 | @Autowired
19 | public CategoriaController(CategoriaService service) {
20 | super(service);
21 | this.categoriaService = service;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/EspecieController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.controllers.generics.RestBasicController;
4 | import com.kdmeubichinho.dto.EspecieRequestDTO;
5 | import com.kdmeubichinho.entities.Especie;
6 | import com.kdmeubichinho.services.EspecieService;
7 |
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | @RestController
13 | @RequestMapping(path = "especie")
14 | public class EspecieController extends RestBasicController {
15 |
16 | @Autowired
17 | EspecieService especieService;
18 |
19 | @Autowired
20 | public EspecieController(EspecieService service) {
21 | super(service);
22 | this.especieService = service;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/FotoController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import java.io.IOException;
4 | import java.util.Date;
5 | import java.util.Optional;
6 |
7 | import com.kdmeubichinho.enums.EnumException;
8 | import com.kdmeubichinho.exception.ValidationException;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.web.bind.annotation.CrossOrigin;
11 | import org.springframework.web.bind.annotation.DeleteMapping;
12 | import org.springframework.web.bind.annotation.GetMapping;
13 | import org.springframework.web.bind.annotation.PathVariable;
14 | import org.springframework.web.bind.annotation.PostMapping;
15 | import org.springframework.web.bind.annotation.PutMapping;
16 | import org.springframework.web.bind.annotation.RequestBody;
17 | import org.springframework.web.bind.annotation.RequestMapping;
18 | import org.springframework.web.bind.annotation.RequestParam;
19 | import org.springframework.web.bind.annotation.RestController;
20 | import org.springframework.web.multipart.MultipartFile;
21 | import org.springframework.util.StringUtils;
22 |
23 | import com.kdmeubichinho.entities.Foto;
24 | import com.kdmeubichinho.repositories.FotoRepository;
25 | import com.kdmeubichinho.util.FileUploadUtil;
26 |
27 | @RestController
28 | @RequestMapping(path = "foto")
29 | public class FotoController {
30 |
31 | @Autowired
32 | private FotoRepository fotoRepository;
33 |
34 | @GetMapping()
35 | public Iterable getFoto() {
36 | return fotoRepository.findAll();
37 | }
38 |
39 | @GetMapping("/{id}")
40 | public Optional getById(@PathVariable Integer id) {
41 | return fotoRepository.findById(id);
42 | }
43 |
44 | @CrossOrigin
45 | @PostMapping()
46 | public String saveImg(@RequestParam("image") MultipartFile file) {
47 | String fileName = StringUtils.cleanPath(file.getOriginalFilename());
48 | String uploadDir = "target/classes/static";
49 |
50 | Date date = new Date();
51 | String filePrefix = date.getTime() + "-";
52 | fileName = filePrefix + fileName;
53 |
54 | try {
55 | FileUploadUtil.saveFile(uploadDir, fileName, file);
56 | } catch (IOException e) {
57 | return ("Não foi possível salvar o arquivo: " + fileName);
58 | }
59 | return fileName;
60 | }
61 |
62 | @PutMapping("/{idFoto}")
63 | public Foto updateFoto(@PathVariable Integer idFoto, @RequestBody Foto dadosFoto) {
64 | Foto meuFoto = fotoRepository.findById(idFoto)
65 | .orElseThrow(() -> new ValidationException(EnumException.ITEM_NAO_ENCONTRADO));
66 |
67 | if (!dadosFoto.getCaminho().isEmpty()) meuFoto.setCaminho(dadosFoto.getCaminho());
68 |
69 | fotoRepository.save(meuFoto);
70 |
71 | return meuFoto;
72 | }
73 |
74 | @DeleteMapping("/{id}")
75 | public void deleteFoto(@PathVariable Integer id) {
76 | fotoRepository.deleteById(id);
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/JwtAuthenticationController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.config.JwtTokenUtil;
4 | import com.kdmeubichinho.entities.Pessoa;
5 | import com.kdmeubichinho.enums.EnumException;
6 | import com.kdmeubichinho.exception.ValidationException;
7 | import com.kdmeubichinho.model.JwtRequest;
8 | import com.kdmeubichinho.model.JwtResponse;
9 | import com.kdmeubichinho.services.PessoaService;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.security.authentication.AuthenticationManager;
13 | import org.springframework.security.authentication.BadCredentialsException;
14 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
15 | import org.springframework.web.bind.annotation.CrossOrigin;
16 | import org.springframework.web.bind.annotation.PostMapping;
17 | import org.springframework.web.bind.annotation.RequestBody;
18 | import org.springframework.web.bind.annotation.RestController;
19 |
20 | @RestController
21 | @CrossOrigin
22 | public class JwtAuthenticationController {
23 |
24 | private AuthenticationManager authenticationManager;
25 | private JwtTokenUtil jwtTokenUtil;
26 | private PessoaService usuarioService;
27 |
28 | @Autowired
29 | public JwtAuthenticationController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, PessoaService usuarioService) {
30 | this.authenticationManager = authenticationManager;
31 | this.jwtTokenUtil = jwtTokenUtil;
32 | this.usuarioService = usuarioService;
33 | }
34 |
35 | @PostMapping(value = "/authenticate")
36 | public ResponseEntity createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) {
37 |
38 | Pessoa p = usuarioService.getPersonByEmail(authenticationRequest.getUsername()).orElseThrow(() ->
39 | new ValidationException(EnumException.ITEM_NAO_ENCONTRADO));
40 |
41 | authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
42 |
43 | final String token = jwtTokenUtil.generateToken(p,
44 | authenticationRequest.getSpecificClaim() != null ? authenticationRequest.getSpecificClaim().toString().replace("=", ":") : "");
45 |
46 | return ResponseEntity.ok(new JwtResponse(token));
47 | }
48 |
49 | private void authenticate(String username, String password) throws ValidationException {
50 | try {
51 | authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
52 | } catch (BadCredentialsException e) {
53 | throw new ValidationException(EnumException.INVALID_CREDENTIALS);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/MensagemController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.CrossOrigin;
7 | import org.springframework.web.bind.annotation.DeleteMapping;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.PathVariable;
10 | import org.springframework.web.bind.annotation.PostMapping;
11 | import org.springframework.web.bind.annotation.PutMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RequestMapping;
14 | import org.springframework.web.bind.annotation.RestController;
15 |
16 | import com.kdmeubichinho.entities.Mensagem;
17 | import com.kdmeubichinho.services.MensagemService;
18 |
19 | @RestController
20 | @RequestMapping(path = "/mensagem")
21 | @CrossOrigin
22 | public class MensagemController {
23 |
24 | @Autowired
25 | private MensagemService mensagemService;
26 |
27 | @GetMapping()
28 | public Iterable getAllMessages(){
29 | return mensagemService.getAll();
30 | }
31 |
32 | @GetMapping("/{id}")
33 | public Optional getMessageById(@PathVariable Integer id){
34 | return mensagemService.getById(id);
35 | }
36 |
37 | @PostMapping()
38 | public Mensagem addMessage(@RequestBody Mensagem message){
39 | return mensagemService.save(message);
40 | }
41 |
42 | @PutMapping("/{idMessage}")
43 | public Mensagem updateMessage(@PathVariable Integer idMessage,@RequestBody Mensagem dataMessage) throws Exception{
44 | return mensagemService.updateMessage(idMessage, dataMessage);
45 | }
46 |
47 | @DeleteMapping("/{id}")
48 | public void deleteMessage(@PathVariable Integer id) {
49 | mensagemService.deleteMessage(id);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/PessoaController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.CrossOrigin;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.PutMapping;
13 | import org.springframework.web.bind.annotation.DeleteMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RequestMapping;
16 | import org.springframework.web.bind.annotation.RequestParam;
17 | import org.springframework.web.bind.annotation.ResponseStatus;
18 | import org.springframework.web.bind.annotation.RestController;
19 |
20 | import com.kdmeubichinho.dto.CredenciaisDTO;
21 | import com.kdmeubichinho.dto.PessoaDTO;
22 | import com.kdmeubichinho.dto.TokenDTO;
23 | import com.kdmeubichinho.entities.Pessoa;
24 | import com.kdmeubichinho.services.PessoaService;
25 |
26 |
27 | import lombok.RequiredArgsConstructor;
28 |
29 | @RestController
30 | @RequestMapping(path = "/pessoa")
31 | @RequiredArgsConstructor
32 | @CrossOrigin
33 | public class PessoaController {
34 |
35 | @Autowired
36 | private PessoaService pessoaService;
37 |
38 | @GetMapping()
39 | public Iterable getAll(){
40 | return pessoaService.getAll();
41 | }
42 |
43 | @GetMapping("/{id}")
44 | public Optional getById(@PathVariable Integer id){
45 | return pessoaService.getById(id);
46 | }
47 |
48 | @GetMapping("/email")
49 | public Optional getPersonByEmail(@RequestParam String email) {
50 | return pessoaService.getPersonByEmail(email);
51 | }
52 |
53 | @PostMapping
54 | @ResponseStatus(HttpStatus.CREATED)
55 | public Pessoa salvar(@RequestBody com.kdmeubichinho.dto.PessoaDTO pessoa) {
56 | return pessoaService.savePerson(pessoa);
57 | }
58 |
59 | @PostMapping("/auth")
60 | public ResponseEntity autenticar(@RequestBody CredenciaisDTO credenciais) {
61 | return pessoaService.authenticatePerson(credenciais);
62 | }
63 |
64 | @PutMapping("/{emailPerson}")
65 | public Pessoa updatePessoa(@PathVariable String emailPerson,@RequestBody PessoaDTO dataPerson) throws Exception{
66 | return pessoaService.updatePerson(emailPerson, dataPerson);
67 | }
68 |
69 | @DeleteMapping("/{id}")
70 | public void deletePessoa(@PathVariable Integer id) {
71 | pessoaService.deleteById(id);
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/controllers/generics/RestBasicController.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers.generics;
2 |
3 | import com.kdmeubichinho.dto.generics.ObjectDTO;
4 | import com.kdmeubichinho.entities.generics.BaseEntity;
5 | import com.kdmeubichinho.enums.EnumException;
6 | import com.kdmeubichinho.exception.ValidationException;
7 | import com.kdmeubichinho.services.generics.RestBasicService;
8 | import org.springframework.data.domain.Page;
9 | import org.springframework.data.domain.Pageable;
10 | import org.springframework.data.web.PageableDefault;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.web.bind.annotation.*;
13 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
14 |
15 | import java.net.URI;
16 | import java.util.List;
17 | import java.util.Optional;
18 |
19 | public class RestBasicController {
20 |
21 | final RestBasicService basicService;
22 |
23 | public RestBasicController(RestBasicService basicService) {
24 | this.basicService = basicService;
25 | }
26 |
27 | /**
28 | * @param page responsible for changing the default paging behaviour
29 | * @return pageable list of results
30 | */
31 | @GetMapping(value = {"full"})
32 | public Page getAllPaged(@PageableDefault(size = 50) Pageable page) {
33 | return this.basicService.getAll(page);
34 | }
35 |
36 | /**
37 | * @return Return a list of all DTOs
38 | */
39 | @GetMapping(value = {"", "all"})
40 | public List getAll() {
41 | return this.basicService.getAll();
42 | }
43 |
44 | @GetMapping(value = "{id}")
45 | public Optional getById(@PathVariable("id") Integer id) {
46 | return basicService.getById(id);
47 | }
48 |
49 | /**
50 | * create a resource
51 | *
52 | * @param i -> generic type to be persisted
53 | * @return Response entity containing the resource location and the resource it self
54 | */
55 | @PostMapping(consumes = "application/json")
56 | public ResponseEntity save(@RequestBody I i) {
57 | I saved = basicService.save(i);
58 | URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{id}").buildAndExpand(saved.build().getId()).toUri();
59 | return ResponseEntity.created(uri).body(saved);
60 | }
61 |
62 | /**
63 | * delete a resource searching by its ID
64 | * @param id
65 | * @return
66 | */
67 | @DeleteMapping("/{id}")
68 | public ResponseEntity delete(@PathVariable Integer id) {
69 | T t = basicService.getById(id)
70 | .orElseThrow(() -> new ValidationException(EnumException.ITEM_NAO_ENCONTRADO));
71 | basicService.deleteById(t.getId());
72 | return ResponseEntity.noContent().build();
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/converters/AnimalClassificacaoEtariaConverter.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import javax.persistence.AttributeConverter;
4 | import javax.persistence.Converter;
5 |
6 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
7 |
8 | @Converter(autoApply = true)
9 | public class AnimalClassificacaoEtariaConverter implements AttributeConverter {
10 |
11 | @Override
12 | public String convertToDatabaseColumn(AnimalClassificacaoEtaria classificacaoEtaria) {
13 | if(classificacaoEtaria == null) {
14 | return null;
15 | }
16 | return classificacaoEtaria.getDescricao();
17 | }
18 |
19 | @Override
20 | public AnimalClassificacaoEtaria convertToEntityAttribute(String descricao) {
21 | if(descricao == null) {
22 | return null;
23 | }
24 |
25 | return AnimalClassificacaoEtaria.of(descricao);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/converters/AnimalPorteConverter.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import javax.persistence.AttributeConverter;
4 | import javax.persistence.Converter;
5 |
6 | import com.kdmeubichinho.enums.AnimalPorte;
7 |
8 |
9 | @Converter(autoApply = true)
10 | public class AnimalPorteConverter implements AttributeConverter {
11 |
12 | @Override
13 | public String convertToDatabaseColumn(AnimalPorte porte) {
14 | if(porte == null) {
15 | return null;
16 | }
17 | return porte.getDescricao();
18 | }
19 |
20 | @Override
21 | public AnimalPorte convertToEntityAttribute(String descricao) {
22 | if(descricao == null) {
23 | return null;
24 | }
25 |
26 | return AnimalPorte.of(descricao);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/converters/AnimalSexoConverter.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import javax.persistence.AttributeConverter;
4 | import javax.persistence.Converter;
5 |
6 | import com.kdmeubichinho.enums.AnimalSexo;
7 |
8 | @Converter(autoApply = true)
9 | public class AnimalSexoConverter implements AttributeConverter{
10 |
11 | @Override
12 | public String convertToDatabaseColumn(AnimalSexo sexo) {
13 | if(sexo == null) {
14 | return null;
15 | }
16 | return sexo.getDescricao();
17 | }
18 |
19 | @Override
20 | public AnimalSexo convertToEntityAttribute(String descricao) {
21 | if(descricao == null) {
22 | return null;
23 | }
24 |
25 | return AnimalSexo.of(descricao);
26 | }
27 |
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/converters/AnimalTipoConverter.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import javax.persistence.AttributeConverter;
4 | import javax.persistence.Converter;
5 |
6 | import com.kdmeubichinho.enums.AnimalTipo;
7 |
8 |
9 |
10 | @Converter(autoApply = true)
11 | public class AnimalTipoConverter implements AttributeConverter {
12 |
13 | @Override
14 | public String convertToDatabaseColumn(AnimalTipo tipo) {
15 | if(tipo == null) {
16 | return null;
17 | }
18 | return tipo.getDescricao();
19 | }
20 |
21 | @Override
22 | public AnimalTipo convertToEntityAttribute(String descricao) {
23 | if(descricao == null) {
24 | return null;
25 | }
26 |
27 | return AnimalTipo.of(descricao);
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/converters/AnuncioStatusConverter.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import javax.persistence.AttributeConverter;
4 | import javax.persistence.Converter;
5 |
6 | import com.kdmeubichinho.enums.AnuncioStatus;
7 |
8 | @Converter(autoApply = true)
9 | public class AnuncioStatusConverter implements AttributeConverter {
10 |
11 |
12 | @Override
13 | public String convertToDatabaseColumn(AnuncioStatus status) {
14 | if(status == null) {
15 | return null;
16 | }
17 | return status.getDescricao();
18 | }
19 |
20 | @Override
21 | public AnuncioStatus convertToEntityAttribute(String descricao) {
22 | if(descricao == null) {
23 | return null;
24 | }
25 |
26 | return AnuncioStatus.of(descricao);
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/CategoriaRequestDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.dto.generics.ObjectDTO;
4 | import com.kdmeubichinho.entities.Categoria;
5 | import lombok.*;
6 |
7 | @Getter
8 | @Setter
9 | @NoArgsConstructor
10 | @AllArgsConstructor
11 | public class CategoriaRequestDTO implements ObjectDTO {
12 |
13 | private String classificacao;
14 |
15 | public Categoria build() {
16 | return new Categoria()
17 | .setClassificacao(this.classificacao);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/CredenciaisDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import lombok.*;
4 |
5 | @Getter
6 | @Setter
7 | @NoArgsConstructor
8 | @AllArgsConstructor
9 | public class CredenciaisDTO {
10 | private String email;
11 | private String senha;
12 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/CustomExceptionDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 |
8 | @NoArgsConstructor
9 | @AllArgsConstructor
10 | @Getter
11 | @Setter
12 | public class CustomExceptionDTO {
13 | private String message;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/EspecieRequestDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 |
4 | import com.kdmeubichinho.dto.generics.ObjectDTO;
5 | import com.kdmeubichinho.entities.Especie;
6 | import lombok.*;
7 |
8 | @Getter
9 | @Setter
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 | public class EspecieRequestDTO implements ObjectDTO {
13 |
14 | private String nome;
15 |
16 | public Especie build() {
17 | return new Especie()
18 | .setNome(this.nome);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/MensagemDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.dto.generics.ObjectDTO;
4 | import com.kdmeubichinho.entities.Anuncio;
5 | import com.kdmeubichinho.entities.Mensagem;
6 | import com.kdmeubichinho.entities.Pessoa;
7 | import lombok.AllArgsConstructor;
8 | import lombok.NoArgsConstructor;
9 |
10 | import java.util.Date;
11 |
12 | @NoArgsConstructor
13 | @AllArgsConstructor
14 | public class MensagemDTO implements ObjectDTO {
15 |
16 | private Integer idMensagem;
17 | private Date dataMensagem;
18 | private String mensagem;
19 | private Pessoa idPessoa;
20 | private Anuncio idAnuncio;
21 |
22 | @Override
23 | public Mensagem build() {
24 | return new Mensagem();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/PessoaDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 |
5 | import lombok.*;
6 |
7 | @Getter
8 | @Setter
9 | @NoArgsConstructor
10 | @AllArgsConstructor
11 | public class PessoaDTO {
12 | private Integer idPessoa;
13 | private String nome;
14 | private String email;
15 | private String cep;
16 | private String logradouro;
17 | private String complemento;
18 | private String bairro;
19 | private String localidade;
20 | private String uf;
21 | private String ibge;
22 | private String ddd;
23 | private String numeroResidencial;
24 | private String celular;
25 | private String senha;
26 |
27 | public Pessoa build() {
28 | return new Pessoa(this.idPessoa, this.nome, this.email, this.cep, this.logradouro, this.complemento, this.bairro, this.localidade,
29 | this.uf, this.ibge, this.ddd, this.numeroResidencial, this.celular, this.senha, true);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/TokenDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import lombok.*;
4 |
5 | @Getter
6 | @Setter
7 | @NoArgsConstructor
8 | @AllArgsConstructor
9 | public class TokenDTO {
10 | private String email;
11 | private String token;
12 |
13 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/dto/generics/ObjectDTO.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto.generics;
2 |
3 | import com.kdmeubichinho.entities.generics.BaseEntity;
4 |
5 | public interface ObjectDTO {
6 | BaseEntity build();
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Animal.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
4 | import com.kdmeubichinho.enums.AnimalPorte;
5 | import com.kdmeubichinho.enums.AnimalSexo;
6 | import lombok.*;
7 | import lombok.experimental.Accessors;
8 |
9 | import javax.persistence.*;
10 |
11 | @Entity
12 | @Getter
13 | @Setter
14 | @NoArgsConstructor
15 | @AllArgsConstructor
16 | @Accessors(chain = true)
17 | public class Animal {
18 |
19 | @Id
20 | @GeneratedValue(strategy = GenerationType.IDENTITY)
21 | @Column(name = "id_animal")
22 | private Integer idAnimal;
23 | @Column(nullable = false)
24 | private AnimalSexo sexo;
25 | @Column(nullable = false)
26 | private AnimalClassificacaoEtaria classificacaoEtaria;
27 | @Column(nullable = false)
28 | private AnimalPorte porte;
29 | @Column(nullable = false)
30 | private Boolean castrado;
31 | @Column(nullable = false)
32 | private Boolean vacinado;
33 | @Column(nullable = true)
34 | private String nome;
35 | @Column(nullable = false)
36 | private String cep;
37 | private String logradouro;
38 | private String complemento;
39 | private String bairro;
40 | private String localidade;
41 | private String uf;
42 | private String ibge;
43 | private String ddd;
44 | @OneToOne()
45 | @JoinColumn(name = "fk_id_especie")
46 | private Especie especie;
47 |
48 | @OneToOne(cascade = CascadeType.ALL)
49 | @JoinColumn(name = "fk_id_foto")
50 | private Foto fotos;
51 |
52 | public Animal(AnimalSexo animalSexo, AnimalClassificacaoEtaria classificacaoEtaria, AnimalPorte animalPorte,
53 | Boolean castrado, Boolean vacinado, String cep){
54 | sexo = animalSexo;
55 | this.classificacaoEtaria = classificacaoEtaria;
56 | porte = animalPorte;
57 | this.castrado = castrado;
58 | this.vacinado = vacinado;
59 | this.cep = cep;
60 | }
61 |
62 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Anuncio.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import java.util.Date;
4 | import java.util.Set;
5 |
6 | import javax.persistence.CascadeType;
7 | import javax.persistence.Column;
8 | import javax.persistence.Entity;
9 | import javax.persistence.GeneratedValue;
10 | import javax.persistence.GenerationType;
11 | import javax.persistence.Id;
12 | import javax.persistence.JoinColumn;
13 | import javax.persistence.OneToMany;
14 | import javax.persistence.OneToOne;
15 |
16 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
17 | import com.kdmeubichinho.enums.AnuncioStatus;
18 |
19 |
20 | import lombok.AllArgsConstructor;
21 | import lombok.Getter;
22 | import lombok.NoArgsConstructor;
23 | import lombok.Setter;
24 | import lombok.experimental.Accessors;
25 | import org.hibernate.annotations.CreationTimestamp;
26 |
27 | @Entity
28 | @Setter
29 | @Getter
30 | @AllArgsConstructor
31 | @NoArgsConstructor
32 | @Accessors(chain = true)
33 | public class Anuncio {
34 |
35 | @Id
36 | @GeneratedValue(strategy = GenerationType.IDENTITY)
37 | @Column(name = "id_anuncio")
38 | private Integer idAnuncio;
39 |
40 | @Column(name = "status_anuncio", nullable = false)
41 | private AnuncioStatus status;
42 |
43 | @CreationTimestamp
44 | @Column(name = "data_criacao", nullable = false)
45 | private Date dataCriacao;
46 |
47 | @Column(name = "data_encerramento")
48 | private Date dataEncerramento;
49 |
50 | @OneToOne()
51 | @JoinColumn(name = "fk_id_pessoa")
52 | @JsonIgnoreProperties(value = {"senha"})
53 | private Pessoa idPessoa;
54 |
55 | @OneToOne(cascade = CascadeType.ALL)
56 | @JoinColumn(name = "fk_id_animal")
57 | private Animal idAnimal;
58 |
59 | @OneToOne()
60 | @JoinColumn(name = "fk_id_categoria")
61 | private Categoria idCategoria;
62 |
63 | @JoinColumn(name = "fk_id_anuncio")
64 | @OneToMany()
65 | @JsonIgnoreProperties("id_anuncio")
66 | private Set mensagens;
67 |
68 | public Anuncio(AnuncioStatus anuncioStatus, Date dataCriacao){
69 | status = anuncioStatus;
70 | this.dataCriacao = dataCriacao;
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Categoria.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import javax.persistence.*;
4 |
5 | import com.fasterxml.jackson.annotation.JsonIgnore;
6 | import com.kdmeubichinho.entities.generics.BaseEntity;
7 | import lombok.*;
8 | import lombok.experimental.Accessors;
9 |
10 | @Entity
11 | @Getter
12 | @Setter
13 | @NoArgsConstructor
14 | @AllArgsConstructor
15 | @Accessors(chain = true)
16 | public class Categoria implements BaseEntity {
17 |
18 | @Id
19 | @GeneratedValue(strategy = GenerationType.IDENTITY)
20 | @Column(name = "id_categoria")
21 | private Integer idCategoria;
22 |
23 | @Column(nullable = false)
24 | private String classificacao;
25 |
26 | @Transient
27 | @Override
28 | @JsonIgnore
29 | public Integer getId() {
30 | return this.getIdCategoria();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Especie.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import javax.persistence.*;
4 |
5 |
6 | import com.fasterxml.jackson.annotation.JsonIgnore;
7 | import com.kdmeubichinho.entities.generics.BaseEntity;
8 | import lombok.AllArgsConstructor;
9 | import lombok.Getter;
10 | import lombok.NoArgsConstructor;
11 | import lombok.Setter;
12 | import lombok.experimental.Accessors;
13 |
14 | @Entity
15 | @Getter
16 | @Setter
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | @Accessors(chain = true)
20 | public class Especie implements BaseEntity {
21 |
22 | @Id
23 | @GeneratedValue(strategy = GenerationType.IDENTITY)
24 | @Column(name = "id_especie")
25 | private Integer idEspecie;
26 |
27 | @Column(nullable = false)
28 | private String nome;
29 |
30 | @Transient
31 | @Override
32 | @JsonIgnore
33 | public Integer getId() {
34 | return this.getIdEspecie();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Foto.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 |
9 | import lombok.AllArgsConstructor;
10 | import lombok.Getter;
11 | import lombok.NoArgsConstructor;
12 | import lombok.Setter;
13 |
14 | @Entity
15 | @Getter
16 | @Setter
17 | @AllArgsConstructor
18 | @NoArgsConstructor
19 | public class Foto {
20 |
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.IDENTITY)
23 | @Column(name = "id_foto")
24 | private Integer idFoto;
25 |
26 | @Column(nullable = false)
27 | private String caminho;
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Mensagem.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import java.util.Date;
4 |
5 | import javax.persistence.Column;
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.JoinColumn;
11 | import javax.persistence.ManyToOne;
12 | import javax.persistence.OneToOne;
13 |
14 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
15 |
16 | import com.kdmeubichinho.entities.generics.BaseEntity;
17 | import lombok.AllArgsConstructor;
18 | import lombok.Getter;
19 | import lombok.NoArgsConstructor;
20 | import lombok.Setter;
21 |
22 | @AllArgsConstructor
23 | @NoArgsConstructor
24 | @Entity
25 | @Getter
26 | @Setter
27 | public class Mensagem implements BaseEntity {
28 |
29 | @Id
30 | @GeneratedValue(strategy = GenerationType.IDENTITY)
31 | @Column(name = "id_mensagem")
32 | private Integer idMensagem;
33 |
34 | @Column(name = "data_mensagem", nullable = false)
35 | private Date dataMensagem;
36 |
37 | @Column(nullable = false, name = "mensagem")
38 | private String msgConteudo;
39 |
40 | @JoinColumn(name = "fk_id_pessoa")
41 | @OneToOne
42 | private Pessoa idPessoa;
43 |
44 | @JoinColumn(name = "fk_id_anuncio")
45 | @ManyToOne
46 | @JsonIgnoreProperties("mensagens")
47 | private Anuncio idAnuncio;
48 |
49 | @Override
50 | public Integer getId(){
51 | return this.getIdMensagem();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/Pessoa.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import lombok.AllArgsConstructor;
11 | import lombok.Builder;
12 | import lombok.Getter;
13 | import lombok.NoArgsConstructor;
14 | import lombok.Setter;
15 | import lombok.experimental.Accessors;
16 | import org.springframework.security.core.GrantedAuthority;
17 | import org.springframework.security.core.userdetails.UserDetails;
18 |
19 | import java.util.Collection;
20 | import java.util.Collections;
21 |
22 | @Entity
23 | @Builder
24 | @NoArgsConstructor
25 | @AllArgsConstructor
26 | @Getter
27 | @Setter
28 | @Accessors(chain = true)
29 | @Table(name = "pessoa")
30 | public class Pessoa implements UserDetails {
31 |
32 | @Id
33 | @GeneratedValue(strategy = GenerationType.IDENTITY)
34 | @Column(name = "id_pessoa")
35 | private Integer idPessoa;
36 |
37 | @Column(nullable = false)
38 | private String nome;
39 |
40 | @Column(nullable = false)
41 | private String email;
42 |
43 | @Column(nullable = false)
44 | private String cep;
45 |
46 | private String logradouro;
47 | private String complemento;
48 | private String bairro;
49 | private String localidade;
50 | private String uf;
51 | private String ibge;
52 | private String ddd;
53 |
54 | @Column(name = "numero_residencial")
55 | private String numeroResidencial;
56 |
57 | @Column(nullable = false)
58 | private String celular;
59 |
60 | @Column(nullable = false)
61 | private String senha;
62 |
63 | private boolean admin;
64 |
65 | public Pessoa(String nome, String email, String cep, String celular, String senha){
66 | this.nome = nome;
67 | this.email = email;
68 | this.cep = cep;
69 | this.celular = celular;
70 | this.senha = senha;
71 | }
72 |
73 | @Override
74 | public Collection extends GrantedAuthority> getAuthorities() {
75 | return Collections.emptyList();
76 | }
77 |
78 | @Override
79 | public String getPassword() {
80 | return this.getSenha();
81 | }
82 |
83 | @Override
84 | public String getUsername() {
85 | return this.getEmail();
86 | }
87 |
88 | @Override
89 | public boolean isAccountNonExpired() {
90 | return true;
91 | }
92 |
93 | @Override
94 | public boolean isAccountNonLocked() {
95 | return true;
96 | }
97 |
98 | @Override
99 | public boolean isCredentialsNonExpired() {
100 | return true;
101 | }
102 |
103 | @Override
104 | public boolean isEnabled() {
105 | return true;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/entities/generics/BaseEntity.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities.generics;
2 |
3 | /**
4 | *
5 | */
6 | public interface BaseEntity {
7 | Integer getId();
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/enums/AnimalClassificacaoEtaria.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 | import java.util.stream.*;
3 | public enum AnimalClassificacaoEtaria {
4 | FILHOTE("Filhote"),
5 | ADULTO("Adulto");
6 |
7 | private String descricao;
8 |
9 | private AnimalClassificacaoEtaria(String descricao) {
10 | this.descricao = descricao;
11 | }
12 | public String getDescricao() {
13 | return descricao;
14 | }
15 | public static AnimalClassificacaoEtaria of(String descricao) {
16 | return Stream.of(AnimalClassificacaoEtaria.values())
17 | .filter(t -> t.getDescricao().equalsIgnoreCase(descricao))
18 | .findFirst()
19 | .orElseThrow(IllegalArgumentException::new);
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/enums/AnimalPorte.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import java.util.stream.Stream;
4 |
5 | public enum AnimalPorte{
6 | PEQUENO("Pequeno"),
7 | MEDIO("Médio"),
8 | GRANDE("Grande");
9 |
10 | private String descricao;
11 |
12 | private AnimalPorte(String descricao) {
13 | this.descricao = descricao;
14 | }
15 |
16 | public String getDescricao() {
17 | return descricao;
18 | }
19 |
20 | public static AnimalPorte of(String descricao) {
21 | return Stream.of(AnimalPorte.values())
22 | .filter(t -> t.getDescricao().equalsIgnoreCase(descricao))
23 | .findFirst()
24 | .orElseThrow(IllegalArgumentException::new);
25 | }
26 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/enums/AnimalSexo.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 | import java.util.stream.Stream;
3 |
4 | public enum AnimalSexo {
5 |
6 | MACHO("Macho"),
7 | FEMEA("Fêmea"),
8 | NAO_IDENTIFICADO("Não identificado");
9 |
10 | private String descricao;
11 |
12 | private AnimalSexo(String descricao){
13 | this.descricao = descricao;
14 | }
15 | public String getDescricao() {
16 | return descricao;
17 | }
18 | public static AnimalSexo of(String descricao) {
19 | return Stream.of(AnimalSexo.values())
20 | .filter(t -> t.getDescricao().equalsIgnoreCase(descricao))
21 | .findFirst()
22 | .orElseThrow(IllegalArgumentException::new);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/enums/AnimalTipo.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import java.util.stream.Stream;
4 |
5 | public enum AnimalTipo {
6 | CACHORRO("Cachorro"), GATO("Gato"), COELHO("Coelho"), HAMSTER("Hamster");
7 |
8 | private String descricao;
9 |
10 | private AnimalTipo(String descricao) {
11 | this.descricao = descricao;
12 | }
13 | public String getDescricao() {
14 | return descricao;
15 | }
16 |
17 | public static AnimalTipo of(String descricao) {
18 | return Stream.of(AnimalTipo.values())
19 | .filter(t -> t.getDescricao().equalsIgnoreCase(descricao))
20 | .findFirst()
21 | .orElseThrow(IllegalArgumentException::new);
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/enums/AnuncioStatus.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import java.util.stream.Stream;
4 |
5 | public enum AnuncioStatus {
6 | ATIVO("Ativo"),
7 | INATIVO("Inativo");
8 |
9 | private String descricao;
10 |
11 | private AnuncioStatus(String descricao) {
12 | this.descricao = descricao;
13 | }
14 | public String getDescricao() {
15 | return descricao;
16 | }
17 | public static AnuncioStatus of(String descricao) {
18 | return Stream.of(AnuncioStatus.values())
19 | .filter(t -> t.getDescricao().equalsIgnoreCase(descricao))
20 | .findFirst()
21 | .orElseThrow(IllegalArgumentException::new);
22 | }
23 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/enums/EnumException.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.springframework.http.HttpStatus;
4 |
5 | import java.util.stream.Stream;
6 |
7 | public enum EnumException {
8 |
9 | ITEM_NAO_ENCONTRADO(HttpStatus.NOT_FOUND, "O recurso solicitado nao esta disponivel no servidor"),
10 | USER_DISABLED(HttpStatus.BAD_REQUEST, "Usuario desabilitado"),
11 | INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Credenciais informadas incorretamente");
12 |
13 | private final HttpStatus httpStatus;
14 | private final String descricao;
15 |
16 | EnumException(HttpStatus httpStatus, String descricao) {
17 | this.httpStatus = httpStatus;
18 | this.descricao = descricao;
19 | }
20 |
21 | public String getDescricao() {
22 | return descricao;
23 | }
24 |
25 | public HttpStatus getHttpStatus() {
26 | return httpStatus;
27 | }
28 |
29 | public static EnumException of(String descricao) {
30 | return Stream.of(EnumException.values())
31 | .filter(t -> t.getDescricao().equalsIgnoreCase(descricao))
32 | .findFirst()
33 | .orElseThrow(IllegalArgumentException::new);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/exception/GlobalControllerExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.exception;
2 |
3 | import com.kdmeubichinho.dto.CustomExceptionDTO;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.orm.jpa.JpaSystemException;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.ResponseBody;
10 |
11 | @ControllerAdvice
12 | public class GlobalControllerExceptionHandler {
13 |
14 | @ExceptionHandler(ValidationException.class)
15 | @ResponseBody
16 | public ResponseEntity handleCustomSimpleException(ValidationException validationException) {
17 | HttpStatus responseStatus = validationException.getHttpStatus();
18 | return new ResponseEntity<>(new CustomExceptionDTO(validationException.getDescription()), responseStatus);
19 | }
20 |
21 | @ExceptionHandler(JpaSystemException.class)
22 | @ResponseBody
23 | public ResponseEntity handleJpaException(JpaSystemException ex) {
24 | String errorMessage = "Ocorreu um erro ao tentar executar a operação";
25 |
26 | if(null != ex.getCause().getCause()) {
27 | String[] errors = ex.getCause().getCause().toString().split("#");
28 | if (errors.length > 1) {
29 | errorMessage = errors[2];
30 | }
31 | } else{
32 | errorMessage += ex.getCause();
33 | }
34 | return new ResponseEntity<>(new CustomExceptionDTO(errorMessage), HttpStatus.INTERNAL_SERVER_ERROR);
35 | }
36 |
37 | @ExceptionHandler(Exception.class)
38 | @ResponseBody
39 | public ResponseEntity handleAllOtherException(Exception ex) {
40 | return new ResponseEntity<>(new CustomExceptionDTO(ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/exception/ValidationException.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.exception;
2 |
3 | import com.kdmeubichinho.enums.EnumException;
4 | import org.springframework.http.HttpStatus;
5 |
6 | /**
7 | * Validation exceptions. Exceptions related to server-side verifications (i.e. user not found (404 - NOT_FOUND), etc).
8 | */
9 | public class ValidationException extends RuntimeException{
10 |
11 | /**
12 | *
13 | */
14 | private static final long serialVersionUID = 5957756808614122964L;
15 |
16 | private final HttpStatus httpStatus;
17 | private final String description;
18 |
19 | public ValidationException(EnumException exceptionEnum) {
20 | this.description = exceptionEnum.getDescricao();
21 | this.httpStatus = exceptionEnum.getHttpStatus();
22 | }
23 |
24 | public ValidationException(String description, HttpStatus httpStatus) {
25 | this.description = description;
26 | this.httpStatus = httpStatus;
27 | }
28 |
29 | public HttpStatus getHttpStatus() {
30 | return httpStatus;
31 | }
32 |
33 | public String getDescription() {
34 | return description;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/model/JwtRequest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 |
8 | @AllArgsConstructor
9 | @NoArgsConstructor
10 | public class JwtRequest {
11 |
12 | @Getter
13 | @Setter
14 | private String username;
15 |
16 | @Getter
17 | @Setter
18 | private String password;
19 |
20 | @Getter
21 | @Setter
22 | private Object specificClaim;
23 |
24 | public JwtRequest(String username, String password) {
25 | this.setUsername(username);
26 | this.setPassword(password);
27 | }
28 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/model/JwtResponse.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.model;
2 |
3 | public class JwtResponse {
4 |
5 | private final String jwttoken;
6 |
7 | public JwtResponse(String jwttoken) {
8 | this.jwttoken = jwttoken;
9 | }
10 |
11 | public String getToken() {
12 | return this.jwttoken;
13 | }
14 |
15 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/AnimalRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.repositories;
2 |
3 | import org.springframework.data.repository.CrudRepository;
4 | import com.kdmeubichinho.entities.Animal;
5 |
6 |
7 |
8 | public interface AnimalRepository extends CrudRepository{
9 |
10 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/AnuncioRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.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.JpaSpecificationExecutor;
9 |
10 | import com.kdmeubichinho.entities.Anuncio;
11 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
12 | import com.kdmeubichinho.enums.AnimalPorte;
13 | import com.kdmeubichinho.enums.AnimalSexo;
14 |
15 |
16 | public interface AnuncioRepository extends JpaRepository, JpaSpecificationExecutor{
17 |
18 | Page findByIdAnimalSexo(AnimalSexo sexo, Pageable pageable);
19 | Page findByIdAnimalEspecieIdEspecie(Integer id, Pageable pageable);
20 | Page findByIdCategoriaIdCategoria(Integer id, Pageable pageable);
21 | Page findByIdAnimalClassificacaoEtaria(AnimalClassificacaoEtaria classificacaoEtaria, Pageable pageable);
22 | Page findByIdAnimalPorte(AnimalPorte porte, Pageable pageable);
23 | List findByIdAnimalSexoAndIdAnimalPorte(AnimalSexo sexo, AnimalPorte porte);
24 | Page findByidPessoaEmail(String email, Pageable pageable);
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/CategoriaRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import com.kdmeubichinho.entities.Categoria;
7 |
8 |
9 | @Repository
10 | public interface CategoriaRepository extends JpaRepository {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/EspecieRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.repositories;
2 |
3 | import com.kdmeubichinho.entities.Especie;
4 | import org.springframework.data.repository.PagingAndSortingRepository;
5 |
6 |
7 | public interface EspecieRepository extends PagingAndSortingRepository {
8 |
9 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/FotoRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.repositories;
2 |
3 | import org.springframework.data.repository.CrudRepository;
4 | import com.kdmeubichinho.entities.Foto;
5 | public interface FotoRepository extends CrudRepository {
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/MensagemRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.repositories;
2 |
3 | import com.kdmeubichinho.entities.Mensagem;
4 | import org.springframework.data.repository.PagingAndSortingRepository;
5 |
6 | public interface MensagemRepository extends PagingAndSortingRepository {
7 |
8 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/repositories/PessoaRepository.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.repositories;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.kdmeubichinho.entities.Pessoa;
8 |
9 |
10 |
11 | public interface PessoaRepository extends JpaRepository{
12 |
13 | Pessoa findOneByEmail(String email);
14 | Optional findByEmail(String email);
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/security/AutenticacaoService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.security;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import com.kdmeubichinho.services.PessoaService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.context.annotation.Lazy;
7 | import org.springframework.security.core.userdetails.UserDetails;
8 | import org.springframework.security.core.userdetails.UserDetailsService;
9 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
10 | import org.springframework.stereotype.Service;
11 |
12 | import java.util.Optional;
13 |
14 | @Service
15 | public class AutenticacaoService implements UserDetailsService {
16 |
17 | private PessoaService service;
18 |
19 | @Autowired
20 | public AutenticacaoService(@Lazy PessoaService service){
21 | this.service = service;
22 | }
23 |
24 | @Override
25 | public UserDetails loadUserByUsername(String username) {
26 | Optional p = service.getPersonByEmail(username);
27 |
28 | if (p.isPresent()) {
29 | return p.get();
30 | }
31 |
32 | throw new UsernameNotFoundException("Dados inválidos!");
33 | }
34 |
35 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/AnimalService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import java.util.Optional;
4 |
5 | import com.kdmeubichinho.enums.EnumException;
6 | import com.kdmeubichinho.exception.ValidationException;
7 | import org.apache.commons.lang.StringUtils;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.stereotype.Service;
10 |
11 | import com.kdmeubichinho.converters.AnimalClassificacaoEtariaConverter;
12 | import com.kdmeubichinho.converters.AnimalPorteConverter;
13 | import com.kdmeubichinho.converters.AnimalSexoConverter;
14 | import com.kdmeubichinho.entities.Animal;
15 | import com.kdmeubichinho.repositories.AnimalRepository;
16 |
17 | @Service
18 | public class AnimalService {
19 |
20 | @Autowired
21 | AnimalRepository animalRepository;
22 |
23 | public Iterable getAllAnimals(){
24 | return animalRepository.findAll();
25 | }
26 |
27 | public Optional getById(Integer id){
28 | return animalRepository.findById(id);
29 | }
30 | public Animal save(Animal animal) {
31 | return animalRepository.save(animal);
32 | }
33 | public Animal updateAnimal(Integer idAnimal, Animal dadosAnimal){
34 |
35 | AnimalPorteConverter porteAnimalConverter = new AnimalPorteConverter();
36 | AnimalClassificacaoEtariaConverter classificacaoEtariaAnimalConverter = new AnimalClassificacaoEtariaConverter();
37 | AnimalSexoConverter sexoAnimalConverter = new AnimalSexoConverter();
38 |
39 | Animal meuAnimal = animalRepository.findById(idAnimal)
40 | .orElseThrow(()-> new ValidationException(EnumException.ITEM_NAO_ENCONTRADO));
41 |
42 | if(dadosAnimal.getCastrado() != null) meuAnimal.setCastrado(dadosAnimal.getCastrado());
43 | if(dadosAnimal.getVacinado() != null) meuAnimal.setVacinado(dadosAnimal.getVacinado());
44 | if(dadosAnimal.getEspecie() != null) meuAnimal.setEspecie(dadosAnimal.getEspecie());
45 | if(!StringUtils.isBlank(dadosAnimal.getCep())) meuAnimal.setCep(dadosAnimal.getCep());
46 | if(!StringUtils.isBlank(dadosAnimal.getNome())) meuAnimal.setNome(dadosAnimal.getNome());
47 | if(null != dadosAnimal.getPorte()) meuAnimal.setPorte(porteAnimalConverter.convertToEntityAttribute(dadosAnimal.getPorte().getDescricao()));
48 | if(null != dadosAnimal.getClassificacaoEtaria()) meuAnimal.setClassificacaoEtaria(classificacaoEtariaAnimalConverter.convertToEntityAttribute(dadosAnimal.getClassificacaoEtaria().getDescricao()));
49 | if(null != dadosAnimal.getSexo()) meuAnimal.setSexo(sexoAnimalConverter.convertToEntityAttribute(dadosAnimal.getSexo().getDescricao()));
50 |
51 | animalRepository.save(meuAnimal);
52 | return meuAnimal;
53 | }
54 | public void deleteAnimal(Integer id) {
55 | animalRepository.deleteById(id);
56 | }
57 |
58 | }
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/AnuncioService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import java.text.SimpleDateFormat;
4 | import java.util.Date;
5 | import java.util.List;
6 | import java.util.Optional;
7 |
8 | import com.kdmeubichinho.enums.*;
9 | import com.kdmeubichinho.exception.ValidationException;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.data.domain.Page;
12 | import org.springframework.data.domain.Pageable;
13 | import org.springframework.data.jpa.domain.Specification;
14 |
15 | import com.kdmeubichinho.converters.AnuncioStatusConverter;
16 | import com.kdmeubichinho.entities.Anuncio;
17 | import com.kdmeubichinho.entities.Pessoa;
18 | import com.kdmeubichinho.repositories.AnuncioRepository;
19 | import com.kdmeubichinho.repositories.PessoaRepository;
20 | import com.kdmeubichinho.specification.AnuncioSpecification;
21 | import org.springframework.stereotype.Service;
22 |
23 | @Service
24 | public class AnuncioService {
25 |
26 | @Autowired
27 | private AnuncioRepository anuncioRepository;
28 |
29 | @Autowired
30 | private PessoaRepository pessoaRepository;
31 |
32 | private AnuncioSpecification specification = new AnuncioSpecification();
33 |
34 | public Iterable getFilteredAnnounce(Pageable pageable, String cep, AnuncioStatus status, AnimalSexo sexo,
35 | AnimalPorte porte, AnimalClassificacaoEtaria classificacaoEtaria, Integer idCategoria, Integer idEspecie,
36 | Boolean castrado, Boolean vacinado) {
37 | return anuncioRepository
38 | .findAll(Specification.where(cep == null ? null : specification.animalCepFilter(cep))
39 | .and(status == null ? null : specification.statusFilter(status))
40 | .and(sexo == null ? null : specification.animalSexoFilter(sexo))
41 | .and(idCategoria == null ? null : specification.anuncioCategoriaFilter(idCategoria))
42 | .and(idEspecie == null ? null : specification.animalEspecieFilter(idEspecie))
43 | .and(classificacaoEtaria == null ? null
44 | : specification.animalClassificacaoEtariaFilter(classificacaoEtaria))
45 | .and(vacinado == null ? null : specification.animalVacinadoFilter(vacinado))
46 | .and(castrado == null ? null : specification.animalCastradoFilter(castrado))
47 | .and(porte == null ? null : specification.animalPorteFilter(porte)), pageable);
48 | }
49 |
50 | public Optional getAnnounceById(Integer id) {
51 | return anuncioRepository.findById(id);
52 | }
53 |
54 | public Page getAnnounceByEmailPessoa(String email, Pageable pageable) {
55 | return anuncioRepository.findByidPessoaEmail(email, pageable);
56 | }
57 |
58 | public Anuncio save(Anuncio anuncio) {
59 |
60 | Optional pessoa = pessoaRepository.findByEmail(anuncio.getIdPessoa().getEmail());
61 | if (pessoa.isPresent()) {
62 | Integer pessoaId = pessoa.get().getIdPessoa();
63 | anuncio.getIdPessoa().setIdPessoa(pessoaId);
64 | }
65 |
66 | if (anuncio.getIdAnimal().getNome().isEmpty()) {
67 | anuncio.getIdAnimal().setNome("Desconhecido");
68 | }
69 | anuncio.setStatus(AnuncioStatus.ATIVO);
70 |
71 | anuncioRepository.save(anuncio);
72 | return anuncio;
73 | }
74 |
75 | public Anuncio updateStatusAnnounce(Integer idAnuncio) {
76 |
77 | AnuncioStatusConverter statusConverter = new AnuncioStatusConverter();
78 | Anuncio meuAnuncio = anuncioRepository.findById(idAnuncio).orElseThrow(() -> new ValidationException(EnumException.ITEM_NAO_ENCONTRADO));
79 |
80 | Date date = new Date();
81 | date.setHours((date.getHours()) - 3);
82 |
83 | SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
84 |
85 | if (meuAnuncio.getStatus() == AnuncioStatus.ATIVO) {
86 | meuAnuncio.setStatus(statusConverter.convertToEntityAttribute("Inativo"));
87 | meuAnuncio.setDataEncerramento(date);
88 |
89 | } else if (meuAnuncio.getStatus() == AnuncioStatus.INATIVO) {
90 | meuAnuncio.setStatus(statusConverter.convertToEntityAttribute("Ativo"));
91 | meuAnuncio.setDataEncerramento(null);
92 | }
93 |
94 | anuncioRepository.save(meuAnuncio);
95 | return meuAnuncio;
96 | }
97 |
98 | public void deleteAnnounce(Integer id) {
99 | anuncioRepository.deleteById(id);
100 | }
101 |
102 | public List getAll(){
103 | return this.anuncioRepository.findAll();
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/CategoriaService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import com.kdmeubichinho.services.generics.RestBasicService;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 |
9 | import com.kdmeubichinho.dto.CategoriaRequestDTO;
10 | import com.kdmeubichinho.entities.Categoria;
11 | import com.kdmeubichinho.repositories.CategoriaRepository;
12 | import org.springframework.data.domain.Page;
13 | import org.springframework.data.domain.Pageable;
14 | import org.springframework.stereotype.Service;
15 |
16 | @Service
17 | public class CategoriaService implements RestBasicService {
18 |
19 | @Autowired
20 | CategoriaRepository categoriaRepository;
21 |
22 | @Override
23 | public Page getAll(Pageable page) {
24 | return categoriaRepository.findAll(page);
25 | }
26 |
27 | @Override
28 | public Optional getById(Integer id) {
29 | return categoriaRepository.findById(id);
30 | }
31 |
32 | @Override
33 | public List getAll() {
34 | return categoriaRepository.findAll();
35 | }
36 |
37 | @Override
38 | public CategoriaRequestDTO save(CategoriaRequestDTO i) {
39 | categoriaRepository.save(i.build());
40 | return i;
41 | }
42 |
43 | @Override
44 | public void deleteById(Integer id) {
45 | categoriaRepository.deleteById(id);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/EspecieService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import com.kdmeubichinho.services.generics.RestBasicService;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.data.domain.Page;
9 | import org.springframework.data.domain.Pageable;
10 | import org.springframework.stereotype.Service;
11 |
12 | import com.kdmeubichinho.dto.EspecieRequestDTO;
13 | import com.kdmeubichinho.entities.Especie;
14 | import com.kdmeubichinho.repositories.EspecieRepository;
15 |
16 | @Service
17 | public class EspecieService implements RestBasicService {
18 |
19 | @Autowired
20 | EspecieRepository especieRepository;
21 |
22 | @Override
23 | public List getAll() {
24 | return (List) especieRepository.findAll();
25 | }
26 |
27 | @Override
28 | public Page getAll(Pageable page) {
29 | return especieRepository.findAll(page);
30 | }
31 |
32 | @Override
33 | public Optional getById(Integer id) {
34 | return especieRepository.findById(id);
35 | }
36 |
37 | @Override
38 | public EspecieRequestDTO save(EspecieRequestDTO i) {
39 | especieRepository.save(i.build());
40 | return i;
41 | }
42 |
43 | @Override
44 | public void deleteById(Integer id) {
45 | especieRepository.deleteById(id);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/JwtService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import io.jsonwebtoken.Claims;
5 | import io.jsonwebtoken.ExpiredJwtException;
6 | import io.jsonwebtoken.Jwts;
7 | import io.jsonwebtoken.SignatureAlgorithm;
8 | import org.springframework.beans.factory.annotation.Value;
9 | import org.springframework.stereotype.Service;
10 |
11 | import java.time.Instant;
12 | import java.time.LocalDateTime;
13 | import java.time.ZoneId;
14 | import java.util.Date;
15 |
16 | @Service
17 | public class JwtService {
18 |
19 | @Value("${security.jwt.expiracao}")
20 | private String expiracao;
21 |
22 | @Value("${security.jwt.chave-assinatura}")
23 | private String chaveAssinatura;
24 |
25 |
26 | public String gerarToken(Pessoa pessoa) {
27 | long expString = Long.parseLong(expiracao);
28 | LocalDateTime dataHoraExpiracao = LocalDateTime.now().plusDays(expString);
29 | Instant instant = dataHoraExpiracao.atZone(ZoneId.systemDefault()).toInstant();
30 | Date data = Date.from(instant);
31 |
32 | return Jwts
33 | .builder()
34 | .setSubject(pessoa.getEmail())
35 | .setExpiration(data)
36 | .signWith(SignatureAlgorithm.HS512, chaveAssinatura)
37 | .compact();
38 | }
39 |
40 | private Claims obterClaims(String token) throws ExpiredJwtException {
41 | return Jwts
42 | .parser()
43 | .setSigningKey(chaveAssinatura)
44 | .parseClaimsJws(token)
45 | .getBody();
46 | }
47 |
48 | public boolean tokenValido(String token) {
49 | try {
50 | Claims claims = obterClaims(token);
51 | Date dataExpiracao = claims.getExpiration();
52 | LocalDateTime data =
53 | dataExpiracao.toInstant()
54 | .atZone(ZoneId.systemDefault()).toLocalDateTime();
55 | return !LocalDateTime.now().isAfter(data);
56 | } catch (Exception e) {
57 | return false;
58 | }
59 | }
60 |
61 | public String obterEmailUsuario(String token) throws ExpiredJwtException {
62 | return obterClaims(token).getSubject();
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/MensagemService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import com.kdmeubichinho.dto.MensagemDTO;
7 | import com.kdmeubichinho.services.generics.RestBasicService;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.data.domain.Page;
10 | import org.springframework.data.domain.Pageable;
11 | import org.springframework.stereotype.Service;
12 |
13 | import com.kdmeubichinho.entities.Mensagem;
14 | import com.kdmeubichinho.repositories.MensagemRepository;
15 | import com.kdmeubichinho.repositories.PessoaRepository;
16 |
17 | import com.kdmeubichinho.entities.Pessoa;
18 |
19 | @Service
20 | public class MensagemService implements RestBasicService {
21 |
22 | private MensagemRepository mensagemRepository;
23 |
24 | private PessoaRepository pessoaRepository;
25 |
26 | @Autowired
27 | public MensagemService(MensagemRepository mensagemRepository, PessoaRepository pessoaRepository) {
28 | this.mensagemRepository = mensagemRepository;
29 | this.pessoaRepository = pessoaRepository;
30 | }
31 |
32 | @Override
33 | public List getAll() {
34 | return (List) mensagemRepository.findAll();
35 | }
36 |
37 | @Override
38 | public Page getAll(Pageable page) {
39 | return mensagemRepository.findAll(page);
40 | }
41 |
42 | @Override
43 | public Optional getById(Integer id) {
44 | return mensagemRepository.findById(id);
45 | }
46 |
47 | @Override
48 | public MensagemDTO save(MensagemDTO i) {
49 | return null;
50 | }
51 |
52 | public Mensagem save(Mensagem message){
53 | Optional pessoa = pessoaRepository.findByEmail(message.getIdPessoa().getEmail());
54 | if(pessoa.isPresent()) {
55 | Integer pessoaId = pessoa.get().getIdPessoa();
56 | message.getIdPessoa().setIdPessoa(pessoaId);
57 | }
58 | mensagemRepository.save(message);
59 | return message;
60 | }
61 |
62 | public Mensagem updateMessage(Integer idMessage, Mensagem dataMessage) throws Exception{
63 | Mensagem messageToUpdate = mensagemRepository.findById(idMessage)
64 | .orElseThrow(()-> new IllegalAccessException());
65 |
66 | if(!dataMessage.getMsgConteudo().isEmpty()) messageToUpdate.setMsgConteudo(dataMessage.getMsgConteudo());
67 |
68 | mensagemRepository.save(messageToUpdate);
69 | return messageToUpdate;
70 | }
71 |
72 | public void deleteMessage(Integer id) {
73 | mensagemRepository.deleteById(id);
74 | }
75 |
76 | @Override
77 | public void deleteById(Integer id) {
78 | this.mensagemRepository.deleteById(id);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/PessoaService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.dto.CredenciaisDTO;
4 | import com.kdmeubichinho.dto.PessoaDTO;
5 | import com.kdmeubichinho.dto.TokenDTO;
6 | import com.kdmeubichinho.entities.Pessoa;
7 | import com.kdmeubichinho.repositories.PessoaRepository;
8 | import com.kdmeubichinho.services.generics.RestBasicService;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.data.domain.Pageable;
12 | import org.springframework.http.HttpStatus;
13 | import org.springframework.http.ResponseEntity;
14 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
15 | import org.springframework.security.crypto.password.PasswordEncoder;
16 | import org.springframework.stereotype.Service;
17 | import org.springframework.web.server.ResponseStatusException;
18 |
19 | import javax.transaction.Transactional;
20 | import java.util.List;
21 | import java.util.Optional;
22 |
23 | @Service
24 | public class PessoaService implements RestBasicService {
25 |
26 | private final PasswordEncoder passwordEncoder;
27 | private final JwtService jwtService;
28 | private final PessoaRepository pessoaRepository;
29 |
30 | @Autowired
31 | public PessoaService(PasswordEncoder passwordEncoder, JwtService jwtService,
32 | PessoaRepository pessoaRepository) {
33 | this.passwordEncoder = passwordEncoder;
34 | this.jwtService = jwtService;
35 | this.pessoaRepository = pessoaRepository;
36 | }
37 |
38 | @Override
39 | public List getAll() {
40 | return pessoaRepository.findAll();
41 | }
42 |
43 | @Override
44 | public Page getAll(Pageable page) {
45 | return pessoaRepository.findAll(page);
46 | }
47 |
48 | @Override
49 | public Optional getById(Integer id) {
50 | return pessoaRepository.findById(id);
51 | }
52 |
53 | @Override
54 | public PessoaDTO save(PessoaDTO i) {
55 | this.pessoaRepository.save(i.build());
56 | return i;
57 | }
58 |
59 | public Pessoa save(Pessoa p) {
60 | return this.pessoaRepository.save(p);
61 | }
62 |
63 | @Override
64 | public void deleteById(Integer id) {
65 | this.pessoaRepository.deleteById(id);
66 | }
67 |
68 | public Optional getPersonByEmail(String email) {
69 | return pessoaRepository.findByEmail(email);
70 | }
71 |
72 | @Transactional
73 | public Pessoa savePerson(PessoaDTO pessoa) {
74 | String senhaCriptografada = passwordEncoder.encode(pessoa.getSenha());
75 | pessoa.setSenha(senhaCriptografada);
76 | return pessoaRepository.save(pessoa.build());
77 | }
78 |
79 | public Pessoa updatePerson(String emailPerson, PessoaDTO dataPerson) throws Exception{
80 | Pessoa myPerson = pessoaRepository.findByEmail(emailPerson)
81 | .orElseThrow(()-> new IllegalAccessException());
82 |
83 | if(!dataPerson.getNome().isEmpty()) myPerson.setNome(dataPerson.getNome());
84 | if(!dataPerson.getCelular().isEmpty()) myPerson.setCelular(dataPerson.getCelular());
85 | if(!dataPerson.getCep().isEmpty()) myPerson.setCep(dataPerson.getCep());
86 | if(!dataPerson.getLogradouro().isEmpty()) myPerson.setLogradouro(dataPerson.getLogradouro());
87 | if(!dataPerson.getComplemento().isEmpty()) myPerson.setComplemento(dataPerson.getComplemento());
88 | if(!dataPerson.getBairro().isEmpty()) myPerson.setBairro(dataPerson.getBairro());
89 | if(!dataPerson.getLocalidade().isEmpty()) myPerson.setLocalidade(dataPerson.getLocalidade());
90 | if(!dataPerson.getUf().isEmpty()) myPerson.setUf(dataPerson.getUf());
91 | if(!dataPerson.getIbge().isEmpty()) myPerson.setIbge(dataPerson.getIbge());
92 | if(!dataPerson.getDdd().isEmpty()) myPerson.setDdd(dataPerson.getDdd());
93 | if(!dataPerson.getNumeroResidencial().isEmpty()) myPerson.setNumeroResidencial(dataPerson.getNumeroResidencial());
94 | myPerson.setComplemento(dataPerson.getComplemento());
95 |
96 | pessoaRepository.save(myPerson);
97 | return myPerson;
98 | }
99 |
100 | public ResponseEntity authenticatePerson(CredenciaisDTO credenciais) {
101 | try {
102 | Pessoa pessoa = Pessoa.builder()
103 | .email(credenciais.getEmail())
104 | .senha(credenciais.getSenha()).build();
105 | Pessoa p = getPersonByEmail(pessoa.getEmail()).orElseThrow(() -> new UsernameNotFoundException(""));
106 | String token = jwtService.gerarToken(p);
107 | TokenDTO tokenDto = new TokenDTO(p.getEmail(), token);
108 | return new ResponseEntity<>(tokenDto, HttpStatus.OK);
109 |
110 | } catch (UsernameNotFoundException e) {
111 | throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, e.getMessage());
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/services/generics/RestBasicService.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services.generics;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.domain.Pageable;
5 |
6 | import java.util.List;
7 | import java.util.Optional;
8 |
9 | /***
10 | * T stands for TYPE to be returned
11 | * I stands for Interface to be returned
12 | * @param
13 | * @param
14 | */
15 | public interface RestBasicService {
16 |
17 | List getAll();
18 |
19 | Page getAll(Pageable page);
20 |
21 | Optional getById(Integer id);
22 |
23 | I save(I i);
24 |
25 | void deleteById(Integer id);
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/specification/AnuncioSpecification.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.specification;
2 |
3 | import com.kdmeubichinho.entities.Anuncio;
4 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
5 | import com.kdmeubichinho.enums.AnimalPorte;
6 | import com.kdmeubichinho.enums.AnimalSexo;
7 | import com.kdmeubichinho.enums.AnuncioStatus;
8 | import org.springframework.data.jpa.domain.Specification;
9 |
10 | import java.text.MessageFormat;
11 |
12 | public class AnuncioSpecification {
13 |
14 | public static final String ID_ANIMAL = "idAnimal";
15 |
16 | public Specification statusFilter(AnuncioStatus status) {
17 | return (root, criteriaQuery, criteriaBuilder) ->
18 | criteriaBuilder.equal(root.get("status"), status);
19 | }
20 |
21 | public Specification animalSexoFilter(AnimalSexo sexo) {
22 | return (root, criteriaQuery, criteriaBuilder) ->
23 | criteriaBuilder.equal(root.join(ID_ANIMAL).get("sexo"), sexo);
24 | }
25 |
26 | public Specification animalPorteFilter(AnimalPorte porte) {
27 | return (root, criteriaQuery, criteriaBuilder) ->
28 | criteriaBuilder.equal(root.join(ID_ANIMAL).get("porte"), porte);
29 | }
30 |
31 | public Specification animalClassificacaoEtariaFilter(AnimalClassificacaoEtaria classificacaoEtaria) {
32 | return (root, criteriaQuery, criteriaBuilder) ->
33 | criteriaBuilder.equal(root.join(ID_ANIMAL).get("classificacaoEtaria"), classificacaoEtaria);
34 | }
35 |
36 | public Specification animalCepFilter(String cep) {
37 | return (root, criteriaQuery, criteriaBuilder) ->
38 | criteriaBuilder.like(root.join(ID_ANIMAL).get("cep"), contains(cep));
39 | }
40 |
41 | private String contains(String expression) {
42 | return MessageFormat.format("{0}%", expression);
43 | }
44 |
45 | public Specification anuncioCategoriaFilter(Integer idCategoria) {
46 | return (root, criteriaQuery, criteriaBuilder) ->
47 | criteriaBuilder.equal(root.join("idCategoria").get("idCategoria"), idCategoria);
48 | }
49 |
50 | public Specification animalEspecieFilter(Integer idEspecie) {
51 | return (root, criteriaQuery, criteriaBuilder) ->
52 | criteriaBuilder.equal(root.join(ID_ANIMAL).get("especie"), idEspecie);
53 | }
54 |
55 | public Specification animalVacinadoFilter(Boolean vacinado) {
56 | return (root, criteriaQuery, criteriaBuilder) ->
57 | criteriaBuilder.equal(root.join(ID_ANIMAL).get("vacinado"), vacinado);
58 | }
59 |
60 | public Specification animalCastradoFilter(Boolean castrado) {
61 | return (root, criteriaQuery, criteriaBuilder) ->
62 | criteriaBuilder.equal(root.join(ID_ANIMAL).get("castrado"), castrado);
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/kdmeubichinho/util/FileUploadUtil.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.util;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 | import java.nio.file.Paths;
8 | import java.nio.file.StandardCopyOption;
9 |
10 | import org.springframework.web.multipart.MultipartFile;
11 |
12 | public class FileUploadUtil {
13 |
14 | private FileUploadUtil(){
15 | //Apenas para ocultaro construtor padrao
16 | }
17 |
18 | public static void saveFile(String uploadDir, String fileName,
19 | MultipartFile multipartFile) throws IOException {
20 | Path uploadPath = Paths.get(uploadDir);
21 |
22 | if (!Files.exists(uploadPath)) {
23 | Files.createDirectories(uploadPath);
24 | }
25 |
26 | try (InputStream inputStream = multipartFile.getInputStream()) {
27 | Path filePath = uploadPath.resolve(fileName);
28 | Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
29 | } catch (IOException ioe) {
30 | throw new IOException("Could not save image file: " + fileName, ioe);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/resources/application-integrationtest.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=jdbc:h2:mem:testdb
2 | spring.datasource.driverClassName=org.h2.Driver
3 | spring.datasource.username=sa
4 | spring.datasource.password=password
5 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
6 | spring.jpa.properties.hibernate.show_sql=false
7 |
8 | #JWT configs
9 | security.jwt.chave-assinatura=teste
10 | security.jwt.expiracao=60
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url = ${DATABASE_URL}
2 | spring.datasource.username = ${DATABASE_USERNAME}
3 | spring.datasource.password = ${DATABASE_PASSWORD}
4 |
5 | spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
6 | spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
7 | spring.jpa.hibernate.ddl-auto = update
8 |
9 | spring.jpa.properties.hibernate.show_sql=true
10 | spring.jpa.properties.hibernate.format_sql=true
11 |
12 | security.jwt.expiracao=${JWT_EXPIRATION_KEY}
13 | security.jwt.chave-assinatura=${JWT_SECRET_KEY}
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/config/JwtRequestFilterTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.config;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import com.kdmeubichinho.services.JwtService;
5 | import com.kdmeubichinho.services.PessoaService;
6 | import org.junit.jupiter.api.BeforeAll;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.jupiter.api.TestInstance;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.mock.web.MockFilterChain;
12 | import org.springframework.mock.web.MockHttpServletRequest;
13 | import org.springframework.mock.web.MockHttpServletResponse;
14 | import org.springframework.test.context.TestPropertySource;
15 |
16 | import javax.servlet.ServletException;
17 | import java.io.IOException;
18 |
19 | import static org.junit.jupiter.api.Assertions.*;
20 |
21 | @SpringBootTest
22 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
23 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
24 | class JwtRequestFilterTest {
25 |
26 | private String TOKEN = "";
27 | private static final String TOKEN_INVALIDO = "eyJhbiJIUzUxMiJ9.eyJzdWIiOiJnZXJhclRva2VuIiwiZXhwIjoxNjMyNzI5NzMyfQ.BmjkI2ys3R0KPbY1p8dAnBLlasoUGW8Xx7M-JjA0hrECKc1dkF9r4uQsIwoFDbSyNvhfbRc5KdyR0YmgOqIXaw";
28 | private static final String TOKEN_EXPIRADO = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJnZXJhclRva2VuIiwiZXhwIjoxNjI3NTQ2NjQ1fQ.zRrgyDHdOUguRiSQKRSE2EmcOGcZXnJuyeMEmfHQt33_bx2QOjt09MBeXnQzvY8Qhynalrok9OaPjiZx7rHn5Q";
29 |
30 | private JwtRequestFilter filter;
31 | private final JwtService jwtService;
32 | private final PessoaService pessoaService;
33 |
34 | @Autowired
35 | public JwtRequestFilterTest(JwtRequestFilter filter, JwtService jwtService, PessoaService pessoaService){
36 | this.filter = filter;
37 | this.jwtService = jwtService;
38 | this.pessoaService = pessoaService;
39 | }
40 |
41 | @BeforeAll
42 | public void setup() {
43 | Pessoa pessoa = new Pessoa(
44 | 1, "gerarToken", "gerarToken@example.com", "cep", "logradouro", "complemento", "bairro",
45 | "localidade", "uf", "ibge", "ddd", "numeroResidencial", "celular",
46 | "senha", true);
47 |
48 | this.pessoaService.save(pessoa);
49 | Pessoa build = Pessoa.builder()
50 | .nome("gerarToken")
51 | .email("gerarToken@example.com")
52 | .build();
53 |
54 | TOKEN = this.jwtService.gerarToken(build);
55 | }
56 |
57 | @Test
58 | void doFilterInternalNotBearer() throws ServletException, IOException {
59 | MockHttpServletRequest request = new MockHttpServletRequest();
60 | MockHttpServletResponse response = new MockHttpServletResponse();
61 | MockFilterChain chain = new MockFilterChain();
62 |
63 | request.setServerName("localhost:8080");
64 | request.setRequestURI("/animal");
65 | request.addHeader("Authorization", TOKEN );
66 |
67 | filter.doFilterInternal(request, response, chain);
68 |
69 | assertTrue(true);
70 | }
71 |
72 | @Test
73 | void doFilterInternalInvalidToken() throws ServletException, IOException {
74 | MockHttpServletRequest request = new MockHttpServletRequest();
75 | MockHttpServletResponse response = new MockHttpServletResponse();
76 | MockFilterChain chain = new MockFilterChain();
77 |
78 | request.setServerName("localhost:8080");
79 | request.setRequestURI("/animal");
80 | request.addHeader("Authorization", "Bearer " + TOKEN_INVALIDO );
81 |
82 | filter.doFilterInternal(request, response, chain);
83 |
84 | assertTrue(true);
85 | }
86 |
87 | @Test
88 | void doFilterInternalExpiredToken() throws ServletException, IOException {
89 | MockHttpServletRequest request = new MockHttpServletRequest();
90 | MockHttpServletResponse response = new MockHttpServletResponse();
91 | MockFilterChain chain = new MockFilterChain();
92 |
93 | request.setServerName("localhost:8080");
94 | request.setRequestURI("/animal");
95 | request.addHeader("Authorization", "Bearer " + TOKEN_EXPIRADO );
96 |
97 | filter.doFilterInternal(request, response, chain);
98 |
99 | assertTrue(true);
100 | }
101 |
102 | @Test
103 | void doFilterInternal() throws ServletException, IOException {
104 | MockHttpServletRequest request = new MockHttpServletRequest();
105 | MockHttpServletResponse response = new MockHttpServletResponse();
106 | MockFilterChain chain = new MockFilterChain();
107 |
108 | request.setServerName("localhost:8080");
109 | request.setRequestURI("/animal");
110 | request.addHeader("Authorization", "Bearer " + TOKEN );
111 |
112 | filter.doFilterInternal(request, response, chain);
113 |
114 | assertTrue(true);
115 | }
116 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/controllers/AnimalControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.entities.Animal;
4 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
5 | import com.kdmeubichinho.enums.AnimalPorte;
6 | import com.kdmeubichinho.enums.AnimalSexo;
7 | import org.junit.jupiter.api.*;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.context.TestPropertySource;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 |
14 | import java.util.List;
15 | import java.util.Optional;
16 |
17 | import static org.junit.jupiter.api.Assertions.*;
18 |
19 | @SpringBootTest
20 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
21 | @RunWith(SpringRunner.class)
22 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
23 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
24 | class AnimalControllerTest {
25 |
26 | private AnimalController controller;
27 |
28 | @Autowired
29 | public AnimalControllerTest(AnimalController controller){
30 | this.controller = controller;
31 | }
32 |
33 | @BeforeAll
34 | public void setup(){
35 | Animal a = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
36 | true, true, "00000-000");
37 | this.controller.addAnimal(a);
38 | }
39 |
40 | @Test
41 | @Order(1)
42 | void getAllAnimais() {
43 | List allAnimals = (List) this.controller.getAllAnimais();
44 | assertFalse(allAnimals.isEmpty());
45 | }
46 |
47 | @Test
48 | @Order(2)
49 | void getById() {
50 | List allAnimals = (List) this.controller.getAllAnimais();
51 | Optional byId = this.controller.getById(allAnimals.get(allAnimals.size() - 1).getIdAnimal());
52 | assertTrue(byId.isPresent());
53 | }
54 |
55 | @Test
56 | @Order(3)
57 | void addAnimal() {
58 | Animal a = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
59 | true, true, "00000-000");
60 | Animal animal = this.controller.addAnimal(a);
61 | Optional byId = this.controller.getById(animal.getIdAnimal());
62 | assertTrue(byId.isPresent());
63 | }
64 |
65 | @Test
66 | @Order(4)
67 | void updateAnimal() {
68 | Animal a = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
69 | true, true, "00000-000");
70 | Animal animal = this.controller.addAnimal(a);
71 |
72 | Animal update = this.controller.updateAnimal(animal.getIdAnimal(), animal);
73 |
74 | assertEquals("00000-000", update.getCep());
75 | }
76 |
77 | @Test
78 | @Order(5)
79 | void deleteAnimal() {
80 | Animal a = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
81 | true, true, "00000-000");
82 | Animal animal = this.controller.addAnimal(a);
83 | List allAnimals = (List) this.controller.getAllAnimais();
84 | this.controller.deleteAnimal(allAnimals.get(allAnimals.size() - 1).getIdAnimal());
85 | Optional byId = this.controller.getById(animal.getIdAnimal());
86 | assertFalse(byId.isPresent());
87 | }
88 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/controllers/CategoriaControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.dto.CategoriaRequestDTO;
4 | import com.kdmeubichinho.entities.Categoria;
5 | import com.kdmeubichinho.entities.generics.BaseEntity;
6 | import org.junit.jupiter.api.*;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.boot.test.context.SpringBootTest;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.data.domain.PageRequest;
12 | import org.springframework.test.context.TestPropertySource;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import java.util.List;
16 | import java.util.Optional;
17 |
18 | import static org.junit.jupiter.api.Assertions.*;
19 |
20 | @SpringBootTest
21 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
22 | @RunWith(SpringRunner.class)
23 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
24 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
25 | class CategoriaControllerTest {
26 |
27 | private CategoriaController controller;
28 | private CategoriaRequestDTO dto = new CategoriaRequestDTO("Categoria de Teste");
29 |
30 | @Autowired
31 | public CategoriaControllerTest(CategoriaController controller) {
32 | this.controller = controller;
33 | }
34 |
35 | @BeforeAll
36 | void setup() {
37 | for (int i = 0; i < 60; i++) {
38 | this.controller.save(dto);
39 | }
40 | }
41 |
42 | @AfterAll
43 | void rollback() {
44 | this.controller.getAll()
45 | .forEach(item -> this.controller.delete(((BaseEntity) item).getId()));
46 | }
47 |
48 | @Test
49 | @Order(1)
50 | void getAllPaged() {
51 | Page all = this.controller.getAllPaged(PageRequest.of(0, 50));
52 | assertEquals(50, all.stream().count());
53 | }
54 |
55 | @Test
56 | @Order(2)
57 | void getAll() {
58 | List all = this.controller.getAll();
59 | assertEquals(60, all.size());
60 | }
61 |
62 | @Test
63 | @Order(3)
64 | void getById() {
65 | Optional byId = this.controller.getById(1);
66 | assertTrue(byId.isPresent());
67 | }
68 |
69 | @Test
70 | @Order(4)
71 | void save() {
72 | this.controller.save(dto);
73 | List all = this.controller.getAll();
74 | assertEquals(61, all.size());
75 | }
76 |
77 | @Test
78 | @Order(5)
79 | void delete() {
80 | BaseEntity primeiro = (BaseEntity) this.controller.getAll().get(0);
81 | controller.delete(primeiro.getId());
82 | Optional byId = controller.getById(primeiro.getId());
83 | assertFalse(byId.isPresent());
84 | }
85 |
86 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/controllers/EspecieControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.dto.EspecieRequestDTO;
4 | import com.kdmeubichinho.entities.Especie;
5 | import com.kdmeubichinho.entities.generics.BaseEntity;
6 | import org.junit.jupiter.api.*;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.boot.test.context.SpringBootTest;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.data.domain.PageRequest;
12 | import org.springframework.test.context.TestPropertySource;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import java.util.List;
16 | import java.util.Optional;
17 |
18 | import static org.junit.jupiter.api.Assertions.*;
19 |
20 | @SpringBootTest
21 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
22 | @RunWith(SpringRunner.class)
23 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
24 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
25 | class EspecieControllerTest {
26 |
27 | private EspecieController controller;
28 | private EspecieRequestDTO dto = new EspecieRequestDTO("Especie de Teste");
29 |
30 | @Autowired
31 | public EspecieControllerTest(EspecieController controller) {
32 | this.controller = controller;
33 | }
34 |
35 | @BeforeAll
36 | void setup() {
37 | for (int i = 0; i < 60; i++) {
38 | this.controller.save(dto);
39 | }
40 | }
41 |
42 | @AfterAll
43 | void rollback() {
44 | this.controller.getAll()
45 | .forEach(item -> this.controller.delete(((BaseEntity) item).getId()));
46 | }
47 |
48 | @Test
49 | @Order(1)
50 | void getAllPaged() {
51 | Page all = this.controller.getAllPaged(PageRequest.of(0, 50));
52 | assertEquals(50, all.stream().count());
53 | }
54 |
55 | @Test
56 | @Order(2)
57 | void getAll() {
58 | List all = this.controller.getAll();
59 | assertEquals(60, all.size());
60 | }
61 |
62 | @Test
63 | @Order(3)
64 | void getById() {
65 | Optional byId = this.controller.getById(1);
66 | assertTrue(byId.isPresent());
67 | }
68 |
69 | @Test
70 | @Order(4)
71 | void save() {
72 | this.controller.save(dto);
73 | List all = this.controller.getAll();
74 | assertEquals(61, all.size());
75 | }
76 |
77 | @Test
78 | @Order(5)
79 | void delete() {
80 | BaseEntity primeiro = (BaseEntity) this.controller.getAll().get(0);
81 | controller.delete(primeiro.getId());
82 | Optional byId = controller.getById(primeiro.getId());
83 | assertFalse(byId.isPresent());
84 | }
85 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/controllers/FotoControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.entities.Foto;
4 | import com.kdmeubichinho.repositories.FotoRepository;
5 | import org.junit.jupiter.api.*;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.http.client.MultipartBodyBuilder;
10 | import org.springframework.test.context.TestPropertySource;
11 | import org.springframework.test.context.junit4.SpringRunner;
12 |
13 | import java.util.List;
14 | import java.util.Optional;
15 |
16 | import static org.junit.jupiter.api.Assertions.*;
17 |
18 | @SpringBootTest
19 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
20 | @RunWith(SpringRunner.class)
21 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
22 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
23 | class FotoControllerTest {
24 |
25 | private FotoController controller;
26 | private FotoRepository fotoRepository;
27 |
28 | @Autowired
29 | public FotoControllerTest(FotoController controller, FotoRepository fotoRepository){
30 | this.controller = controller;
31 | this.fotoRepository = fotoRepository;
32 | }
33 |
34 | @BeforeAll
35 | public void setup(){
36 | Foto foto = new Foto(1, "caminho-foto");
37 | this.fotoRepository.save(foto);
38 | }
39 |
40 | @Test
41 | @Order(1)
42 | void getFoto() {
43 | List fotoList = (List) this.controller.getFoto();
44 | assertFalse(fotoList.isEmpty());
45 | }
46 |
47 | @Test
48 | @Order(2)
49 | void getById() {
50 | List fotoList = (List) this.controller.getFoto();
51 | Optional byId = this.controller.getById(fotoList.get(fotoList.size() - 1).getIdFoto());
52 | assertTrue(byId.isPresent());
53 | }
54 |
55 | @Test
56 | @Order(3)
57 | void saveImg() {
58 |
59 | }
60 |
61 | @Test
62 | @Order(4)
63 | void updateFoto() {
64 | List fotoList = (List) this.controller.getFoto();
65 | Foto f = fotoList.get(fotoList.size() -1);
66 | Foto foto = this.controller.updateFoto(f.getIdFoto(), f);
67 |
68 | assertEquals(f.getCaminho(), foto.getCaminho());
69 | }
70 |
71 | @Test
72 | @Order(5)
73 | void deleteFoto() {
74 | Foto foto = new Foto(null, "caminho-foto");
75 | this.fotoRepository.save(foto);
76 |
77 | List fotoList = (List) this.controller.getFoto();
78 | this.controller.deleteFoto(fotoList.get(fotoList.size() - 1).getIdFoto());
79 | Optional byId = this.controller.getById(fotoList.get(fotoList.size() - 1).getIdFoto());
80 | assertFalse(byId.isPresent());
81 | }
82 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/controllers/JwtAuthenticationControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.controllers;
2 |
3 | import com.kdmeubichinho.dto.PessoaDTO;
4 | import com.kdmeubichinho.entities.Pessoa;
5 | import com.kdmeubichinho.exception.ValidationException;
6 | import com.kdmeubichinho.model.JwtRequest;
7 | import com.kdmeubichinho.services.PessoaService;
8 | import org.junit.jupiter.api.Test;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.http.HttpStatus;
12 | import org.springframework.http.ResponseEntity;
13 | import org.springframework.test.context.TestPropertySource;
14 |
15 | import static org.junit.jupiter.api.Assertions.assertEquals;
16 | import static org.junit.jupiter.api.Assertions.assertThrows;
17 |
18 | @SpringBootTest
19 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
20 | class JwtAuthenticationControllerTest {
21 |
22 | private PessoaService pessoaService;
23 | private JwtAuthenticationController controller;
24 |
25 | private static final String SENHA = "teste-senha";
26 |
27 | @Autowired
28 | public JwtAuthenticationControllerTest(PessoaService pessoaService, JwtAuthenticationController controller) {
29 | this.pessoaService = pessoaService;
30 | this.controller = controller;
31 | }
32 |
33 | @Test
34 | void createAuthenticationToken() {
35 | PessoaDTO p = getPessoaDTO();
36 | Pessoa save = this.pessoaService.savePerson(p);
37 | JwtRequest jwtRequest = new JwtRequest(p.getEmail(), SENHA);
38 |
39 | ResponseEntity authenticationToken = this.controller.createAuthenticationToken(jwtRequest);
40 |
41 | assertEquals(HttpStatus.OK, authenticationToken.getStatusCode());
42 | }
43 |
44 | @Test
45 | void createAuthenticationTokenUserNotFound() {
46 | PessoaDTO p = getPessoaDTO();
47 | p.setEmail("createAuthenticationTokenUserNotFound");
48 | JwtRequest jwtRequest = new JwtRequest(p.getEmail(), SENHA);
49 |
50 | assertThrows(ValidationException.class, () -> this.controller.createAuthenticationToken(jwtRequest));
51 | }
52 |
53 | @Test
54 | void createAuthenticationTokenUserBadCredentials() {
55 | PessoaDTO p = getPessoaDTO();
56 | p.setEmail("createAuthenticationTokenUserBadCredentials");
57 | p.setNome("createAuthenticationTokenUserBadCredentials");
58 | Pessoa save = this.pessoaService.savePerson(p);
59 | JwtRequest jwtRequest = new JwtRequest(p.getEmail(), "senha-diferente");
60 |
61 | assertThrows(ValidationException.class, () -> this.controller.createAuthenticationToken(jwtRequest));
62 | }
63 |
64 | private PessoaDTO getPessoaDTO() {
65 | PessoaDTO pessoaDTO = new PessoaDTO();
66 |
67 | pessoaDTO.setNome("createAuthenticationToken");
68 | pessoaDTO.setEmail("email-test@teste.com");
69 | pessoaDTO.setCep("00000-000");
70 | pessoaDTO.setCelular("000 000 000");
71 | pessoaDTO.setSenha("teste-senha");
72 |
73 | return pessoaDTO;
74 | }
75 |
76 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/converters/AnimalClassificacaoEtariaConverterTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class AnimalClassificacaoEtariaConverterTest {
9 |
10 | @Test
11 | void convertToDatabaseColumn() {
12 | AnimalClassificacaoEtariaConverter animalConverter = new AnimalClassificacaoEtariaConverter();
13 | String s = animalConverter.convertToDatabaseColumn(AnimalClassificacaoEtaria.ADULTO);
14 | assertEquals("Adulto", s);
15 | }
16 |
17 | @Test
18 | void convertToEntityAttribute() {
19 | AnimalClassificacaoEtariaConverter animalConverter = new AnimalClassificacaoEtariaConverter();
20 | AnimalClassificacaoEtaria convert = animalConverter.convertToEntityAttribute("Adulto");
21 | assertEquals(AnimalClassificacaoEtaria.ADULTO, convert);
22 | }
23 |
24 | @Test
25 | void convertToDatabaseColumnNull() {
26 | AnimalClassificacaoEtariaConverter animalConverter = new AnimalClassificacaoEtariaConverter();
27 | String s = animalConverter.convertToDatabaseColumn(null);
28 | assertNull(s);
29 | }
30 |
31 | @Test
32 | void convertToEntityAttributeNull() {
33 | AnimalClassificacaoEtariaConverter animalConverter = new AnimalClassificacaoEtariaConverter();
34 | AnimalClassificacaoEtaria convert = animalConverter.convertToEntityAttribute(null);
35 | assertNull(convert);
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/converters/AnimalPorteConverterTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import com.kdmeubichinho.enums.AnimalPorte;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class AnimalPorteConverterTest {
9 |
10 | @Test
11 | void convertToDatabaseColumn() {
12 | AnimalPorteConverter converter = new AnimalPorteConverter();
13 | String convert = converter.convertToDatabaseColumn(AnimalPorte.GRANDE);
14 | assertEquals("Grande", convert);
15 | }
16 |
17 | @Test
18 | void convertToEntityAttribute() {
19 | AnimalPorteConverter converter = new AnimalPorteConverter();
20 | AnimalPorte convert = converter.convertToEntityAttribute("Grande");
21 | assertEquals(AnimalPorte.GRANDE, convert);
22 | }
23 |
24 | @Test
25 | void convertToDatabaseColumnNull() {
26 | AnimalPorteConverter converter = new AnimalPorteConverter();
27 | String convert = converter.convertToDatabaseColumn(null);
28 | assertNull(convert);
29 | }
30 |
31 | @Test
32 | void convertToEntityAttributeNull() {
33 | AnimalPorteConverter converter = new AnimalPorteConverter();
34 | AnimalPorte convert = converter.convertToEntityAttribute(null);
35 | assertNull(convert);
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/converters/AnimalSexoConverterTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import com.kdmeubichinho.enums.AnimalSexo;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class AnimalSexoConverterTest {
9 |
10 | @Test
11 | void convertToDatabaseColumn() {
12 | AnimalSexoConverter converter = new AnimalSexoConverter();
13 | String s = converter.convertToDatabaseColumn(AnimalSexo.MACHO);
14 | assertEquals("Macho", s);
15 | }
16 |
17 | @Test
18 | void convertToEntityAttribute() {
19 | AnimalSexoConverter converter = new AnimalSexoConverter();
20 | AnimalSexo convert = converter.convertToEntityAttribute("Macho");
21 | assertEquals(AnimalSexo.MACHO, convert);
22 | }
23 |
24 | @Test
25 | void convertToDatabaseColumnNull() {
26 | AnimalSexoConverter converter = new AnimalSexoConverter();
27 | String s = converter.convertToDatabaseColumn(null);
28 | assertNull(s);
29 | }
30 |
31 | @Test
32 | void convertToEntityAttributeNull() {
33 | AnimalSexoConverter converter = new AnimalSexoConverter();
34 | AnimalSexo convert = converter.convertToEntityAttribute(null);
35 | assertNull(convert);
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/converters/AnimalTipoConverterTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import com.kdmeubichinho.enums.AnimalTipo;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class AnimalTipoConverterTest {
9 |
10 | @Test
11 | void convertToDatabaseColumn() {
12 | AnimalTipoConverter converter = new AnimalTipoConverter();
13 | String convert = converter.convertToDatabaseColumn(AnimalTipo.CACHORRO);
14 | assertEquals("Cachorro", convert);
15 | }
16 |
17 | @Test
18 | void convertToEntityAttribute() {
19 | AnimalTipoConverter converter = new AnimalTipoConverter();
20 | AnimalTipo convert = converter.convertToEntityAttribute("Cachorro");
21 | assertEquals(AnimalTipo.CACHORRO, convert);
22 | }
23 |
24 | @Test
25 | void convertToDatabaseColumnNull() {
26 | AnimalTipoConverter converter = new AnimalTipoConverter();
27 | String convert = converter.convertToDatabaseColumn(null);
28 | assertNull(convert);
29 | }
30 |
31 | @Test
32 | void convertToEntityAttributeNull() {
33 | AnimalTipoConverter converter = new AnimalTipoConverter();
34 | AnimalTipo convert = converter.convertToEntityAttribute(null);
35 | assertNull(convert);
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/converters/AnuncioStatusConverterTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.converters;
2 |
3 | import com.kdmeubichinho.enums.AnuncioStatus;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class AnuncioStatusConverterTest {
9 |
10 | @Test
11 | void convertToDatabaseColumn() {
12 | AnuncioStatusConverter converter = new AnuncioStatusConverter();
13 | String convert = converter.convertToDatabaseColumn(AnuncioStatus.ATIVO);
14 | assertEquals("Ativo", convert);
15 | }
16 |
17 | @Test
18 | void convertToEntityAttribute() {
19 | AnuncioStatusConverter converter = new AnuncioStatusConverter();
20 | AnuncioStatus convert = converter.convertToEntityAttribute("Inativo");
21 | assertEquals(AnuncioStatus.INATIVO, convert);
22 | }
23 |
24 | @Test
25 | void convertToDatabaseColumnNull() {
26 | AnuncioStatusConverter converter = new AnuncioStatusConverter();
27 | String convert = converter.convertToDatabaseColumn(null);
28 | assertNull(convert);
29 | }
30 |
31 | @Test
32 | void convertToEntityAttributeNull() {
33 | AnuncioStatusConverter converter = new AnuncioStatusConverter();
34 | AnuncioStatus convert = converter.convertToEntityAttribute(null);
35 | assertNull(convert);
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/CategoriaRequestDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.entities.Categoria;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class CategoriaRequestDTOTest {
9 |
10 | @Test
11 | void testAllArgsConstructorAndGetter(){
12 | CategoriaRequestDTO c = new CategoriaRequestDTO("testAllArgsConstructorAndGetter");
13 | assertEquals("testAllArgsConstructorAndGetter", c.getClassificacao());
14 | }
15 |
16 | @Test
17 | void testSetter(){
18 | CategoriaRequestDTO dto = new CategoriaRequestDTO();
19 | dto.setClassificacao("testSetter");
20 |
21 | assertEquals("testSetter", dto.getClassificacao());
22 | }
23 |
24 | @Test
25 | void testBuild(){
26 | CategoriaRequestDTO dto = new CategoriaRequestDTO("testBuild");
27 | Categoria build = dto.build();
28 | assertEquals("testBuild", build.getClassificacao());
29 | }
30 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/CredenciaisDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class CredenciaisDTOTest {
8 |
9 | @Test
10 | void testAllArgsConstructorAndGetter(){
11 | CredenciaisDTO dto = new CredenciaisDTO("testAllArgsConstructorAndGetter", "testAllArgsConstructorAndGetter");
12 | assertEquals("testAllArgsConstructorAndGetter", dto.getEmail());
13 | }
14 |
15 | @Test
16 | void testSetters(){
17 | CredenciaisDTO dto = new CredenciaisDTO();
18 | dto.setEmail("testSetters");
19 | dto.setSenha("testSetterstestSetters");
20 |
21 | assertEquals("testSetters", dto.getEmail());
22 | }
23 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/CustomExceptionDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class CustomExceptionDTOTest {
8 |
9 | @Test
10 | void testAllArgsConstructorAndGetter(){
11 | CustomExceptionDTO dto = new CustomExceptionDTO("testAllArgsConstructorAndGetter");
12 | assertEquals("testAllArgsConstructorAndGetter", dto.getMessage());
13 | }
14 |
15 | @Test
16 | void testSetter(){
17 | CustomExceptionDTO dto = new CustomExceptionDTO();
18 | dto.setMessage("testSetter");
19 |
20 | assertEquals("testSetter", dto.getMessage());
21 | }
22 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/EspecieRequestDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.entities.Especie;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class EspecieRequestDTOTest {
9 |
10 | @Test
11 | void testAllArgsConstructorAndGetter(){
12 | EspecieRequestDTO dto = new EspecieRequestDTO("testAllArgsConstructorAndGetter");
13 | assertEquals("testAllArgsConstructorAndGetter", dto.getNome());
14 | }
15 |
16 | @Test
17 | void testSetter(){
18 | EspecieRequestDTO dto = new EspecieRequestDTO();
19 | dto.setNome("testSetter");
20 |
21 | assertEquals("testSetter", dto.getNome());
22 | }
23 |
24 | @Test
25 | void testBuild(){
26 | EspecieRequestDTO dto = new EspecieRequestDTO("testBuild");
27 | Especie build = dto.build();
28 | assertEquals("testBuild", build.getNome());
29 | }
30 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/MensagemDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.entities.Anuncio;
4 | import com.kdmeubichinho.entities.Mensagem;
5 | import com.kdmeubichinho.entities.Pessoa;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import java.util.Date;
9 |
10 | import static org.junit.jupiter.api.Assertions.*;
11 |
12 | class MensagemDTOTest {
13 |
14 | @Test
15 | void testAllArgsConstructor(){
16 | MensagemDTO mensagem = new MensagemDTO(1, new Date(), "mensagem", new Pessoa(), new Anuncio());
17 | assertNotNull(mensagem);
18 | }
19 |
20 | @Test
21 | void testNoArgsConstructor(){
22 | MensagemDTO mensagemDTO = new MensagemDTO();
23 | assertNotNull(mensagemDTO);
24 | }
25 |
26 | @Test
27 | void testBuid(){
28 | MensagemDTO mensagemDTO = new MensagemDTO();
29 | Mensagem build = mensagemDTO.build();
30 | assertNotNull(build);
31 | assertTrue(build instanceof Mensagem);
32 | }
33 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/PessoaDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class PessoaDTOTest {
9 |
10 | @Test
11 | void testAlLArgsConstructorAndGetter(){
12 | PessoaDTO p = new PessoaDTO(1, "nome", "email", "cep", "logradouro",
13 | "complemento", "bairro", "localidade", "uf",
14 | "ibge", "ddd", "numeroResidencial", "celular", "senha");
15 |
16 | assertEquals(1,p.getIdPessoa());
17 | assertEquals("nome",p.getNome());
18 | assertEquals("email",p.getEmail());
19 | assertEquals("cep",p.getCep());
20 | assertEquals("logradouro",p.getLogradouro());
21 | assertEquals("complemento",p.getComplemento());
22 | assertEquals("bairro",p.getBairro());
23 | assertEquals("localidade",p.getLocalidade());
24 | assertEquals("uf",p.getUf());
25 | assertEquals("ibge",p.getIbge());
26 | assertEquals("ddd",p.getDdd());
27 | assertEquals("numeroResidencial",p.getNumeroResidencial());
28 | assertEquals("celular",p.getCelular());
29 | assertEquals("senha",p.getSenha());
30 | }
31 |
32 | @Test
33 | void testNoArgsConstructor(){
34 | PessoaDTO pessoaDTO = new PessoaDTO();
35 | assertNotNull(pessoaDTO);
36 | }
37 |
38 | @Test
39 | void testBuild(){
40 | PessoaDTO p = new PessoaDTO(1, "nome", "email", "cep", "logradouro",
41 | "complemento", "bairro", "localidade", "uf",
42 | "ibge", "ddd", "numeroResidencial", "celular", "senha");
43 | Pessoa build = p.build();
44 | assertTrue(build instanceof Pessoa);
45 | assertEquals("numeroResidencial", build.getNumeroResidencial());
46 | }
47 |
48 | @Test
49 | void testSetter(){
50 | PessoaDTO p = new PessoaDTO();
51 | p.setIdPessoa(1);
52 | p.setNome("nome");
53 | p.setEmail("email");
54 | p.setCep("cep");
55 | p.setLogradouro("logradouro");
56 | p.setComplemento("complemento");
57 | p.setBairro("bairro");
58 | p.setLocalidade("localidade");
59 | p.setUf("uf");
60 | p.setIbge("ibge");
61 | p.setDdd("ddd");
62 | p.setNumeroResidencial("numeroResidencial");
63 | p.setCelular("celular");
64 | p.setSenha("senha");
65 |
66 | assertEquals(1,p.getIdPessoa());
67 | assertEquals("nome",p.getNome());
68 | assertEquals("email",p.getEmail());
69 | assertEquals("cep",p.getCep());
70 | assertEquals("logradouro",p.getLogradouro());
71 | assertEquals("complemento",p.getComplemento());
72 | assertEquals("bairro",p.getBairro());
73 | assertEquals("localidade",p.getLocalidade());
74 | assertEquals("uf",p.getUf());
75 | assertEquals("ibge",p.getIbge());
76 | assertEquals("ddd",p.getDdd());
77 | assertEquals("numeroResidencial",p.getNumeroResidencial());
78 | assertEquals("celular",p.getCelular());
79 | assertEquals("senha",p.getSenha());
80 | }
81 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/dto/TokenDTOTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.dto;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class TokenDTOTest {
8 |
9 | @Test
10 | void testAllArgsConstructorAndGetter(){
11 | TokenDTO dto = new TokenDTO("testAllArgsConstructorAndGetter", "testAllArgsConstructorAndGetter");
12 | assertEquals("testAllArgsConstructorAndGetter", dto.getToken());
13 | assertEquals("testAllArgsConstructorAndGetter", dto.getEmail());
14 | }
15 |
16 | @Test
17 | void testSetter(){
18 | TokenDTO dto = new TokenDTO();
19 | dto.setToken("testSetter");
20 | dto.setEmail("testSetter");
21 |
22 | assertEquals("testSetter", dto.getEmail());
23 | assertEquals("testSetter", dto.getToken());
24 | }
25 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/AnimalTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
4 | import com.kdmeubichinho.enums.AnimalPorte;
5 | import com.kdmeubichinho.enums.AnimalSexo;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | class AnimalTest {
11 |
12 | @Test
13 | void allArgsConstructorAndGetter() {
14 | Foto f = new Foto();
15 | Especie e = new Especie();
16 | Animal a = new Animal(1,
17 | AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO, true,
18 | true, "animal", "00000-000", "logradouro", "complemento",
19 | "bairro", "localidade", "uf", "ibge", "ddd", e, f);
20 |
21 | assertEquals(1,a.getIdAnimal());
22 | assertEquals(AnimalSexo.MACHO,a.getSexo());
23 | assertEquals(AnimalClassificacaoEtaria.ADULTO,a.getClassificacaoEtaria());
24 | assertEquals(AnimalPorte.PEQUENO,a.getPorte());
25 | assertEquals(true, a.getCastrado());
26 | assertEquals(true, a.getVacinado());
27 | assertEquals("animal",a.getNome());
28 | assertEquals("00000-000", a.getCep());
29 | assertEquals("logradouro",a.getLogradouro());
30 | assertEquals("complemento", a.getComplemento());
31 | assertEquals("bairro", a.getBairro());
32 | assertEquals("localidade", a.getLocalidade());
33 | assertEquals("uf", a.getUf());
34 | assertEquals("ibge", a.getIbge());
35 | assertEquals("ddd", a.getDdd());
36 | assertEquals(e, a.getEspecie());
37 | assertEquals(f, a.getFotos());
38 | }
39 |
40 | @Test
41 | void minimalConstructor() {
42 | Animal a = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
43 | true, true, "00000-000");
44 | assertEquals("00000-000", a.getCep());
45 | }
46 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/AnuncioTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import com.kdmeubichinho.enums.AnuncioStatus;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import java.util.Date;
7 | import java.util.Set;
8 | import java.util.TreeSet;
9 |
10 | import static org.junit.jupiter.api.Assertions.assertEquals;
11 | import static org.junit.jupiter.api.Assertions.assertTrue;
12 |
13 | class AnuncioTest {
14 |
15 | @Test
16 | void testAllArgsConstructorAndGetter() {
17 | Date d = new Date();
18 | Pessoa p = new Pessoa();
19 | Animal a = new Animal();
20 | Categoria c = new Categoria();
21 | Set set = new TreeSet();
22 | Anuncio anuncio = new Anuncio(1, AnuncioStatus.ATIVO, d, d, p, a, c, set);
23 |
24 | assertEquals(1, anuncio.getIdAnuncio());
25 | assertEquals(AnuncioStatus.ATIVO, anuncio.getStatus());
26 | assertEquals(d, anuncio.getDataCriacao());
27 | assertEquals(d, anuncio.getDataEncerramento());
28 | assertEquals(p, anuncio.getIdPessoa());
29 | assertEquals(a, anuncio.getIdAnimal());
30 | assertEquals(c, anuncio.getIdCategoria());
31 | assertTrue(anuncio.getMensagens().isEmpty());
32 | }
33 |
34 | @Test
35 | void testMinimalConstructor(){
36 | Anuncio anuncio = new Anuncio(AnuncioStatus.ATIVO, new Date());
37 | assertEquals(AnuncioStatus.ATIVO, anuncio.getStatus());
38 | }
39 |
40 | @Test
41 | void testSetter(){
42 | Anuncio a = new Anuncio();
43 | a.setStatus(AnuncioStatus.ATIVO);
44 | a.setIdAnimal(new Animal());
45 | a.setIdPessoa(new Pessoa());
46 | a.setIdAnuncio(3);
47 | a.setDataEncerramento(new Date());
48 | a.setDataCriacao(new Date());
49 | a.setIdCategoria(new Categoria());
50 | a.setMensagens(new TreeSet<>());
51 |
52 | assertEquals(3, a.getIdAnuncio());
53 | }
54 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/CategoriaTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class CategoriaTest {
8 |
9 | @Test
10 | void allArgsConstructorAndGetter(){
11 | Categoria categoria = new Categoria(1, "classificacao-categoria");
12 | assertEquals(1, categoria.getIdCategoria());
13 | assertEquals(1, categoria.getId());
14 | assertEquals("classificacao-categoria", categoria.getClassificacao());
15 | }
16 |
17 | @Test
18 | void testSetter(){
19 | Categoria categoria = new Categoria();
20 | categoria.setIdCategoria(3);
21 | categoria.setClassificacao("classificacao-categoria-2");
22 |
23 | assertEquals(3, categoria.getId());
24 | assertEquals("classificacao-categoria-2", categoria.getClassificacao());
25 | }
26 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/EspecieTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class EspecieTest {
8 |
9 | @Test
10 | void allArgsConstructorAndGetter(){
11 | Especie especie = new Especie(1, "nome-especie");
12 | assertEquals(1, especie.getIdEspecie());
13 | assertEquals(1, especie.getId());
14 | assertEquals("nome-especie", especie.getNome());
15 | }
16 |
17 | @Test
18 | void testSetter(){
19 | Especie especie = new Especie();
20 | especie.setIdEspecie(3);
21 | especie.setNome("nome-especie-2");
22 |
23 | assertEquals(3, especie.getId());
24 | assertEquals("nome-especie-2", especie.getNome());
25 | }
26 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/FotoTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class FotoTest {
8 |
9 | @Test
10 | void allArgsConstructorAndGetter(){
11 | Foto foto = new Foto(1, "caminho-imagem");
12 | assertEquals(1, foto.getIdFoto());
13 | assertEquals("caminho-imagem", foto.getCaminho());
14 | }
15 |
16 | @Test
17 | void testSetter(){
18 | Foto foto = new Foto();
19 | foto.setIdFoto(3);
20 | foto.setCaminho("caminho-2");
21 |
22 | assertEquals(3, foto.getIdFoto());
23 | assertEquals("caminho-2", foto.getCaminho());
24 | }
25 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/MensagemTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import java.util.Date;
6 |
7 | import static org.junit.jupiter.api.Assertions.assertEquals;
8 | import static org.junit.jupiter.api.Assertions.assertNotNull;
9 |
10 | class MensagemTest {
11 |
12 | @Test
13 | void noArgsConstructor(){
14 | Mensagem mensagem = new Mensagem();
15 | assertNotNull(mensagem);
16 | }
17 |
18 | @Test
19 | void allArgsConstructorAndGetter(){
20 | Date d = new Date();
21 | Pessoa p = new Pessoa();
22 | Anuncio a = new Anuncio();
23 | Mensagem mensagem = new Mensagem(1, d, "mensagem", p, a);
24 | assertEquals(1, mensagem.getIdMensagem());
25 | assertEquals(1, mensagem.getId());
26 | assertEquals(d, mensagem.getDataMensagem());
27 | assertEquals("mensagem", mensagem.getMsgConteudo());
28 | assertEquals(p, mensagem.getIdPessoa());
29 | assertEquals(a, mensagem.getIdAnuncio());
30 | }
31 |
32 | @Test
33 | void setters(){
34 | Mensagem m = new Mensagem();
35 | m.setIdMensagem(1);
36 | m.setDataMensagem(new Date());
37 | m.setMsgConteudo("msg-de-teste");
38 | m.setIdPessoa(new Pessoa());
39 | m.setIdAnuncio(new Anuncio());
40 |
41 | assertEquals("msg-de-teste", m.getMsgConteudo());
42 | }
43 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/entities/PessoaTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.entities;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.Test;
5 | import org.junit.jupiter.api.TestInstance;
6 | import org.springframework.security.core.GrantedAuthority;
7 |
8 | import javax.persistence.Column;
9 | import javax.persistence.GeneratedValue;
10 | import javax.persistence.GenerationType;
11 | import javax.persistence.Id;
12 | import java.util.Collection;
13 |
14 | import static org.junit.jupiter.api.Assertions.*;
15 |
16 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
17 | class PessoaTest {
18 |
19 | Pessoa p;
20 |
21 | @BeforeAll
22 | public void setup(){
23 | this.p = new Pessoa(
24 | 1, "nome", "email", "cep", "logradouro", "complemento", "bairro",
25 | "localidade", "uf", "ibge", "ddd", "numeroResidencial", "celular",
26 | "senha", true);
27 | }
28 |
29 | @Test
30 | void noArgsConstructor(){
31 | Pessoa pessoa = new Pessoa();
32 | assertNotNull(pessoa);
33 | }
34 |
35 | @Test
36 | void setters() {
37 | Pessoa pessoa = new Pessoa()
38 | .setIdPessoa(1)
39 | .setNome("teste-nome")
40 | .setEmail("")
41 | .setCep("00000000")
42 | .setLogradouro("")
43 | .setComplemento("")
44 | .setBairro("")
45 | .setLocalidade("")
46 | .setUf("")
47 | .setIbge("")
48 | .setDdd("")
49 | .setNumeroResidencial("")
50 | .setCelular("")
51 | .setSenha("")
52 | .setAdmin(true);
53 | assertEquals("teste-nome", pessoa.getNome());
54 | }
55 |
56 | @Test
57 | void testConstructorAndGetter() {
58 | assertEquals(1, p.getIdPessoa());
59 | assertEquals("email",p.getEmail());
60 | assertEquals("email",p.getUsername());
61 | assertEquals("cep",p.getCep());
62 | assertEquals("logradouro",p.getLogradouro());
63 | assertEquals("complemento",p.getComplemento());
64 | assertEquals("bairro",p.getBairro());
65 | assertEquals("localidade",p.getLocalidade());
66 | assertEquals("uf",p.getUf());
67 | assertEquals("ibge",p.getIbge());
68 | assertEquals("ddd",p.getDdd());
69 | assertEquals("numeroResidencial",p.getNumeroResidencial());
70 | assertEquals("celular",p.getCelular());
71 | assertEquals("senha",p.getSenha());
72 | assertEquals("senha",p.getPassword());
73 | }
74 |
75 | @Test
76 | void testMinimalConstructorAndGetter(){
77 | Pessoa pessoa = new Pessoa("nome2", "email2", "cep2", "celular2", "senha2");
78 | assertEquals("nome2",pessoa.getNome());
79 | assertEquals("email2",pessoa.getEmail());
80 | assertEquals("cep2",pessoa.getCep());
81 | assertEquals("celular2",pessoa.getCelular());
82 | assertEquals("senha2",pessoa.getSenha());
83 | }
84 |
85 | @Test
86 | void isAccountNonExpired() {
87 | assertTrue(p.isAccountNonExpired());
88 | }
89 |
90 | @Test
91 | void isAccountNonLocked() {
92 | assertTrue(p.isAccountNonLocked());
93 | }
94 |
95 | @Test
96 | void isCredentialsNonExpired() {
97 | assertTrue(p.isCredentialsNonExpired());
98 | }
99 |
100 | @Test
101 | void isEnabled() {
102 | assertTrue(p.isEnabled());
103 | }
104 |
105 | @Test
106 | void builder() {
107 | Pessoa pessoa = Pessoa.builder()
108 | .idPessoa(1)
109 | .nome("teste-nome")
110 | .email("")
111 | .cep("00000000")
112 | .logradouro("")
113 | .complemento("")
114 | .bairro("")
115 | .localidade("")
116 | .uf("")
117 | .ibge("")
118 | .ddd("")
119 | .numeroResidencial("")
120 | .celular("")
121 | .senha("")
122 | .admin(true)
123 | .build();
124 | assertEquals("teste-nome", pessoa.getNome());
125 | }
126 |
127 | @Test
128 | void isAdmin() {
129 | assertTrue(p.isAdmin());
130 | }
131 |
132 | @Test
133 | void getAuthority(){
134 | Collection extends GrantedAuthority> authorities = p.getAuthorities();
135 | assertEquals(0, authorities.size());
136 | }
137 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/enums/AnimalClassificacaoEtariaTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class AnimalClassificacaoEtariaTest {
8 |
9 | @Test
10 | void getDescricao() {
11 | AnimalClassificacaoEtaria classificacaoEtaria = AnimalClassificacaoEtaria.ADULTO;
12 | assertEquals("Adulto", classificacaoEtaria.getDescricao());
13 | }
14 |
15 | @Test
16 | void of() {
17 | AnimalClassificacaoEtaria classificacaoEtaria = AnimalClassificacaoEtaria.of("Adulto");
18 | assertEquals(AnimalClassificacaoEtaria.ADULTO, classificacaoEtaria);
19 | }
20 |
21 | @Test
22 | void values() {
23 | AnimalClassificacaoEtaria[] values = AnimalClassificacaoEtaria.values();
24 | assertTrue(values.length > 0);
25 | }
26 |
27 | @Test
28 | void valueOf() {
29 | AnimalClassificacaoEtaria classificacaoEtaria = AnimalClassificacaoEtaria.valueOf("ADULTO");
30 | assertEquals(AnimalClassificacaoEtaria.ADULTO, classificacaoEtaria);
31 | }
32 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/enums/AnimalPorteTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 | import static org.junit.jupiter.api.Assertions.assertTrue;
7 |
8 | class AnimalPorteTest {
9 |
10 | @Test
11 | void getDescricao() {
12 | AnimalPorte animal = AnimalPorte.PEQUENO;
13 | assertEquals("Pequeno", animal.getDescricao());
14 | }
15 |
16 | @Test
17 | void of() {
18 | AnimalPorte animal = AnimalPorte.of("Pequeno");
19 | assertEquals(AnimalPorte.PEQUENO, animal);
20 | }
21 |
22 | @Test
23 | void values() {
24 | AnimalPorte[] values = AnimalPorte.values();
25 | assertTrue(values.length > 0);
26 | }
27 |
28 | @Test
29 | void valueOf() {
30 | AnimalPorte animal = AnimalPorte.valueOf("PEQUENO");
31 | assertEquals(AnimalPorte.PEQUENO, animal);
32 | }
33 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/enums/AnimalSexoTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class AnimalSexoTest {
8 |
9 | @Test
10 | void getDescricao() {
11 | AnimalSexo animal = AnimalSexo.MACHO;
12 | assertEquals("Macho", animal.getDescricao());
13 | }
14 |
15 | @Test
16 | void of() {
17 | AnimalSexo animal = AnimalSexo.of("Macho");
18 | assertEquals(AnimalSexo.MACHO, animal);
19 | }
20 |
21 | @Test
22 | void values() {
23 | AnimalSexo[] values = AnimalSexo.values();
24 | assertTrue(values.length > 0);
25 | }
26 |
27 | @Test
28 | void valueOf() {
29 | AnimalSexo animal = AnimalSexo.valueOf("FEMEA");
30 | assertEquals(AnimalSexo.FEMEA, animal);
31 | }
32 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/enums/AnimalTipoTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class AnimalTipoTest {
8 |
9 | @Test
10 | void getDescricao() {
11 | AnimalTipo animal = AnimalTipo.CACHORRO;
12 | assertEquals("Cachorro", animal.getDescricao());
13 | }
14 |
15 | @Test
16 | void of() {
17 | AnimalTipo animal = AnimalTipo.of("Cachorro");
18 | assertEquals(AnimalTipo.CACHORRO, animal);
19 | }
20 |
21 | @Test
22 | void values() {
23 | AnimalTipo[] values = AnimalTipo.values();
24 | assertTrue(values.length > 0);
25 | }
26 |
27 | @Test
28 | void valueOf() {
29 | AnimalTipo animal = AnimalTipo.valueOf("CACHORRO");
30 | assertEquals(AnimalTipo.CACHORRO, animal);
31 | }
32 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/enums/AnuncioStatusTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class AnuncioStatusTest {
8 |
9 | @Test
10 | void getDescricao() {
11 | AnuncioStatus anuncio = AnuncioStatus.ATIVO;
12 | assertEquals("Ativo", anuncio.getDescricao());
13 | }
14 |
15 | @Test
16 | void of() {
17 | AnuncioStatus anuncio = AnuncioStatus.of("Ativo");
18 | assertEquals(AnuncioStatus.ATIVO, anuncio);
19 | }
20 |
21 | @Test
22 | void values() {
23 | AnuncioStatus[] values = AnuncioStatus.values();
24 | assertTrue(values.length > 0);
25 | }
26 |
27 | @Test
28 | void valueOf() {
29 | AnuncioStatus anuncio = AnuncioStatus.valueOf("ATIVO");
30 | assertEquals(AnuncioStatus.ATIVO, anuncio);
31 | }
32 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/enums/EnumExceptionTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.enums;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.http.HttpStatus;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class EnumExceptionTest {
9 |
10 | @Test
11 | void getDescricao() {
12 | EnumException anuncio = EnumException.ITEM_NAO_ENCONTRADO;
13 | assertEquals("O recurso solicitado nao esta disponivel no servidor", anuncio.getDescricao());
14 | }
15 |
16 | @Test
17 | void of() {
18 | EnumException anuncio = EnumException.of("O recurso solicitado nao esta disponivel no servidor");
19 | assertEquals(EnumException.ITEM_NAO_ENCONTRADO, anuncio);
20 | }
21 |
22 | @Test
23 | void values() {
24 | EnumException[] values = EnumException.values();
25 | assertTrue(values.length > 0);
26 | }
27 |
28 | @Test
29 | void valueOf() {
30 | EnumException exception = EnumException.valueOf("ITEM_NAO_ENCONTRADO");
31 | assertEquals(EnumException.ITEM_NAO_ENCONTRADO, exception);
32 | }
33 |
34 | @Test
35 | void getHttpStatus() {
36 | EnumException exception = EnumException.ITEM_NAO_ENCONTRADO;
37 | assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
38 | }
39 |
40 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/exception/GlobalControllerExceptionHandlerTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.exception;
2 |
3 | import com.kdmeubichinho.dto.CustomExceptionDTO;
4 | import com.kdmeubichinho.enums.EnumException;
5 | import org.junit.jupiter.api.Test;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.orm.jpa.JpaSystemException;
9 |
10 | import static org.junit.jupiter.api.Assertions.*;
11 |
12 | class GlobalControllerExceptionHandlerTest {
13 |
14 | @Test
15 | void handleCustomSimpleException() {
16 | GlobalControllerExceptionHandler handler = new GlobalControllerExceptionHandler();
17 | ValidationException exception = new ValidationException(EnumException.ITEM_NAO_ENCONTRADO);
18 | ResponseEntity responseEntity = handler.handleCustomSimpleException(exception);
19 |
20 | assertEquals("O recurso solicitado nao esta disponivel no servidor", ((CustomExceptionDTO)responseEntity.getBody()).getMessage());
21 | assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
22 | }
23 |
24 | @Test
25 | void handleJpaException() {
26 | GlobalControllerExceptionHandler handler = new GlobalControllerExceptionHandler();
27 | JpaSystemException exception = new JpaSystemException(new RuntimeException("#Exception JPA#"));
28 | ResponseEntity responseEntity = handler.handleJpaException(exception);
29 |
30 | assertTrue(responseEntity.getBody().getMessage().contains("#Exception JPA#"));
31 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode());
32 | }
33 |
34 | @Test
35 | void handleJpaExceptionAnotherConstructor() {
36 | GlobalControllerExceptionHandler handler = new GlobalControllerExceptionHandler();
37 | JpaSystemException exception = new JpaSystemException(new RuntimeException("#Exception JPA#Exception JPA", new RuntimeException("#Exception JPA#Exception JPA")));
38 | ResponseEntity responseEntity = handler.handleJpaException(exception);
39 |
40 | assertTrue(responseEntity.getBody().getMessage().contains("Exception JPA"));
41 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode());
42 | }
43 |
44 | @Test
45 | void handleAllAnotherException() {
46 | GlobalControllerExceptionHandler handler = new GlobalControllerExceptionHandler();
47 | NumberFormatException exception = new NumberFormatException("NFE");
48 | ResponseEntity responseEntity = handler.handleAllOtherException(exception);
49 |
50 | assertEquals("NFE", ((CustomExceptionDTO)responseEntity.getBody()).getMessage());
51 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode());
52 | }
53 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/exception/ValidationExceptionTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.exception;
2 |
3 | import com.kdmeubichinho.enums.EnumException;
4 | import org.junit.jupiter.api.Test;
5 | import org.springframework.http.HttpStatus;
6 |
7 | import static org.junit.jupiter.api.Assertions.*;
8 |
9 | class ValidationExceptionTest {
10 |
11 | @Test
12 | void getHttpStatus() {
13 | ValidationException validationException = new ValidationException(EnumException.ITEM_NAO_ENCONTRADO);
14 | assertEquals(HttpStatus.NOT_FOUND, validationException.getHttpStatus());
15 | }
16 |
17 | @Test
18 | void testConstructor() {
19 | ValidationException validationException = new ValidationException("ERRO", HttpStatus.BAD_REQUEST);
20 | assertEquals(HttpStatus.BAD_REQUEST, validationException.getHttpStatus());
21 | assertEquals("ERRO", validationException.getDescription());
22 | }
23 |
24 | @Test
25 | void getDescription() {
26 | ValidationException validationException = new ValidationException(EnumException.ITEM_NAO_ENCONTRADO);
27 | assertEquals("O recurso solicitado nao esta disponivel no servidor", validationException.getDescription());
28 | }
29 |
30 | @Test
31 | void getHttpStatusSecondConstructor() {
32 | ValidationException validationException = new ValidationException("TESTE Exception", HttpStatus.BAD_REQUEST);
33 | assertEquals(HttpStatus.BAD_REQUEST, validationException.getHttpStatus());
34 | assertEquals("TESTE Exception", validationException.getDescription());
35 | }
36 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/model/JwtRequestTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.model;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class JwtRequestTest {
8 |
9 | @Test
10 | void testAllConstructorsAndGetter(){
11 | JwtRequest jwtRequest = new JwtRequest("username", "password", "claims");
12 |
13 | assertEquals("username", jwtRequest.getUsername());
14 | assertEquals("password", jwtRequest.getPassword());
15 | assertEquals("claims", jwtRequest.getSpecificClaim());
16 | }
17 |
18 | @Test
19 | void testConstructorsAndGetter(){
20 | JwtRequest jwtRequest = new JwtRequest("username", "password");
21 |
22 | assertEquals("username", jwtRequest.getUsername());
23 | assertEquals("password", jwtRequest.getPassword());
24 | }
25 |
26 | @Test
27 | void nonArgsConstructor(){
28 | JwtRequest jwtRequest = new JwtRequest();
29 | assertNotNull(jwtRequest);
30 | }
31 |
32 | @Test
33 | void testSetter(){
34 | JwtRequest j = new JwtRequest();
35 | j.setPassword("testSetter1");
36 | j.setUsername("testSetter12");
37 | j.setSpecificClaim("testSetter123");
38 |
39 | assertEquals("testSetter12", j.getUsername());
40 | assertEquals("testSetter1", j.getPassword());
41 | assertEquals("testSetter123", j.getSpecificClaim());
42 | }
43 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/model/JwtResponseTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.model;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class JwtResponseTest {
8 |
9 | @Test
10 | void getToken() {
11 | JwtResponse j = new JwtResponse("getToken");
12 | assertEquals("getToken", j.getToken());
13 | }
14 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/security/AutenticacaoServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.security;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import com.kdmeubichinho.services.PessoaService;
5 | import org.junit.jupiter.api.*;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.security.core.userdetails.UserDetails;
10 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
11 | import org.springframework.test.context.TestPropertySource;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 |
14 | import static org.junit.jupiter.api.Assertions.*;
15 |
16 | @SpringBootTest
17 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
18 | @RunWith(SpringRunner.class)
19 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
20 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
21 | class AutenticacaoServiceTest {
22 |
23 | private PessoaService pessoaService;
24 | private AutenticacaoService autenticacaoService;
25 |
26 | @Autowired
27 | public AutenticacaoServiceTest(PessoaService pessoaService, AutenticacaoService autenticacaoService){
28 | this.pessoaService = pessoaService;
29 | this.autenticacaoService = autenticacaoService;
30 | }
31 |
32 | @BeforeAll
33 | public void setup(){
34 | Pessoa p = new Pessoa("testeautenticacaoservice", "testeautenticacaoservice@example.com", "cep", "celular", "senha");
35 | this.pessoaService.save(p);
36 | }
37 |
38 | @Test
39 | void loadUserByUsername() {
40 | UserDetails nome = this.autenticacaoService.loadUserByUsername("testeautenticacaoservice@example.com");
41 | assertNotNull(nome);
42 | }
43 |
44 | @Test()
45 | void loadUserByUsernameNaoExistente() {
46 | assertThrows(UsernameNotFoundException.class, () -> this.autenticacaoService.loadUserByUsername("teste de nome nao existente"));
47 | }
48 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/services/AnimalServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.entities.Animal;
4 | import com.kdmeubichinho.entities.Foto;
5 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
6 | import com.kdmeubichinho.enums.AnimalPorte;
7 | import com.kdmeubichinho.enums.AnimalSexo;
8 | import org.junit.jupiter.api.*;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.test.context.TestPropertySource;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import java.util.List;
16 | import java.util.Optional;
17 |
18 | import static org.junit.jupiter.api.Assertions.*;
19 |
20 | @SpringBootTest
21 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
22 | @RunWith(SpringRunner.class)
23 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
24 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
25 | class AnimalServiceTest {
26 |
27 | private AnimalService service;
28 |
29 | @Autowired
30 | public AnimalServiceTest(AnimalService service) {
31 | this.service = service;
32 | }
33 |
34 | @BeforeAll
35 | public void setup() {
36 | Foto f = new Foto(1, "");
37 | Animal a = new Animal(1,
38 | AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO, true,
39 | true, "animal", "00000-000", "logradouro", "complemento",
40 | "bairro", "localidade", "uf", "ibge", "ddd", null, f);
41 |
42 | this.service.save(a);
43 | }
44 |
45 | @Test
46 | @Order(1)
47 | void getAllAnimals() {
48 | List allAnimals = (List) this.service.getAllAnimals();
49 | assertFalse(allAnimals.isEmpty());
50 | }
51 |
52 | @Test
53 | @Order(2)
54 | void getById() {
55 | List allAnimals = (List) this.service.getAllAnimals();
56 | Optional byId = this.service.getById(allAnimals.get(allAnimals.size() - 1).getIdAnimal());
57 | assertTrue(byId.isPresent());
58 | }
59 |
60 | @Test
61 | @Order(3)
62 | void save() {
63 | Foto f = new Foto(1, "");
64 | Animal a = new Animal(5,
65 | AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO, true,
66 | true, "save-animal", "00000-000", "logradouro", "complemento",
67 | "bairro", "localidade", "uf", "ibge", "ddd", null, f);
68 |
69 | Animal save = this.service.save(a);
70 | assertEquals("save-animal", save.getNome());
71 | }
72 |
73 | @Test
74 | @Order(4)
75 | void updateAnimal() {
76 | List allAnimals = (List) this.service.getAllAnimals();
77 | Animal a = allAnimals.get(allAnimals.size() - 1);
78 | Animal animal = this.service.updateAnimal(a.getIdAnimal(), a);
79 | assertEquals(a.getNome(), animal.getNome());
80 | }
81 |
82 | @Test
83 | @Order(5)
84 | void deleteAnimal() {
85 | Animal a = new Animal(null,
86 | AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO, true,
87 | true, "save-animal", "00000-000", "logradouro", "complemento",
88 | "bairro", "localidade", "uf", "ibge", "ddd", null, null);
89 |
90 | Animal save = this.service.save(a);
91 |
92 | this.service.deleteAnimal(save.getIdAnimal());
93 | Optional byId = this.service.getById(save.getIdAnimal());
94 | assertFalse(byId.isPresent());
95 | }
96 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/services/AnuncioServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.entities.Animal;
4 | import com.kdmeubichinho.entities.Anuncio;
5 | import com.kdmeubichinho.entities.Categoria;
6 | import com.kdmeubichinho.entities.Pessoa;
7 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
8 | import com.kdmeubichinho.enums.AnimalPorte;
9 | import com.kdmeubichinho.enums.AnimalSexo;
10 | import com.kdmeubichinho.enums.AnuncioStatus;
11 | import org.junit.jupiter.api.*;
12 | import org.junit.runner.RunWith;
13 | import org.springframework.beans.factory.annotation.Autowired;
14 | import org.springframework.boot.test.context.SpringBootTest;
15 | import org.springframework.data.domain.Page;
16 | import org.springframework.data.domain.PageRequest;
17 | import org.springframework.test.context.TestPropertySource;
18 | import org.springframework.test.context.junit4.SpringRunner;
19 |
20 | import java.util.Date;
21 | import java.util.List;
22 | import java.util.Optional;
23 |
24 | import static org.junit.jupiter.api.Assertions.*;
25 |
26 | @SpringBootTest
27 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
28 | @RunWith(SpringRunner.class)
29 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
30 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
31 | class AnuncioServiceTest {
32 |
33 | private AnuncioService service;
34 | private PessoaService pessoaService;
35 | private Pessoa pessoa;
36 |
37 | @Autowired
38 | public AnuncioServiceTest(AnuncioService service, PessoaService pessoaService){
39 | this.service = service;
40 | this.pessoaService = pessoaService;
41 | }
42 |
43 | @BeforeAll
44 | public void setup(){
45 | Pessoa p = new Pessoa("nome", "setup", "cep", "celular", "senha");
46 | Anuncio a = new Anuncio(AnuncioStatus.ATIVO, new Date());
47 |
48 | Animal an = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
49 | true, true, "00000-000");
50 | an.setNome("");
51 |
52 | this.pessoa = this.pessoaService.save(p);
53 |
54 | a.setIdPessoa(this.pessoa);
55 | a.setIdAnimal(an);
56 |
57 | this.service.save(a);
58 | }
59 |
60 | @Test
61 | void getFilteredAnnounce() {
62 | Iterable cep = this.service.getFilteredAnnounce(
63 | PageRequest.of(0, 50),
64 | "cep",
65 | AnuncioStatus.ATIVO,
66 | AnimalSexo.MACHO,
67 | AnimalPorte.PEQUENO,
68 | AnimalClassificacaoEtaria.ADULTO,
69 | 1,
70 | 1,
71 | true,
72 | true
73 | );
74 |
75 | assertNotNull(cep);
76 | }
77 |
78 | @Test
79 | void getAnnounceById() {
80 | this.addAnnounce();
81 | List all = this.service.getAll();
82 | Optional announceById = this.service.getAnnounceById(all.get(all.size() - 1).getIdAnuncio());
83 | assertTrue(announceById.isPresent());
84 | }
85 |
86 | @Test
87 | void getAnnounceByEmailPessoa() {
88 | Page byEmailPessoa = this.service.getAnnounceByEmailPessoa("setup", PageRequest.of(0, 50));
89 | assertFalse(byEmailPessoa.isEmpty());
90 | }
91 |
92 | @Test
93 | void save() {
94 | Pessoa p = new Pessoa("save", "save" + Math.random(), "save", "save", "save");
95 | Anuncio a = new Anuncio(AnuncioStatus.ATIVO, new Date());
96 |
97 | Animal an = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
98 | true, true, "00000-000");
99 | an.setNome("save");
100 |
101 | this.pessoa = this.pessoaService.save(p);
102 |
103 | a.setIdPessoa(this.pessoa);
104 | a.setIdAnimal(an);
105 |
106 | Anuncio save = this.service.save(a);
107 |
108 | assertEquals(AnuncioStatus.ATIVO, save.getStatus());
109 | }
110 |
111 | @Test
112 | void updateStatusAnnounce() {
113 | this.addAnnounce();
114 | List all = this.service.getAll();
115 | Anuncio anuncio = service.updateStatusAnnounce(all.size() - 1);
116 | assertEquals(AnuncioStatus.INATIVO, anuncio.getStatus());
117 |
118 | anuncio = service.updateStatusAnnounce(all.size() - 1);
119 | assertEquals(AnuncioStatus.ATIVO, anuncio.getStatus());
120 | }
121 |
122 | @Test
123 | void deleteAnnounce() {
124 | List all = this.service.getAll();
125 | this.service.deleteAnnounce(all.get(all.size() - 1).getIdAnuncio());
126 | Optional announceById = this.service.getAnnounceById(all.get(all.size() - 1).getIdAnuncio());
127 | assertFalse(announceById.isPresent());
128 | }
129 |
130 | private void addAnnounce(){
131 | Pessoa p = new Pessoa("nome", "email" + Math.random(), "cep", "celular", "senha");
132 | Anuncio a = new Anuncio(AnuncioStatus.ATIVO, new Date());
133 |
134 | Animal an = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
135 | true, true, "00000-000");
136 | an.setNome("Rex");
137 |
138 | this.pessoa = this.pessoaService.save(p);
139 |
140 | a.setIdPessoa(this.pessoa);
141 | a.setIdAnimal(an);
142 |
143 | this.service.save(a);
144 | }
145 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/services/JwtServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.entities.Pessoa;
4 | import org.junit.jupiter.api.*;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.boot.test.context.SpringBootTest;
7 | import org.springframework.test.context.TestPropertySource;
8 |
9 | import static org.junit.jupiter.api.Assertions.*;
10 |
11 | @SpringBootTest
12 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
13 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
14 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
15 | class JwtServiceTest {
16 |
17 | private JwtService service;
18 | private static final String TOKEN_EXPIRADO = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJnZXJhclRva2VuIiwiZXhwIjoxNjI3NTQ2NjQ1fQ.zRrgyDHdOUguRiSQKRSE2EmcOGcZXnJuyeMEmfHQt33_bx2QOjt09MBeXnQzvY8Qhynalrok9OaPjiZx7rHn5Q";
19 |
20 | @Autowired
21 | public JwtServiceTest(JwtService service){
22 | this.service = service;
23 | }
24 |
25 | @Test
26 | @Order(1)
27 | void gerarToken() {
28 | Pessoa build = Pessoa.builder()
29 | .nome("gerarToken")
30 | .email("gerarToken")
31 | .build();
32 |
33 | String token = this.service.gerarToken(build);
34 | assertNotNull(token);
35 | }
36 |
37 | @Test
38 | void tokenValido() {
39 | Pessoa build = Pessoa.builder()
40 | .nome("tokenValido")
41 | .email("tokenValido")
42 | .build();
43 |
44 | String token = this.service.gerarToken(build);
45 | assertTrue(this.service.tokenValido(token));
46 | }
47 |
48 | @Test
49 | void tokenInvalido() {
50 | assertFalse(this.service.tokenValido("tokenInvalido"));
51 | }
52 |
53 | @Test
54 | void tokenExpirado() {
55 | assertFalse(this.service.tokenValido(TOKEN_EXPIRADO));
56 | }
57 |
58 | @Test
59 | void obterEmailUsuario() {
60 | Pessoa build = Pessoa.builder()
61 | .nome("obterEmailUsuario")
62 | .email("obterEmailUsuario")
63 | .build();
64 |
65 | String token = this.service.gerarToken(build);
66 |
67 | String email = this.service.obterEmailUsuario(token);
68 |
69 | assertEquals("obterEmailUsuario", email);
70 | }
71 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/services/MensagemServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.dto.MensagemDTO;
4 | import com.kdmeubichinho.entities.Animal;
5 | import com.kdmeubichinho.entities.Anuncio;
6 | import com.kdmeubichinho.entities.Mensagem;
7 | import com.kdmeubichinho.entities.Pessoa;
8 | import com.kdmeubichinho.entities.generics.BaseEntity;
9 | import com.kdmeubichinho.enums.AnimalClassificacaoEtaria;
10 | import com.kdmeubichinho.enums.AnimalPorte;
11 | import com.kdmeubichinho.enums.AnimalSexo;
12 | import com.kdmeubichinho.enums.AnuncioStatus;
13 | import org.junit.jupiter.api.*;
14 | import org.junit.runner.RunWith;
15 | import org.springframework.beans.factory.annotation.Autowired;
16 | import org.springframework.boot.test.context.SpringBootTest;
17 | import org.springframework.data.domain.Page;
18 | import org.springframework.data.domain.PageRequest;
19 | import org.springframework.test.context.TestPropertySource;
20 | import org.springframework.test.context.junit4.SpringRunner;
21 |
22 | import java.util.Date;
23 | import java.util.List;
24 | import java.util.Optional;
25 |
26 | import static org.junit.jupiter.api.Assertions.*;
27 |
28 | @SpringBootTest
29 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
30 | @RunWith(SpringRunner.class)
31 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
32 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
33 | class MensagemServiceTest {
34 |
35 | private MensagemService service;
36 | private final PessoaService pessoaService;
37 | private final AnuncioService anuncioService;
38 | private AnimalService animalService;
39 | private Pessoa pessoa;
40 | private Anuncio anuncio;
41 |
42 | @Autowired
43 | public MensagemServiceTest(MensagemService service, PessoaService pessoaService, AnuncioService anuncioService,
44 | AnimalService animalService){
45 | this.service = service;
46 | this.pessoaService = pessoaService;
47 | this.anuncioService = anuncioService;
48 | this.animalService = animalService;
49 | }
50 |
51 | @BeforeAll
52 | public void setup() {
53 | Pessoa p = new Pessoa("nome", "email", "cep", "celular", "senha");
54 | Anuncio a = new Anuncio(AnuncioStatus.ATIVO, new Date());
55 | Animal an = new Animal(AnimalSexo.MACHO, AnimalClassificacaoEtaria.ADULTO, AnimalPorte.PEQUENO,
56 | true, true, "00000-000");
57 | an.setNome("Rex");
58 |
59 | this.pessoa = this.pessoaService.save(p);
60 |
61 | a.setIdPessoa(this.pessoa);
62 | a.setIdAnimal(an);
63 | this.anuncio = this.anuncioService.save(a);
64 |
65 | for (int i = 0; i < 60; i++) {
66 | this.service.save(getMensagem());
67 | }
68 | }
69 |
70 | @AfterAll
71 | public void rollback() {
72 | this.service.getAll()
73 | .forEach(item -> this.service.deleteById(((BaseEntity)item).getId()));
74 | }
75 |
76 | @Test
77 | @Order(1)
78 | void getAllPaged() {
79 | Page all = this.service.getAll(PageRequest.of(0, 50));
80 | assertEquals(50, all.stream().count());
81 | }
82 |
83 | @Test
84 | @Order(2)
85 | void getAll() {
86 | List all = this.service.getAll();
87 | assertEquals(60, all.size());
88 | }
89 |
90 | @Test
91 | @Order(3)
92 | void getById() {
93 | Optional byId = this.service.getById(1);
94 | assertTrue(byId.isPresent());
95 | }
96 |
97 | @Test
98 | @Order(4)
99 | void save() {
100 | Mensagem mensagem = getMensagem();
101 | this.service.save(mensagem);
102 | List all = this.service.getAll();
103 | assertEquals(61, all.size());
104 | }
105 |
106 | @Test
107 | @Order(4)
108 | void saveWithNullParameter() {
109 | MensagemDTO save = this.service.save(new MensagemDTO());
110 | assertNull(save);
111 | }
112 |
113 | @Test
114 | @Order(5)
115 | void delete() {
116 | BaseEntity primeiro = (BaseEntity) this.service.getAll().get(0);
117 | service.deleteById(primeiro.getId());
118 | Optional byId = service.getById(primeiro.getId());
119 | assertFalse(byId.isPresent());
120 | }
121 |
122 | private Mensagem getMensagem(){
123 | return new Mensagem(null, new Date(), "mensagem de teste", pessoa, anuncio);
124 | }
125 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/services/PessoaServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.services;
2 |
3 | import com.kdmeubichinho.dto.CredenciaisDTO;
4 | import com.kdmeubichinho.dto.PessoaDTO;
5 | import com.kdmeubichinho.dto.TokenDTO;
6 | import com.kdmeubichinho.entities.Pessoa;
7 | import org.junit.jupiter.api.*;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.data.domain.Page;
12 | import org.springframework.data.domain.PageRequest;
13 | import org.springframework.http.HttpStatus;
14 | import org.springframework.http.ResponseEntity;
15 | import org.springframework.test.context.TestPropertySource;
16 | import org.springframework.test.context.junit4.SpringRunner;
17 | import org.springframework.web.server.ResponseStatusException;
18 |
19 | import java.text.DecimalFormat;
20 | import java.util.List;
21 | import java.util.Optional;
22 |
23 | import static org.junit.jupiter.api.Assertions.*;
24 |
25 | @SpringBootTest
26 | @TestPropertySource(locations = "classpath:application-integrationtest.properties")
27 | @RunWith(SpringRunner.class)
28 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
29 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
30 | class PessoaServiceTest {
31 |
32 | private PessoaService service;
33 |
34 | @Autowired
35 | public PessoaServiceTest(PessoaService service) {
36 | this.service = service;
37 | }
38 |
39 | @BeforeAll
40 | public void setup() {
41 | String nome = "nome-%s";
42 | String email = "email-%s";
43 |
44 | for (int i = 0; i < 60; i++) {
45 | Pessoa p = new Pessoa(String.format(nome, new DecimalFormat("00").format(i)), String.format(email, new DecimalFormat("00").format(i)), "cep", "celular", "senha");
46 | this.service.save(p);
47 | }
48 | }
49 |
50 | @Test
51 | @Order(1)
52 | void getAllPaged() {
53 | Page all = this.service.getAll(PageRequest.of(0, 50));
54 | assertEquals(50, all.stream().count());
55 | }
56 |
57 | @Test
58 | @Order(2)
59 | void getAll() {
60 | List all = this.service.getAll();
61 | assertTrue(all.size() > 60);
62 | }
63 |
64 | @Test
65 | @Order(3)
66 | void getById() {
67 | Optional byId = this.service.getById(1);
68 | assertTrue(byId.isPresent());
69 | }
70 |
71 | @Test
72 | void save() {
73 | Pessoa p = new Pessoa("nome-test-save", "nome-test-save", "cep", "celular", "senha");
74 | Pessoa save = this.service.save(p);
75 | assertEquals("nome-test-save", save.getNome());
76 | }
77 |
78 | @Test
79 | void testSave() {
80 | PessoaDTO pessoaDTO = getPessoaDTO();
81 |
82 | PessoaDTO save = this.service.save(pessoaDTO);
83 | assertEquals("nome-teste-dto", save.getNome());
84 | }
85 |
86 | @Test
87 | void deleteById() {
88 | List all = this.service.getAll();
89 | this.service.deleteById(all.get(all.size() - 1).getIdPessoa());
90 | Optional byId = this.service.getById(all.get(all.size() - 1).getIdPessoa());
91 | assertFalse(byId.isPresent());
92 | }
93 |
94 | @Test
95 | void getPersonByEmail() {
96 | PessoaDTO pessoaDTO = getPessoaDTO();
97 | pessoaDTO.setEmail("getPersonByEmail");
98 |
99 | PessoaDTO save = this.service.save(pessoaDTO);
100 | assertEquals("getPersonByEmail", save.getEmail());
101 | }
102 |
103 | @Test
104 | void savePerson() {
105 | PessoaDTO pessoaDTO = getPessoaDTO();
106 | pessoaDTO.setEmail("savePerson");
107 |
108 | final Pessoa save = this.service.savePerson(pessoaDTO);
109 | assertEquals("savePerson", save.getEmail());
110 | }
111 |
112 | @Test
113 | void authenticatePerson() {
114 | PessoaDTO pessoaDTO = getPessoaDTO();
115 | pessoaDTO.setNome("authenticatePerson");
116 | pessoaDTO.setEmail("authenticatePerson");
117 | PessoaDTO save = this.service.save(pessoaDTO);
118 | CredenciaisDTO credenciaisDTO = new CredenciaisDTO(save.getEmail(), save.getSenha());
119 |
120 | ResponseEntity entity = this.service.authenticatePerson(credenciaisDTO);
121 |
122 | assertEquals(HttpStatus.OK, entity.getStatusCode());
123 | }
124 |
125 | @Test
126 | void authenticatePersonNaoExistente() {
127 | CredenciaisDTO credenciaisDTO = new CredenciaisDTO("authenticatePersonNaoExistente", "authenticatePersonNaoExistente");
128 | assertThrows(ResponseStatusException.class, () -> this.service.authenticatePerson(credenciaisDTO));
129 | }
130 |
131 | private PessoaDTO getPessoaDTO() {
132 | PessoaDTO pessoaDTO = new PessoaDTO();
133 |
134 | pessoaDTO.setNome("nome-teste-dto");
135 | pessoaDTO.setEmail("email-teste-dto");
136 | pessoaDTO.setCep("00000-000");
137 | pessoaDTO.setCelular("000 000 000");
138 | pessoaDTO.setSenha("teste-senha");
139 |
140 | return pessoaDTO;
141 | }
142 | }
--------------------------------------------------------------------------------
/src/test/java/com/kdmeubichinho/specification/AnuncioSpecificationTest.java:
--------------------------------------------------------------------------------
1 | package com.kdmeubichinho.specification;
2 |
3 | import com.kdmeubichinho.entities.Anuncio;
4 | import com.kdmeubichinho.enums.AnuncioStatus;
5 | import org.junit.jupiter.api.Test;
6 | import org.springframework.data.jpa.domain.Specification;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class AnuncioSpecificationTest {
11 |
12 |
13 | }
--------------------------------------------------------------------------------