├── .github ├── scripts │ └── build.sh └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── db ├── cassandra │ └── schema.cql ├── mongo │ └── schema.js └── mysql │ └── migrations │ └── v0.0.1.sql ├── docker ├── Dockerfile.app ├── README.md └── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── scripts ├── README.md └── start_server.sh ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── bestpractice │ │ └── api │ │ ├── Application.java │ │ ├── app │ │ ├── AdviceController.java │ │ ├── AppBean.java │ │ ├── InterceptorController.java │ │ ├── v1 │ │ │ ├── AuthController.java │ │ │ ├── HelloController.java │ │ │ ├── RdbmsController.java │ │ │ └── UserController.java │ │ └── v2 │ │ │ └── AuthorizationController.java │ │ ├── common │ │ ├── exception │ │ │ ├── BadRequest.java │ │ │ ├── Conflict.java │ │ │ ├── Forbidden.java │ │ │ ├── InternalServerError.java │ │ │ ├── NotFound.java │ │ │ ├── RequestTimeout.java │ │ │ ├── ServiceUnavailable.java │ │ │ └── UnAuthorized.java │ │ ├── property │ │ │ └── CredentialProperty.java │ │ └── util │ │ │ └── Util.java │ │ ├── domain │ │ ├── DomainBean.java │ │ ├── component │ │ │ ├── AuthComponent.java │ │ │ ├── BCryptPasswordEncryptionComponent.java │ │ │ └── RequestInfoComponent.java │ │ ├── model │ │ │ ├── AuthByEmailRequest.java │ │ │ ├── AuthByRefreshTokenRequest.java │ │ │ ├── AuthResponse.java │ │ │ ├── Credential.java │ │ │ ├── ErrorResponse.java │ │ │ ├── InfoRequest.java │ │ │ ├── InfoResponse.java │ │ │ ├── UserRequest.java │ │ │ └── UserResponse.java │ │ └── service │ │ │ ├── AuthService.java │ │ │ ├── AuthServiceImpl.java │ │ │ ├── InfoService.java │ │ │ ├── InfoServiceImpl.java │ │ │ ├── UserService.java │ │ │ └── UserServiceImpl.java │ │ └── infrastrucuture │ │ ├── InfrastructureBean.java │ │ ├── cache │ │ ├── CacheRepository.java │ │ ├── local │ │ │ └── LocalCacheRepository.java │ │ └── redis │ │ │ ├── RedisCacheRepository.java │ │ │ └── RedisProperty.java │ │ ├── entity │ │ ├── Info.java │ │ ├── SharedData.java │ │ └── User.java │ │ └── persistent │ │ ├── InfoPersistentRepository.java │ │ ├── UserPersistentRepository.java │ │ ├── cassandra │ │ ├── CassandraInfoPersistentRepository.java │ │ ├── CassandraUserPersistentRepository.java │ │ └── property │ │ │ └── CassandraProperty.java │ │ ├── local │ │ ├── LocalInfoPersistentRepository.java │ │ └── LocalUserPersistentRepository.java │ │ ├── mongo │ │ ├── MongoInfoPersistentRepository.java │ │ ├── MongoUserPersistentRepository.java │ │ ├── entity │ │ │ ├── MongoInfoEntity.java │ │ │ └── MongoUserEntity.java │ │ └── property │ │ │ └── MongoProperty.java │ │ └── rdbms │ │ ├── RdbmsInfoPersistentRepository.java │ │ └── RdbmsUserPersistentRepository.java └── resources │ ├── application-db_cassandra.yml │ ├── application-db_local.yml │ ├── application-db_mongo.yml │ ├── application-db_rdbms.yml │ ├── application-dev.yml │ ├── application-local.yml │ ├── application-prod.yml │ └── application.yml └── test ├── java └── com │ └── bestpractice │ └── api │ └── ApplicationTests.java └── resources └── application-test.yml /.github/scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | ver=$(cat build.gradle | grep pkgVersion | sed 's/def pkgVersion =//g' | sed "s/'//g" | sed -n 1P | sed 's/\"//g' | sed 's/ //g') 6 | 7 | ./gradlew clean build -x test 8 | docker login -u "${DOCKER_USER}" -p "${DOCKER_PASSWORD}" 9 | docker build -f docker/Dockerfile.app -t tomohito/springboot-bestpractice:"${ver}" -t tomohito/springboot-bestpractice:latest . 10 | docker push tomohito/springboot-bestpractice 11 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: springboot-bestpractice 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | skipci: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '[ci skip]')" 13 | steps: 14 | - run: echo "${{ github.event.head_commit.message }}" 15 | 16 | test: 17 | runs-on: ubuntu-latest 18 | if: github.ref != 'refs/heads/master' 19 | steps: 20 | - name: 'Set up Java' 21 | uses: actions/setup-java@v3 22 | with: 23 | distribution: 'zulu' 24 | java-version: '17' 25 | 26 | - name: checkout 27 | uses: actions/checkout@v1 28 | 29 | - name: unit-test 30 | run: ./gradlew clean test 31 | 32 | build: 33 | runs-on: ubuntu-latest 34 | if: github.ref == 'refs/heads/master' 35 | steps: 36 | - name: 'Set up Java' 37 | uses: actions/setup-java@v3 38 | with: 39 | distribution: 'zulu' 40 | java-version: '17' 41 | 42 | - name: checkout 43 | uses: actions/checkout@v1 44 | 45 | - name: build 46 | env: 47 | DOCKER_USER: ${{ secrets.DOCKER_USER }} 48 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} 49 | run: sh .github/scripts/build.sh 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .gradle/ 3 | out/ 4 | build/ 5 | credentials.yml 6 | .java-version 7 | docker/Cassandra/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [2023] [tomoyane] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot best practice 2 | [![springboot-bestpractice](https://github.com/tomoyane/springboot-bestpractice/actions/workflows/ci.yml/badge.svg)](https://github.com/tomoyane/springboot-bestpractice/actions/workflows/ci.yml) 3 | [![Apache License](https://img.shields.io/badge/license-Apatch-mediumpurple.svg?style=flat)](https://github.com/herts-stack/herts/blob/master/LICENSE) 4 | 5 | About Spring Boot architecture. 6 | 7 | This repository support multiple database by SPRING_PROFILES_ACTIVE 8 | * RDBMS 9 | * MongoDB 10 | * Cassandra 11 | * Redis 12 | 13 | ## Requirements 14 | * Docker engine 15 | * Docker Compose 16 | * OpenJDK 17 17 | * Spring Boot 2 18 | 19 | ### Docker database 20 | MySQL8 21 | * **Standalone** 22 | 23 | MongoDB 24 | * **Standalone** 25 | 26 | Cassandra cluster. 27 | * **3 Nodes** 28 | 29 | ## Architecture 30 | The "app" package holds controllers for API endpoints and provides interception. The "app" package can depend on the "domain" package. 31 | 32 | The "domain" package provides business logic and holds Spring Component Beans or Service Beans. It cannot depend on the "app" package but relies on the "infrastructure" package. 33 | 34 | The "infrastructure" package provides data storage by holding Spring Repository Beans. It is independent and cannot depend on the "app" and "domain" packages. 35 | 36 | The "common" package offers generic functions. 37 | 38 | Initialization processes during server startup depend on "SPRING_PROFILES_ACTIVE" and assume the specified data store's Bean as a prerequisite for the initial startup. 39 | 40 | 41 | ### Directory structure 42 | 43 | ```bash 44 | java 45 | │   │   └── com 46 | │   │   └── bestpractice 47 | │   │   └── api 48 | │   │   ├── Application.java 49 | │   │   ├── app 50 | │   │   │   ├── AdviceController.java 51 | │   │   │   ├── AppBean.java 52 | │   │   │   ├── InterceptorController.java 53 | │   │   │   ├── v1 54 | │   │   │   │   ├── AuthController.java 55 | │   │   │   │   ├── HelloController.java 56 | │   │   │   │   ├── RdbmsController.java 57 | │   │   │   │   └── UserController.java 58 | │   │   │   └── v2 59 | │   │   │   └── AuthorizationController.java 60 | │   │   ├── common 61 | │   │   │   ├── exception 62 | │   │   │   │   ├── BadRequest.java 63 | │   │   │   │   ├── Conflict.java 64 | │   │   │   │   ├── Forbidden.java 65 | │   │   │   │   ├── InternalServerError.java 66 | │   │   │   │   ├── NotFound.java 67 | │   │   │   │   ├── RequestTimeout.java 68 | │   │   │   │   ├── ServiceUnavailable.java 69 | │   │   │   │   └── UnAuthorized.java 70 | │   │   │   ├── property 71 | │   │   │   │   └── CredentialProperty.java 72 | │   │   │   └── util 73 | │   │   │   └── Util.java 74 | │   │   ├── domain 75 | │   │   │   ├── DomainBean.java 76 | │   │   │   ├── component 77 | │   │   │   │   ├── AuthComponent.java 78 | │   │   │   │   ├── BCryptPasswordEncryptionComponent.java 79 | │   │   │   │   └── RequestInfoComponent.java 80 | │   │   │   ├── model 81 | │   │   │   │   ├── AuthByEmailRequest.java 82 | │   │   │   │   ├── AuthByRefreshTokenRequest.java 83 | │   │   │   │   ├── AuthResponse.java 84 | │   │   │   │   ├── Credential.java 85 | │   │   │   │   ├── ErrorResponse.java 86 | │   │   │   │   ├── InfoRequest.java 87 | │   │   │   │   ├── InfoResponse.java 88 | │   │   │   │   ├── UserRequest.java 89 | │   │   │   │   └── UserResponse.java 90 | │   │   │   └── service 91 | │   │   │   ├── AuthService.java 92 | │   │   │   ├── AuthServiceImpl.java 93 | │   │   │   ├── InfoService.java 94 | │   │   │   ├── InfoServiceImpl.java 95 | │   │   │   ├── UserService.java 96 | │   │   │   └── UserServiceImpl.java 97 | │   │   └── infrastrucuture 98 | │   │   ├── InfrastructureBean.java 99 | │   │   ├── cache 100 | │   │   │   ├── CacheRepository.java 101 | │   │   │   ├── local 102 | │   │   │   │   └── LocalCacheRepository.java 103 | │   │   │   └── redis 104 | │   │   │   ├── RedisCacheRepository.java 105 | │   │   │   └── RedisProperty.java 106 | │   │   ├── entity 107 | │   │   │   ├── Info.java 108 | │   │   │   ├── SharedData.java 109 | │   │   │   └── User.java 110 | │   │   └── persistent 111 | │   │   ├── InfoPersistentRepository.java 112 | │   │   ├── UserPersistentRepository.java 113 | │   │   ├── cassandra 114 | │   │   │   ├── CassandraInfoPersistentRepository.java 115 | │   │   │   ├── CassandraUserPersistentRepository.java 116 | │   │   │   └── property 117 | │   │   │   └── CassandraProperty.java 118 | │   │   ├── local 119 | │   │   │   ├── LocalInfoPersistentRepository.java 120 | │   │   │   └── LocalUserPersistentRepository.java 121 | │   │   ├── mongo 122 | │   │   │   ├── MongoInfoPersistentRepository.java 123 | │   │   │   ├── MongoUserPersistentRepository.java 124 | │   │   │   ├── entity 125 | │   │   │   │   ├── MongoInfoEntity.java 126 | │   │   │   │   └── MongoUserEntity.java 127 | │   │   │   └── property 128 | │   │   │   └── MongoProperty.java 129 | │   │   └── rdbms 130 | │   │   ├── RdbmsInfoPersistentRepository.java 131 | │   │   └── RdbmsUserPersistentRepository.java 132 | ``` 133 | 134 | ### Interceptor JWT verification 135 | 136 | * app/InterceptorController.java 137 | 138 | ### MySQL Repository injection 139 | 140 | * infrastructure/persistent/rdbms/RdbmsUserPersistentRepository.java 141 | * infrastructure/persistent/rdbms/RdbmsInfoPersistentRepository.java 142 | 143 | ### MongoDB Repository injection 144 | 145 | * infrastructure/persistent/mongo/RdbmsUserPersistentRepository.java 146 | * infrastructure/persistent/mongo/RdbmsInfoPersistentRepository.java 147 | 148 | ### Cassandra Repository injection 149 | 150 | * infrastructure/persistent/cassandra/RdbmsUserPersistentRepository.java 151 | * infrastructure/persistent/cassandra/RdbmsInfoPersistentRepository.java 152 | 153 | ### Redis Repository injection 154 | 155 | * infrastructure/cache/redis/RedisCacheRepository.java 156 | 157 | ## Getting Started 158 | 159 | Start database process 160 | ```bash 161 | # RDBMS 162 | docker-compose run -p 3306:3306 mysql_db 163 | 164 | # Mongo 165 | docker-compose run -p 27017:27017 mongo_db 166 | 167 | # Cassandra 168 | docker-compose up cassandra_01 cassandra_02 cassandra_03 169 | ``` 170 | 171 | Start api server via script 172 | ```bash 173 | # RDBMS 174 | ./scripts/start_server.sh --spring_profile=local,db_rdbms 175 | 176 | # Mongo 177 | ./scripts/start_server.sh --spring_profile=local,db_mongo 178 | 179 | # Cassandra 180 | ./scripts/start_server.sh --spring_profile=local,db_cassandra 181 | ``` 182 | 183 | ## License 184 | [Apache-2.0](https://github.com/tomoyane/springboot-bestpractice/blob/master/LICENSE) 185 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.5.5' 4 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 5 | } 6 | 7 | def pkgName = 'com.bestpractice.api' 8 | def pkgVersion = "1.1.0" 9 | def javaVersion = !project.hasProperty('javaVersion') ? '17' : project.getProperty('javaVersion') 10 | def artifactId = 'spring-boot-bestpractice' 11 | 12 | sourceCompatibility = javaVersion 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | configurations.all { 19 | exclude group: 'org.slf4j', module: 'slf4j-nop' 20 | } 21 | 22 | dependencies { 23 | // Spring 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | implementation "org.springframework.boot:spring-boot-starter-data-jpa" 26 | implementation "org.springframework.boot:spring-boot-configuration-processor" 27 | implementation "org.springframework.boot:spring-boot-starter-security" 28 | implementation "org.springframework.boot:spring-boot-starter-data-redis" 29 | implementation "io.springfox:springfox-swagger2:2.8.0" 30 | implementation "io.springfox:springfox-swagger-ui:2.8.0" 31 | 32 | // Token 33 | implementation 'com.auth0:java-jwt:4.4.0' 34 | 35 | // Database 36 | implementation "mysql:mysql-connector-java" 37 | implementation "org.postgresql:postgresql" 38 | implementation 'redis.clients:jedis:3.7.0' 39 | implementation 'org.mongodb:mongo-java-driver:3.12.14' 40 | implementation 'com.datastax.oss:java-driver-core:4.17.0' 41 | implementation 'com.datastax.oss:java-driver-query-builder:4.17.0' 42 | 43 | // Third party 44 | implementation 'javax.validation:validation-api:2.0.1.Final' 45 | implementation 'org.hibernate.validator:hibernate-validator:6.2.0.Final' 46 | 47 | testImplementation "org.hsqldb:hsqldb" 48 | testImplementation "org.hibernate:hibernate-entitymanager" 49 | testImplementation "org.springframework.boot:spring-boot-starter-test" 50 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 51 | } 52 | 53 | ext.profile = (!project.hasProperty('profile') || !profile) ? 'local' : profile 54 | sourceSets { 55 | main { 56 | resources { 57 | srcDirs "src/main/resources", "src/main/resources-${profile}" 58 | } 59 | } 60 | } 61 | 62 | processResources { 63 | duplicatesStrategy = DuplicatesStrategy.INCLUDE 64 | } -------------------------------------------------------------------------------- /db/cassandra/schema.cql: -------------------------------------------------------------------------------- 1 | CREATE KEYSPACE IF NOT EXISTS spring_boot 2 | WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}; 3 | 4 | CREATE TABLE IF NOT EXISTS spring_boot.infos 5 | ( 6 | id TEXT PRIMARY KEY, 7 | title TEXT, 8 | description TEXT 9 | ); 10 | 11 | CREATE TABLE IF NOT EXISTS spring_boot.users 12 | ( 13 | id TEXT PRIMARY KEY, 14 | username TEXT, 15 | email TEXT, 16 | password TEXT 17 | ); 18 | -------------------------------------------------------------------------------- /db/mongo/schema.js: -------------------------------------------------------------------------------- 1 | db.createUser({ 2 | user: "spring_boot", 3 | pwd: "spring_boot", 4 | roles: [ 5 | {role: "readWrite", db: "spring_boot"} 6 | ] 7 | }); 8 | 9 | db.createCollection('users') 10 | db.createCollection('infos') -------------------------------------------------------------------------------- /db/mysql/migrations/v0.0.1.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS infos; 2 | DROP TABLE IF EXISTS users; 3 | 4 | -- users table 5 | CREATE TABLE users ( 6 | id varchar(64) NOT NULL, 7 | username varchar(128) NOT NULL, 8 | email varchar(128) NOT NULL, 9 | password varchar(128) NOT NULL, 10 | created_at datetime(6), 11 | PRIMARY KEY (id), 12 | UNIQUE (email) 13 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 14 | 15 | -- infos table 16 | CREATE TABLE infos ( 17 | id varchar(64) NOT NULL, 18 | title varchar(128) NOT NULL, 19 | description varchar(128) NOT NULL, 20 | created_at datetime(6), 21 | PRIMARY KEY (id) 22 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 23 | -------------------------------------------------------------------------------- /docker/Dockerfile.app: -------------------------------------------------------------------------------- 1 | FROM openjdk:17.0.1-jdk-buster 2 | 3 | VOLUME /tmp 4 | 5 | RUN mkdir /spring-boot-bestpractice 6 | 7 | WORKDIR /spring-boot-bestpractice 8 | COPY build/libs/*.jar spring-boot-bestpractice.jar 9 | COPY src/main/resources/* /spring-boot-bestpractice 10 | 11 | ENTRYPOINT ["sh","-c","java -jar spring-boot-bestpractice.jar"] 12 | -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- 1 | ## How to use 2 | 3 | RDBMS 4 | ```bash 5 | docker-compose run -p 3306:3306 mysql_db 6 | ``` 7 | 8 | MongoDB 9 | ```bash 10 | docker-compose run -p 27017:27017 mongo_db 11 | ``` 12 | 13 | Cassandra 14 | ```bash 15 | docker-compose up cassandra_01 cassandra_02 cassandra_03 16 | ``` -------------------------------------------------------------------------------- /docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.9' 2 | 3 | services: 4 | mysql_db: 5 | image: mysql:8 6 | container_name: mysql_container 7 | restart: always 8 | ports: 9 | - "3306:3306" 10 | environment: 11 | MYSQL_ROOT_PASSWORD: password 12 | MYSQL_DATABASE: test 13 | MYSQL_USER: user 14 | MYSQL_PASSWORD: password 15 | volumes: 16 | - ../db/mysql/migrations:/docker-entrypoint-initdb.d 17 | 18 | redis_db: 19 | image: redis:6.2 20 | container_name: redis_container 21 | ports: 22 | - '6379:6379' 23 | 24 | mongo_db: 25 | image: mongo:6.0 26 | container_name: mongo_container 27 | restart: always 28 | environment: 29 | MONGO_INITDB_ROOT_USERNAME: root 30 | MONGO_INITDB_ROOT_PASSWORD: root_pw 31 | ports: 32 | - "27017:27017" 33 | volumes: 34 | - ../db/mongo/schema.js:/docker-entrypoint-initdb.d/schema.js:ro 35 | 36 | cassandra_01: 37 | container_name: cassandra01 38 | image: cassandra 39 | ports: 40 | - 9042:9042 41 | environment: 42 | CASSANDRA_SEEDS: cassandra_01 43 | CASSANDRA_CLUSTER_NAME: "TestCluster" 44 | CASSANDRA_ENDPOINT_SNITCH: "GossipingPropertyFileSnitch" 45 | CASSANDRA_DC: dc01 46 | CASSANDRA_RACK: rack01 47 | CASSANDRA_LISTEN_ADDRESS: cassandra_01 48 | restart: always 49 | 50 | cassandra_02: 51 | container_name: cassandra02 52 | image: cassandra 53 | ports: 54 | - 9043:9042 55 | environment: 56 | CASSANDRA_SEEDS: cassandra_01 57 | CASSANDRA_ENDPOINT_SNITCH: "GossipingPropertyFileSnitch" 58 | CASSANDRA_CLUSTER_NAME: "TestCluster" 59 | CASSANDRA_DC: dc01 60 | CASSANDRA_RACK: rack01 61 | CASSANDRA_LISTEN_ADDRESS: cassandra_02 62 | depends_on: 63 | - cassandra_01 64 | restart: always 65 | 66 | cassandra_03: 67 | container_name: cassandra03 68 | image: cassandra 69 | ports: 70 | - 9044:9042 71 | environment: 72 | CASSANDRA_SEEDS: cassandra_01 73 | CASSANDRA_CLUSTER_NAME: "TestCluster" 74 | CASSANDRA_ENDPOINT_SNITCH: "GossipingPropertyFileSnitch" 75 | CASSANDRA_DC: dc01 76 | CASSANDRA_RACK: rack01 77 | CASSANDRA_LISTEN_ADDRESS: cassandra_03 78 | depends_on: 79 | - cassandra_01 80 | restart: always -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomoyane/springboot-bestpractice/40170d2067fc65909cf2f240f01981385cff3824/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-8.0-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original 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 POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 134 | 135 | Please set the JAVA_HOME variable in your environment to match the 136 | location of your Java installation." 137 | fi 138 | 139 | # Increase the maximum file descriptors if we can. 140 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 141 | case $MAX_FD in #( 142 | max*) 143 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 144 | # shellcheck disable=SC3045 145 | MAX_FD=$( ulimit -H -n ) || 146 | warn "Could not query maximum file descriptor limit" 147 | esac 148 | case $MAX_FD in #( 149 | '' | soft) :;; #( 150 | *) 151 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 152 | # shellcheck disable=SC3045 153 | ulimit -n "$MAX_FD" || 154 | warn "Could not set maximum file descriptor limit to $MAX_FD" 155 | esac 156 | fi 157 | 158 | # Collect all arguments for the java command, stacking in reverse order: 159 | # * args from the command line 160 | # * the main class name 161 | # * -classpath 162 | # * -D...appname settings 163 | # * --module-path (only if needed) 164 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 165 | 166 | # For Cygwin or MSYS, switch paths to Windows format before running java 167 | if "$cygwin" || "$msys" ; then 168 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 169 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 170 | 171 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 172 | 173 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 174 | for arg do 175 | if 176 | case $arg in #( 177 | -*) false ;; # don't mess with options #( 178 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 179 | [ -e "$t" ] ;; #( 180 | *) false ;; 181 | esac 182 | then 183 | arg=$( cygpath --path --ignore --mixed "$arg" ) 184 | fi 185 | # Roll the args list around exactly as many times as the number of 186 | # args, so each arg winds up back in the position where it started, but 187 | # possibly modified. 188 | # 189 | # NB: a `for` loop captures its iteration list before it begins, so 190 | # changing the positional parameters here affects neither the number of 191 | # iterations, nor the values presented in `arg`. 192 | shift # remove old arg 193 | set -- "$@" "$arg" # push replacement arg 194 | done 195 | fi 196 | 197 | 198 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 199 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 200 | 201 | # Collect all arguments for the java command; 202 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 203 | # shell script including quotes and variable substitutions, so put them in 204 | # double quotes to make sure that they get re-expanded; and 205 | # * put everything else in single quotes, so that it's not re-expanded. 206 | 207 | set -- \ 208 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 209 | -classpath "$CLASSPATH" \ 210 | org.gradle.wrapper.GradleWrapperMain \ 211 | "$@" 212 | 213 | # Stop when "xargs" is not available. 214 | if ! command -v xargs >/dev/null 2>&1 215 | then 216 | die "xargs is not available" 217 | fi 218 | 219 | # Use "xargs" to parse quoted args. 220 | # 221 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 222 | # 223 | # In Bash we could simply go: 224 | # 225 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 226 | # set -- "${ARGS[@]}" "$@" 227 | # 228 | # but POSIX shell has neither arrays nor command substitution, so instead we 229 | # post-process each arg (as a line of input to sed) to backslash-escape any 230 | # character that might be a shell metacharacter, then use eval to reverse 231 | # that process (while maintaining the separation between arguments), and wrap 232 | # the whole thing up as a single "set" statement. 233 | # 234 | # This will of course break if any of these variables contains a newline or 235 | # an unmatched quote. 236 | # 237 | 238 | eval "set -- $( 239 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 240 | xargs -n1 | 241 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 242 | tr '\n' ' ' 243 | )" '"$@"' 244 | 245 | exec "$JAVACMD" "$@" 246 | -------------------------------------------------------------------------------- /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 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /scripts/README.md: -------------------------------------------------------------------------------- 1 | ## How to start API server 2 | 3 | Local datasource 4 | ```bash 5 | ./scripts/start_server.sh --spring_profile=local,db_local 6 | ``` 7 | 8 | RDBMS 9 | ```bash 10 | ./scripts/start_server.sh --spring_profile=local,db_rdbms 11 | ``` 12 | 13 | MongoDB 14 | ```bash 15 | ./scripts/start_server.sh --spring_profile=local,db_mongo 16 | ``` 17 | 18 | Cassandra 19 | ```bash 20 | ./scripts/start_server.sh --spring_profile=local,db_cassandra 21 | ``` -------------------------------------------------------------------------------- /scripts/start_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | if [ "$#" -eq 0 ]; then 6 | echo "Default argument" 7 | fi 8 | 9 | SPRING_PROFILE="local,db_local" 10 | 11 | while [ "$#" -gt 0 ]; do 12 | case "$1" in 13 | --spring_profile=*) 14 | SPRING_PROFILE="${1#*=}" 15 | ;; 16 | *) 17 | echo "Invalid: $1" 18 | exit 1 19 | ;; 20 | esac 21 | shift 22 | done 23 | 24 | echo "SPRING_PROFILES_ACTIVE: $SPRING_PROFILE" 25 | export SPRING_PROFILES_ACTIVE=$SPRING_PROFILE 26 | 27 | if echo "$SPRING_PROFILE" | grep -q "db_rdbms"; then 28 | echo "Using RDBMS" 29 | export MYSQL_DB_HOST=localhost 30 | export MYSQL_DB_NAME=test 31 | export MYSQL_DB_USER=user 32 | export MYSQL_DB_PASS=password 33 | export REDIS_DB_HOST=localhost 34 | export REDIS_DB_PORT=6379 35 | export REDIS_DB_PASS=root 36 | fi 37 | 38 | if echo "$SPRING_PROFILE" | grep -q "db_mongo"; then 39 | echo "Using Mongo" 40 | fi 41 | 42 | if echo "$SPRING_PROFILE" | grep -q "db_cassandra"; then 43 | echo "Using Cassandra" 44 | fi 45 | 46 | ./gradlew bootRun 47 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-boot-bestpractice' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/Application.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 6 | import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; 7 | import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; 8 | 9 | @SpringBootApplication(exclude = { 10 | DataSourceAutoConfiguration.class, 11 | SecurityAutoConfiguration.class, 12 | MongoAutoConfiguration.class, 13 | }) 14 | public class Application { 15 | public static void main(String[] args) { 16 | SpringApplication.run(Application.class, args); 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/AdviceController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app; 2 | 3 | import com.bestpractice.api.common.exception.BadRequest; 4 | import com.bestpractice.api.common.exception.Conflict; 5 | import com.bestpractice.api.common.exception.Forbidden; 6 | import com.bestpractice.api.common.exception.NotFound; 7 | import com.bestpractice.api.common.exception.UnAuthorized; 8 | import com.bestpractice.api.domain.model.ErrorResponse; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.web.bind.annotation.*; 11 | import org.springframework.web.servlet.NoHandlerFoundException; 12 | 13 | @RestControllerAdvice 14 | public class AdviceController { 15 | 16 | @ResponseStatus(HttpStatus.BAD_REQUEST) 17 | @ExceptionHandler(BadRequest.class) 18 | public ErrorResponse badRequest() { 19 | ErrorResponse res = new ErrorResponse(); 20 | res.setStatus(400); 21 | res.setError("Bad request"); 22 | res.setMessage("Bad request parameter"); 23 | return res; 24 | } 25 | 26 | @ResponseStatus(HttpStatus.UNAUTHORIZED) 27 | @ExceptionHandler(UnAuthorized.class) 28 | public ErrorResponse unAuthorized() { 29 | ErrorResponse res = new ErrorResponse(); 30 | res.setStatus(401); 31 | res.setError("Unauthorized"); 32 | res.setMessage("Incorrect authentication info"); 33 | return res; 34 | } 35 | 36 | @ResponseStatus(HttpStatus.FORBIDDEN) 37 | @ExceptionHandler(Forbidden.class) 38 | public ErrorResponse forbidden() { 39 | ErrorResponse res = new ErrorResponse(); 40 | res.setStatus(403); 41 | res.setError("Forbidden"); 42 | res.setMessage("Not allowed"); 43 | return res; 44 | } 45 | 46 | @ResponseStatus(HttpStatus.NOT_FOUND) 47 | @ExceptionHandler(NoHandlerFoundException.class) 48 | public ErrorResponse notFound01() { 49 | return shareNotFound(); 50 | } 51 | 52 | @ResponseStatus(HttpStatus.NOT_FOUND) 53 | @ExceptionHandler(NotFound.class) 54 | public ErrorResponse notFound02() { 55 | return shareNotFound(); 56 | } 57 | 58 | @ResponseStatus(HttpStatus.CONFLICT) 59 | @ExceptionHandler(Conflict.class) 60 | public ErrorResponse conflict() { 61 | ErrorResponse res = new ErrorResponse(); 62 | res.setStatus(409); 63 | res.setError("Conflict"); 64 | res.setMessage("Already exist data"); 65 | return res; 66 | } 67 | 68 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 69 | @ExceptionHandler(Exception.class) 70 | public ErrorResponse serverError(Exception e) { 71 | e.printStackTrace(); 72 | ErrorResponse res = new ErrorResponse(); 73 | res.setStatus(500); 74 | res.setError("Internal server error"); 75 | res.setMessage("Internal server error"); 76 | return res; 77 | } 78 | 79 | private ErrorResponse shareNotFound() { 80 | ErrorResponse res = new ErrorResponse(); 81 | res.setStatus(404); 82 | res.setError("Not found"); 83 | res.setMessage("Not found path"); 84 | return res; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/AppBean.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app; 2 | 3 | import com.bestpractice.api.domain.component.AuthComponent; 4 | import com.bestpractice.api.domain.component.RequestInfoComponent; 5 | import com.google.common.base.Predicates; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | import springfox.documentation.builders.PathSelectors; 12 | import springfox.documentation.service.ApiInfo; 13 | import springfox.documentation.spi.DocumentationType; 14 | import springfox.documentation.spring.web.plugins.Docket; 15 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 16 | 17 | public class AppBean { 18 | 19 | @Configuration 20 | @EnableSwagger2 21 | public static class SwaggerConfig { 22 | 23 | @Configuration 24 | public static class WebMvcConfig implements WebMvcConfigurer { 25 | @Autowired 26 | private RequestInfoComponent requestInfo; 27 | @Autowired 28 | private AuthComponent authComponent; 29 | 30 | @Bean 31 | public InterceptorController interceptorController() { 32 | return new InterceptorController(this.authComponent, this.requestInfo); 33 | } 34 | 35 | @Override 36 | public void addInterceptors(InterceptorRegistry registry) { 37 | registry.addInterceptor(interceptorController()).addPathPatterns("/api/**"); 38 | } 39 | } 40 | 41 | @Bean 42 | public Docket swaggerSpringMvcPlugin() { 43 | 44 | return new Docket(DocumentationType.SWAGGER_2) 45 | .select() 46 | .paths(Predicates.not(PathSelectors.regex("/error"))) 47 | .build() 48 | .apiInfo(apiInfo()); 49 | } 50 | 51 | private ApiInfo apiInfo() { 52 | return new ApiInfo( 53 | "Spring boot best practice API", 54 | "Spring boot best practice API document", 55 | "0.0.1", 56 | "", 57 | "Spring boot best practice", 58 | "", 59 | "" 60 | ); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/InterceptorController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app; 2 | 3 | import com.auth0.jwt.interfaces.DecodedJWT; 4 | import com.bestpractice.api.common.exception.UnAuthorized; 5 | import com.bestpractice.api.common.util.Util; 6 | import com.bestpractice.api.domain.component.AuthComponent; 7 | import com.bestpractice.api.domain.component.RequestInfoComponent; 8 | import java.io.IOException; 9 | import java.util.Enumeration; 10 | import java.util.List; 11 | import java.util.UUID; 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.lang.Nullable; 17 | import org.springframework.web.servlet.HandlerInterceptor; 18 | import org.springframework.web.servlet.ModelAndView; 19 | 20 | public class InterceptorController implements HandlerInterceptor { 21 | private final Logger logger = LoggerFactory.getLogger(InterceptorController.class); 22 | 23 | private static final String SPRING_ERROR_PATH = "error"; 24 | private static final List DISABLE_AUTH_ENDPOINTS = List.of("/api/v1/user", "/api/v1/auth"); 25 | 26 | private final AuthComponent authComponent; 27 | private final RequestInfoComponent requestInfo; 28 | 29 | public InterceptorController(AuthComponent authComponent, RequestInfoComponent requestInfo) { 30 | this.authComponent = authComponent; 31 | this.requestInfo = requestInfo; 32 | } 33 | 34 | @Override 35 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { 36 | this.requestInfo.setRequestId(UUID.randomUUID().toString()); 37 | this.requestInfo.setPath(request.getRequestURI()); 38 | this.requestInfo.setHttpMethod(request.getMethod()); 39 | 40 | StringBuilder accessLogBuilder = new StringBuilder(); 41 | accessLogBuilder.append("AUDIT ") 42 | .append("RequestId: ") 43 | .append(this.requestInfo.getRequestId()) 44 | .append(", Path: ") 45 | .append(this.requestInfo.getPath()) 46 | .append(", Method: ") 47 | .append(this.requestInfo.getHttpMethod()); 48 | 49 | if (!this.requestInfo.getPath().startsWith(SPRING_ERROR_PATH) && 50 | !DISABLE_AUTH_ENDPOINTS.contains(this.requestInfo.getPath()) && 51 | !Util.getSpringProfileActive().contains("local")) { 52 | 53 | Enumeration authorization = request.getHeaders("Authorization"); 54 | if (!authorization.hasMoreElements()) { 55 | logger.info(accessLogBuilder.toString()); 56 | throw new UnAuthorized("Authorization header is empty"); 57 | } 58 | 59 | String bearerToken = authorization.nextElement(); 60 | if (!bearerToken.contains("Bearer")) { 61 | logger.info(accessLogBuilder.toString()); 62 | throw new UnAuthorized("Authorization supports Bearer format"); 63 | } 64 | 65 | bearerToken = bearerToken.replace("Bearer", "").trim(); 66 | DecodedJWT decodedJWT = this.authComponent.decodeJwt(bearerToken); 67 | this.requestInfo.setUserId(decodedJWT.getSubject()); 68 | this.requestInfo.setUserEmail(decodedJWT.getClaim(AuthComponent.ClaimUserEmailKey).asString()); 69 | this.requestInfo.setRefreshToken(decodedJWT.getClaim(AuthComponent.ClaimRefreshKey).asBoolean()); 70 | 71 | accessLogBuilder.append(". UserId: ") 72 | .append(this.requestInfo.getUserId()); 73 | } 74 | 75 | if (!this.requestInfo.getPath().startsWith(SPRING_ERROR_PATH)) { 76 | logger.info(accessLogBuilder.toString()); 77 | } 78 | 79 | return !this.requestInfo.getPath().startsWith(SPRING_ERROR_PATH); 80 | } 81 | 82 | @Override 83 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) { 84 | } 85 | 86 | @Override 87 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 88 | } 89 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/v1/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app.v1; 2 | 3 | import com.bestpractice.api.common.exception.BadRequest; 4 | import com.bestpractice.api.domain.model.AuthByEmailRequest; 5 | import com.bestpractice.api.domain.model.AuthByRefreshTokenRequest; 6 | import com.bestpractice.api.domain.model.AuthResponse; 7 | import com.bestpractice.api.domain.service.AuthService; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.validation.BindingResult; 12 | import org.springframework.validation.annotation.Validated; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RequestMethod; 17 | import org.springframework.web.bind.annotation.ResponseBody; 18 | import org.springframework.web.bind.annotation.ResponseStatus; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | @RestController 22 | @RequestMapping("/api/v1/auth") 23 | public class AuthController { 24 | 25 | private final AuthService authService; 26 | 27 | public AuthController(AuthService authService) { 28 | this.authService = authService; 29 | } 30 | 31 | @RequestMapping(method= RequestMethod.OPTIONS) 32 | public ResponseEntity optionsAuth() { 33 | HttpHeaders responseHeaders = new HttpHeaders(); 34 | responseHeaders.set("Allow", "POST,OPTIONS"); 35 | responseHeaders.set("Access-Control-Allow-Origin", "*"); 36 | 37 | return ResponseEntity.ok() 38 | .headers(responseHeaders) 39 | .body(null); 40 | } 41 | 42 | @ResponseBody 43 | @ResponseStatus(value = HttpStatus.OK) 44 | @PostMapping(value = "/email-login") 45 | public AuthResponse login( 46 | @RequestBody @Validated AuthByEmailRequest request, 47 | BindingResult bdResult) { 48 | 49 | if (bdResult.hasErrors()) { 50 | throw new BadRequest(bdResult.getObjectName()); 51 | } 52 | return this.authService.login(request.getEmail(), request.getPassword()); 53 | } 54 | 55 | @ResponseBody 56 | @ResponseStatus(value = HttpStatus.OK) 57 | @PostMapping(value = "/refreshtoken-login") 58 | public AuthResponse login( 59 | @RequestBody @Validated AuthByRefreshTokenRequest request, 60 | BindingResult bdResult) { 61 | 62 | if (bdResult.hasErrors()) { 63 | throw new BadRequest(bdResult.getObjectName()); 64 | } 65 | return this.authService.login(request.getRefreshToken()); 66 | } 67 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/v1/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app.v1; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.ResponseBody; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import java.util.Collections; 9 | import java.util.Map; 10 | 11 | @RestController 12 | @RequestMapping("/api/v1") 13 | public class HelloController { 14 | 15 | @ResponseBody 16 | @GetMapping(value="/hello") 17 | public Map sample1() { 18 | return Collections.singletonMap("key", "Hello world."); 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/v1/RdbmsController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app.v1; 2 | 3 | import com.bestpractice.api.domain.model.InfoRequest; 4 | import com.bestpractice.api.domain.model.InfoResponse; 5 | import com.bestpractice.api.domain.service.InfoServiceImpl; 6 | import java.net.URI; 7 | import java.net.URISyntaxException; 8 | import java.util.Collections; 9 | import java.util.List; 10 | import java.util.Map; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.web.bind.annotation.DeleteMapping; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.PostMapping; 16 | import org.springframework.web.bind.annotation.PutMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | @RestController 22 | @RequestMapping("/api/v1/infos") 23 | public class RdbmsController { 24 | 25 | private final InfoServiceImpl infoService; 26 | 27 | public RdbmsController(InfoServiceImpl infoService) { 28 | this.infoService = infoService; 29 | } 30 | 31 | @GetMapping() 32 | public List getInfos() { 33 | return this.infoService.getInfos(); 34 | } 35 | 36 | @GetMapping(value="/{id}") 37 | public InfoResponse getInfo(@PathVariable("id") String id) { 38 | return this.infoService.getInfo(id); 39 | } 40 | 41 | @PostMapping 42 | public ResponseEntity postInfo( 43 | @RequestBody InfoRequest req) 44 | throws URISyntaxException { 45 | 46 | InfoResponse res = this.infoService.generateInfo(req); 47 | return ResponseEntity 48 | .created(new URI("/api/v1/infos/" + res.getId())) 49 | .body(res); 50 | } 51 | 52 | @PutMapping(value="/{id}") 53 | public InfoResponse putInfo( 54 | @PathVariable("id") String id, 55 | @RequestBody InfoRequest req) { 56 | 57 | return this.infoService.updateInfo(id, req); 58 | } 59 | 60 | @DeleteMapping(value = "/{id}") 61 | public Map deleteInfo(@PathVariable("id") String id) { 62 | this.infoService.deleteInfo(id); 63 | return Collections.singletonMap("message", "ok"); 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/v1/UserController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app.v1; 2 | 3 | import com.bestpractice.api.common.exception.BadRequest; 4 | import com.bestpractice.api.domain.model.UserRequest; 5 | import com.bestpractice.api.domain.model.UserResponse; 6 | import com.bestpractice.api.domain.service.UserService; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.validation.BindingResult; 9 | import org.springframework.validation.annotation.Validated; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | import org.springframework.web.bind.annotation.ResponseStatus; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | @RestController 18 | @RequestMapping("/api/v1/user") 19 | public class UserController { 20 | 21 | private final UserService userService; 22 | 23 | public UserController(UserService userService) { 24 | this.userService = userService; 25 | } 26 | 27 | @ResponseBody 28 | @ResponseStatus(value = HttpStatus.CREATED) 29 | @PostMapping() 30 | public UserResponse createUser( 31 | @RequestBody @Validated UserRequest request, 32 | BindingResult bdResult) { 33 | if (bdResult.hasErrors()) { 34 | throw new BadRequest(bdResult.getObjectName()); 35 | } 36 | return this.userService.generateUser(request); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/app/v2/AuthorizationController.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.app.v2; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | @RequestMapping("/api/v2/") 8 | public class AuthorizationController { 9 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/BadRequest.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class BadRequest extends RuntimeException { 4 | public BadRequest() { 5 | super(); 6 | } 7 | 8 | public BadRequest(String msg) { 9 | super(msg); 10 | } 11 | 12 | public BadRequest(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public BadRequest(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/Conflict.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class Conflict extends RuntimeException { 4 | public Conflict() { 5 | super(); 6 | } 7 | 8 | public Conflict(String msg) { 9 | super(msg); 10 | } 11 | 12 | public Conflict(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public Conflict(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/Forbidden.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class Forbidden extends RuntimeException { 4 | public Forbidden() { 5 | super(); 6 | } 7 | 8 | public Forbidden(String msg) { 9 | super(msg); 10 | } 11 | 12 | public Forbidden(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public Forbidden(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/InternalServerError.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class InternalServerError extends RuntimeException { 4 | public InternalServerError() { 5 | super(); 6 | } 7 | 8 | public InternalServerError(String msg) { 9 | super(msg); 10 | } 11 | 12 | public InternalServerError(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public InternalServerError(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/NotFound.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class NotFound extends RuntimeException { 4 | public NotFound() { 5 | super(); 6 | } 7 | 8 | public NotFound(String msg) { 9 | super(msg); 10 | } 11 | 12 | public NotFound(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public NotFound(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/RequestTimeout.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class RequestTimeout extends RuntimeException { 4 | public RequestTimeout() { 5 | super(); 6 | } 7 | 8 | public RequestTimeout(String msg) { 9 | super(msg); 10 | } 11 | 12 | public RequestTimeout(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public RequestTimeout(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/ServiceUnavailable.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class ServiceUnavailable extends RuntimeException { 4 | public ServiceUnavailable() { 5 | super(); 6 | } 7 | 8 | public ServiceUnavailable(String msg) { 9 | super(msg); 10 | } 11 | 12 | public ServiceUnavailable(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public ServiceUnavailable(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/exception/UnAuthorized.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.exception; 2 | 3 | public class UnAuthorized extends RuntimeException { 4 | public UnAuthorized() { 5 | super(); 6 | } 7 | 8 | public UnAuthorized(String msg) { 9 | super(msg); 10 | } 11 | 12 | public UnAuthorized(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public UnAuthorized(String msg, Throwable cause) { 17 | super(msg, cause); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/property/CredentialProperty.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties(prefix = "credentials") 8 | public class CredentialProperty { 9 | private String key; 10 | private String provider; 11 | private String subject; 12 | private String alg; 13 | private String hmacSecret; 14 | private String expiresHourStr; 15 | 16 | public String getKey() { 17 | return key; 18 | } 19 | 20 | public void setKey(String key) { 21 | this.key = key; 22 | } 23 | 24 | public String getProvider() { 25 | return provider; 26 | } 27 | 28 | public void setProvider(String provider) { 29 | this.provider = provider; 30 | } 31 | 32 | public String getSubject() { 33 | return subject; 34 | } 35 | 36 | public void setSubject(String subject) { 37 | this.subject = subject; 38 | } 39 | 40 | public String getAlg() { 41 | return alg; 42 | } 43 | 44 | public void setAlg(String alg) { 45 | this.alg = alg; 46 | } 47 | 48 | public String getHmacSecret() { 49 | return hmacSecret; 50 | } 51 | 52 | public void setHmacSecret(String hmacSecret) { 53 | this.hmacSecret = hmacSecret; 54 | } 55 | 56 | public String getExpiresHourStr() { 57 | return expiresHourStr; 58 | } 59 | 60 | public void setExpiresHourStr(String expiresHourStr) { 61 | this.expiresHourStr = expiresHourStr; 62 | } 63 | 64 | public Integer convertToIntExpires() { 65 | if (this.expiresHourStr.equals("-")) { 66 | return null; 67 | } 68 | 69 | try{ 70 | return Integer.parseInt(this.expiresHourStr); 71 | } 72 | catch (NumberFormatException ignore) { 73 | return null; 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/common/util/Util.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.common.util; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.util.Calendar; 9 | import java.util.Date; 10 | 11 | public class Util { 12 | 13 | public static Date calculateDate() { 14 | Date date = new Date(); 15 | Calendar calendar = Calendar.getInstance(); 16 | calendar.setTime(date); 17 | calendar.add(Calendar.YEAR, 1); 18 | date = calendar.getTime(); 19 | 20 | return date; 21 | } 22 | 23 | public static T deepClone(T object) throws IOException, ClassNotFoundException { 24 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 25 | ObjectOutputStream oos = new ObjectOutputStream(baos); 26 | oos.writeObject(object); 27 | ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); 28 | ObjectInputStream ois = new ObjectInputStream(bais); 29 | return (T) ois.readObject(); 30 | } 31 | 32 | public static String getSpringProfileActive() { 33 | return System.getenv("SPRING_PROFILES_ACTIVE"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/DomainBean.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | import org.springframework.security.crypto.password.PasswordEncoder; 7 | 8 | @Configuration 9 | public class DomainBean { 10 | @Bean 11 | public PasswordEncoder passwordEncoder() { 12 | return new BCryptPasswordEncoder(); 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/component/AuthComponent.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.component; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTCreator; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.exceptions.IncorrectClaimException; 7 | import com.auth0.jwt.exceptions.JWTDecodeException; 8 | import com.auth0.jwt.exceptions.MissingClaimException; 9 | import com.auth0.jwt.exceptions.SignatureVerificationException; 10 | import com.auth0.jwt.exceptions.TokenExpiredException; 11 | import com.auth0.jwt.interfaces.DecodedJWT; 12 | import com.bestpractice.api.common.exception.InternalServerError; 13 | import com.bestpractice.api.common.exception.UnAuthorized; 14 | import com.bestpractice.api.common.property.CredentialProperty; 15 | import com.bestpractice.api.domain.model.Credential; 16 | import java.util.Calendar; 17 | import java.util.Date; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | import org.springframework.stereotype.Component; 21 | 22 | @Component 23 | public class AuthComponent { 24 | private final CredentialProperty credentialProperty; 25 | private final Algorithm algorithm; 26 | 27 | public AuthComponent(CredentialProperty credentialProperty) { 28 | this.credentialProperty = credentialProperty; 29 | this.algorithm = Algorithm.HMAC256(this.credentialProperty.getHmacSecret()); 30 | } 31 | 32 | public DecodedJWT decodeJwt(String token) { 33 | try { 34 | return JWT.require(this.algorithm) 35 | .build() 36 | .verify(token); 37 | } catch (SignatureVerificationException ex) { 38 | throw new InternalServerError("Unknown signature secret key"); 39 | } catch (TokenExpiredException ex) { 40 | throw new UnAuthorized("Token is expired time"); 41 | } catch (MissingClaimException | IncorrectClaimException | JWTDecodeException ex) { 42 | throw new UnAuthorized("Invalid token"); 43 | } catch (Exception ex) { 44 | throw new InternalServerError("Unexpected error occurred"); 45 | } 46 | } 47 | 48 | public static final String ClaimUserIdKey = "user_id"; 49 | public static final String ClaimUserEmailKey = "user_email"; 50 | public static final String ClaimRefreshKey = "refresh_token"; 51 | public Credential generateJwt(String userId, String email, boolean isRefresh) { 52 | Integer expiresHour = this.credentialProperty.convertToIntExpires(); 53 | 54 | Map header = new HashMap<>(); 55 | header.put("alg", this.algorithm.getName()); 56 | header.put("typ", "JWT"); 57 | 58 | JWTCreator.Builder builder = JWT.create() 59 | .withIssuer(this.credentialProperty.getProvider()) 60 | .withAudience("any") 61 | .withIssuedAt(new Date()) 62 | .withHeader(header) 63 | .withClaim(ClaimUserIdKey, userId) 64 | .withClaim(ClaimUserEmailKey, email) 65 | .withSubject(userId); 66 | 67 | Date exp = null; 68 | if (expiresHour != null && !isRefresh) { 69 | exp = getExpiration(expiresHour); 70 | builder = builder.withExpiresAt(exp); 71 | } 72 | if (isRefresh) { 73 | builder = builder.withClaim(ClaimRefreshKey, true); 74 | } else { 75 | builder = builder.withClaim(ClaimRefreshKey, false); 76 | } 77 | return new Credential(builder.sign(this.algorithm), "Bearer", exp, isRefresh); 78 | } 79 | 80 | private static Date getExpiration(int hour) { 81 | Calendar calendar = Calendar.getInstance(); 82 | calendar.add(Calendar.HOUR, hour); 83 | return calendar.getTime(); 84 | } 85 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/component/BCryptPasswordEncryptionComponent.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.component; 2 | 3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 4 | import org.springframework.security.crypto.password.PasswordEncoder; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | public class BCryptPasswordEncryptionComponent { 9 | private final PasswordEncoder passwordEncoder; 10 | 11 | public BCryptPasswordEncryptionComponent() { 12 | this.passwordEncoder = new BCryptPasswordEncoder(); 13 | } 14 | 15 | public String encodePassword(String rawPassword) { 16 | return this.passwordEncoder.encode(rawPassword); 17 | } 18 | 19 | public boolean matchedPassword(String rawPassword, String encryptedPassword) { 20 | return passwordEncoder.matches(rawPassword, encryptedPassword); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/component/RequestInfoComponent.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.component; 2 | 3 | import org.springframework.stereotype.Component; 4 | import org.springframework.web.context.annotation.RequestScope; 5 | 6 | @Component 7 | @RequestScope 8 | public class RequestInfoComponent { 9 | private String userId; 10 | private String userEmail; 11 | private boolean isRefreshToken; 12 | private String path; 13 | private String httpMethod; 14 | private String requestId; 15 | 16 | public String getUserId() { 17 | return userId; 18 | } 19 | 20 | public void setUserId(String userId) { 21 | this.userId = userId; 22 | } 23 | 24 | public String getUserEmail() { 25 | return userEmail; 26 | } 27 | 28 | public void setUserEmail(String userEmail) { 29 | this.userEmail = userEmail; 30 | } 31 | 32 | public boolean isRefreshToken() { 33 | return isRefreshToken; 34 | } 35 | 36 | public void setRefreshToken(boolean refreshToken) { 37 | isRefreshToken = refreshToken; 38 | } 39 | 40 | public String getPath() { 41 | return path; 42 | } 43 | 44 | public void setPath(String path) { 45 | this.path = path; 46 | } 47 | 48 | public String getHttpMethod() { 49 | return httpMethod; 50 | } 51 | 52 | public void setHttpMethod(String httpMethod) { 53 | this.httpMethod = httpMethod; 54 | } 55 | 56 | public String getRequestId() { 57 | return requestId; 58 | } 59 | 60 | public void setRequestId(String requestId) { 61 | this.requestId = requestId; 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/AuthByEmailRequest.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import javax.validation.constraints.NotNull; 5 | import org.hibernate.validator.constraints.Email; 6 | 7 | public class AuthByEmailRequest { 8 | @Email 9 | @NotNull 10 | @JsonProperty("email") 11 | private String email; 12 | 13 | @NotNull 14 | @JsonProperty("password") 15 | private String password; 16 | 17 | public String getEmail() { 18 | return email; 19 | } 20 | 21 | public void setEmail(String email) { 22 | this.email = email; 23 | } 24 | 25 | public String getPassword() { 26 | return password; 27 | } 28 | 29 | public void setPassword(String password) { 30 | this.password = password; 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/AuthByRefreshTokenRequest.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import javax.validation.constraints.NotNull; 4 | 5 | public class AuthByRefreshTokenRequest { 6 | @NotNull 7 | private String refreshToken; 8 | 9 | public String getRefreshToken() { 10 | return refreshToken; 11 | } 12 | 13 | public void setRefreshToken(String refreshToken) { 14 | this.refreshToken = refreshToken; 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/AuthResponse.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import java.util.Date; 5 | import javax.validation.constraints.NotNull; 6 | 7 | public class AuthResponse { 8 | 9 | @NotNull 10 | @JsonProperty("token_type") 11 | private final String tokenType; 12 | 13 | @NotNull 14 | @JsonProperty("token") 15 | private final String token; 16 | 17 | @NotNull 18 | @JsonProperty("refresh_token") 19 | private final String refreshToken; 20 | 21 | @JsonProperty("expired_at") 22 | private final Date expiresAt; 23 | 24 | public AuthResponse(String tokenType, String token, String refreshToken, Date expiresAt) { 25 | this.tokenType = tokenType; 26 | this.token = token; 27 | this.refreshToken = refreshToken; 28 | this.expiresAt = expiresAt; 29 | } 30 | 31 | public String getTokenType() { 32 | return tokenType; 33 | } 34 | 35 | public String getToken() { 36 | return token; 37 | } 38 | 39 | public String getRefreshToken() { 40 | return refreshToken; 41 | } 42 | 43 | public Date getExpiresAt() { 44 | return expiresAt; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/Credential.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import java.util.Date; 4 | 5 | public class Credential { 6 | private final String token; 7 | private final String tokenType; 8 | private final Date exp; 9 | private final boolean isRefresh; 10 | 11 | public Credential(String token, String tokenType, Date exp, boolean isRefresh) { 12 | this.token = token; 13 | this.tokenType = tokenType; 14 | this.exp = exp; 15 | this.isRefresh = isRefresh; 16 | } 17 | 18 | public String getToken() { 19 | return token; 20 | } 21 | 22 | public String getTokenType() { 23 | return tokenType; 24 | } 25 | 26 | public Date getExp() { 27 | return exp; 28 | } 29 | 30 | public boolean isRefresh() { 31 | return isRefresh; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/ErrorResponse.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | public class ErrorResponse { 4 | private int status; 5 | private String error; 6 | private String message; 7 | 8 | public int getStatus() { 9 | return status; 10 | } 11 | 12 | public void setStatus(int status) { 13 | this.status = status; 14 | } 15 | 16 | public String getError() { 17 | return error; 18 | } 19 | 20 | public void setError(String error) { 21 | this.error = error; 22 | } 23 | 24 | public String getMessage() { 25 | return message; 26 | } 27 | 28 | public void setMessage(String message) { 29 | this.message = message; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/InfoRequest.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.Info; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import javax.validation.constraints.NotNull; 6 | 7 | public class InfoRequest { 8 | 9 | @NotNull 10 | @JsonProperty("title") 11 | private String title; 12 | 13 | @NotNull 14 | @JsonProperty("description") 15 | private String description; 16 | 17 | public String getTitle() { 18 | return title; 19 | } 20 | 21 | public void setTitle(String title) { 22 | this.title = title; 23 | } 24 | 25 | public String getDescription() { 26 | return description; 27 | } 28 | 29 | public void setDescription(String description) { 30 | this.description = description; 31 | } 32 | 33 | public Info convert(String id) { 34 | Info info = new Info(); 35 | info.setId(id); 36 | info.setTitle(this.title); 37 | info.setDescription(this.description); 38 | return info; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/InfoResponse.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public class InfoResponse { 6 | 7 | @JsonProperty("id") 8 | private final String id; 9 | 10 | @JsonProperty("title") 11 | private final String title; 12 | 13 | @JsonProperty("description") 14 | private final String description; 15 | 16 | public InfoResponse(String id, String title, String description) { 17 | this.id = id; 18 | this.title = title; 19 | this.description = description; 20 | } 21 | 22 | public String getId() { 23 | return id; 24 | } 25 | 26 | public String getTitle() { 27 | return title; 28 | } 29 | 30 | public String getDescription() { 31 | return description; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/UserRequest.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.User; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import javax.validation.constraints.NotNull; 6 | import org.hibernate.validator.constraints.Email; 7 | 8 | public class UserRequest { 9 | @JsonProperty("username") 10 | @NotNull 11 | private String username; 12 | 13 | @NotNull 14 | @Email 15 | @JsonProperty("email") 16 | private String email; 17 | 18 | @NotNull 19 | @JsonProperty("password") 20 | private String password; 21 | 22 | public String getUsername() { 23 | return username; 24 | } 25 | 26 | public void setUsername(String username) { 27 | this.username = username; 28 | } 29 | 30 | public String getEmail() { 31 | return email; 32 | } 33 | 34 | public void setEmail(String email) { 35 | this.email = email; 36 | } 37 | 38 | public String getPassword() { 39 | return password; 40 | } 41 | 42 | public void setPassword(String password) { 43 | this.password = password; 44 | } 45 | 46 | public User convert(String id, String encodePw) { 47 | User user = new User(); 48 | user.setId(id); 49 | user.setPassword(encodePw); 50 | user.setEmail(this.email); 51 | user.setUsername(this.username); 52 | return user; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/model/UserResponse.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public class UserResponse { 6 | @JsonProperty("id") 7 | private final String id; 8 | @JsonProperty("username") 9 | private final String username; 10 | @JsonProperty("email") 11 | private final String email; 12 | 13 | public UserResponse(String id, String username, String email) { 14 | this.id = id; 15 | this.username = username; 16 | this.email = email; 17 | } 18 | 19 | public String getId() { 20 | return id; 21 | } 22 | 23 | public String getUsername() { 24 | return username; 25 | } 26 | 27 | public String getEmail() { 28 | return email; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/service/AuthService.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.service; 2 | 3 | import com.bestpractice.api.domain.model.AuthResponse; 4 | 5 | public interface AuthService { 6 | AuthResponse login(String email, String password); 7 | AuthResponse login(String refreshToken); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/service/AuthServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.service; 2 | 3 | import com.auth0.jwt.interfaces.DecodedJWT; 4 | import com.bestpractice.api.common.exception.UnAuthorized; 5 | import com.bestpractice.api.domain.component.AuthComponent; 6 | import com.bestpractice.api.domain.component.BCryptPasswordEncryptionComponent; 7 | import com.bestpractice.api.domain.model.AuthResponse; 8 | import com.bestpractice.api.domain.model.Credential; 9 | import com.bestpractice.api.infrastrucuture.entity.User; 10 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 11 | import org.springframework.stereotype.Service; 12 | 13 | @Service 14 | public class AuthServiceImpl implements AuthService { 15 | private final BCryptPasswordEncryptionComponent encryptionComponent; 16 | private final AuthComponent authComponent; 17 | private final UserPersistentRepository userPersistentRepository; 18 | 19 | public AuthServiceImpl(BCryptPasswordEncryptionComponent encryptionComponent, 20 | AuthComponent authComponent, 21 | UserPersistentRepository userPersistentRepository) { 22 | 23 | this.encryptionComponent = encryptionComponent; 24 | this.authComponent = authComponent; 25 | this.userPersistentRepository = userPersistentRepository; 26 | } 27 | 28 | public AuthResponse login(String email, String password) { 29 | User user = this.userPersistentRepository.findByEmail(email); 30 | if (user == null) { 31 | throw new UnAuthorized("Email or password is invalid"); 32 | } 33 | if (!this.encryptionComponent.matchedPassword(password, user.getPassword())) { 34 | throw new UnAuthorized("Email or password is invalid"); 35 | } 36 | 37 | Credential token = this.authComponent.generateJwt(user.getId(), user.getEmail(), false); 38 | Credential refreshToken = this.authComponent.generateJwt(user.getId(), user.getEmail(), true); 39 | return new AuthResponse(token.getTokenType(), token.getToken(), refreshToken.getToken(), token.getExp()); 40 | } 41 | 42 | public AuthResponse login(String refreshToken) { 43 | DecodedJWT decodedJWT = this.authComponent.decodeJwt(refreshToken); 44 | String email = decodedJWT.getClaim(AuthComponent.ClaimUserEmailKey).asString(); 45 | boolean isRefresh = decodedJWT.getClaim(AuthComponent.ClaimRefreshKey).asBoolean(); 46 | 47 | User user = this.userPersistentRepository.findByEmail(email); 48 | if (user == null || !isRefresh) { 49 | throw new UnAuthorized("Token invalid"); 50 | } 51 | 52 | Credential token = this.authComponent.generateJwt(user.getId(), user.getEmail(), false); 53 | Credential rToken = this.authComponent.generateJwt(user.getId(), user.getEmail(), true); 54 | return new AuthResponse(token.getTokenType(), token.getToken(), rToken.getToken(), token.getExp()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/service/InfoService.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.service; 2 | 3 | import com.bestpractice.api.domain.model.InfoRequest; 4 | import com.bestpractice.api.domain.model.InfoResponse; 5 | import java.util.List; 6 | 7 | public interface InfoService { 8 | List getInfos(); 9 | InfoResponse getInfo(String id); 10 | InfoResponse updateInfo(String id, InfoRequest req); 11 | InfoResponse generateInfo(InfoRequest request); 12 | void deleteInfo(String id); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/service/InfoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.service; 2 | 3 | import com.bestpractice.api.common.exception.BadRequest; 4 | import com.bestpractice.api.common.exception.Conflict; 5 | import com.bestpractice.api.common.exception.InternalServerError; 6 | import com.bestpractice.api.domain.model.InfoRequest; 7 | import com.bestpractice.api.domain.model.InfoResponse; 8 | import com.bestpractice.api.infrastrucuture.entity.Info; 9 | import com.bestpractice.api.infrastrucuture.persistent.InfoPersistentRepository; 10 | import java.util.ArrayList; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.List; 14 | 15 | @Service 16 | public class InfoServiceImpl implements InfoService { 17 | 18 | private final InfoPersistentRepository infoRepository; 19 | 20 | public InfoServiceImpl(InfoPersistentRepository infoRepository) { 21 | this.infoRepository = infoRepository; 22 | } 23 | 24 | @Override 25 | public List getInfos() { 26 | List infoEntities; 27 | try { 28 | infoEntities = this.infoRepository.findAll(); 29 | } catch (Exception ex) { 30 | throw new InternalServerError(ex); 31 | } 32 | 33 | List res = new ArrayList<>(); 34 | for (Info i : infoEntities) { 35 | res.add(new InfoResponse(i.getId(), i.getTitle(), i.getDescription())); 36 | } 37 | return res; 38 | } 39 | 40 | @Override 41 | public InfoResponse getInfo(String id) { 42 | Info info; 43 | try { 44 | info = this.infoRepository.findById(id); 45 | } catch (Exception ex) { 46 | throw new InternalServerError(ex); 47 | } 48 | return new InfoResponse(info.getId(), info.getTitle(), info.getDescription()); 49 | } 50 | 51 | @Override 52 | public InfoResponse updateInfo(String id, InfoRequest req) { 53 | Info info; 54 | try { 55 | info = this.infoRepository.findById(id); 56 | } catch (Exception ex) { 57 | throw new BadRequest(); 58 | } 59 | 60 | info = req.convert(info.getId()); 61 | try { 62 | info = this.infoRepository.insert(info); 63 | } catch (Exception ex) { 64 | throw new InternalServerError(ex); 65 | } 66 | 67 | return new InfoResponse(info.getId(),info.getTitle(), info.getDescription()); 68 | } 69 | 70 | @Override 71 | public InfoResponse generateInfo(InfoRequest request) { 72 | Info info; 73 | try { 74 | info = this.infoRepository.insert(request.convert(this.infoRepository.newId())); 75 | } catch (Conflict ex) { 76 | throw new Conflict(ex); 77 | } catch (Exception ex) { 78 | throw new InternalServerError(ex); 79 | } 80 | return new InfoResponse(info.getId(), info.getTitle(), info.getDescription()); 81 | } 82 | 83 | @Override 84 | public void deleteInfo(String id) { 85 | try { 86 | this.infoRepository.removeById(id); 87 | } catch (Exception ex) { 88 | throw new InternalServerError(ex); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.service; 2 | 3 | import com.bestpractice.api.domain.model.UserRequest; 4 | import com.bestpractice.api.domain.model.UserResponse; 5 | import com.bestpractice.api.infrastrucuture.entity.User; 6 | 7 | public interface UserService { 8 | User getUserById(String id); 9 | User getAuthenticatedUser(String email, String rawPw); 10 | UserResponse generateUser(UserRequest request); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/domain/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.domain.service; 2 | 3 | import com.bestpractice.api.common.exception.Conflict; 4 | import com.bestpractice.api.common.exception.InternalServerError; 5 | import com.bestpractice.api.common.exception.UnAuthorized; 6 | import com.bestpractice.api.domain.component.BCryptPasswordEncryptionComponent; 7 | import com.bestpractice.api.domain.model.UserRequest; 8 | import com.bestpractice.api.domain.model.UserResponse; 9 | import com.bestpractice.api.infrastrucuture.entity.User; 10 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 11 | import org.springframework.stereotype.Service; 12 | 13 | @Service 14 | public class UserServiceImpl implements UserService { 15 | 16 | private final UserPersistentRepository userRepository; 17 | private final BCryptPasswordEncryptionComponent encryptionComponent; 18 | 19 | public UserServiceImpl( 20 | UserPersistentRepository userRepository, 21 | BCryptPasswordEncryptionComponent encryptionComponent) { 22 | 23 | this.userRepository = userRepository; 24 | this.encryptionComponent = encryptionComponent; 25 | } 26 | 27 | @Override 28 | public User getUserById(String id) { 29 | return this.userRepository.findById(id); 30 | } 31 | 32 | @Override 33 | public User getAuthenticatedUser(String email, String rawPw) { 34 | User user = getUserByEmail(email); 35 | if (user == null) { 36 | throw new UnAuthorized(); 37 | } 38 | 39 | if (!this.encryptionComponent.matchedPassword(user.getPassword(), rawPw)) { 40 | throw new UnAuthorized(); 41 | } 42 | return user; 43 | } 44 | 45 | @Override 46 | public UserResponse generateUser(UserRequest request) { 47 | String encPw = this.encryptionComponent.encodePassword(request.getPassword()); 48 | User user = request.convert(this.userRepository.newId(), encPw); 49 | try { 50 | user = this.userRepository.insert(user); 51 | } catch (Conflict ex) { 52 | throw new Conflict(ex); 53 | } catch (Exception ex) { 54 | throw new InternalServerError(ex); 55 | } 56 | return new UserResponse(user.getId(), user.getUsername(), user.getEmail()); 57 | } 58 | 59 | private User getUserByEmail(String email) { 60 | User user; 61 | 62 | try { 63 | user = this.userRepository.findByEmail(email); 64 | } catch (Exception ex) { 65 | throw new InternalServerError(ex); 66 | } 67 | 68 | return user; 69 | } 70 | } -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/InfrastructureBean.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture; 2 | 3 | import static org.bson.codecs.configuration.CodecRegistries.fromProviders; 4 | import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; 5 | 6 | import com.bestpractice.api.infrastrucuture.cache.redis.RedisProperty; 7 | import com.bestpractice.api.infrastrucuture.persistent.InfoPersistentRepository; 8 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 9 | import com.bestpractice.api.infrastrucuture.persistent.cassandra.CassandraInfoPersistentRepository; 10 | import com.bestpractice.api.infrastrucuture.persistent.cassandra.property.CassandraProperty; 11 | import com.bestpractice.api.infrastrucuture.persistent.local.LocalInfoPersistentRepository; 12 | import com.bestpractice.api.infrastrucuture.persistent.local.LocalUserPersistentRepository; 13 | import com.bestpractice.api.infrastrucuture.persistent.mongo.MongoInfoPersistentRepository; 14 | import com.bestpractice.api.infrastrucuture.persistent.mongo.MongoUserPersistentRepository; 15 | import com.bestpractice.api.infrastrucuture.persistent.mongo.property.MongoProperty; 16 | import com.bestpractice.api.infrastrucuture.persistent.rdbms.RdbmsInfoPersistentRepository; 17 | import com.bestpractice.api.infrastrucuture.persistent.rdbms.RdbmsUserPersistentRepository; 18 | import com.datastax.oss.driver.api.core.CqlIdentifier; 19 | import com.datastax.oss.driver.api.core.CqlSession; 20 | import com.datastax.oss.driver.api.core.CqlSessionBuilder; 21 | import com.mongodb.MongoClientSettings; 22 | import com.mongodb.MongoCredential; 23 | import com.mongodb.ServerAddress; 24 | import com.mongodb.client.MongoClient; 25 | import com.mongodb.client.MongoClients; 26 | import com.mongodb.client.MongoDatabase; 27 | import java.net.InetSocketAddress; 28 | import java.util.List; 29 | import org.bson.codecs.configuration.CodecRegistry; 30 | import org.bson.codecs.pojo.PojoCodecProvider; 31 | import org.springframework.beans.factory.annotation.Value; 32 | import org.springframework.cache.annotation.EnableCaching; 33 | import org.springframework.context.annotation.Bean; 34 | import org.springframework.context.annotation.Configuration; 35 | import org.springframework.context.annotation.Profile; 36 | import org.springframework.jdbc.core.JdbcTemplate; 37 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 38 | import org.springframework.jdbc.datasource.DriverManagerDataSource; 39 | 40 | @Configuration 41 | @EnableCaching 42 | @Profile("!test") 43 | public class InfrastructureBean { 44 | 45 | @Configuration 46 | @Profile("cache_local") 47 | public static class LocalCacheRepository { 48 | 49 | } 50 | 51 | @Configuration 52 | @Profile("cache_redis") 53 | public static class RedisCacheRepository { 54 | 55 | private final RedisProperty redisProperty; 56 | 57 | public RedisCacheRepository(RedisProperty redisProperty) { 58 | this.redisProperty = redisProperty; 59 | } 60 | } 61 | 62 | @Configuration 63 | @Profile("db_local") 64 | public static class LocalDbRepository { 65 | 66 | @Bean 67 | public UserPersistentRepository userRepository() { 68 | return new LocalUserPersistentRepository(); 69 | } 70 | 71 | @Bean 72 | public InfoPersistentRepository infoRepository() { 73 | return new LocalInfoPersistentRepository(); 74 | } 75 | } 76 | 77 | @Configuration 78 | @Profile("db_rdbms") 79 | public static class RdbmsDbRepository { 80 | 81 | @Value("${spring.datasource.url}") 82 | private String url; 83 | @Value("${spring.datasource.username}") 84 | private String username; 85 | @Value("${spring.datasource.password}") 86 | private String password; 87 | @Value("${spring.datasource.driver-class-name}") 88 | private String driverClassName; 89 | 90 | @Bean 91 | public DriverManagerDataSource dataSource() { 92 | DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); 93 | driverManagerDataSource.setDriverClassName(driverClassName); 94 | driverManagerDataSource.setUrl(url); 95 | driverManagerDataSource.setUsername(username); 96 | driverManagerDataSource.setPassword(password); 97 | return driverManagerDataSource; 98 | } 99 | 100 | @Bean 101 | public DataSourceTransactionManager transactionManager() { 102 | return new DataSourceTransactionManager(dataSource()); 103 | } 104 | 105 | @Bean 106 | public JdbcTemplate jdbcTemplate() { 107 | return new JdbcTemplate(dataSource()); 108 | } 109 | 110 | @Bean 111 | public UserPersistentRepository userRepository(JdbcTemplate jdbcTemplate) { 112 | return new RdbmsUserPersistentRepository(jdbcTemplate); 113 | } 114 | 115 | @Bean 116 | public InfoPersistentRepository infoRepository() { 117 | return new RdbmsInfoPersistentRepository(jdbcTemplate()); 118 | } 119 | } 120 | 121 | @Configuration 122 | @Profile("db_cassandra") 123 | public static class CassandraDbRepository { 124 | 125 | private final CassandraProperty cassandraProperty; 126 | 127 | public CassandraDbRepository(CassandraProperty cassandraProperty) { 128 | this.cassandraProperty = cassandraProperty; 129 | } 130 | 131 | @Bean 132 | public CqlSession cqlSession() { 133 | CqlSessionBuilder builder = CqlSession.builder(); 134 | for (String hostAndPort : cassandraProperty.getHosts()) { 135 | String[] splitHostAndPort = hostAndPort.split(":"); 136 | builder = builder.addContactPoint( 137 | new InetSocketAddress(splitHostAndPort[0], Integer.parseInt(splitHostAndPort[1]))); 138 | } 139 | return builder 140 | .withLocalDatacenter("dc01") 141 | .withKeyspace(CqlIdentifier.fromCql(cassandraProperty.getKeyspace())) 142 | .build(); 143 | } 144 | 145 | @Bean 146 | public UserPersistentRepository userRepository() { 147 | return new LocalUserPersistentRepository(); 148 | } 149 | 150 | @Bean 151 | public InfoPersistentRepository infoRepository() { 152 | return new CassandraInfoPersistentRepository(cqlSession()); 153 | } 154 | } 155 | 156 | @Configuration 157 | @Profile("db_mongo") 158 | public static class MongoDbRepository { 159 | 160 | private final MongoProperty mongoProperty; 161 | 162 | public MongoDbRepository(MongoProperty mongoProperty) { 163 | this.mongoProperty = mongoProperty; 164 | } 165 | 166 | @Bean 167 | public MongoClient mongoClient() { 168 | MongoCredential credential = MongoCredential.createCredential( 169 | mongoProperty.getUser(), 170 | mongoProperty.getAuthDatabase(), 171 | mongoProperty.getPassword().toCharArray()); 172 | 173 | CodecRegistry pojoCodecRegistry = fromRegistries( 174 | MongoClientSettings.getDefaultCodecRegistry(), 175 | fromProviders(PojoCodecProvider.builder().automatic(true).build())); 176 | 177 | ServerAddress serverAddress = new ServerAddress(mongoProperty.getHost(), 178 | mongoProperty.getPort()); 179 | return MongoClients.create(MongoClientSettings.builder() 180 | .codecRegistry(pojoCodecRegistry) 181 | .applyToClusterSettings(builder -> builder.hosts(List.of(serverAddress))) 182 | .credential(credential) 183 | .build()); 184 | } 185 | 186 | @Bean 187 | public MongoDatabase mongoDatabase() { 188 | return mongoClient().getDatabase(mongoProperty.getPlatformDatabase()); 189 | } 190 | 191 | @Bean 192 | public UserPersistentRepository userRepository() { 193 | return new MongoUserPersistentRepository(mongoClient(), mongoDatabase()); 194 | } 195 | 196 | @Bean 197 | public InfoPersistentRepository infoRepository() { 198 | return new MongoInfoPersistentRepository(mongoClient(), mongoDatabase()); 199 | } 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/cache/CacheRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.cache; 2 | 3 | public class CacheRepository { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/cache/local/LocalCacheRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.cache.local; 2 | 3 | public class LocalCacheRepository { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/cache/redis/RedisCacheRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.cache.redis; 2 | 3 | public class RedisCacheRepository { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/cache/redis/RedisProperty.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.cache.redis; 2 | 3 | import org.springframework.context.annotation.Profile; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @Profile("cache_redis") 8 | public class RedisProperty { 9 | private String host; 10 | private int port; 11 | private String password; 12 | 13 | public String getHost() { 14 | return host; 15 | } 16 | 17 | public void setHost(String host) { 18 | this.host = host; 19 | } 20 | 21 | public int getPort() { 22 | return port; 23 | } 24 | 25 | public void setPort(int port) { 26 | this.port = port; 27 | } 28 | 29 | public String getPassword() { 30 | return password; 31 | } 32 | 33 | public void setPassword(String password) { 34 | this.password = password; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/entity/Info.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.entity; 2 | 3 | import javax.persistence.Column; 4 | import javax.validation.constraints.NotNull; 5 | 6 | public class Info extends SharedData { 7 | 8 | @Column(name = "id") 9 | private String id; 10 | 11 | @NotNull 12 | @Column(nullable = false, name = "title") 13 | private String title; 14 | 15 | @NotNull 16 | @Column(nullable = false, name = "description") 17 | private String description; 18 | 19 | public String getId() { 20 | return id; 21 | } 22 | 23 | public void setId(String id) { 24 | this.id = id; 25 | } 26 | 27 | public String getTitle() { 28 | return title; 29 | } 30 | 31 | public void setTitle(String title) { 32 | this.title = title; 33 | } 34 | 35 | public String getDescription() { 36 | return description; 37 | } 38 | 39 | public void setDescription(String description) { 40 | this.description = description; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/entity/SharedData.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | 5 | import java.util.Date; 6 | import javax.persistence.Column; 7 | import javax.persistence.MappedSuperclass; 8 | import javax.persistence.PrePersist; 9 | import javax.persistence.Temporal; 10 | import javax.persistence.TemporalType; 11 | 12 | @MappedSuperclass 13 | public class SharedData { 14 | @Temporal(TemporalType.TIMESTAMP) 15 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 16 | @Column(nullable = false, name = "created_at") 17 | private Date createdAt; 18 | 19 | @PrePersist 20 | public void onPrePersist() { 21 | setCreatedAt(new Date()); 22 | } 23 | 24 | public Date getCreatedAt() { 25 | return createdAt; 26 | } 27 | 28 | public void setCreatedAt(Date createdAt) { 29 | this.createdAt = createdAt; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.entity; 2 | 3 | import java.io.Serializable; 4 | import javax.persistence.Column; 5 | import javax.validation.constraints.NotNull; 6 | 7 | public class User extends SharedData implements Serializable { 8 | 9 | @Column(name = "id") 10 | private String id; 11 | 12 | @Column(nullable = false, name = "username") 13 | private String username; 14 | 15 | @Column(nullable = false, name = "email") 16 | private String email; 17 | 18 | @NotNull 19 | @Column(nullable = false, name = "password") 20 | private String password; 21 | 22 | public User() { 23 | } 24 | 25 | public User(String id, String username, String email, String password) { 26 | this.id = id; 27 | this.username = username; 28 | this.email = email; 29 | this.password = password; 30 | } 31 | 32 | public String getId() { 33 | return id; 34 | } 35 | 36 | public void setId(String id) { 37 | this.id = id; 38 | } 39 | 40 | public String getUsername() { 41 | return username; 42 | } 43 | 44 | public void setUsername(String username) { 45 | this.username = username; 46 | } 47 | 48 | public String getEmail() { 49 | return email; 50 | } 51 | 52 | public void setEmail(String email) { 53 | this.email = email; 54 | } 55 | 56 | public String getPassword() { 57 | return password; 58 | } 59 | 60 | public void setPassword(String password) { 61 | this.password = password; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/InfoPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.Info; 4 | import java.util.List; 5 | import org.springframework.context.annotation.Profile; 6 | 7 | @Profile("!test") 8 | public interface InfoPersistentRepository { 9 | String newId(); 10 | 11 | List findAll(); 12 | 13 | Info findById(String id); 14 | 15 | Info insert(Info info); 16 | 17 | Info replace(String id, Info info); 18 | 19 | boolean removeById(String id); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/UserPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.User; 4 | import org.springframework.context.annotation.Profile; 5 | 6 | @Profile("!test") 7 | public interface UserPersistentRepository { 8 | String newId(); 9 | 10 | User findByEmail(String email); 11 | 12 | User findById(String id); 13 | 14 | User insert(User user); 15 | 16 | User replace(String id, User user); 17 | 18 | boolean removeById(String id); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/cassandra/CassandraInfoPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.cassandra; 2 | 3 | import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.bindMarker; 4 | import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.deleteFrom; 5 | import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.insertInto; 6 | import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.selectFrom; 7 | import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.update; 8 | import static com.datastax.oss.driver.api.querybuilder.update.Assignment.setColumn; 9 | 10 | import com.bestpractice.api.infrastrucuture.entity.Info; 11 | import com.bestpractice.api.infrastrucuture.persistent.InfoPersistentRepository; 12 | import com.datastax.oss.driver.api.core.CqlSession; 13 | import com.datastax.oss.driver.api.core.cql.PreparedStatement; 14 | import com.datastax.oss.driver.api.core.cql.ResultSet; 15 | import com.datastax.oss.driver.api.core.cql.Row; 16 | import com.datastax.oss.driver.api.querybuilder.delete.Delete; 17 | import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; 18 | import com.datastax.oss.driver.api.querybuilder.select.Select; 19 | import com.datastax.oss.driver.api.querybuilder.update.Update; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.UUID; 23 | 24 | public class CassandraInfoPersistentRepository implements InfoPersistentRepository { 25 | 26 | private final CqlSession session; 27 | private final Select selectInfo = selectFrom("infos") 28 | .all(); 29 | 30 | private final Select selectInfoWithWhere = selectFrom("infos") 31 | .all().whereColumn("id").isEqualTo(bindMarker()); 32 | 33 | private final RegularInsert insertInfo = insertInto("infos") 34 | .value("id", bindMarker()) 35 | .value("title", bindMarker()) 36 | .value("description", bindMarker()); 37 | 38 | private final Update updateInfo = update("infos") 39 | .set(setColumn("title", bindMarker()), 40 | setColumn("description", bindMarker())) 41 | .whereColumn("id").isEqualTo(bindMarker()); 42 | 43 | private final Delete deleteInfo = deleteFrom("infos") 44 | .whereColumn("id").isEqualTo(bindMarker()); 45 | 46 | public CassandraInfoPersistentRepository(CqlSession session) { 47 | this.session = session; 48 | } 49 | 50 | @Override 51 | public String newId() { 52 | return UUID.randomUUID().toString(); 53 | } 54 | 55 | @Override 56 | public List findAll() { 57 | // Limit is required if cassandra 58 | PreparedStatement preparedSelectInfo = session.prepare(selectInfo.build()); 59 | ResultSet resultSet = session.execute(preparedSelectInfo.bind()); 60 | 61 | List infos = new ArrayList<>(); 62 | for (Row row : resultSet) { 63 | Info info = new Info(); 64 | info.setId(row.getString("id")); 65 | info.setTitle(row.getString("title")); 66 | info.setDescription(row.getString("description")); 67 | infos.add(info); 68 | } 69 | return infos; 70 | } 71 | 72 | @Override 73 | public Info findById(String id) { 74 | PreparedStatement preparedSelectInfo = session.prepare(selectInfoWithWhere.build()); 75 | ResultSet resultSet = session.execute(preparedSelectInfo.bind(id)); 76 | 77 | Row row = resultSet.one(); 78 | if (row == null) { 79 | return null; 80 | } 81 | 82 | Info info = new Info(); 83 | info.setId(row.getString("id")); 84 | info.setTitle(row.getString("title")); 85 | info.setDescription(row.getString("description")); 86 | return info; 87 | } 88 | 89 | @Override 90 | public Info insert(Info info) { 91 | PreparedStatement preparedSelectInfo = session.prepare(insertInfo.build()); 92 | ResultSet resultSet = session.execute( 93 | preparedSelectInfo.bind(info.getId(), info.getTitle(), info.getDescription())); 94 | 95 | if (!resultSet.wasApplied()) { 96 | return null; 97 | } 98 | return info; 99 | } 100 | 101 | @Override 102 | public Info replace(String id, Info info) { 103 | PreparedStatement preparedSelectInfo = session.prepare(updateInfo.build()); 104 | ResultSet resultSet = session.execute( 105 | preparedSelectInfo.bind(info.getTitle(), info.getDescription(), info.getId())); 106 | 107 | if (!resultSet.wasApplied()) { 108 | return null; 109 | } 110 | return info; 111 | } 112 | 113 | @Override 114 | public boolean removeById(String id) { 115 | PreparedStatement preparedSelectInfo = session.prepare(deleteInfo.build()); 116 | ResultSet resultSet = session.execute( 117 | preparedSelectInfo.bind(id)); 118 | 119 | if (!resultSet.wasApplied()) { 120 | return false; 121 | } 122 | return true; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/cassandra/CassandraUserPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.cassandra; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.User; 4 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 5 | 6 | public class CassandraUserPersistentRepository implements UserPersistentRepository { 7 | 8 | @Override 9 | public String newId() { 10 | return null; 11 | } 12 | 13 | @Override 14 | public User findByEmail(String email) { 15 | return null; 16 | } 17 | 18 | @Override 19 | public User findById(String id) { 20 | return null; 21 | } 22 | 23 | @Override 24 | public User insert(User user) { 25 | return null; 26 | } 27 | 28 | @Override 29 | public User replace(String id, User user) { 30 | return null; 31 | } 32 | 33 | @Override 34 | public boolean removeById(String id) { 35 | return false; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/cassandra/property/CassandraProperty.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.cassandra.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties(prefix = "cassandra") 8 | public class CassandraProperty { 9 | private String[] hosts; 10 | private String keyspace; 11 | private String user; 12 | private String password; 13 | 14 | public String[] getHosts() { 15 | return hosts; 16 | } 17 | 18 | public void setHosts(String[] hosts) { 19 | this.hosts = hosts; 20 | } 21 | 22 | public String getKeyspace() { 23 | return keyspace; 24 | } 25 | 26 | public void setKeyspace(String keyspace) { 27 | this.keyspace = keyspace; 28 | } 29 | 30 | public String getUser() { 31 | return user; 32 | } 33 | 34 | public void setUser(String user) { 35 | this.user = user; 36 | } 37 | 38 | public String getPassword() { 39 | return password; 40 | } 41 | 42 | public void setPassword(String password) { 43 | this.password = password; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/local/LocalInfoPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.local; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.Info; 4 | import com.bestpractice.api.infrastrucuture.persistent.InfoPersistentRepository; 5 | import java.util.ArrayList; 6 | import java.util.Collections; 7 | import java.util.List; 8 | import java.util.NoSuchElementException; 9 | import java.util.UUID; 10 | 11 | public class LocalInfoPersistentRepository implements InfoPersistentRepository { 12 | 13 | private final List infos = Collections.synchronizedList(new ArrayList<>()); 14 | 15 | @Override 16 | public String newId() { 17 | return UUID.randomUUID().toString(); 18 | } 19 | 20 | @Override 21 | public List findAll() { 22 | return this.infos; 23 | } 24 | 25 | @Override 26 | public Info findById(String id) { 27 | try { 28 | var info = this.infos.stream().filter(u -> u.getId().equals(id)).findFirst(); 29 | return info.get(); 30 | } catch (NullPointerException | NoSuchElementException ignored) { 31 | return null; 32 | } 33 | } 34 | 35 | @Override 36 | public Info insert(Info info) { 37 | this.infos.add(info); 38 | return info; 39 | } 40 | 41 | @Override 42 | public Info replace(String id, Info info) { 43 | Integer removeIndex = null; 44 | for (int i = 0; i < this.infos.size(); i++) { 45 | if (this.infos.get(i).getId().equals(id)) { 46 | continue; 47 | } 48 | removeIndex = i; 49 | break; 50 | } 51 | if (removeIndex == null) { 52 | throw new RuntimeException("Data does not exist."); 53 | } 54 | 55 | this.infos.set(removeIndex, info); 56 | return null; 57 | } 58 | 59 | @Override 60 | public boolean removeById(String id) { 61 | Integer removeIndex = null; 62 | for (int i = 0; i < this.infos.size(); i++) { 63 | if (!this.infos.get(i).getId().equals(id)) { 64 | continue; 65 | } 66 | removeIndex = i; 67 | break; 68 | } 69 | if (removeIndex == null) { 70 | return true; 71 | } 72 | 73 | this.infos.remove((int) removeIndex); 74 | return true; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/local/LocalUserPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.local; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.User; 4 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collections; 8 | import java.util.List; 9 | import java.util.NoSuchElementException; 10 | import java.util.UUID; 11 | 12 | public class LocalUserPersistentRepository implements UserPersistentRepository { 13 | private final List users = Collections.synchronizedList(new ArrayList<>()); 14 | 15 | @Override 16 | public String newId() { 17 | return UUID.randomUUID().toString(); 18 | } 19 | 20 | @Override 21 | public User findByEmail(String email) { 22 | try { 23 | var user = this.users.stream().filter(u -> u.getEmail().equals(email)).findFirst(); 24 | return user.get(); 25 | } catch (NullPointerException | NoSuchElementException ignored) { 26 | return null; 27 | } 28 | } 29 | 30 | @Override 31 | public User findById(String id) { 32 | try { 33 | var user = this.users.stream().filter(u -> u.getId().equals(id)).findFirst(); 34 | return user.get(); 35 | } catch (NullPointerException | NoSuchElementException ignored) { 36 | return null; 37 | } 38 | } 39 | 40 | @Override 41 | public User insert(User user) { 42 | this.users.add(user); 43 | return user; 44 | } 45 | 46 | @Override 47 | public User replace(String id, User user) { 48 | Integer removeIndex = null; 49 | for (int i = 0; i < this.users.size(); i++) { 50 | if (!this.users.get(i).getId().equals(id)) { 51 | continue; 52 | } 53 | removeIndex = i; 54 | break; 55 | } 56 | if (removeIndex == null) { 57 | throw new RuntimeException("Data does not exist."); 58 | } 59 | 60 | this.users.set(removeIndex, user); 61 | return null; 62 | } 63 | 64 | @Override 65 | public boolean removeById(String id) { 66 | Integer removeIndex = null; 67 | for (int i = 0; i < this.users.size(); i++) { 68 | if (!this.users.get(i).getId().equals(id)) { 69 | continue; 70 | } 71 | removeIndex = i; 72 | break; 73 | } 74 | if (removeIndex == null) { 75 | return true; 76 | } 77 | 78 | this.users.remove((int)removeIndex); 79 | return true; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/mongo/MongoInfoPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.mongo; 2 | 3 | import com.bestpractice.api.common.exception.InternalServerError; 4 | import com.bestpractice.api.infrastrucuture.entity.Info; 5 | import com.bestpractice.api.infrastrucuture.persistent.InfoPersistentRepository; 6 | import com.bestpractice.api.infrastrucuture.persistent.mongo.entity.MongoInfoEntity; 7 | import com.mongodb.client.FindIterable; 8 | import com.mongodb.client.MongoClient; 9 | import com.mongodb.client.MongoCollection; 10 | import com.mongodb.client.MongoCursor; 11 | import com.mongodb.client.MongoDatabase; 12 | import com.mongodb.client.model.Filters; 13 | import com.mongodb.client.model.ReplaceOptions; 14 | import com.mongodb.client.result.DeleteResult; 15 | import com.mongodb.client.result.UpdateResult; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | import java.util.Objects; 19 | import org.bson.conversions.Bson; 20 | import org.bson.types.ObjectId; 21 | 22 | public class MongoInfoPersistentRepository implements InfoPersistentRepository { 23 | 24 | private static final String COLLECTION_NAME = "infos"; 25 | private final MongoClient mongoClient; 26 | private final MongoDatabase mongoDatabase; 27 | private final MongoCollection collection; 28 | 29 | public MongoInfoPersistentRepository(MongoClient mongoClient, MongoDatabase mongoDatabase) { 30 | this.mongoClient = mongoClient; 31 | this.mongoDatabase = mongoDatabase; 32 | this.collection = this.mongoDatabase.getCollection(COLLECTION_NAME, MongoInfoEntity.class); 33 | } 34 | 35 | @Override 36 | public String newId() { 37 | return new ObjectId().toString(); 38 | } 39 | 40 | @Override 41 | public List findAll() { 42 | FindIterable find = this.collection.find(); 43 | 44 | List data = new ArrayList<>(); 45 | try (MongoCursor iterator = find.iterator()) { 46 | while (iterator.hasNext()) { 47 | MongoInfoEntity next = iterator.next(); 48 | data.add(next.convertTo()); 49 | } 50 | } catch (Exception ex) { 51 | throw new InternalServerError("Failed to get data of range from database", ex); 52 | } 53 | return data; 54 | } 55 | 56 | @Override 57 | public Info findById(String id) { 58 | Bson filter = Filters.and( 59 | Filters.eq("_id", new ObjectId(id))); 60 | 61 | try { 62 | return Objects.requireNonNull(this.collection.find(filter).first()).convertTo(); 63 | } catch (Exception ex) { 64 | throw new InternalServerError("Failed to get detail from database", ex); 65 | } 66 | } 67 | 68 | @Override 69 | public Info insert(Info info) { 70 | try { 71 | this.collection.insertOne(MongoInfoEntity.convertFrom(info)); 72 | return info; 73 | } catch (Exception ex) { 74 | throw new InternalServerError("Failed to insert", ex); 75 | } 76 | } 77 | 78 | @Override 79 | public Info replace(String id, Info info) { 80 | MongoInfoEntity mongoInfoEntity = MongoInfoEntity.convertFrom(info); 81 | Bson filter = Filters.and( 82 | Filters.eq("_id", mongoInfoEntity.getId())); 83 | 84 | try { 85 | ReplaceOptions opts = new ReplaceOptions().upsert(true); 86 | UpdateResult result = this.collection.replaceOne(filter, mongoInfoEntity, opts); 87 | if (!result.wasAcknowledged()) { 88 | throw new RuntimeException("Failed to get Acknowledged on replace operation"); 89 | } 90 | return info; 91 | } catch (Exception ex) { 92 | throw new InternalServerError("Failed to insert", ex); 93 | } 94 | } 95 | 96 | @Override 97 | public boolean removeById(String id) { 98 | ObjectId objectId = new ObjectId(id); 99 | Bson filter = Filters.and( 100 | Filters.eq("_id", objectId)); 101 | try { 102 | DeleteResult result = this.collection.deleteOne(filter); 103 | return result.wasAcknowledged(); 104 | } catch (Exception ex) { 105 | throw new InternalServerError("Failed to delete", ex); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/mongo/MongoUserPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.mongo; 2 | 3 | import com.bestpractice.api.common.exception.InternalServerError; 4 | import com.bestpractice.api.infrastrucuture.entity.User; 5 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 6 | import com.bestpractice.api.infrastrucuture.persistent.mongo.entity.MongoUserEntity; 7 | import com.mongodb.client.MongoClient; 8 | import com.mongodb.client.MongoCollection; 9 | import com.mongodb.client.MongoDatabase; 10 | import com.mongodb.client.model.Filters; 11 | import com.mongodb.client.model.ReplaceOptions; 12 | import com.mongodb.client.result.DeleteResult; 13 | import com.mongodb.client.result.UpdateResult; 14 | import java.util.Objects; 15 | import org.bson.conversions.Bson; 16 | import org.bson.types.ObjectId; 17 | 18 | public class MongoUserPersistentRepository implements UserPersistentRepository { 19 | 20 | private static final String COLLECTION_NAME = "users"; 21 | private final MongoClient mongoClient; 22 | private final MongoDatabase mongoDatabase; 23 | private final MongoCollection collection; 24 | 25 | public MongoUserPersistentRepository(MongoClient mongoClient, MongoDatabase mongoDatabase) { 26 | this.mongoClient = mongoClient; 27 | this.mongoDatabase = mongoDatabase; 28 | this.collection = this.mongoDatabase.getCollection(COLLECTION_NAME, MongoUserEntity.class); 29 | } 30 | 31 | @Override 32 | public String newId() { 33 | return new ObjectId().toString(); 34 | } 35 | 36 | @Override 37 | public User findByEmail(String email) { 38 | Bson filter = Filters.and( 39 | Filters.eq("email", email)); 40 | 41 | try { 42 | return Objects.requireNonNull(this.collection.find(filter).first()).convertTo(); 43 | } catch (Exception ex) { 44 | throw new InternalServerError("Failed to get detail from database", ex); 45 | } 46 | } 47 | 48 | @Override 49 | public User findById(String id) { 50 | Bson filter = Filters.and( 51 | Filters.eq("_id", new ObjectId(id))); 52 | 53 | try { 54 | return Objects.requireNonNull(this.collection.find(filter).first()).convertTo(); 55 | } catch (Exception ex) { 56 | throw new InternalServerError("Failed to get detail from database", ex); 57 | } 58 | } 59 | 60 | @Override 61 | public User insert(User user) { 62 | try { 63 | this.collection.insertOne(MongoUserEntity.convertFrom(user)); 64 | return user; 65 | } catch (Exception ex) { 66 | throw new InternalServerError("Failed to insert", ex); 67 | } 68 | } 69 | 70 | @Override 71 | public User replace(String id, User user) { 72 | MongoUserEntity mongoUserEntity = MongoUserEntity.convertFrom(user); 73 | Bson filter = Filters.and( 74 | Filters.eq("_id", mongoUserEntity.getId())); 75 | 76 | try { 77 | ReplaceOptions opts = new ReplaceOptions().upsert(true); 78 | UpdateResult result = this.collection.replaceOne(filter, mongoUserEntity, opts); 79 | if (!result.wasAcknowledged()) { 80 | throw new RuntimeException("Failed to get Acknowledged on replace operation"); 81 | } 82 | return user; 83 | } catch (Exception ex) { 84 | throw new InternalServerError("Failed to insert", ex); 85 | } 86 | } 87 | 88 | @Override 89 | public boolean removeById(String id) { 90 | ObjectId objectId = new ObjectId(id); 91 | Bson filter = Filters.and( 92 | Filters.eq("_id", objectId)); 93 | try { 94 | DeleteResult result = this.collection.deleteOne(filter); 95 | return result.wasAcknowledged(); 96 | } catch (Exception ex) { 97 | throw new InternalServerError("Failed to delete", ex); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/mongo/entity/MongoInfoEntity.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.mongo.entity; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.Info; 4 | import org.bson.types.ObjectId; 5 | 6 | public class MongoInfoEntity { 7 | private ObjectId id; 8 | private String title; 9 | private String description; 10 | 11 | public MongoInfoEntity() { 12 | } 13 | 14 | public MongoInfoEntity(ObjectId id, String title, String description) { 15 | this.id = id; 16 | this.title = title; 17 | this.description = description; 18 | } 19 | 20 | public void setId(ObjectId id) { 21 | this.id = id; 22 | } 23 | 24 | public void setTitle(String title) { 25 | this.title = title; 26 | } 27 | 28 | public void setDescription(String description) { 29 | this.description = description; 30 | } 31 | 32 | public ObjectId getId() { 33 | return id; 34 | } 35 | 36 | public String getTitle() { 37 | return title; 38 | } 39 | 40 | public String getDescription() { 41 | return description; 42 | } 43 | 44 | public static MongoInfoEntity convertFrom(Info info) { 45 | return new MongoInfoEntity(new ObjectId(info.getId()), info.getTitle(), info.getDescription()); 46 | } 47 | 48 | public Info convertTo() { 49 | Info info = new Info(); 50 | info.setId(this.id.toString()); 51 | info.setTitle(this.title); 52 | info.setDescription(this.description); 53 | return info; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/mongo/entity/MongoUserEntity.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.mongo.entity; 2 | 3 | import com.bestpractice.api.infrastrucuture.entity.User; 4 | import org.bson.types.ObjectId; 5 | 6 | public class MongoUserEntity { 7 | private ObjectId id; 8 | private String username; 9 | private String email; 10 | private String password; 11 | 12 | public MongoUserEntity() { 13 | } 14 | 15 | public MongoUserEntity(ObjectId id, String username, String email, String password) { 16 | this.id = id; 17 | this.username = username; 18 | this.email = email; 19 | this.password = password; 20 | } 21 | 22 | public void setId(ObjectId id) { 23 | this.id = id; 24 | } 25 | 26 | public void setUsername(String username) { 27 | this.username = username; 28 | } 29 | 30 | public void setEmail(String email) { 31 | this.email = email; 32 | } 33 | 34 | public void setPassword(String password) { 35 | this.password = password; 36 | } 37 | 38 | public ObjectId getId() { 39 | return id; 40 | } 41 | 42 | public String getUsername() { 43 | return username; 44 | } 45 | 46 | public String getEmail() { 47 | return email; 48 | } 49 | 50 | public String getPassword() { 51 | return password; 52 | } 53 | 54 | public static MongoUserEntity convertFrom(User user) { 55 | return new MongoUserEntity(new ObjectId(user.getId()), user.getUsername(), user.getEmail(), user.getPassword()); 56 | } 57 | 58 | public User convertTo() { 59 | User user = new User(); 60 | user.setId(this.id.toString()); 61 | user.setUsername(this.username); 62 | user.setPassword(this.password); 63 | return user; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/mongo/property/MongoProperty.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.mongo.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties(prefix = "mongo") 8 | public class MongoProperty { 9 | private String host; 10 | private int port; 11 | private String authDatabase; 12 | private String platformDatabase; 13 | private String user; 14 | private String password; 15 | 16 | public String getHost() { 17 | return host; 18 | } 19 | 20 | public void setHost(String host) { 21 | this.host = host; 22 | } 23 | 24 | public int getPort() { 25 | return port; 26 | } 27 | 28 | public void setPort(int port) { 29 | this.port = port; 30 | } 31 | 32 | public String getAuthDatabase() { 33 | return authDatabase; 34 | } 35 | 36 | public void setAuthDatabase(String authDatabase) { 37 | this.authDatabase = authDatabase; 38 | } 39 | 40 | public String getPlatformDatabase() { 41 | return platformDatabase; 42 | } 43 | 44 | public void setPlatformDatabase(String platformDatabase) { 45 | this.platformDatabase = platformDatabase; 46 | } 47 | 48 | public String getUser() { 49 | return user; 50 | } 51 | 52 | public void setUser(String user) { 53 | this.user = user; 54 | } 55 | 56 | public String getPassword() { 57 | return password; 58 | } 59 | 60 | public void setPassword(String password) { 61 | this.password = password; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/rdbms/RdbmsInfoPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.rdbms; 2 | 3 | import com.bestpractice.api.common.exception.Conflict; 4 | import com.bestpractice.api.common.exception.InternalServerError; 5 | import com.bestpractice.api.infrastrucuture.entity.Info; 6 | import com.bestpractice.api.infrastrucuture.persistent.InfoPersistentRepository; 7 | import java.sql.Connection; 8 | import java.sql.PreparedStatement; 9 | import java.sql.SQLException; 10 | import java.sql.Statement; 11 | import java.util.List; 12 | import java.util.UUID; 13 | import org.springframework.jdbc.core.BeanPropertyRowMapper; 14 | import org.springframework.jdbc.core.DataClassRowMapper; 15 | import org.springframework.jdbc.core.JdbcTemplate; 16 | import org.springframework.jdbc.support.GeneratedKeyHolder; 17 | import org.springframework.jdbc.support.KeyHolder; 18 | 19 | public class RdbmsInfoPersistentRepository implements InfoPersistentRepository { 20 | private final JdbcTemplate jdbcTemplate; 21 | 22 | public RdbmsInfoPersistentRepository(JdbcTemplate jdbcTemplate) { 23 | this.jdbcTemplate = jdbcTemplate; 24 | } 25 | 26 | @Override 27 | public String newId() { 28 | return UUID.randomUUID().toString(); 29 | } 30 | 31 | @Override 32 | public List findAll() { 33 | var sql = "SELECT * FROM infos"; 34 | return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Info.class)); 35 | } 36 | 37 | @Override 38 | public Info findById(String id) { 39 | var sql = "SELECT * FROM users WHERE id = ?"; 40 | return jdbcTemplate.queryForObject(sql, new DataClassRowMapper<>(Info.class), id); 41 | } 42 | 43 | @Override 44 | public Info insert(Info info) { 45 | KeyHolder keyHolder = new GeneratedKeyHolder(); 46 | String sql = "INSERT INTO infos (id, title, description) VALUES (?, ?, ?)"; 47 | 48 | try { 49 | jdbcTemplate.update(connection -> preparedStatement(connection, sql, info), keyHolder); 50 | } catch (org.springframework.dao.DuplicateKeyException e) { 51 | throw new Conflict(e); 52 | } 53 | return info; 54 | } 55 | 56 | @Override 57 | public Info replace(String id, Info info) { 58 | String sql = "UPDATE infos SET title = ?, description = ? WHERE id = ?"; 59 | jdbcTemplate.update(sql, info.getTitle(), info.getDescription(), id); 60 | return info; 61 | } 62 | 63 | @Override 64 | public boolean removeById(String id) { 65 | String deleteSql = "DELETE FROM infos WHERE id = ?"; 66 | try { 67 | jdbcTemplate.update(deleteSql, id); 68 | return true; 69 | } catch (Exception ignored) { 70 | return false; 71 | } 72 | } 73 | 74 | private PreparedStatement preparedStatement(Connection connection, String sql, Info info) { 75 | try { 76 | PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); 77 | ps.setString(1, info.getId()); 78 | ps.setString(2, info.getTitle()); 79 | ps.setString(3, info.getDescription()); 80 | return ps; 81 | } catch (SQLException e) { 82 | throw new InternalServerError("Failed to run sql."); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/bestpractice/api/infrastrucuture/persistent/rdbms/RdbmsUserPersistentRepository.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api.infrastrucuture.persistent.rdbms; 2 | 3 | import com.bestpractice.api.common.exception.Conflict; 4 | import com.bestpractice.api.infrastrucuture.entity.User; 5 | import com.bestpractice.api.infrastrucuture.persistent.UserPersistentRepository; 6 | 7 | import java.util.UUID; 8 | import org.springframework.jdbc.core.DataClassRowMapper; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | 11 | public class RdbmsUserPersistentRepository implements UserPersistentRepository { 12 | private final JdbcTemplate jdbcTemplate; 13 | 14 | public RdbmsUserPersistentRepository(JdbcTemplate jdbcTemplate) { 15 | this.jdbcTemplate = jdbcTemplate; 16 | } 17 | 18 | @Override 19 | public String newId() { 20 | return UUID.randomUUID().toString(); 21 | } 22 | 23 | @Override 24 | public User findByEmail(String email) { 25 | var sql = "SELECT * FROM users WHERE email = ?"; 26 | return jdbcTemplate.queryForObject(sql, new DataClassRowMapper<>(User.class), email); 27 | } 28 | 29 | @Override 30 | public User findById(String id) { 31 | var sql = "SELECT * FROM users WHERE id = ?"; 32 | return jdbcTemplate.queryForObject(sql, new DataClassRowMapper<>(User.class), id); 33 | } 34 | 35 | @Override 36 | public User insert(User user) { 37 | String sql = "INSERT INTO users (id, username, email, password) VALUES (?, ?, ?, ?)"; 38 | 39 | try { 40 | jdbcTemplate.update( 41 | sql, 42 | user.getId(), 43 | user.getUsername(), 44 | user.getEmail(), 45 | user.getPassword() 46 | ); 47 | } catch (org.springframework.dao.DuplicateKeyException e) { 48 | throw new Conflict(e); 49 | } 50 | return user; 51 | } 52 | 53 | @Override 54 | public User replace(String id, User user) { 55 | String updateSql = "UPDATE users SET username = ?, email = ?, password = ? WHERE id = ?"; 56 | jdbcTemplate.update( 57 | updateSql, 58 | user.getUsername(), 59 | user.getEmail(), 60 | user.getPassword(), 61 | id 62 | ); 63 | return user; 64 | } 65 | 66 | @Override 67 | public boolean removeById(String id) { 68 | String deleteSql = "DELETE FROM users WHERE id = ?"; 69 | 70 | try { 71 | jdbcTemplate.update(deleteSql, id); 72 | return true; 73 | } catch (Exception ignored) { 74 | return false; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/resources/application-db_cassandra.yml: -------------------------------------------------------------------------------- 1 | # Persistent database setting 2 | # Cassandra database 3 | 4 | cassandra: 5 | hosts: 6 | - 127.0.0.1:9042 7 | keyspace: spring_boot 8 | user: root 9 | password: root_pw 10 | -------------------------------------------------------------------------------- /src/main/resources/application-db_local.yml: -------------------------------------------------------------------------------- 1 | # Persistent database setting 2 | # Local database so this is not use persistent oss 3 | 4 | spring: 5 | jpa: 6 | open-in-view: false 7 | sql: 8 | init: 9 | mode: never -------------------------------------------------------------------------------- /src/main/resources/application-db_mongo.yml: -------------------------------------------------------------------------------- 1 | # Persistent database setting 2 | # Mongo database 3 | 4 | mongo: 5 | host: localhost 6 | port: 27017 7 | auth-database: admin 8 | platform-database: spring_boot 9 | user: root 10 | password: root_pw 11 | -------------------------------------------------------------------------------- /src/main/resources/application-db_rdbms.yml: -------------------------------------------------------------------------------- 1 | # Persistent database setting 2 | # RDBMS database 3 | 4 | spring: 5 | jpa: 6 | open-in-view: true 7 | datasource: 8 | url: jdbc:mysql://${MYSQL_DB_HOST}:3306/${MYSQL_DB_NAME}?useSSL=false&allowPublicKeyRetrieval=true 9 | username: ${MYSQL_DB_USER} 10 | password: ${MYSQL_DB_PASS} 11 | driver-class-name: com.mysql.jdbc.Driver 12 | redis: 13 | host: ${REDIS_DB_HOST} 14 | port: ${REDIS_DB_PORT} 15 | password: ${REDIS_DB_PASS} 16 | jackson: 17 | property-naming-strategy: SNAKE_CASE 18 | sql: 19 | init: 20 | encoding: UTF-8 21 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | # Application development setting 2 | # Independents datasource 3 | 4 | credentials: 5 | provider: best-practice 6 | subject: localhost 7 | alg: HS512 8 | key: apikey 9 | hmac-secret: test-secret 10 | expires-hour-str: 1 -------------------------------------------------------------------------------- /src/main/resources/application-local.yml: -------------------------------------------------------------------------------- 1 | # Application local development setting 2 | # Independents datasource 3 | 4 | credentials: 5 | provider: best-practice 6 | subject: localhost 7 | alg: HS512 8 | key: apikey 9 | hmac-secret: test-secret 10 | expires-hour-str: 1 -------------------------------------------------------------------------------- /src/main/resources/application-prod.yml: -------------------------------------------------------------------------------- 1 | # Application production setting 2 | # Independents datasource 3 | 4 | credentials: 5 | provider: best-practice 6 | subject: localhost 7 | alg: HS512 8 | key: apikey 9 | hmac-secret: test-secret 10 | expires-hour-str: 1 -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | com.bestpractice.api: INFO -------------------------------------------------------------------------------- /src/test/java/com/bestpractice/api/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.bestpractice.api; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | import org.springframework.test.context.ActiveProfiles; 6 | 7 | @ActiveProfiles("test") 8 | @SpringBootTest 9 | public class ApplicationTests { 10 | 11 | @Test 12 | public void contextLoads(){} 13 | } 14 | -------------------------------------------------------------------------------- /src/test/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | jpa: 3 | database: HSQL 4 | hibernate: 5 | ddl-auto: create-drop 6 | properties: 7 | hibernate: 8 | dialect: org.hibernate.dialect.HSQLDialect 9 | datasource: 10 | driver-class-name: org.hsqldb.jdbcDriver 11 | url: jdbc:hsqldb:mem:scratchdb 12 | username: test 13 | password: test 14 | 15 | credentials: 16 | provider: best-practice 17 | subject: localhost 18 | alg: HS512 19 | key: apikey 20 | --------------------------------------------------------------------------------