├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── br │ │ └── com │ │ └── alura │ │ └── bytebank │ │ ├── BytebankApplication.kt │ │ ├── controller │ │ └── TransactionController.kt │ │ ├── converter │ │ └── LocalDateTimeConverter.kt │ │ ├── dto │ │ └── TransactionDto.kt │ │ ├── model │ │ ├── Contact.kt │ │ ├── PasswordValidator.kt │ │ └── Transaction.kt │ │ ├── repository │ │ └── TransactionRepository.kt │ │ └── service │ │ └── TransactionService.kt └── resources │ ├── application-dev.yml │ └── application.yml └── test └── kotlin └── br └── com └── alura └── bytebank └── BytebankApplicationTests.kt /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | 34 | ### database ### 35 | /database/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bytebank web API 2 | 3 | Web API em Spring Boot para consumo do App em Flutter do Bytebank 4 | 5 | ## Funcionalidades 6 | 7 | A Web API oferece as seguintes funcionalidades: 8 | 9 | - Listagem e cadastro de transações. 10 | 11 | ## Como baixar 12 | 13 | Você pode baixar o arquivo jar aqui: https://github.com/alura-cursos/bytebank-api/archive/runnable.zip 14 | 15 | ## Como executar 16 | 17 | Após clonar o projeto, dentro do diretório raiz, execute a task `bootRun` do Gradle. A primeira execução vai realizar o download de todas dependências necessárias. 18 | 19 | > O uso do Wrapper é recomendado `gradlew` ou `gradlew.bat` para garantir a compatibilidade. 20 | 21 | Também é possível executar o projeto via arquivo jar gerado pela task `build` que é armazenado no diretório **build/libs/file-name.jar**. Para executar basta usar o seguinte comando: 22 | 23 | ``` 24 | java -jar file-name.jar 25 | ``` 26 | 27 | > A build do projeto foi feita com base no Java 8, portanto, é recomendado usar o Java 8 para que tudo funcione como esperado. 28 | 29 | ## Modificando properties de inicialização 30 | 31 | Por padrão o Spring Boot vai rodar a aplicação na porta `8080` e vai exigir a senha para criar transação com o valor `1000`. 32 | 33 | Caso queria modificar ambos valores, edite os valores das propriedades: 34 | 35 | 36 | ``` 37 | server: 38 | port: ${port:8081} 39 | user: 40 | password: ${password:2000} 41 | ``` 42 | 43 | Na amostra acima, durante a execução a aplicação vai operar na porta `8081` e a senha para as transações será `2000`. 44 | 45 | ## Modificando propriedades durante a execução 46 | 47 | Também é possível modificar as propriedades via command line durante a execução. 48 | 49 | ### Via task `bootRun` do Gradle 50 | 51 | Com o Gradle você pode alterar os valores das properties por meio do comando `-args`: 52 | 53 | ``` 54 | ./gradlew bootRun --args='--server.port=8081 --user.password=2000' 55 | ``` 56 | 57 | ### Via arquivo jar gerado 58 | 59 | Caso execute pelo arquivo jar, 60 | 61 | ``` 62 | java -jar file-name.jar --server.port=8081 --user.password=2000 63 | ``` 64 | 65 | ## Mapeamento de end-points 66 | 67 | Para acessar as funcionalidades foram disponibilizados os seguintes end-points: 68 | 69 | - `/transactions`: 70 | - **GET**: Listagem: 71 | - O resultado é ordenado pela data e hora da criação em ordem crescente. 72 | 73 | ``` 74 | // response example 75 | [ 76 | { 77 | "id": "b9663ef3-3749-400e-be8f-1280db94aac8", 78 | "value": 200.00, 79 | "contact": { 80 | "name": "gui", 81 | "accountNumber": 1000 82 | }, 83 | "dateTime": "2019-11-06 12:57:23" 84 | }, 85 | { 86 | "id": "d1bf689c-caa2-4e45-b1fc-5a90b10d6d48", 87 | "value": 200.00, 88 | "contact": { 89 | "name": "gui", 90 | "accountNumber": 1500 91 | }, 92 | "dateTime": "2019-11-06 12:57:37" 93 | } 94 | ] 95 | ``` 96 | 97 | - **POST**: Inserção: 98 | - Para salvar a transação é necessário o envio do *header* `password` conforme o valor configurado na aplicação: 99 | - Caso não seja enviado, é retornado `400 BAD REQUEST`; 100 | - Caso falhar na autenticação `401 UNAUTHORIZED`. 101 | - Não é possível alterar a transação, caso haja a tentativa é retornado `409 CONFLICT`. 102 | 103 | ``` 104 | // request body example 105 | { 106 | "value": 200.0, 107 | "contact": { 108 | "name": "gui", 109 | "accountNumber": 1000 110 | } 111 | } 112 | 113 | // response example 114 | { 115 | "id": "b9663ef3-3749-400e-be8f-1280db94aac8", 116 | "value": 200.00, 117 | "contact": { 118 | "name": "gui", 119 | "accountNumber": 1000 120 | }, 121 | "dateTime": "2019-11-06 12:57:23" 122 | } 123 | ``` 124 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.1.9.RELEASE" 5 | id("io.spring.dependency-management") version "1.0.8.RELEASE" 6 | kotlin("jvm") version "1.2.71" 7 | kotlin("plugin.spring") version "1.2.71" 8 | kotlin("plugin.jpa") version "1.2.71" 9 | } 10 | 11 | group = "br.com.alura" 12 | version = "0.0.1-SNAPSHOT" 13 | java.sourceCompatibility = JavaVersion.VERSION_1_8 14 | 15 | val developmentOnly by configurations.creating 16 | configurations { 17 | runtimeClasspath { 18 | extendsFrom(developmentOnly) 19 | } 20 | } 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | dependencies { 27 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 28 | implementation("org.springframework.boot:spring-boot-starter-web") 29 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 30 | implementation("org.jetbrains.kotlin:kotlin-reflect") 31 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 32 | developmentOnly("org.springframework.boot:spring-boot-devtools") 33 | runtimeOnly("org.hsqldb:hsqldb") 34 | testImplementation("org.springframework.boot:spring-boot-starter-test") 35 | } 36 | 37 | tasks.withType { 38 | kotlinOptions { 39 | freeCompilerArgs = listOf("-Xjsr305=strict") 40 | jvmTarget = "1.8" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alura-cursos/bytebank-api/b1195640196f0b7f4ef0418f698f771696630681/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "bytebank" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/BytebankApplication.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class BytebankApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/controller/TransactionController.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.controller 2 | 3 | import br.com.alura.bytebank.dto.TransactionRequest 4 | import br.com.alura.bytebank.dto.TransactionResponse 5 | import br.com.alura.bytebank.model.PasswordValidator 6 | import br.com.alura.bytebank.service.TransactionService 7 | import org.springframework.http.HttpEntity 8 | import org.springframework.http.HttpStatus 9 | import org.springframework.http.ResponseEntity 10 | import org.springframework.web.bind.annotation.* 11 | 12 | private const val transactionExists = "transaction already exists" 13 | private const val authenticationFail = "authentication failed" 14 | 15 | @RestController 16 | @RequestMapping("/transactions") 17 | class TransactionController( 18 | private val service: TransactionService, 19 | private val validator: PasswordValidator) { 20 | 21 | @GetMapping 22 | fun all(): HttpEntity> { 23 | return service.findAll().map { TransactionResponse(it) } 24 | .let { response -> 25 | ResponseEntity.ok(response) 26 | } 27 | } 28 | 29 | @PostMapping 30 | fun save(@RequestBody request: TransactionRequest, 31 | @RequestHeader("password") password: String): HttpEntity { 32 | if (validator.valida(password)) { 33 | request.transaction.let { transactionReceived -> 34 | if (service.exists(transactionReceived.id)) { 35 | return ResponseEntity(transactionExists, HttpStatus.CONFLICT) 36 | } 37 | return service.save(transactionReceived) 38 | .let { savedTransaction -> 39 | ResponseEntity.ok(savedTransaction) 40 | } 41 | } 42 | } 43 | return ResponseEntity(authenticationFail, HttpStatus.UNAUTHORIZED) 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/converter/LocalDateTimeConverter.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.converter 2 | 3 | import java.sql.Timestamp 4 | import java.time.LocalDateTime 5 | import javax.persistence.AttributeConverter 6 | import javax.persistence.Converter 7 | 8 | @Converter 9 | class LocalDateTimeConverter : AttributeConverter { 10 | 11 | override fun convertToDatabaseColumn(date: LocalDateTime?) = 12 | date?.let { Timestamp.valueOf(date) } 13 | 14 | override fun convertToEntityAttribute(value: Timestamp?) = 15 | value?.let { value.toLocalDateTime() } 16 | 17 | } -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/dto/TransactionDto.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.dto 2 | 3 | import br.com.alura.bytebank.model.Contact 4 | import br.com.alura.bytebank.model.Transaction 5 | import com.fasterxml.jackson.annotation.JsonFormat 6 | import java.math.BigDecimal 7 | import java.time.LocalDateTime 8 | import java.util.* 9 | 10 | open class TransactionRequest( 11 | id: String?, 12 | contact: Contact, 13 | value: BigDecimal) { 14 | 15 | val transaction: Transaction = Transaction( 16 | id = id ?: UUID.randomUUID().toString(), 17 | contact = contact, 18 | value = value 19 | ) 20 | 21 | } 22 | 23 | class TransactionResponse( 24 | transaction: Transaction, 25 | val id: String = transaction.id, 26 | val value: BigDecimal = transaction.value, 27 | val contact: Contact = transaction.contact, 28 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 29 | val dateTime: LocalDateTime = transaction.dateTime 30 | ) 31 | 32 | -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/model/Contact.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.model 2 | 3 | import javax.persistence.Embeddable 4 | 5 | @Embeddable 6 | class Contact( 7 | val name: String, 8 | val accountNumber: Int 9 | ) -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/model/PasswordValidator.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.model 2 | 3 | import org.springframework.beans.factory.annotation.Value 4 | import org.springframework.stereotype.Component 5 | 6 | @Component 7 | class PasswordValidator { 8 | 9 | @Value("\${user.password}") 10 | private lateinit var passwordApplication: String 11 | 12 | fun valida(password: String) = password == passwordApplication 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/model/Transaction.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.model 2 | 3 | import java.math.BigDecimal 4 | import java.time.LocalDateTime 5 | import java.util.* 6 | import javax.persistence.Embedded 7 | import javax.persistence.Entity 8 | import javax.persistence.Id 9 | 10 | @Entity 11 | class Transaction( 12 | @Id 13 | val id: String = UUID.randomUUID().toString(), 14 | val value: BigDecimal, 15 | @Embedded 16 | val contact: Contact, 17 | val dateTime: LocalDateTime = LocalDateTime.now() 18 | ) 19 | -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/repository/TransactionRepository.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.repository 2 | 3 | import br.com.alura.bytebank.model.Transaction 4 | import org.springframework.data.repository.PagingAndSortingRepository 5 | import org.springframework.stereotype.Repository 6 | 7 | @Repository 8 | interface TransactionRepository : PagingAndSortingRepository { 9 | fun findAllByOrderByDateTimeAsc(): List 10 | } 11 | -------------------------------------------------------------------------------- /src/main/kotlin/br/com/alura/bytebank/service/TransactionService.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank.service 2 | 3 | import br.com.alura.bytebank.model.Transaction 4 | import br.com.alura.bytebank.repository.TransactionRepository 5 | import org.springframework.stereotype.Service 6 | 7 | @Service 8 | class TransactionService(private val repository: TransactionRepository) { 9 | 10 | fun findAll() = repository.findAllByOrderByDateTimeAsc() 11 | 12 | fun save(transaction: Transaction) = repository.save(transaction) 13 | 14 | fun exists(id: String) = repository.existsById(id) 15 | 16 | } -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:hsqldb:file:database/main/db 4 | server: 5 | port: ${port:8080} 6 | user: 7 | password: ${password:1000} -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: dev 4 | datasource: 5 | username: sa 6 | driver-class-name: org.hsqldb.jdbc.JDBCDriver 7 | jpa: 8 | properties: 9 | hibernate: 10 | dialect: org.hibernate.dialect.HSQLDialect 11 | event: 12 | merge: 13 | entity_copy_observer: allow 14 | hibernate: 15 | ddl-auto: update -------------------------------------------------------------------------------- /src/test/kotlin/br/com/alura/bytebank/BytebankApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package br.com.alura.bytebank 2 | 3 | import org.junit.Test 4 | import org.junit.runner.RunWith 5 | import org.springframework.boot.test.context.SpringBootTest 6 | import org.springframework.test.context.junit4.SpringRunner 7 | 8 | @RunWith(SpringRunner::class) 9 | @SpringBootTest 10 | class BytebankApplicationTests { 11 | 12 | @Test 13 | fun contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------