Repository: team-dodn/spring-boot-java-template Branch: main Commit: 750675f8bb7b Files: 76 Total size: 69.8 KB Directory structure: gitextract_fd7p_zqw/ ├── .gitattributes ├── .githooks/ │ └── pre-commit ├── .github/ │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .springjavaformatconfig ├── LICENCE.md ├── README.md ├── build.gradle ├── clients/ │ └── client-example/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── dodn/ │ │ │ └── springboot/ │ │ │ └── client/ │ │ │ └── example/ │ │ │ ├── ExampleApi.java │ │ │ ├── ExampleClient.java │ │ │ ├── ExampleConfig.java │ │ │ ├── ExampleRequestDto.java │ │ │ ├── ExampleResponseDto.java │ │ │ └── model/ │ │ │ └── ExampleClientResult.java │ │ └── resources/ │ │ └── client-example.yml │ └── test/ │ ├── java/ │ │ └── io/ │ │ └── dodn/ │ │ └── springboot/ │ │ └── client/ │ │ ├── ClientExampleContextTest.java │ │ ├── ClientExampleTestApplication.java │ │ └── example/ │ │ └── ExampleClientTest.java │ └── resources/ │ └── application.yml ├── core/ │ ├── core-api/ │ │ ├── build.gradle │ │ └── src/ │ │ ├── docs/ │ │ │ └── asciidoc/ │ │ │ └── index.adoc │ │ ├── main/ │ │ │ ├── java/ │ │ │ │ └── io/ │ │ │ │ └── dodn/ │ │ │ │ └── springboot/ │ │ │ │ ├── CoreApiApplication.java │ │ │ │ └── core/ │ │ │ │ ├── api/ │ │ │ │ │ ├── config/ │ │ │ │ │ │ ├── AsyncConfig.java │ │ │ │ │ │ └── AsyncExceptionHandler.java │ │ │ │ │ └── controller/ │ │ │ │ │ ├── ApiControllerAdvice.java │ │ │ │ │ ├── HealthController.java │ │ │ │ │ └── v1/ │ │ │ │ │ ├── ExampleController.java │ │ │ │ │ ├── request/ │ │ │ │ │ │ └── ExampleRequestDto.java │ │ │ │ │ └── response/ │ │ │ │ │ ├── ExampleItemResponseDto.java │ │ │ │ │ └── ExampleResponseDto.java │ │ │ │ ├── domain/ │ │ │ │ │ ├── ExampleData.java │ │ │ │ │ ├── ExampleResult.java │ │ │ │ │ └── ExampleService.java │ │ │ │ └── support/ │ │ │ │ ├── error/ │ │ │ │ │ ├── CoreException.java │ │ │ │ │ ├── ErrorCode.java │ │ │ │ │ ├── ErrorMessage.java │ │ │ │ │ └── ErrorType.java │ │ │ │ └── response/ │ │ │ │ ├── ApiResponse.java │ │ │ │ └── ResultType.java │ │ │ └── resources/ │ │ │ └── application.yml │ │ └── test/ │ │ └── java/ │ │ └── io/ │ │ └── dodn/ │ │ └── springboot/ │ │ ├── ContextTest.java │ │ ├── CoreApiApplicationTest.java │ │ ├── DevelopTest.java │ │ └── core/ │ │ └── api/ │ │ └── controller/ │ │ └── v1/ │ │ └── ExampleControllerTest.java │ └── core-enum/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── java/ │ └── io/ │ └── dodn/ │ └── springboot/ │ └── core/ │ └── enums/ │ └── ExampleEnum.java ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── lint.gradle ├── settings.gradle ├── storage/ │ └── db-core/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── dodn/ │ │ │ └── springboot/ │ │ │ └── storage/ │ │ │ └── db/ │ │ │ └── core/ │ │ │ ├── BaseEntity.java │ │ │ ├── ExampleEntity.java │ │ │ ├── ExampleRepository.java │ │ │ └── config/ │ │ │ ├── CoreDataSourceConfig.java │ │ │ └── CoreJpaConfig.java │ │ └── resources/ │ │ └── db-core.yml │ └── test/ │ ├── java/ │ │ └── io/ │ │ └── dodn/ │ │ └── springboot/ │ │ └── storage/ │ │ └── db/ │ │ ├── CoreDbContextTest.java │ │ ├── CoreDbTestApplication.java │ │ └── core/ │ │ └── ExampleRepositoryIT.java │ └── resources/ │ └── application.yml ├── support/ │ ├── logging/ │ │ ├── build.gradle │ │ └── src/ │ │ └── main/ │ │ └── resources/ │ │ ├── logback/ │ │ │ ├── logback-dev.xml │ │ │ ├── logback-live.xml │ │ │ ├── logback-local-dev.xml │ │ │ ├── logback-local.xml │ │ │ └── logback-staging.xml │ │ └── logging.yml │ └── monitoring/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── resources/ │ └── monitoring.yml └── tests/ └── api-docs/ ├── build.gradle └── src/ └── main/ └── java/ └── io/ └── dodn/ └── springboot/ └── test/ └── api/ └── RestDocsTest.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ .githooks/** linguist-vendored gradlew linguist-vendored ================================================ FILE: .githooks/pre-commit ================================================ #!/bin/bash GIT_DIR=$(git rev-parse --show-toplevel) $GIT_DIR/gradlew checkFormat ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] permissions: contents: read jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK uses: actions/setup-java@v3 with: java-version: '21' distribution: 'adopt' - name: Lint uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 with: arguments: checkFormat - name: Test uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 with: arguments: test ================================================ FILE: .gitignore ================================================ .gradle build/ !gradle/wrapper/gradle-wrapper.jar !**/src/main/** !**/src/test/** ### IDEA ### .idea *.iws *.iml *.ipr out/ ================================================ FILE: .springjavaformatconfig ================================================ indentation-style=spaces ================================================ FILE: LICENCE.md ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # SpringBoot Java Template [![Twitter](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fgeminikims)](https://twitter.com/geminikims) [![Youtube](https://img.shields.io/youtube/channel/views/UCDh8zEDofOcrOMAOnSVL9Tg?label=Youtube&style=social)](https://www.youtube.com/@geminikims) [![CI](https://github.com/team-dodn/spring-boot-java-template/actions/workflows/ci.yml/badge.svg)](https://github.com/team-dodn/spring-boot-java-template/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://opensource.org/licenses/Apache-2.0) This is not the best structure. This is a good basic structure to use early in the project when productivity is important. Remember, as your software grows, your structure must grow too. # **Modules** ## Core Each submodule of this module is responsible for one domain service. This must make the modular structure grow with the growth of the service. ### core:core-api It is the only executable module in the project. It is structured to have domains to maximize initial development productivity. It is also responsible for providing APIs and setting up frameworks for services. ### core:core-enum This module contains enums that are used by `core-api` and must be delivered to external modules.
## Clients Submodules of this module are responsible for integrating with external systems. ### clients:clients-example This module shows an example of HTTP communication with `Spring-Cloud-Open-Feign`.
## Storage Submodules of this module are responsible for integrating with the various storages. ### storage:db-core This module shows an example of connecting to `MySql` using `Spring-Data-JPA`.
## Support Submodules of this module are responsible for additional support. ### support:logging This module supports logging of service and has a dependency added for distributed tracing support. It also includes dependencies to support `Sentry`. ### support:monitoring This module supports monitoring of services.
## Tests Submodules of this module are responsible for the convenience of writing test codes. ### tests:api-docs This module is for writing spring-rest-docs conveniently.
# Dependency Management All dependency versioning is done through `gradle.properties` file. If you want to add a new dependency, put the version in `gradle.properties` and load it in `build.gradle`.
# Runtime Profiles ## local This profile aims to configure an environment that can be developed even if the network is disconnected. ## local-dev This profile aims configurations that allow me to connect to the DEV environment from my local machine. ## dev This profile exists for deploying Development environments. ## staging This profile exists for deploying Staging environments. ## live This profile exists for deploying Live environments.
# Test Tasks & Tags ## test This is a collection of test-tasks that we want to run on `CI`. If you want to change the settings, modify the `build.gradle` file. ## unitTest This is a group of tests that typically have no dependencies, are fast to run, and test a single feature. ## contextTest This is a task that runs with SpringContext and has integration tests. ## restDocsTest This is a task to create asciidoc based on spring-rest-docs. ## developTest This is a task of tests that should not be run in `CI`. This is a good tag to use if you're not good at writing tests.
# Recommended Preferences ## Git Hook This setting makes run `lint` on every commit. ``` $ git config core.hookspath .githooks ``` ## IntelliJ IDEA This setting makes it easier to run the `test code` out of the box. ``` // Gradle Build and run with IntelliJ IDEA Build, Execution, Deployment > Build Tools > Gradle > Run tests using > IntelliJ IDEA ``` If you want to apply lint settings to the format of IDEA, please refer to the guide below. [Spring Java Format IntelliJ IDEA](https://github.com/spring-io/spring-javaformat#intellij-idea) --- # Supported By
JetBrains Logo (Main) logo.
================================================ FILE: build.gradle ================================================ plugins { id 'java-library' id 'org.springframework.boot' apply(false) id 'io.spring.dependency-management' id 'io.spring.javaformat' apply(false) id 'org.asciidoctor.jvm.convert' apply(false) } apply from: 'lint.gradle' allprojects { group = "${projectGroup}" version = "${applicationVersion}" repositories { mavenCentral() } } subprojects { apply plugin: 'java-library' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'org.asciidoctor.jvm.convert' dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudDependenciesVersion}" } } dependencies { annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' testImplementation 'org.springframework.boot:spring-boot-test' testImplementation 'org.junit.jupiter:junit-jupiter-api' testImplementation 'org.junit.jupiter:junit-jupiter-engine' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' testImplementation 'org.assertj:assertj-core' testImplementation 'org.mockito:mockito-core' } java { toolchain { languageVersion = JavaLanguageVersion.of(project.javaVersion) } } bootJar.enabled = false jar.enabled = true test { useJUnitPlatform { excludeTags 'develop', 'restdocs' } } testing { suites { test { targets { unitTest { testTask.configure { group = 'verification' useJUnitPlatform { excludeTags 'develop', 'context', 'restdocs' } } } contextTest { testTask.configure { group = 'verification' useJUnitPlatform { includeTags 'context' } } } restDocsTest { testTask.configure { group = 'verification' useJUnitPlatform { includeTags 'restdocs' } } } developTest { testTask.configure { group = 'verification' useJUnitPlatform { includeTags 'develop' } } } } } } } tasks.named('asciidoctor').configure { dependsOn restDocsTest } } ================================================ FILE: clients/client-example/build.gradle ================================================ dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' implementation 'io.github.openfeign:feign-hc5' implementation 'io.github.openfeign:feign-micrometer' testImplementation 'com.fasterxml.jackson.core:jackson-databind' } ================================================ FILE: clients/client-example/src/main/java/io/dodn/springboot/client/example/ExampleApi.java ================================================ package io.dodn.springboot.client.example; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(value = "example-api", url = "${example.api.url}") interface ExampleApi { @RequestMapping(method = RequestMethod.POST, value = "/example/example-api", consumes = MediaType.APPLICATION_JSON_VALUE) ExampleResponseDto example(@RequestBody ExampleRequestDto request); } ================================================ FILE: clients/client-example/src/main/java/io/dodn/springboot/client/example/ExampleClient.java ================================================ package io.dodn.springboot.client.example; import io.dodn.springboot.client.example.model.ExampleClientResult; import org.springframework.stereotype.Component; @Component public class ExampleClient { private final ExampleApi exampleApi; public ExampleClient(ExampleApi exampleApi) { this.exampleApi = exampleApi; } public ExampleClientResult example(String exampleParameter) { ExampleRequestDto request = new ExampleRequestDto(exampleParameter); return exampleApi.example(request).toResult(); } } ================================================ FILE: clients/client-example/src/main/java/io/dodn/springboot/client/example/ExampleConfig.java ================================================ package io.dodn.springboot.client.example; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Configuration; @EnableFeignClients @Configuration class ExampleConfig { } ================================================ FILE: clients/client-example/src/main/java/io/dodn/springboot/client/example/ExampleRequestDto.java ================================================ package io.dodn.springboot.client.example; record ExampleRequestDto(String exampleRequestValue) { } ================================================ FILE: clients/client-example/src/main/java/io/dodn/springboot/client/example/ExampleResponseDto.java ================================================ package io.dodn.springboot.client.example; import io.dodn.springboot.client.example.model.ExampleClientResult; record ExampleResponseDto(String exampleResponseValue) { ExampleClientResult toResult() { return new ExampleClientResult(exampleResponseValue); } } ================================================ FILE: clients/client-example/src/main/java/io/dodn/springboot/client/example/model/ExampleClientResult.java ================================================ package io.dodn.springboot.client.example.model; public record ExampleClientResult(String exampleResult) { } ================================================ FILE: clients/client-example/src/main/resources/client-example.yml ================================================ example: api: url: https://default.example.example exampleValue: exampleDefaultValue spring.cloud.openfeign: client: config: example-api: connectTimeout: 2100 readTimeout: 5000 loggerLevel: full compression: response: enabled: false httpclient: max-connections: 2000 max-connections-per-route: 500 --- spring.config.activate.on-profile: local --- spring.config.activate.on-profile: - local-dev - dev --- spring.config.activate.on-profile: - staging - live example: api: url: https://live.example.example exampleValue: exampleLiveValue ================================================ FILE: clients/client-example/src/test/java/io/dodn/springboot/client/ClientExampleContextTest.java ================================================ package io.dodn.springboot.client; import org.junit.jupiter.api.Tag; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestConstructor; @ActiveProfiles("local") @Tag("context") @SpringBootTest @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) public abstract class ClientExampleContextTest { } ================================================ FILE: clients/client-example/src/test/java/io/dodn/springboot/client/ClientExampleTestApplication.java ================================================ package io.dodn.springboot.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @ConfigurationPropertiesScan @SpringBootApplication public class ClientExampleTestApplication { public static void main(String[] args) { SpringApplication.run(ClientExampleTestApplication.class, args); } } ================================================ FILE: clients/client-example/src/test/java/io/dodn/springboot/client/example/ExampleClientTest.java ================================================ package io.dodn.springboot.client.example; import static org.assertj.core.api.Assertions.assertThat; import feign.RetryableException; import io.dodn.springboot.client.ClientExampleContextTest; import org.junit.jupiter.api.Test; public class ExampleClientTest extends ClientExampleContextTest { private final ExampleClient exampleClient; public ExampleClientTest(ExampleClient exampleClient) { this.exampleClient = exampleClient; } @Test public void shouldBeThrownExceptionWhenExample() { try { exampleClient.example("HELLO!"); } catch (Exception e) { assertThat(e).isExactlyInstanceOf(RetryableException.class); } } } ================================================ FILE: clients/client-example/src/test/resources/application.yml ================================================ spring.application.name: client-example-test spring: config: import: - client-example.yml ================================================ FILE: core/core-api/build.gradle ================================================ bootJar.enabled = true jar.enabled = false dependencies { implementation project(":core:core-enum") implementation project(":support:monitoring") implementation project(":support:logging") implementation project(":storage:db-core") implementation project(":clients:client-example") testImplementation project(":tests:api-docs") implementation 'org.springframework.boot:spring-boot-starter-webmvc' } ================================================ FILE: core/core-api/src/docs/asciidoc/index.adoc ================================================ = API Docs :doctype: book :icons: font :source-highlighter: highlightjs :toc: left :toclevels: 3 :sectlinks: :snippets: build/generated-snippets == Introduce This is the Core API documentation. == Example API === Example GET API ==== Curl Request include::{snippets}/exampleGet/curl-request.adoc[] ==== Path Parameters include::{snippets}/exampleGet/path-parameters.adoc[] ==== Query Parameters include::{snippets}/exampleGet/query-parameters.adoc[] ==== Http Response include::{snippets}/exampleGet/http-response.adoc[] ==== Response Fields include::{snippets}/exampleGet/response-fields.adoc[] ''' === Example POST API ==== Curl Request include::{snippets}/examplePost/curl-request.adoc[] ==== Request Fields include::{snippets}/examplePost/request-fields.adoc[] ==== Http Response include::{snippets}/examplePost/http-response.adoc[] ==== Response Fields include::{snippets}/examplePost/response-fields.adoc[] ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/CoreApiApplication.java ================================================ package io.dodn.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @ConfigurationPropertiesScan @SpringBootApplication public class CoreApiApplication { public static void main(String[] args) { SpringApplication.run(CoreApiApplication.class, args); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/config/AsyncConfig.java ================================================ package io.dodn.springboot.core.api.config; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Bean @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(10); executor.setQueueCapacity(10000); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(10); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new AsyncExceptionHandler(); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/config/AsyncExceptionHandler.java ================================================ package io.dodn.springboot.core.api.config; import io.dodn.springboot.core.support.error.CoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import java.lang.reflect.Method; public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler { private final Logger log = LoggerFactory.getLogger(getClass()); @Override public void handleUncaughtException(Throwable e, Method method, Object... params) { if (e instanceof CoreException) { switch (((CoreException) e).getErrorType().getLogLevel()) { case ERROR -> log.error("CoreException : {}", e.getMessage(), e); case WARN -> log.warn("CoreException : {}", e.getMessage(), e); default -> log.info("CoreException : {}", e.getMessage(), e); } } else { log.error("Exception : {}", e.getMessage(), e); } } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/controller/ApiControllerAdvice.java ================================================ package io.dodn.springboot.core.api.controller; import io.dodn.springboot.core.support.error.CoreException; import io.dodn.springboot.core.support.error.ErrorType; import io.dodn.springboot.core.support.response.ApiResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class ApiControllerAdvice { private final Logger log = LoggerFactory.getLogger(getClass()); @ExceptionHandler(CoreException.class) public ResponseEntity> handleCoreException(CoreException e) { switch (e.getErrorType().getLogLevel()) { case ERROR -> log.error("CoreException : {}", e.getMessage(), e); case WARN -> log.warn("CoreException : {}", e.getMessage(), e); default -> log.info("CoreException : {}", e.getMessage(), e); } return new ResponseEntity<>(ApiResponse.error(e.getErrorType(), e.getData()), e.getErrorType().getStatus()); } @ExceptionHandler(Exception.class) public ResponseEntity> handleException(Exception e) { log.error("Exception : {}", e.getMessage(), e); return new ResponseEntity<>(ApiResponse.error(ErrorType.DEFAULT_ERROR), ErrorType.DEFAULT_ERROR.getStatus()); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/controller/HealthController.java ================================================ package io.dodn.springboot.core.api.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HealthController { @GetMapping("/health") public ResponseEntity health() { return ResponseEntity.status(HttpStatus.OK).build(); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/controller/v1/ExampleController.java ================================================ package io.dodn.springboot.core.api.controller.v1; import io.dodn.springboot.core.api.controller.v1.request.ExampleRequestDto; import io.dodn.springboot.core.api.controller.v1.response.ExampleItemResponseDto; import io.dodn.springboot.core.api.controller.v1.response.ExampleResponseDto; import io.dodn.springboot.core.domain.ExampleData; import io.dodn.springboot.core.domain.ExampleResult; import io.dodn.springboot.core.domain.ExampleService; import io.dodn.springboot.core.support.response.ApiResponse; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; import java.time.LocalDateTime; @RestController public class ExampleController { private final ExampleService exampleExampleService; public ExampleController(ExampleService exampleExampleService) { this.exampleExampleService = exampleExampleService; } @GetMapping("/get/{exampleValue}") public ApiResponse exampleGet(@PathVariable String exampleValue, @RequestParam String exampleParam) { ExampleResult result = exampleExampleService.processExample(new ExampleData(exampleValue, exampleParam)); return ApiResponse.success(new ExampleResponseDto(result.data(), LocalDate.now(), LocalDateTime.now(), ExampleItemResponseDto.build())); } @PostMapping("/post") public ApiResponse examplePost(@RequestBody ExampleRequestDto request) { ExampleResult result = exampleExampleService.processExample(request.toExampleData()); return ApiResponse.success(new ExampleResponseDto(result.data(), LocalDate.now(), LocalDateTime.now(), ExampleItemResponseDto.build())); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/controller/v1/request/ExampleRequestDto.java ================================================ package io.dodn.springboot.core.api.controller.v1.request; import io.dodn.springboot.core.domain.ExampleData; public record ExampleRequestDto(String data) { public ExampleData toExampleData() { return new ExampleData(data, data); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/controller/v1/response/ExampleItemResponseDto.java ================================================ package io.dodn.springboot.core.api.controller.v1.response; import java.util.List; public record ExampleItemResponseDto(String key) { public static List build() { return List.of(new ExampleItemResponseDto("1"), new ExampleItemResponseDto("2")); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/api/controller/v1/response/ExampleResponseDto.java ================================================ package io.dodn.springboot.core.api.controller.v1.response; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; public record ExampleResponseDto(String result, LocalDate date, LocalDateTime datetime, List items) { } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/domain/ExampleData.java ================================================ package io.dodn.springboot.core.domain; public record ExampleData(String value, String param) { } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/domain/ExampleResult.java ================================================ package io.dodn.springboot.core.domain; public record ExampleResult(String data) { } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/domain/ExampleService.java ================================================ package io.dodn.springboot.core.domain; import org.springframework.stereotype.Service; @Service public class ExampleService { public ExampleResult processExample(ExampleData exampleData) { return new ExampleResult(exampleData.value()); } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/support/error/CoreException.java ================================================ package io.dodn.springboot.core.support.error; public class CoreException extends RuntimeException { private final ErrorType errorType; private final Object data; public CoreException(ErrorType errorType) { super(errorType.getMessage()); this.errorType = errorType; this.data = null; } public CoreException(ErrorType errorType, Object data) { super(errorType.getMessage()); this.errorType = errorType; this.data = data; } public ErrorType getErrorType() { return errorType; } public Object getData() { return data; } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/support/error/ErrorCode.java ================================================ package io.dodn.springboot.core.support.error; public enum ErrorCode { E500 } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/support/error/ErrorMessage.java ================================================ package io.dodn.springboot.core.support.error; public class ErrorMessage { private final String code; private final String message; private final Object data; public ErrorMessage(ErrorType errorType) { this.code = errorType.getCode().name(); this.message = errorType.getMessage(); this.data = null; } public ErrorMessage(ErrorType errorType, Object data) { this.code = errorType.getCode().name(); this.message = errorType.getMessage(); this.data = data; } public String getCode() { return code; } public String getMessage() { return message; } public Object getData() { return data; } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/support/error/ErrorType.java ================================================ package io.dodn.springboot.core.support.error; import org.springframework.boot.logging.LogLevel; import org.springframework.http.HttpStatus; public enum ErrorType { DEFAULT_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.E500, "An unexpected error has occurred.", LogLevel.ERROR); private final HttpStatus status; private final ErrorCode code; private final String message; private final LogLevel logLevel; ErrorType(HttpStatus status, ErrorCode code, String message, LogLevel logLevel) { this.status = status; this.code = code; this.message = message; this.logLevel = logLevel; } public HttpStatus getStatus() { return status; } public ErrorCode getCode() { return code; } public String getMessage() { return message; } public LogLevel getLogLevel() { return logLevel; } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/support/response/ApiResponse.java ================================================ package io.dodn.springboot.core.support.response; import io.dodn.springboot.core.support.error.ErrorMessage; import io.dodn.springboot.core.support.error.ErrorType; public class ApiResponse { private final ResultType result; private final S data; private final ErrorMessage error; private ApiResponse(ResultType result, S data, ErrorMessage error) { this.result = result; this.data = data; this.error = error; } public static ApiResponse success() { return new ApiResponse<>(ResultType.SUCCESS, null, null); } public static ApiResponse success(S data) { return new ApiResponse<>(ResultType.SUCCESS, data, null); } public static ApiResponse error(ErrorType error) { return new ApiResponse<>(ResultType.ERROR, null, new ErrorMessage(error)); } public static ApiResponse error(ErrorType error, Object errorData) { return new ApiResponse<>(ResultType.ERROR, null, new ErrorMessage(error, errorData)); } public ResultType getResult() { return result; } public Object getData() { return data; } public ErrorMessage getError() { return error; } } ================================================ FILE: core/core-api/src/main/java/io/dodn/springboot/core/support/response/ResultType.java ================================================ package io.dodn.springboot.core.support.response; public enum ResultType { SUCCESS, ERROR } ================================================ FILE: core/core-api/src/main/resources/application.yml ================================================ spring.application.name: core-api spring.profiles.active: local spring: config: import: - monitoring.yml - logging.yml - db-core.yml - client-example.yml web.resources.add-mappings: false server: tomcat: max-connections: 20000 threads: max: 600 min-spare: 100 --- spring.config.activate.on-profile: local --- spring.config.activate.on-profile: local-dev --- spring.config.activate.on-profile: dev --- spring.config.activate.on-profile: staging --- spring.config.activate.on-profile: live ================================================ FILE: core/core-api/src/test/java/io/dodn/springboot/ContextTest.java ================================================ package io.dodn.springboot; import org.junit.jupiter.api.Tag; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestConstructor; @Tag("context") @SpringBootTest @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) public abstract class ContextTest { } ================================================ FILE: core/core-api/src/test/java/io/dodn/springboot/CoreApiApplicationTest.java ================================================ package io.dodn.springboot; import org.junit.jupiter.api.Test; public class CoreApiApplicationTest extends ContextTest { @Test public void shouldBeLoadedContext() { // it should be passed } } ================================================ FILE: core/core-api/src/test/java/io/dodn/springboot/DevelopTest.java ================================================ package io.dodn.springboot; import org.junit.jupiter.api.Tag; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestConstructor; @Tag("develop") @SpringBootTest @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) public abstract class DevelopTest { } ================================================ FILE: core/core-api/src/test/java/io/dodn/springboot/core/api/controller/v1/ExampleControllerTest.java ================================================ package io.dodn.springboot.core.api.controller.v1; import io.dodn.springboot.core.api.controller.v1.request.ExampleRequestDto; import io.dodn.springboot.core.domain.ExampleResult; import io.dodn.springboot.core.domain.ExampleService; import io.dodn.springboot.test.api.RestDocsTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.restdocs.operation.preprocess.Preprocessors; import org.springframework.restdocs.payload.JsonFieldType; import tools.jackson.databind.json.JsonMapper; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class ExampleControllerTest extends RestDocsTest { private ExampleService exampleService; @BeforeEach public void setUp() { exampleService = mock(ExampleService.class); mockMvc = mockController(new ExampleController(exampleService)); } @Test public void exampleGet() throws Exception { when(exampleService.processExample(any())).thenReturn(new ExampleResult("BYE")); mockMvc .perform(get("/get/{exampleValue}", "HELLO_PATH").param("exampleParam", "HELLO_PARAM") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("exampleGet", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), pathParameters(parameterWithName("exampleValue").description("ExampleValue")), queryParameters(parameterWithName("exampleParam").description("ExampleParam")), responseFields(fieldWithPath("result").type(JsonFieldType.STRING).description("ResultType"), fieldWithPath("data.result").type(JsonFieldType.STRING).description("Result Data"), fieldWithPath("data.date").type(JsonFieldType.STRING).description("Result Date"), fieldWithPath("data.datetime").type(JsonFieldType.STRING).description("Result Datetime"), fieldWithPath("data.items").type(JsonFieldType.ARRAY).description("Result Items"), fieldWithPath("data.items[].key").type(JsonFieldType.STRING).description("Result Item"), fieldWithPath("error").type(JsonFieldType.NULL).ignored()))); } @Test public void examplePost() throws Exception { when(exampleService.processExample(any())).thenReturn(new ExampleResult("BYE")); mockMvc .perform(post("/post").contentType(MediaType.APPLICATION_JSON) .content(JsonMapper.builder().build().writeValueAsString(new ExampleRequestDto("HELLO_BODY")))) .andExpect(status().isOk()) .andDo(document("examplePost", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), requestFields( fieldWithPath("data").type(JsonFieldType.STRING).description("ExampleBody Data Field")), responseFields(fieldWithPath("result").type(JsonFieldType.STRING).description("ResultType"), fieldWithPath("data.result").type(JsonFieldType.STRING).description("Result Data"), fieldWithPath("data.date").type(JsonFieldType.STRING).description("Result Date"), fieldWithPath("data.datetime").type(JsonFieldType.STRING).description("Result Datetime"), fieldWithPath("data.items").type(JsonFieldType.ARRAY).description("Result Items"), fieldWithPath("data.items[].key").type(JsonFieldType.STRING).description("Result Item"), fieldWithPath("error").type(JsonFieldType.STRING).ignored()))); } } ================================================ FILE: core/core-enum/build.gradle ================================================ ================================================ FILE: core/core-enum/src/main/java/io/dodn/springboot/core/enums/ExampleEnum.java ================================================ package io.dodn.springboot.core.enums; public enum ExampleEnum { } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ ### Application version ### applicationVersion=0.0.1-SNAPSHOT ### Project configs ### projectGroup=io.dodn.springboot javaVersion=25 ### Plugin dependency versions ### asciidoctorConvertVersion=4.0.5 springJavaFormatVersion=0.0.47 ### Spring dependency versions ### springBootVersion=4.0.0 springDependencyManagementVersion=1.1.7 springCloudDependenciesVersion=2025.1.0 ### External dependency versions ### sentryVersion=8.27.1 ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH= @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: lint.gradle ================================================ subprojects { apply plugin: 'java' apply plugin: 'io.spring.javaformat' dependencies { compileOnly "io.spring.javaformat:spring-javaformat-gradle-plugin:${springJavaFormatVersion}" } } ================================================ FILE: settings.gradle ================================================ pluginManagement { plugins { id 'org.springframework.boot' version "${springBootVersion}" id 'io.spring.dependency-management' version "${springDependencyManagementVersion}" id 'org.asciidoctor.jvm.convert' version "${asciidoctorConvertVersion}" id 'io.spring.javaformat' version "${springJavaFormatVersion}" } } rootProject.name = 'spring-boot-java-template' include 'core:core-enum' include 'core:core-api' include 'storage:db-core' include 'tests:api-docs' include 'support:logging' include 'support:monitoring' include 'clients:client-example' ================================================ FILE: storage/db-core/build.gradle ================================================ dependencies { implementation project(':core:core-enum') api 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.mysql:mysql-connector-j' runtimeOnly 'com.h2database:h2' } ================================================ FILE: storage/db-core/src/main/java/io/dodn/springboot/storage/db/core/BaseEntity.java ================================================ package io.dodn.springboot.storage.db.core; import jakarta.persistence.Column; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import java.time.LocalDateTime; @MappedSuperclass public abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @CreationTimestamp @Column private LocalDateTime createdAt; @UpdateTimestamp @Column private LocalDateTime updatedAt; public Long getId() { return id; } public LocalDateTime getCreatedAt() { return createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; } } ================================================ FILE: storage/db-core/src/main/java/io/dodn/springboot/storage/db/core/ExampleEntity.java ================================================ package io.dodn.springboot.storage.db.core; import jakarta.persistence.Column; import jakarta.persistence.Entity; @Entity public class ExampleEntity extends BaseEntity { @Column private String exampleColumn; public ExampleEntity() { } public ExampleEntity(String exampleColumn) { this.exampleColumn = exampleColumn; } public String getExampleColumn() { return exampleColumn; } } ================================================ FILE: storage/db-core/src/main/java/io/dodn/springboot/storage/db/core/ExampleRepository.java ================================================ package io.dodn.springboot.storage.db.core; import org.springframework.data.jpa.repository.JpaRepository; public interface ExampleRepository extends JpaRepository { } ================================================ FILE: storage/db-core/src/main/java/io/dodn/springboot/storage/db/core/config/CoreDataSourceConfig.java ================================================ package io.dodn.springboot.storage.db.core.config; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class CoreDataSourceConfig { @Bean @ConfigurationProperties(prefix = "storage.datasource.core") public HikariConfig coreHikariConfig() { return new HikariConfig(); } @Bean public HikariDataSource coreDataSource(@Qualifier("coreHikariConfig") HikariConfig config) { return new HikariDataSource(config); } } ================================================ FILE: storage/db-core/src/main/java/io/dodn/springboot/storage/db/core/config/CoreJpaConfig.java ================================================ package io.dodn.springboot.storage.db.core.config; import org.springframework.boot.persistence.autoconfigure.EntityScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @EntityScan(basePackages = "io.dodn.springboot.storage.db.core") @EnableJpaRepositories(basePackages = "io.dodn.springboot.storage.db.core") class CoreJpaConfig { } ================================================ FILE: storage/db-core/src/main/resources/db-core.yml ================================================ spring: jpa: open-in-view: false hibernate: ddl-auto: validate properties: hibernate.default_batch_fetch_size: 100 --- spring.config.activate.on-profile: local spring: jpa: hibernate: ddl-auto: create properties: hibernate: format_sql: true show_sql: true h2: console: enabled: true storage: datasource: core: driver-class-name: org.h2.Driver jdbc-url: jdbc:h2:mem:core;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE username: sa pool-name: core-db-pool data-source-properties: rewriteBatchedStatements: true --- spring.config.activate.on-profile: local-dev spring: jpa: properties: hibernate: format_sql: true show_sql: true storage: datasource: core: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://${storage.database.core-db.url} username: ${storage.database.core-db.username} password: ${storage.database.core-db.password} maximum-pool-size: 5 connection-timeout: 1100 keepalive-time: 30000 validation-timeout: 1000 max-lifetime: 600000 pool-name: core-db-pool data-source-properties: socketTimeout: 3000 cachePrepStmts: true prepStmtCacheSize: 250 prepStmtCacheSqlLimit: 2048 useServerPrepStmts: true useLocalSessionState: true rewriteBatchedStatements: true cacheResultSetMetadata: true cacheServerConfiguration: true elideSetAutoCommits: true maintainTimeStats: false --- spring.config.activate.on-profile: dev storage: datasource: core: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://${storage.database.core-db.url} username: ${storage.database.core-db.username} password: ${storage.database.core-db.password} maximum-pool-size: 5 connection-timeout: 1100 keepalive-time: 30000 validation-timeout: 1000 max-lifetime: 600000 pool-name: core-db-pool data-source-properties: socketTimeout: 3000 cachePrepStmts: true prepStmtCacheSize: 250 prepStmtCacheSqlLimit: 2048 useServerPrepStmts: true useLocalSessionState: true rewriteBatchedStatements: true cacheResultSetMetadata: true cacheServerConfiguration: true elideSetAutoCommits: true maintainTimeStats: false --- spring.config.activate.on-profile: staging storage: datasource: core: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://${storage.database.core-db.url} username: ${storage.database.core-db.username} password: ${storage.database.core-db.password} maximum-pool-size: 5 connection-timeout: 1100 keepalive-time: 30000 validation-timeout: 1000 max-lifetime: 600000 pool-name: core-db-pool data-source-properties: socketTimeout: 3000 cachePrepStmts: true prepStmtCacheSize: 250 prepStmtCacheSqlLimit: 2048 useServerPrepStmts: true useLocalSessionState: true rewriteBatchedStatements: true cacheResultSetMetadata: true cacheServerConfiguration: true elideSetAutoCommits: true maintainTimeStats: false --- spring.config.activate.on-profile: live storage: datasource: core: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://${storage.database.core-db.url} username: ${storage.database.core-db.username} password: ${storage.database.core-db.password} maximum-pool-size: 25 connection-timeout: 1100 keepalive-time: 30000 validation-timeout: 1000 max-lifetime: 600000 pool-name: core-db-pool data-source-properties: socketTimeout: 3000 cachePrepStmts: true prepStmtCacheSize: 250 prepStmtCacheSqlLimit: 2048 useServerPrepStmts: true useLocalSessionState: true rewriteBatchedStatements: true cacheResultSetMetadata: true cacheServerConfiguration: true elideSetAutoCommits: true maintainTimeStats: false ================================================ FILE: storage/db-core/src/test/java/io/dodn/springboot/storage/db/CoreDbContextTest.java ================================================ package io.dodn.springboot.storage.db; import org.junit.jupiter.api.Tag; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestConstructor; @ActiveProfiles("local") @Tag("context") @SpringBootTest @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) public abstract class CoreDbContextTest { } ================================================ FILE: storage/db-core/src/test/java/io/dodn/springboot/storage/db/CoreDbTestApplication.java ================================================ package io.dodn.springboot.storage.db; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @ConfigurationPropertiesScan @SpringBootApplication public class CoreDbTestApplication { public static void main(String[] args) { SpringApplication.run(CoreDbTestApplication.class, args); } } ================================================ FILE: storage/db-core/src/test/java/io/dodn/springboot/storage/db/core/ExampleRepositoryIT.java ================================================ package io.dodn.springboot.storage.db.core; import static org.assertj.core.api.Assertions.assertThat; import io.dodn.springboot.storage.db.CoreDbContextTest; import org.junit.jupiter.api.Test; public class ExampleRepositoryIT extends CoreDbContextTest { private final ExampleRepository exampleRepository; public ExampleRepositoryIT(ExampleRepository exampleRepository) { this.exampleRepository = exampleRepository; } @Test public void testShouldBeSavedAndFound() { ExampleEntity saved = exampleRepository.save(new ExampleEntity("SPRING_BOOT")); assertThat(saved.getExampleColumn()).isEqualTo("SPRING_BOOT"); ExampleEntity found = exampleRepository.findById(saved.getId()).get(); assertThat(found.getExampleColumn()).isEqualTo("SPRING_BOOT"); } } ================================================ FILE: storage/db-core/src/test/resources/application.yml ================================================ spring.application.name: db-core-test spring: config: import: - db-core.yml ================================================ FILE: support/logging/build.gradle ================================================ dependencies { implementation 'org.springframework.boot:spring-boot-starter-opentelemetry' implementation "io.sentry:sentry-logback:${property("sentryVersion")}" } ================================================ FILE: support/logging/src/main/resources/logback/logback-dev.xml ================================================ %clr(%d{HH:mm:ss.SSS}){faint}|%clr(${level:-%5p})|%32X{traceId:-},%16X{spanId:-}|%clr(%-40.40logger{39}){cyan}%clr(|){faint}%m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} utf8 YOUR_DSN WARN INFO ================================================ FILE: support/logging/src/main/resources/logback/logback-live.xml ================================================ %clr(%d{HH:mm:ss.SSS}){faint}|%clr(${level:-%5p})|%32X{traceId:-},%16X{spanId:-}|%clr(%-40.40logger{39}){cyan}%clr(|){faint}%m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} utf8 YOUR_DSN WARN INFO ================================================ FILE: support/logging/src/main/resources/logback/logback-local-dev.xml ================================================ %clr(%d{HH:mm:ss.SSS}){faint}|%clr(${level:-%5p})|%32X{traceId:-},%16X{spanId:-}|%clr(%-40.40logger{39}){cyan}%clr(|){faint}%m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} utf8 ================================================ FILE: support/logging/src/main/resources/logback/logback-local.xml ================================================ %clr(%d{HH:mm:ss.SSS}){faint}|%clr(${level:-%5p})|%32X{traceId:-},%16X{spanId:-}|%clr(%-40.40logger{39}){cyan}%clr(|){faint}%m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} utf8 ================================================ FILE: support/logging/src/main/resources/logback/logback-staging.xml ================================================ %clr(%d{HH:mm:ss.SSS}){faint}|%clr(${level:-%5p})|%32X{traceId:-},%16X{spanId:-}|%clr(%-40.40logger{39}){cyan}%clr(|){faint}%m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} utf8 YOUR_DSN WARN INFO ================================================ FILE: support/logging/src/main/resources/logging.yml ================================================ logging.config: classpath:logback/logback-${spring.profiles.active}.xml management.otlp.metrics.export.enabled: false ================================================ FILE: support/monitoring/build.gradle ================================================ dependencies { implementation 'org.springframework.boot:spring-boot-starter-actuator' runtimeOnly 'io.micrometer:micrometer-registry-prometheus' } ================================================ FILE: support/monitoring/src/main/resources/monitoring.yml ================================================ management: endpoints: web: exposure: include: prometheus ================================================ FILE: tests/api-docs/build.gradle ================================================ dependencies { api 'org.springframework.boot:spring-boot-restdocs' api 'org.springframework.restdocs:spring-restdocs-mockmvc' compileOnly 'org.junit.jupiter:junit-jupiter-api' } ================================================ FILE: tests/api-docs/src/main/java/io/dodn/springboot/test/api/RestDocsTest.java ================================================ package io.dodn.springboot.test.api; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @Tag("restdocs") @ExtendWith(RestDocumentationExtension.class) public abstract class RestDocsTest { protected MockMvc mockMvc; private RestDocumentationContextProvider restDocumentation; @BeforeEach public void setUp(RestDocumentationContextProvider restDocumentation) { this.restDocumentation = restDocumentation; } protected MockMvc mockController(Object controller) { return MockMvcBuilders.standaloneSetup(controller) .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation)) .build(); } }