diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..444198c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea/ +target/ +test-santander-api.iml \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..5fd4d502 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c954cec9 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..c133ddcf --- /dev/null +++ b/Dockerfile @@ -0,0 +1,7 @@ +FROM openjdk:8-jdk-alpine +VOLUME /tmp +ARG DEPENDENCY=target/dependency +COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib +COPY ${DEPENDENCY}/META-INF /app/META-INF +COPY ${DEPENDENCY}/BOOT-INF/classes /app +ENTRYPOINT ["java","-cp","app:app/lib/*","dev/wellison/santander/Application"] \ No newline at end of file diff --git a/README.md b/README.md index 15d8f685..b456b554 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,20 @@ # Show me the code +### # Como rodar: + +Primeiramente, ir na pasta raiz do projeto e compilar com o maven +``` + ./mvnw clean install +``` + +Depois executar o Docker + +``` + docker-compose up --build +``` + +As chamadas podem ser importadas no SoapUI, através do arquivo `REST-Project-1-soapui-project.xml` + ### # DESAFIO: API REST para Gestão de Gastos! diff --git a/REST-Project-1-soapui-project.xml b/REST-Project-1-soapui-project.xml new file mode 100644 index 00000000..56b37870 --- /dev/null +++ b/REST-Project-1-soapui-project.xml @@ -0,0 +1,30 @@ + +http://localhost:8080text/plain;charset=UTF-8200dataapplication/json;charset=UTF-8200loc:Response0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0dataapplication/json;charset=UTF-8404loc:Fault0data0data0data0data0dataapplication/json;charset=utf-8200loc:Response0data<xml-fragment/>http://localhost:8080http://localhost/No Authorizationapplication/json;charset=UTF-8500 401add:Faultapplication/json0dataapplication/json;charset=UTF-8200add:Response<xml-fragment/>http://localhost:8080{ + "description" : "Almoco", + "value": "55", + "userCode": "6789", + "date": "2005-05-07" +} +http://localhost/expense/addadminadminBasicBasicGlobal HTTP Settingsapplication/json;charset=UTF-8500 405 401 403ns:Faultapplication/json;charset=utf-8200Response0dataapplication/json;charset=UTF-8200Response<xml-fragment/>http://localhost:8080http://localhost/expense/filtrar/1234/2005-05-06adminadminBasicBasicGlobal HTTP SettingsidTEMPLATEapplication/jsonapplication/json;charset=UTF-8404ns:Faultapplication/json;charset=utf-8200ns:Response<xml-fragment/>http://localhost:8080http://localhost/expense/605173860adminadminBasicBasicGlobal HTTP SettingsiduserCodeTEMPLATEdateTEMPLATEapplication/json;charset=UTF-8500 405ns:Faultapplication/json;charset=utf-8200Response0dataapplication/json;charset=UTF-8200Response<xml-fragment/>http://localhost:8080http://localhost/expense/filtrar/1234/2005-05-06useruserBasicBasicGlobal HTTP Settings + + +userCodedateapplication/json;charset=UTF-8400upd:Faultapplication/jsonapplication/json;charset=utf-8200upd:Response<xml-fragment/>http://localhost:8080{ + "id": 574291043, + "category": { + "id": 3, + "description": "Gastos Caseiros" + } +} +http://localhost/expense/updateadminadminBasicBasicGlobal HTTP Settingsapplication/json;charset=UTF-8200add:Responseapplication/json<xml-fragment/>http://localhost:8080{ + "description":"PC" +} +http://localhost/category/adduseruserBasicBasicGlobal HTTP SettingssearchCategoryTEMPLATEapplication/json;charset=utf-8200Response<xml-fragment/>http://localhost:8080http://localhost/category/find/Gastos%20CaseirosuseruserBasicBasicGlobal HTTP SettingssearchCategoryapplication/jsonapplication/json;charset=UTF-8200add:Response<xml-fragment/>http://localhost:8080{ + "description" : "Teste de teste", + "value": "68", + "userCode": "666", + "date": "2005-05-07", + "category": { + "description": "Gastos Caseiros" + } +} +http://localhost/expense/addCategoryadminadminBasicBasicGlobal HTTP SettingsuserCodeTEMPLATEapplication/json;charset=UTF-8500 405ns:Faultapplication/json;charset=utf-8200Response0dataapplication/json;charset=UTF-8200Response<xml-fragment/>http://localhost:8080http://localhost/expense/filtrar/1234/2005-05-06useruserBasicBasicGlobal HTTP SettingsuserCode \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..35ebc998 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,21 @@ +version: '2.2' +services: + app: + build: . + ports: + - 8080:8080 + networks: + - api-santander + links: + - "db:redis" + db: + image: "redis:alpine" + hostname: redis + ports: + - "6379:6379" + networks: + - api-santander +networks: + api-santander: + driver: bridge + diff --git a/mvnw b/mvnw new file mode 100755 index 00000000..02217b1e --- /dev/null +++ b/mvnw @@ -0,0 +1,233 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100755 index 00000000..4b98b78c --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..2839b908 --- /dev/null +++ b/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + dev.wellison + test-santander-api + 0.1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + + 1.8 + docker.io/hellison999 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + org.projectlombok + lombok + + + org.springframework.boot + spring-boot-starter-data-redis + + + redis.clients + jedis + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + dockerfile-maven-plugin + 1.4.9 + + ${docker.image.prefix}/${project.artifactId} + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack + package + + unpack + + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + + + + + + + diff --git a/src/main/java/dev/wellison/santander/Application.java b/src/main/java/dev/wellison/santander/Application.java new file mode 100644 index 00000000..0e823a26 --- /dev/null +++ b/src/main/java/dev/wellison/santander/Application.java @@ -0,0 +1,13 @@ +package dev.wellison.santander; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/src/main/java/dev/wellison/santander/config/SpringSecurityConfig.java b/src/main/java/dev/wellison/santander/config/SpringSecurityConfig.java new file mode 100644 index 00000000..91a23440 --- /dev/null +++ b/src/main/java/dev/wellison/santander/config/SpringSecurityConfig.java @@ -0,0 +1,47 @@ +package dev.wellison.santander.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + + auth.inMemoryAuthentication() + .withUser("admin").password(encoder().encode("admin")).roles("ADMIN") + .and() + .withUser("user").password(encoder().encode("user")).roles("USER"); + + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.httpBasic() + .and() + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/expense/**").hasAnyRole("USER","ADMIN") + .antMatchers(HttpMethod.POST, "/expense/*").hasRole("ADMIN") + .antMatchers(HttpMethod.PUT, "/expense/**").hasAnyRole("USER","ADMIN") + .antMatchers(HttpMethod.GET, "/category/**").hasAnyRole("USER","ADMIN") + .antMatchers(HttpMethod.POST, "/category/*").hasAnyRole("USER","ADMIN") + .and() + .csrf().disable() + .formLogin().disable(); + } +} diff --git a/src/main/java/dev/wellison/santander/controller/CategoryController.java b/src/main/java/dev/wellison/santander/controller/CategoryController.java new file mode 100644 index 00000000..7f997330 --- /dev/null +++ b/src/main/java/dev/wellison/santander/controller/CategoryController.java @@ -0,0 +1,33 @@ +package dev.wellison.santander.controller; + +import dev.wellison.santander.domain.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import dev.wellison.santander.service.CategoryService; + +import java.util.List; + +@RestController +@RequestMapping("/category") +public class CategoryController { + + + @Autowired + CategoryService categoryService; + + @PostMapping("/add") + public Category addCategory(@RequestBody Category request){ + return categoryService.addCategory(request); + } + + + @GetMapping(value = "/find/{searchCategory}", produces = "application/json; charset=utf-8") + public ResponseEntity> searchCategoryByDescription(@PathVariable String searchCategory) { + + List categories = categoryService.searchCategoryByDescription(searchCategory); + return ResponseEntity.status(HttpStatus.OK).body(categories); + } + +} diff --git a/src/main/java/dev/wellison/santander/controller/ExpenseController.java b/src/main/java/dev/wellison/santander/controller/ExpenseController.java new file mode 100644 index 00000000..e828bd81 --- /dev/null +++ b/src/main/java/dev/wellison/santander/controller/ExpenseController.java @@ -0,0 +1,75 @@ +package dev.wellison.santander.controller; + +import dev.wellison.santander.domain.Expense; +import dev.wellison.santander.service.CategoryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import dev.wellison.santander.service.ExpenseService; + +import java.text.ParseException; +import java.util.List; + +@RestController +@RequestMapping("/expense") +public class ExpenseController{ + + + @Autowired + ExpenseService expenseService; + @Autowired + CategoryService categoryService; + + + @PostMapping("/add") + @PreAuthorize("hasRole('ADMIN')") + public Expense addExpense(@RequestBody Expense expense) + { + return expenseService.saveExpense(expense); + } + + + @GetMapping("/findAll") + @PreAuthorize("hasRole('ADMIN')") + public List getAllExpenses() + { + return expenseService.getAllExpenses(); + } + + @GetMapping(value = "/find/{userCode}/{date}", produces = "application/json; charset=utf-8") + public ResponseEntity> findExpenseByUserCodeAndDate(@PathVariable Long userCode, @PathVariable String date) throws ParseException { + + List expenses = expenseService.findExpenseByUserCodeAndDate(userCode,date); + return ResponseEntity.status(HttpStatus.OK).body(expenses); + } + + @GetMapping(value = "/find/{userCode}", produces = "application/json; charset=utf-8") + public ResponseEntity> findExpenseByUserCode(@PathVariable Long userCode) throws ParseException { + + List expenses = expenseService.findExpenseByUserCode(userCode); + return ResponseEntity.status(HttpStatus.OK).body(expenses); + } + + @DeleteMapping(value = "/{id}", produces = "application/json; charset=utf-8") + @PreAuthorize("hasRole('ADMIN')") + public String deleteExpense(@PathVariable String id) { + return expenseService.deleteExpense(id); + } + + @PutMapping(value = "/update", produces = "application/json; charset=utf-8") + public ResponseEntity updateExpense(@RequestBody Expense request) { + + Expense result = expenseService.updateExpense(request); + return (result!=null)?ResponseEntity.ok().body(result):ResponseEntity.notFound().build(); + } + + + @PostMapping("/addCategory") + public Expense addCategoryAutomatically (@RequestBody Expense expense) { + + return expenseService.addCategoryAutomatically(expense); + } + +} diff --git a/src/main/java/dev/wellison/santander/controller/HealthController.java b/src/main/java/dev/wellison/santander/controller/HealthController.java new file mode 100644 index 00000000..25806016 --- /dev/null +++ b/src/main/java/dev/wellison/santander/controller/HealthController.java @@ -0,0 +1,16 @@ +package dev.wellison.santander.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthController { + + @GetMapping(value = "/healthcheck", produces = "application/json; charset=utf-8") + public String getHealthCheck() + { + return "{ \"isWorking\" : true }"; + } + +} diff --git a/src/main/java/dev/wellison/santander/domain/Category.java b/src/main/java/dev/wellison/santander/domain/Category.java new file mode 100644 index 00000000..961529dc --- /dev/null +++ b/src/main/java/dev/wellison/santander/domain/Category.java @@ -0,0 +1,22 @@ +package dev.wellison.santander.domain; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import org.springframework.data.annotation.Id; +import org.springframework.data.redis.core.RedisHash; +import org.springframework.data.redis.core.index.Indexed; + +@AllArgsConstructor +@Getter +@Setter +@RedisHash("Category") +public class Category { + + private @Id String id; + private @Indexed String description; + + public Category() { + } +} diff --git a/src/main/java/dev/wellison/santander/domain/Expense.java b/src/main/java/dev/wellison/santander/domain/Expense.java new file mode 100644 index 00000000..546ec0d1 --- /dev/null +++ b/src/main/java/dev/wellison/santander/domain/Expense.java @@ -0,0 +1,29 @@ +package dev.wellison.santander.domain; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.springframework.data.annotation.Id; +import org.springframework.data.redis.core.RedisHash; +import org.springframework.data.redis.core.index.Indexed; + +import java.io.Serializable; +import java.util.Date; + +@AllArgsConstructor +@Getter +@Setter +@RedisHash("Expense") +public class Expense implements Serializable { + + private @Id String id; + private String description; + private Double value; + private @Indexed Long userCode; + private @Indexed Date date; + private Category category; + + + public Expense() { + } +} diff --git a/src/main/java/dev/wellison/santander/repository/CategoryRepository.java b/src/main/java/dev/wellison/santander/repository/CategoryRepository.java new file mode 100644 index 00000000..3a80a1db --- /dev/null +++ b/src/main/java/dev/wellison/santander/repository/CategoryRepository.java @@ -0,0 +1,10 @@ +package dev.wellison.santander.repository; + +import dev.wellison.santander.domain.Category; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; + +public interface CategoryRepository extends CrudRepository { + List findByDescription(String description); +} diff --git a/src/main/java/dev/wellison/santander/repository/ExpenseRepository.java b/src/main/java/dev/wellison/santander/repository/ExpenseRepository.java new file mode 100644 index 00000000..5fdfb913 --- /dev/null +++ b/src/main/java/dev/wellison/santander/repository/ExpenseRepository.java @@ -0,0 +1,13 @@ +package dev.wellison.santander.repository; + +import dev.wellison.santander.domain.Expense; +import org.springframework.data.repository.CrudRepository; + +import java.util.Date; +import java.util.List; + +public interface ExpenseRepository extends CrudRepository { + List findByUserCodeAndDate(Long userCode, Date date); + + List findByUserCodeOrderByDateAsc(Long userCode); +} diff --git a/src/main/java/dev/wellison/santander/service/CategoryService.java b/src/main/java/dev/wellison/santander/service/CategoryService.java new file mode 100644 index 00000000..0ab688cf --- /dev/null +++ b/src/main/java/dev/wellison/santander/service/CategoryService.java @@ -0,0 +1,11 @@ +package dev.wellison.santander.service; + +import dev.wellison.santander.domain.Category; + +import java.util.List; + +public interface CategoryService { + + Category addCategory(Category request); + List searchCategoryByDescription(String searchCategory); +} diff --git a/src/main/java/dev/wellison/santander/service/ExpenseService.java b/src/main/java/dev/wellison/santander/service/ExpenseService.java new file mode 100644 index 00000000..d0d0ab39 --- /dev/null +++ b/src/main/java/dev/wellison/santander/service/ExpenseService.java @@ -0,0 +1,17 @@ +package dev.wellison.santander.service; + +import dev.wellison.santander.domain.Expense; + +import java.text.ParseException; +import java.util.List; + +public interface ExpenseService { + + Expense saveExpense(Expense expense); + List getAllExpenses(); + List findExpenseByUserCodeAndDate(Long userCode, String date) throws ParseException; + List findExpenseByUserCode(Long userCode); + String deleteExpense(String id); + Expense updateExpense(Expense expense); + Expense addCategoryAutomatically (Expense expense); +} diff --git a/src/main/java/dev/wellison/santander/service/impl/CategoryServiceImpl.java b/src/main/java/dev/wellison/santander/service/impl/CategoryServiceImpl.java new file mode 100644 index 00000000..b5d2a0c2 --- /dev/null +++ b/src/main/java/dev/wellison/santander/service/impl/CategoryServiceImpl.java @@ -0,0 +1,30 @@ +package dev.wellison.santander.service.impl; + +import dev.wellison.santander.domain.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import dev.wellison.santander.repository.CategoryRepository; +import dev.wellison.santander.service.CategoryService; + +import java.util.List; +import java.util.UUID; + +@Service(value = "categoryService") +public class CategoryServiceImpl implements CategoryService { + + @Autowired + CategoryRepository categoryRepository; + + @Override + public Category addCategory(Category request) { + String id = UUID.randomUUID().toString(); + Category category = new Category(id,request.getDescription()); + return categoryRepository.save(category); + } + + @Override + public List searchCategoryByDescription(String searchCategory) { + + return categoryRepository.findByDescription(searchCategory); + } +} diff --git a/src/main/java/dev/wellison/santander/service/impl/ExpenseServiceImpl.java b/src/main/java/dev/wellison/santander/service/impl/ExpenseServiceImpl.java new file mode 100644 index 00000000..e6612201 --- /dev/null +++ b/src/main/java/dev/wellison/santander/service/impl/ExpenseServiceImpl.java @@ -0,0 +1,80 @@ +package dev.wellison.santander.service.impl; + +import dev.wellison.santander.domain.Category; +import dev.wellison.santander.domain.Expense; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import dev.wellison.santander.repository.CategoryRepository; +import dev.wellison.santander.repository.ExpenseRepository; +import dev.wellison.santander.service.ExpenseService; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Service(value = "expenseService") +public class ExpenseServiceImpl implements ExpenseService { + + @Autowired + ExpenseRepository expenseRepository; + @Autowired + CategoryRepository categoryRepository; + + + public Expense saveExpense(Expense expense) { + String id = UUID.randomUUID().toString(); + Expense exp = new Expense(id, expense.getDescription(), expense.getValue(), expense.getUserCode(), expense.getDate(), expense.getCategory()); + expenseRepository.save(exp); + return exp; + } + + @Override + public List getAllExpenses() { + Iterable result = expenseRepository.findAll(); + List employeesList = new ArrayList(); + result.forEach(employeesList::add); + return employeesList; + } + + @Override + public List findExpenseByUserCodeAndDate(Long userCode, String date) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date d = sdf.parse(date); + + return expenseRepository.findByUserCodeAndDate(userCode, d); + } + + @Override + public List findExpenseByUserCode(Long userCode){ + return expenseRepository.findByUserCodeOrderByDateAsc(userCode); + } + + @Override + public String deleteExpense(String id) { + boolean result = expenseRepository.existsById(id); + expenseRepository.deleteById(id); + return "{ \"success\" : "+ (result ? "true" : "false") +" }"; + } + + @Override + public Expense updateExpense(Expense expense) { + return expenseRepository.findById(expense.getId()).map(recordedExpense -> { + recordedExpense.setCategory(expense.getCategory()); + + return expenseRepository.save(recordedExpense); + }).orElse(null); + } + + @Override + public Expense addCategoryAutomatically(Expense expense) { + List categories = categoryRepository.findByDescription(expense.getCategory().getDescription()); + if (categories.size()>0){ + expense.setCategory(categories.get(0)); + } + + return expenseRepository.save(expense); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..5bbf1bb7 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.session.store-type=redis +server.session.timeout=5 +spring.redis.host=redis +spring.redis.port=6379 \ No newline at end of file diff --git a/src/test/java/dev/wellison/santander/ApplicationTests.java b/src/test/java/dev/wellison/santander/ApplicationTests.java new file mode 100644 index 00000000..4a427e87 --- /dev/null +++ b/src/test/java/dev/wellison/santander/ApplicationTests.java @@ -0,0 +1,175 @@ +package dev.wellison.santander; + +import com.fasterxml.jackson.databind.ObjectMapper; +import dev.wellison.santander.domain.Category; +import dev.wellison.santander.domain.Expense; +import dev.wellison.santander.repository.CategoryRepository; +import dev.wellison.santander.repository.ExpenseRepository; +import dev.wellison.santander.service.CategoryService; +import dev.wellison.santander.service.ExpenseService; +import dev.wellison.santander.util.UtilTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import java.lang.reflect.Array; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class ApplicationTests { + + @Autowired + private MockMvc mockMvc; + + @MockBean + ExpenseService expenseService; + + @MockBean + CategoryService categoryService; + + @MockBean + ExpenseRepository expenseRepository; + + @MockBean + CategoryRepository categoryRepository; + + @Test + public void shouldReturnDefaultMessage() throws Exception { + this.mockMvc.perform(get("/healthcheck")).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json("{ \"isWorking\" : true }")); + } + + @Test + public void testAddExpenseInvalidUser() throws Exception { + + Expense expense = getSampleExpense(); + + String requestBody = UtilTest.asJsonString(expense); + + mockMvc.perform(post("/expense/add").with(httpBasic("invalidUser","oooo")).contentType(APPLICATION_JSON).content(requestBody)).andExpect(status().isUnauthorized()).andReturn(); + } + + @Test + public void testAddExpenseValidUser() throws Exception { + + Expense expense = getSampleExpense(); + + String requestBody = UtilTest.asJsonString(expense); + mockMvc.perform(post("/expense/add") + .with(httpBasic("admin","admin")) + .contentType(APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isOk()); + } + + @Test + public void getAllExpensesValid() throws Exception { + mockMvc.perform(get("/expense/findAll") + .with(httpBasic("admin","admin")) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void findExpenseByUserCodeAndDateValid() throws Exception { + mockMvc.perform(get("/expense/find/1234/2019-02-02") + .with(httpBasic("user","user")) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void findExpenseByUserCodeValid() throws Exception { + mockMvc.perform(get("/expense/find/1234") + .with(httpBasic("user","user")) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void deleteExpenseValid() throws Exception { + mockMvc.perform(delete("/expense/991ec2ca-ed72-499d-9772-0f7c5cb34a74") + .with(httpBasic("admin","admin")) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void updateExpenseValid() throws Exception { + Expense expense = getSampleExpense(); + expense.setId("991ec2ca-ed72-499d-9772-0f7c5cb34a74"); + Category c = new Category("047ac76b-1831-4454-b7ec-55658917a1cf","Automovel"); + expense.setCategory(c); + + Optional optionalExpense = Optional.of(expense); + Mockito.when(expenseRepository.findById(expense.getId())).thenReturn(optionalExpense); + Mockito.when(expenseRepository.save(expense)) + .thenReturn(expense); + expenseService.updateExpense(expense); + + + } + + @Test + public void addCategoryAutomaticallyValid() throws Exception { + + Expense expense = getSampleExpense(); + Category c = new Category(); + c.setDescription("Automovel"); + Category savedCategory = new Category("047ac76b-1831-4454-b7ec-55658917a1cf","Automovel"); + List list = new ArrayList<>(); + list.add(savedCategory); + expense.setCategory(savedCategory); + + Mockito.when(categoryRepository.findByDescription(c.getDescription())) + .thenReturn(list); + Mockito.when(expenseRepository.save(expense)) + .thenReturn(expense); + expenseService.updateExpense(expense); + + +// +// String requestBody = UtilTest.asJsonString(expense); +// mockMvc.perform(post("/expense/update") +// .with(httpBasic("admin","admin")) +// .contentType(APPLICATION_JSON) +// .content(requestBody)) +// .andExpect(status().isOk()); + } + + private Expense getSampleExpense() throws ParseException { + Expense expense = new Expense(); + expense.setDescription("Almoco"); + expense.setValue(46.0); + expense.setUserCode(Long.valueOf("1234") ); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date data = new Date(sdf.parse("2019-06-10").getTime()); + expense.setDate(data); + return expense; + } + + + + +} \ No newline at end of file diff --git a/src/test/java/dev/wellison/santander/util/UtilTest.java b/src/test/java/dev/wellison/santander/util/UtilTest.java new file mode 100644 index 00000000..9121a20e --- /dev/null +++ b/src/test/java/dev/wellison/santander/util/UtilTest.java @@ -0,0 +1,14 @@ +package dev.wellison.santander.util; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class UtilTest { + + public static String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +}