diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..c71a673 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,21 @@ +version: 2 + +updates: + + # ================================ + # UPDATE GRADLE DEPENDENCIES + # ================================ + - package-ecosystem: gradle + directory: / + target-branch: develop + schedule: + interval: weekly + + # ================================ + # UPDATE GITHUB ACTIONS + # ================================ + - package-ecosystem: github-actions + directory: / + target-branch: develop + schedule: + interval: weekly diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..6c3fd86 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,59 @@ + +# Continuous Integration +name: Build + +on: + push: + branches: + - '*' + pull_request: + branches: + - main + - develop + +jobs: + build: + + name: Build + runs-on: ubuntu-latest + + steps: + + # ================================ + # SHALLOW CLONE + # ================================ + - name: Shallow clone + uses: actions/checkout@v4 + + # ================================ + # VALIDATE GRADLE WRAPPER + # ================================ + - name: Validate Gradle Wrapper files + uses: gradle/actions/wrapper-validation@v4 + + # ================================ + # SET UP JDK + # ================================ + - name: Set up JDK + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-package: jdk + java-version: 17 + + # ================================ + # SET UP GRADLE + # ================================ + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + with: + build-scan-publish: true + build-scan-terms-of-use-url: "https://gradle.com/help/legal-terms-of-use" + build-scan-terms-of-use-agree: "yes" + cache-read-only: ${{ github.ref_name != 'main' && github.ref_name != 'develop' }} + + # ================================ + # BUILD + # ================================ + - name: Build + run: ./gradlew build diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..b29f96d --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,49 @@ + +# Discover vulnerabilities with CodeQL +name: CodeQL + +on: + push: + branches: + - main + - develop + pull_request: + branches: + - main + - develop + schedule: + - cron: '0 8 * * 0' + +jobs: + analyze: + + name: Analyze Java + runs-on: ubuntu-latest + timeout-minutes: 360 + permissions: + security-events: write + + steps: + + # ================================ + # SHALLOW CLONE + # ================================ + - name: Shallow clone + uses: actions/checkout@v4 + + # ================================ + # SET UP CODEQL + # ================================ + - name: Set up CodeQL + uses: github/codeql-action/init@v3 + with: + languages: java-kotlin + build-mode: autobuild + + # ================================ + # ANALYZE + # ================================ + - name: Analyze with CodeQL + uses: github/codeql-action/analyze@v3 + with: + category: "/language:java-kotlin" diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml new file mode 100644 index 0000000..e3cd1b5 --- /dev/null +++ b/.github/workflows/dependencies.yml @@ -0,0 +1,41 @@ + +# Submit dependencies +name: Dependencies + +on: + push: + branches: + - main + +permissions: + contents: write + +jobs: + dependencies: + + name: Submit dependencies + runs-on: ubuntu-latest + + steps: + + # ================================ + # SHALLOW CLONE + # ================================ + - name: Shallow clone + uses: actions/checkout@v4 + + # ================================ + # SET UP JDK + # ================================ + - name: Set up JDK + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-package: jdk + java-version: 17 + + # ================================ + # SUBMIT DEPENDENCIES + # ================================ + - name: Generate and submit dependency graph + uses: gradle/actions/dependency-submission@v4 diff --git a/.github/workflows/update-gradle-wrapper.yml b/.github/workflows/update-gradle-wrapper.yml new file mode 100644 index 0000000..dd02cde --- /dev/null +++ b/.github/workflows/update-gradle-wrapper.yml @@ -0,0 +1,42 @@ + +# Schedule Gradle Wrapper updates +name: Update Gradle Wrapper + +on: + schedule: + - cron: "0 8 * * *" + workflow_dispatch: + +jobs: + update-gradle-wrapper: + + name: Update Gradle Wrapper + runs-on: ubuntu-latest + + steps: + + # ================================ + # SHALLOW CLONE + # ================================ + - name: Shallow clone + uses: actions/checkout@v4 + + # ================================ + # SET UP JDK + # ================================ + - name: Set up JDK + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-package: jdk + java-version: 17 + + # ================================ + # UPDATE GRADLE WRAPPER + # ================================ + - name: Update Gradle Wrapper + uses: gradle-update/update-gradle-wrapper-action@v1 + with: + release-channel: stable + base-branch: develop + target-branch: develop diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..253c019 --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +Copyright 2024 Guillermo Calvo + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2102797 --- /dev/null +++ b/README.md @@ -0,0 +1,124 @@ + +[![Build Status][BADGE_BUILD_STATUS]][BUILD_STATUS] +[![Gradle][BADGE_GRADLE]][GRADLE] +[![Spring Boot][BADGE_SPRING_BOOT]][SPRING_BOOT] +[![Maven Central][BADGE_RESULT_ARTIFACTS]][RESULT_ARTIFACTS] +[![Benchmark Report][BADGE_BENCHMARK]][BENCHMARK] + + +# Example Spring Boot Application Using Results + +This is a simple implementation of a [Petstore][PET_STORE] server powered by [Spring Boot][SPRING_BOOT]. + +The purpose of this example application is to demonstrate how to make use of [Result][RESULT_LIBRARY] libraries in +projects based on Spring Boot. For the sake of brevity, the Petstore spec is implemented partially. + + +## Getting Started + +Build and run the application. + +```shell +./gradlew bootRun +``` + +This will start a stand-alone server on port 8080. + + +## Testing the Server + +Once started, you can interact with the API. + +```shell +curl -s -H 'x-type: local' http://localhost:8080/pet/0 +``` + +You should see a JSON response like this: + +```json +{"version":"1.0","result":{"success":{"id":0,"name":"Rocky","status":"AVAILABLE"}}} +``` + + +## Using Swagger-UI + +You can navigate to to inspect the API using an interactive UI. + +![Swagger-UI](swagger-ui.png) + + +## Looking for Support? + +We'd love to help. Check out the [support guidelines][SUPPORT]. + + +## Contributions Welcome + +If you'd like to contribute to this project, please [start here][CONTRIBUTING]. + + +## Code of Conduct + +This project is governed by the [Contributor Covenant Code of Conduct][CODE_OF_CONDUCT]. +By participating, you are expected to uphold this code. + + +## Author + +Copyright 2024 [Guillermo Calvo][AUTHOR]. + +[![][GUILLERMO_IMAGE]][GUILLERMO] + + +## License + +This library is licensed under the *Apache License, Version 2.0* (the "License"); +you may not use it except in compliance with the License. + +You may obtain a copy of the License at + +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. + + +**Permitted:** + +- **Commercial Use**: You may use this library and derivatives for commercial purposes. +- **Modification**: You may modify this library. +- **Distribution**: You may distribute this library. +- **Patent Use**: This license provides an express grant of patent rights from contributors. +- **Private Use**: You may use and modify this library without distributing it. + +**Required:** + +- **License and Copyright Notice**: If you distribute this library you must include a copy of the license and copyright + notice. +- **State Changes**: If you modify and distribute this library you must document changes made to this library. + +**Forbidden:** + +- **Trademark use**: This license does not grant any trademark rights. +- **Liability**: The library author cannot be held liable for damages. +- **Warranty**: This library is provided without any warranty. + + +[AUTHOR]: https://github.com/guillermocalvo/ +[BADGE_BENCHMARK]: https://img.shields.io/endpoint?url=https://dev.leakyabstractions.com/result-benchmark/badge.json&style=flat +[BADGE_BUILD_STATUS]: https://github.com/leakyabstractions/result-example-spring-boot/workflows/Build/badge.svg +[BADGE_GRADLE]: https://img.shields.io/badge/Gradle-1FAEC9?logo=Gradle&logoColor=white +[BADGE_RESULT_ARTIFACTS]: https://img.shields.io/endpoint?url=https://dev.leakyabstractions.com/result/badge.json +[BADGE_SPRING_BOOT]: https://img.shields.io/badge/Spring%20Boot-6DB33F?logo=Spring&logoColor=white +[BENCHMARK]: https://dev.leakyabstractions.com/result-benchmark/ +[BUILD_STATUS]: https://github.com/LeakyAbstractions/result-example-spring-boot/actions?query=workflow%3ABuild +[CODE_OF_CONDUCT]: https://dev.leakyabstractions.com/result/CODE_OF_CONDUCT.html +[CONTRIBUTING]: https://dev.leakyabstractions.com/result/CONTRIBUTING.html +[GRADLE]: https://gradle.org/ +[GUILLERMO]: https://guillermo.dev/ +[GUILLERMO_IMAGE]: https://guillermo.dev/assets/images/thumb.png +[PET_STORE]: https://petstore.swagger.io/ +[RESULT_ARTIFACTS]: https://search.maven.org/artifact/com.leakyabstractions/result/ +[RESULT_LIBRARY]: https://github.com/LeakyAbstractions/result +[SPRING_BOOT]: https://spring.io/projects/spring-boot +[SUPPORT]: https://dev.leakyabstractions.com/result/SUPPORT.html diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..2d14a79 --- /dev/null +++ b/build.gradle @@ -0,0 +1,46 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.3' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'com.leakyabstractions' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +ext { + set('springCloudVersion', "2023.0.2") +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0' + implementation platform('com.leakyabstractions:result-bom:1.0.0.0') + implementation 'com.leakyabstractions:result' + implementation 'com.leakyabstractions:result-jackson' + implementation 'com.leakyabstractions:result-lazy' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'com.leakyabstractions:result-assertj' + testImplementation 'org.assertj:assertj-core' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2b18997 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=5b9c5eb3f9fc2c94abaea57d90bd78747ca117ddbbf96c859d3741181a12bf2a +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/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 +' "$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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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, 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" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +: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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..a001018 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'result-example-spring-boot' diff --git a/src/main/java/com/example/ExampleApplication.java b/src/main/java/com/example/ExampleApplication.java new file mode 100644 index 0000000..90e62f7 --- /dev/null +++ b/src/main/java/com/example/ExampleApplication.java @@ -0,0 +1,47 @@ +package com.example; + +import io.swagger.v3.oas.annotations.*; +import io.swagger.v3.oas.annotations.info.*; +import io.swagger.v3.oas.annotations.servers.Server; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@OpenAPIDefinition( + info = @Info( + title = "Result Petstore", + description = "Example Micronaut application using results", + version = "1.0", + contact = @Contact( + url = "https://guillermo.dev", + name = "Guillermo Calvo", + email = "hello@guillermo.dev" + ), + license = @License( + name = "Apache 2.0", + url = "http://www.apache.org/licenses/LICENSE-2.0.html" + ) + ), + externalDocs = @ExternalDocumentation( + description = "Find out more about Result library for Java", + url = "https://dev.leakyabstractions.com/result/" + ), + tags = @Tag( + name = "pet", + description = "Everything about your Pets" + ), + servers = @Server( + url = "http://localhost:8080", + description = "DEV" + ) +) +@SpringBootApplication +@EnableFeignClients +public class ExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(ExampleApplication.class, args); + } + +} diff --git a/src/main/java/com/example/api/ApiError.java b/src/main/java/com/example/api/ApiError.java new file mode 100644 index 0000000..cf38997 --- /dev/null +++ b/src/main/java/com/example/api/ApiError.java @@ -0,0 +1,70 @@ +package com.example.api; + +import com.fasterxml.jackson.annotation.*; +import feign.FeignException; +import io.swagger.v3.oas.annotations.media.Schema; + +import static com.example.api.ApiErrorCode.*; + +/** + * Pet API error. + */ +@Schema(description = "Pet API Error") +public class ApiError { + + @JsonProperty + @Schema(description = "Error code") + public ApiErrorCode code; + + @JsonProperty + @Schema(description = "Error message") + public String message; + + @JsonCreator + public ApiError() { + } + + public ApiError(ApiErrorCode code, String message) { + setCode(code); + setMessage(message); + } + + public static ApiError notFound(Long id) { + return new ApiError(PET_NOT_FOUND, "Pet not found: " + id); + } + + public static ApiError unexpected(Exception ex) { + return new ApiError(UNEXPECTED_ERROR, ex.getMessage()); + } + + public static ApiError remote(Exception ex) { + if (ex instanceof FeignException http && http.status() == 404) { + return new ApiError(REMOTE_PET_NOT_FOUND, "Remote pet not found"); + } + return new ApiError(UNEXPECTED_REMOTE_ERROR, "Remote error: " + ex.getMessage()); + } + + public static ApiError unavailable(RepositoryType type) { + return new ApiError(PET_STORE_UNAVAILABLE, type.toString() + " is unavailable"); + } + + @JsonGetter + public ApiErrorCode getCode() { + return code; + } + + @JsonSetter + public void setCode(ApiErrorCode code) { + this.code = code; + } + + @JsonGetter + public String getMessage() { + return message; + } + + @JsonSetter + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/example/api/ApiErrorCode.java b/src/main/java/com/example/api/ApiErrorCode.java new file mode 100644 index 0000000..146fc8c --- /dev/null +++ b/src/main/java/com/example/api/ApiErrorCode.java @@ -0,0 +1,16 @@ +package com.example.api; + +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * Pet API error code. + */ +@Schema(description = "Pet API error code", example = "PET_NOT_FOUND") +public enum ApiErrorCode { + + PET_NOT_FOUND, + REMOTE_PET_NOT_FOUND, + PET_STORE_UNAVAILABLE, + UNEXPECTED_ERROR, + UNEXPECTED_REMOTE_ERROR; +} diff --git a/src/main/java/com/example/api/ApiResponse.java b/src/main/java/com/example/api/ApiResponse.java new file mode 100644 index 0000000..9168f8b --- /dev/null +++ b/src/main/java/com/example/api/ApiResponse.java @@ -0,0 +1,71 @@ +package com.example.api; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.leakyabstractions.result.api.Result; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.time.Instant; + +/** + * Pet API response. + * + * @param the type of success + */ +@Schema(description = "Pet API Response") +public class ApiResponse { + + @Schema(description = "API version number", example = "1.0") + @JsonProperty + String version; + + @Schema(description = "Generation date/time", example = "1980-07-07T12:30:00.123Z") + @JsonProperty + Instant generatedOn; + + @Schema(description = "Contains either a success value or a failure value") + @JsonProperty + Result result; + + @JsonCreator + public ApiResponse() { + } + + public ApiResponse(String version, Result result) { + setVersion(version); + setGeneratedOn(Instant.now()); + setResult(result); + } + + @JsonGetter + public String getVersion() { + return version; + } + + @JsonSetter + public void setVersion(String version) { + this.version = version; + } + + @JsonGetter + public Instant getGeneratedOn() { + return generatedOn; + } + + @JsonSetter + public void setGeneratedOn(Instant generatedOn) { + this.generatedOn = generatedOn; + } + + @JsonGetter + public Result getResult() { + return result; + } + + @JsonSetter + public void setResult(Result result) { + this.result = result; + } +} diff --git a/src/main/java/com/example/api/Pet.java b/src/main/java/com/example/api/Pet.java new file mode 100644 index 0000000..2710023 --- /dev/null +++ b/src/main/java/com/example/api/Pet.java @@ -0,0 +1,67 @@ +package com.example.api; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonSetter; +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * Pet in a store. + */ +@Schema(name = "Pet", description = "Pet in a store") +public class Pet { + + @Schema(description = "Pet identifier", example = "123") + Long id; + + @Schema(description = "Pet name", example = "Doggie") + String name; + + @Schema(description = "Pet status", example = "available") + PetStatus status; + + @JsonCreator + public Pet() { + } + + public Pet(Long id, String name, PetStatus status) { + setId(id); + setName(name); + setStatus(status); + } + + @JsonGetter + public Long getId() { + return id; + } + + @JsonSetter + public void setId(Long id) { + this.id = id; + } + + @JsonGetter + public String getName() { + return name; + } + + @JsonSetter + public void setName(String name) { + this.name = name; + } + + @JsonGetter + public PetStatus getStatus() { + return status; + } + + @JsonSetter + public void setStatus(PetStatus status) { + this.status = status; + } + + @Override + public String toString() { + return "Pet#" + id + "(" + name + "/" + status + ")"; + } +} diff --git a/src/main/java/com/example/api/PetStatus.java b/src/main/java/com/example/api/PetStatus.java new file mode 100644 index 0000000..1272a27 --- /dev/null +++ b/src/main/java/com/example/api/PetStatus.java @@ -0,0 +1,21 @@ +package com.example.api; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * Pet status in a store. + */ +@Schema(description = "Pet status in the store", example = "available") +@SuppressWarnings("unused") +public enum PetStatus { + + @JsonProperty("available") + AVAILABLE, + + @JsonProperty("pending") + PENDING, + + @JsonProperty("sold") + SOLD +} diff --git a/src/main/java/com/example/api/RepositoryType.java b/src/main/java/com/example/api/RepositoryType.java new file mode 100644 index 0000000..b99250b --- /dev/null +++ b/src/main/java/com/example/api/RepositoryType.java @@ -0,0 +1,20 @@ +package com.example.api; + +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * Pet repository type. + */ +@Schema(description = "Type of pet repository", example = "LOCAL") +public enum RepositoryType { + + LOCAL, + + GITHUB, + + LOOPBACK, + + SWAGGER, + + SPECIAL +} diff --git a/src/main/java/com/example/client/GithubClient.java b/src/main/java/com/example/client/GithubClient.java new file mode 100644 index 0000000..7ada1e5 --- /dev/null +++ b/src/main/java/com/example/client/GithubClient.java @@ -0,0 +1,30 @@ +package com.example.client; + +import com.example.api.ApiResponse; +import com.example.api.Pet; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.Collection; + +/** + * Github HTTP client. + */ +@FeignClient(value = "github", path = "/result-example-spring-boot/src/test/resources/static") +public interface GithubClient { + + @GetMapping("/all.json") + ApiResponse> remoteList(); + + @GetMapping("/{id}.json") + ApiResponse remoteFindById(@PathVariable Long id); + + @DeleteMapping("/{id}.json") + ApiResponse remoteDeleteById(@PathVariable Long id); + + @PostMapping + ApiResponse remoteCreate(@RequestBody Pet pet); + + @PutMapping + ApiResponse remoteUpdate(@RequestBody Pet pet); +} diff --git a/src/main/java/com/example/client/LoopbackClient.java b/src/main/java/com/example/client/LoopbackClient.java new file mode 100644 index 0000000..4a453eb --- /dev/null +++ b/src/main/java/com/example/client/LoopbackClient.java @@ -0,0 +1,30 @@ +package com.example.client; + +import com.example.api.ApiResponse; +import com.example.api.Pet; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.Collection; + +/** + * Loopback HTTP client. + */ +@FeignClient(value = "loopback", path = "/pet", primary = false) +public interface LoopbackClient { + + @GetMapping + ApiResponse> remoteList(); + + @GetMapping("/{id}") + ApiResponse remoteFindById(@PathVariable Long id); + + @DeleteMapping("/{id}") + ApiResponse remoteDeleteById(@PathVariable Long id); + + @PostMapping + ApiResponse remoteCreate(@RequestBody Pet pet); + + @PutMapping + ApiResponse remoteUpdate(@RequestBody Pet pet); +} diff --git a/src/main/java/com/example/client/SwaggerClient.java b/src/main/java/com/example/client/SwaggerClient.java new file mode 100644 index 0000000..13e656a --- /dev/null +++ b/src/main/java/com/example/client/SwaggerClient.java @@ -0,0 +1,30 @@ +package com.example.client; + +import com.example.api.Pet; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * Swagger HTTP client. + */ +@FeignClient(value = "swagger", path = "/v2/pet") +public interface SwaggerClient { + + @GetMapping("/findByStatus?status=available,pending,sold") + List remoteList(); + + @GetMapping("/{id}") + Pet remoteFindById(@PathVariable Long id); + + @DeleteMapping("/{id}") + ResponseEntity remoteDeleteById(@PathVariable Long id); + + @PostMapping + Pet remoteCreate(@RequestBody Pet pet); + + @PutMapping + Pet remoteUpdate(@RequestBody Pet pet); +} diff --git a/src/main/java/com/example/config/JacksonConfig.java b/src/main/java/com/example/config/JacksonConfig.java new file mode 100644 index 0000000..cb62d7f --- /dev/null +++ b/src/main/java/com/example/config/JacksonConfig.java @@ -0,0 +1,18 @@ +package com.example.config; + +import com.fasterxml.jackson.databind.Module; +import com.leakyabstractions.result.jackson.ResultModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Registers Jackson datatype module for Result. + */ +@Configuration +public class JacksonConfig { + + @Bean + public Module registerResultModule() { + return new ResultModule(); + } +} diff --git a/src/main/java/com/example/config/PetStoreConfig.java b/src/main/java/com/example/config/PetStoreConfig.java new file mode 100644 index 0000000..0e36b7c --- /dev/null +++ b/src/main/java/com/example/config/PetStoreConfig.java @@ -0,0 +1,51 @@ +package com.example.config; + +import com.example.api.Pet; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static java.util.function.Function.identity; + +/** + * Local pet store configuration. + */ +@Configuration +@ConfigurationProperties(prefix = "pet-store") +public class PetStoreConfig { + + String apiVersion; + boolean enabled; + List pets; + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getApiVersion() { + return apiVersion; + } + + public void setApiVersion(String apiVersion) { + this.apiVersion = apiVersion; + } + + public boolean isLocalEnabled() { + return enabled; + } + + public List getPets() { + return pets; + } + + public void setPets(List pets) { + this.pets = pets; + } + + public Map getPetsAsMap() { + return pets.stream().collect(Collectors.toMap(Pet::getId, identity())); + } +} diff --git a/src/main/java/com/example/controller/IndexController.java b/src/main/java/com/example/controller/IndexController.java new file mode 100644 index 0000000..d0fde38 --- /dev/null +++ b/src/main/java/com/example/controller/IndexController.java @@ -0,0 +1,21 @@ +package com.example.controller; + +import io.swagger.v3.oas.annotations.Hidden; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +import java.io.IOException; + +/** + * Redirects to Swagger UI. + */ +@Hidden +@Controller +public class IndexController { + + @GetMapping("/") + public void index(HttpServletResponse response) throws IOException { + response.sendRedirect("/swagger-ui/index.html"); + } +} diff --git a/src/main/java/com/example/controller/PetController.java b/src/main/java/com/example/controller/PetController.java new file mode 100644 index 0000000..cc899fe --- /dev/null +++ b/src/main/java/com/example/controller/PetController.java @@ -0,0 +1,113 @@ +package com.example.controller; + +import com.example.api.ApiError; +import com.example.api.ApiResponse; +import com.example.api.Pet; +import com.example.api.RepositoryType; +import com.example.config.PetStoreConfig; +import com.example.repository.PetRepository; +import com.leakyabstractions.result.api.Result; +import com.leakyabstractions.result.core.Results; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import org.slf4j.Logger; +import org.springframework.web.bind.annotation.*; + +import java.util.Collection; +import java.util.Optional; + +import static org.slf4j.LoggerFactory.getLogger; + +/** + * Interacts with different pet repositories. + */ +@RestController +@Tag(name = "pet") +public class PetController { + + static final Logger log = getLogger(PetController.class); + + final PetStoreConfig config; + final Collection repositories; + + PetController(PetStoreConfig config, Collection repositories) { + this.config = config; + this.repositories = repositories; + } + + @GetMapping("/pet") + @Operation(summary = "List all pets", description = "Returns all pets in a store") + ApiResponse> list(@RequestHeader("X-Type") RepositoryType type) { + log.info("List all pets in {} pet store", type); + return response(locate(type) + .flatMapSuccess(PetRepository::listPets) + .ifSuccess(x -> log.info("Listed {} pet(s) in {}", x.size(), type)) + .ifFailure(this::logError)); + } + + @PostMapping("/pet") + @Operation(summary = "Add new pet", description = "Adds a new pet to a store") + ApiResponse create( + @RequestHeader("X-Type") RepositoryType type, + @RequestBody @Valid Pet pet) { + log.info("Create new pet: {} in {} pet store", pet, type); + return response(locate(type) + .flatMapSuccess(x -> x.createPet(pet)) + .ifSuccess(x -> log.info("Created pet #{} in {}", x.getId(), type)) + .ifFailure(this::logError)); + } + + @PutMapping("/pet") + @Operation(summary = "Update existing pet", description = "Updates an existing pet in a store") + ApiResponse update( + @RequestHeader("X-Type") RepositoryType type, + @RequestBody @Valid Pet pet) { + log.info("Update pet: {} in {} pet store", pet, type); + return response(locate(type) + .flatMapSuccess(x -> x.updatePet(pet)) + .ifSuccess(x -> log.info("Updated #{} in {}: {}", x.getId(), type, x)) + .ifFailure(this::logError)); + } + + @GetMapping("/pet/{id}") + @Operation(summary = "Find pet", description = "Returns a single pet by ID") + ApiResponse find( + @RequestHeader("X-Type") RepositoryType type, + @PathVariable @Parameter(description = "Pet ID to find") Long id) { + log.info("Find pet by ID: {} in {} pet store", id, type); + return response(locate(type) + .flatMapSuccess(x -> x.findPet(id)) + .ifSuccess(x -> log.info("Found #{} in {}: {}", id, type, x)) + .ifFailure(this::logError)); + } + + @DeleteMapping("/pet/{id}") + @Operation(summary = "Delete pet", description = "Deletes a pet by ID") + ApiResponse delete( + @RequestHeader("X-Type") RepositoryType type, + @PathVariable @Parameter(description = "Pet ID to delete") Long id) { + log.info("Delete pet by ID: {} from {} pet store", id, type); + return response(locate(type) + .flatMapSuccess(x -> x.deletePet(id)) + .ifSuccessOrElse(x -> log.info("Deleted #{} from {}", id, type), this::logError)); + } + + Result locate(RepositoryType type) { + final Optional repository = repositories.stream() + .filter(x -> x.getType() == type) + .findAny(); + return Results.ofOptional(repository, () -> ApiError.unavailable(type)).ifSuccessOrElse( + x -> log.info("{} pet store located", type), + x -> log.warn("Could not locate {} pet store", type)); + } + + private void logError(ApiError error) { + log.error(error.getMessage()); + } + + private ApiResponse response(Result result) { + return new ApiResponse<>(config.getApiVersion(), result); + } +} diff --git a/src/main/java/com/example/repository/GithubRepository.java b/src/main/java/com/example/repository/GithubRepository.java new file mode 100644 index 0000000..8e14498 --- /dev/null +++ b/src/main/java/com/example/repository/GithubRepository.java @@ -0,0 +1,61 @@ +package com.example.repository; + +import com.example.api.ApiError; +import com.example.api.Pet; +import com.example.client.GithubClient; +import com.leakyabstractions.result.api.Result; +import org.slf4j.Logger; +import org.springframework.stereotype.Service; + +import java.util.Collection; + +import static com.example.api.RepositoryType.GITHUB; +import static org.slf4j.LoggerFactory.getLogger; + +/** + * Implements the GitHub pet repository. + * + *

Accesses static Github pages.

+ */ +@Service +class GithubRepository extends RemoteRepository { + + static final Logger log = getLogger(GithubRepository.class); + + final GithubClient github; + + GithubRepository(GithubClient github) { + super(GITHUB); + this.github = github; + } + + @Override + public Result, ApiError> listPets() { + log.info("List GitHub pets"); + return evaluate(github::remoteList); + } + + @Override + public Result createPet(Pet pet) { + log.info("Create GitHub pet: {}", pet); + return evaluate(() -> github.remoteCreate(pet)); + } + + @Override + public Result updatePet(Pet pet) { + log.info("Update GitHub pet: {}", pet); + return evaluate(() -> github.remoteUpdate(pet)); + } + + @Override + public Result findPet(Long id) { + log.info("Find GitHub pet by ID: {}", id); + return evaluate(() -> github.remoteFindById(id)); + } + + @Override + public Result deletePet(Long id) { + log.info("Delete GitHub pet by ID: {}", id); + return evaluate(() -> github.remoteDeleteById(id)); + } +} diff --git a/src/main/java/com/example/repository/LocalRepository.java b/src/main/java/com/example/repository/LocalRepository.java new file mode 100644 index 0000000..8840596 --- /dev/null +++ b/src/main/java/com/example/repository/LocalRepository.java @@ -0,0 +1,82 @@ +package com.example.repository; + +import com.example.api.ApiError; +import com.example.api.Pet; +import com.example.api.RepositoryType; +import com.example.config.PetStoreConfig; +import com.leakyabstractions.result.api.Result; +import com.leakyabstractions.result.core.Results; +import org.slf4j.Logger; +import org.springframework.stereotype.Service; + +import java.util.Collection; +import java.util.Map; + +import static com.example.api.RepositoryType.LOCAL; +import static java.lang.Boolean.TRUE; +import static org.slf4j.LoggerFactory.getLogger; + +/** + * Implements the local pet repository. + * + *

Maintains an in-memory collection of pets that can be manipulated.

+ */ +@Service +class LocalRepository implements PetRepository { + + static final Logger log = getLogger(LocalRepository.class); + + final Result, ApiError> pets; + + public LocalRepository(PetStoreConfig config) { + pets = Results.success(config) + .filter(PetStoreConfig::isLocalEnabled, x -> ApiError.unavailable(LOCAL)) + .mapSuccess(PetStoreConfig::getPetsAsMap); + } + + @Override + public RepositoryType getType() { + return LOCAL; + } + + @Override + public Result, ApiError> listPets() { + log.info("List Local pets"); + return pets.mapSuccess(Map::values); + } + + @Override + public Result createPet(Pet pet) { + log.info("Create Local pet: {}", pet); + return pets.flatMapSuccess(db -> { + final Long id = db.keySet().stream().mapToLong(Long.class::cast).max().orElse(0L) + 1; + pet.setId(id); + return Results.ofCallable(() -> db.put(id, pet) != null) + .map(x -> pet, ApiError::unexpected); + }); + } + + @Override + public Result updatePet(Pet pet) { + final Long id = pet.getId(); + log.info("Update Local pet #{}: {}", id, pet); + return pets.flatMapSuccess(db -> Results.ofCallable(() -> db.replace(id, pet) != null) + .mapFailure(ApiError::unexpected) + .filter(TRUE::equals, x -> ApiError.notFound(id)) + .mapSuccess(x -> pet)); + } + + @Override + public Result findPet(Long id) { + log.info("Find Local pet by ID: {}", id); + return pets.flatMapSuccess(db -> Results.ofNullable(db.get(id), () -> ApiError.notFound(id))); + } + + @Override + public Result deletePet(Long id) { + log.info("Delete Local pet by ID: {}", id); + return pets.flatMapSuccess(db -> Results.ofCallable(() -> db.remove(id) != null) + .mapFailure(ApiError::unexpected) + .filter(TRUE::equals, x -> ApiError.notFound(id))); + } +} diff --git a/src/main/java/com/example/repository/LoopbackRepository.java b/src/main/java/com/example/repository/LoopbackRepository.java new file mode 100644 index 0000000..9083acb --- /dev/null +++ b/src/main/java/com/example/repository/LoopbackRepository.java @@ -0,0 +1,61 @@ +package com.example.repository; + +import com.example.api.ApiError; +import com.example.api.Pet; +import com.example.client.LoopbackClient; +import com.leakyabstractions.result.api.Result; +import org.slf4j.Logger; +import org.springframework.stereotype.Service; + +import java.util.Collection; + +import static com.example.api.RepositoryType.LOOPBACK; +import static org.slf4j.LoggerFactory.getLogger; + +/** + * Implements the loopback pet repository. + * + *

Interacts with the local pet store via HTTP.

+ */ +@Service +class LoopbackRepository extends RemoteRepository implements PetRepository { + + static final Logger log = getLogger(LoopbackRepository.class); + + final LoopbackClient loopback; + + LoopbackRepository(LoopbackClient loopback) { + super(LOOPBACK); + this.loopback = loopback; + } + + @Override + public Result createPet(Pet pet) { + log.info("Create Loopback pet: {}", pet); + return evaluate(() -> loopback.remoteCreate(pet)); + } + + @Override + public Result, ApiError> listPets() { + log.info("List Loopback pets"); + return evaluate(loopback::remoteList); + } + + @Override + public Result updatePet(Pet pet) { + log.info("Update Loopback pet: {}", pet); + return evaluate(() -> loopback.remoteUpdate(pet)); + } + + @Override + public Result findPet(Long id) { + log.info("Find Loopback pet by ID: {}", id); + return evaluate(() -> loopback.remoteFindById(id)); + } + + @Override + public Result deletePet(Long id) { + log.info("Delete Loopback pet by ID: {}", id); + return evaluate(() -> loopback.remoteDeleteById(id)); + } +} diff --git a/src/main/java/com/example/repository/PetRepository.java b/src/main/java/com/example/repository/PetRepository.java new file mode 100644 index 0000000..e5bfb17 --- /dev/null +++ b/src/main/java/com/example/repository/PetRepository.java @@ -0,0 +1,60 @@ +package com.example.repository; + +import com.example.api.ApiError; +import com.example.api.Pet; +import com.example.api.RepositoryType; +import com.leakyabstractions.result.api.Result; + +import java.util.Collection; + +/** + * Represents a pet repository. + */ +public interface PetRepository { + + /** + * Returns the type of this repository. + * + * @return the type of this repository + */ + RepositoryType getType(); + + /** + * Returns all pets in this repository. + * + * @return all pets in this repository + */ + Result, ApiError> listPets(); + + /** + * Adds a new pet to this repository + * + * @param pet The pet to add + * @return The added pet + */ + Result createPet(Pet pet); + + /** + * Updates an existing pet in this repository. + * + * @param pet The pet to update + * @return The updated pet + */ + Result updatePet(Pet pet); + + /** + * Returns a single pet by ID. + * + * @param id The pet ID to find + * @return A single pet + */ + Result findPet(Long id); + + /** + * Deletes a pet by ID. + * + * @param id The pet ID to delete + * @return `true` if the pet was deleted + */ + Result deletePet(Long id); +} diff --git a/src/main/java/com/example/repository/RemoteRepository.java b/src/main/java/com/example/repository/RemoteRepository.java new file mode 100644 index 0000000..6f5d458 --- /dev/null +++ b/src/main/java/com/example/repository/RemoteRepository.java @@ -0,0 +1,45 @@ +package com.example.repository; + +import com.example.api.ApiError; +import com.example.api.ApiResponse; +import com.example.api.RepositoryType; +import com.leakyabstractions.result.api.Result; +import com.leakyabstractions.result.core.Results; +import com.leakyabstractions.result.lazy.LazyResults; +import org.springframework.stereotype.Service; + +import java.util.Optional; +import java.util.function.Supplier; + +/** + * Base class for all remote pet repositories. + * + *

Interacts with a remote pet store server via HTTP.

+ */ +@Service +abstract class RemoteRepository implements PetRepository { + + final RepositoryType type; + + RemoteRepository(RepositoryType type) { + this.type = type; + } + + @Override + public RepositoryType getType() { + return type; + } + + protected Result evaluate(Supplier> call) { + return LazyResults.ofSupplier( + () -> Results.ofCallable(() -> Optional.ofNullable(call.get()).orElseGet(ApiResponse::new))) + .mapFailure(ApiError::remote) + .flatMapSuccess(ApiResponse::getResult); + } + + protected Result evaluateAny(Supplier call) { + return LazyResults.ofSupplier( + () -> Results.ofCallable(() -> Optional.ofNullable(call.get()).orElseThrow())) + .mapFailure(ApiError::remote); + } +} diff --git a/src/main/java/com/example/repository/SwaggerRepository.java b/src/main/java/com/example/repository/SwaggerRepository.java new file mode 100644 index 0000000..51e7a1d --- /dev/null +++ b/src/main/java/com/example/repository/SwaggerRepository.java @@ -0,0 +1,65 @@ +package com.example.repository; + +import com.example.api.ApiError; +import com.example.api.Pet; +import com.example.client.SwaggerClient; +import com.leakyabstractions.result.api.Result; +import org.slf4j.Logger; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import java.util.Collection; + +import static com.example.api.RepositoryType.SWAGGER; +import static org.slf4j.LoggerFactory.getLogger; + +/** + * Implements the Swagger pet repository. + * + *

Interacts with Swagger's sample pet store server.

+ */ +@Service +class SwaggerRepository extends RemoteRepository implements PetRepository { + + static final Logger log = getLogger(SwaggerRepository.class); + + final SwaggerClient swagger; + + SwaggerRepository(SwaggerClient swagger) { + super(SWAGGER); + this.swagger = swagger; + } + + @Override + public Result, ApiError> listPets() { + log.info("List pets"); + return evaluateAny(swagger::remoteList); + } + + @Override + public Result createPet(Pet pet) { + log.info("Create pet: {}", pet); + return evaluateAny(() -> swagger.remoteCreate(pet)); + } + + @Override + public Result updatePet(Pet pet) { + log.info("Update pet: {}", pet); + return evaluateAny(() -> swagger.remoteUpdate(pet)); + } + + @Override + public Result findPet(Long id) { + log.info("Find pet by ID: {}", id); + return evaluateAny(() -> swagger.remoteFindById(id)); + } + + @Override + public Result deletePet(Long id) { + log.info("Delete pet by ID: {}", id); + return evaluateAny(() -> swagger.remoteDeleteById(id)) + .mapSuccess(ResponseEntity::getStatusCode) + .mapSuccess(HttpStatus.OK::equals); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..5af1a1c --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,25 @@ +spring.application.name=Example + +spring.jackson.default-property-inclusion=non_null + +spring.cloud.openfeign.autoconfiguration.jackson.enabled=true +spring.cloud.openfeign.client.config.loopback.url=http://localhost:${server.port:8080} +spring.cloud.openfeign.client.config.loopback.default-request-headers.x-type=LOCAL +spring.cloud.openfeign.client.config.github.url=https://dev.leakyabstractions.com +spring.cloud.openfeign.client.config.swagger.url=https://petstore.swagger.io +spring.cloud.openfeign.client.config.swagger.default-request-headers.api_key=special-key + +pet-store.api-version=1.0 +pet-store.enabled=true + +pet-store.pets[0].id=0 +pet-store.pets[0].name=Rocky +pet-store.pets[0].status=available + +pet-store.pets[1].id=1 +pet-store.pets[1].name=Garfield +pet-store.pets[1].status=sold + +pet-store.pets[2].id=2 +pet-store.pets[2].name=Rantanplan +pet-store.pets[2].status=pending diff --git a/src/test/java/com/example/ExampleApplicationTests.java b/src/test/java/com/example/ExampleApplicationTests.java new file mode 100644 index 0000000..0d460f6 --- /dev/null +++ b/src/test/java/com/example/ExampleApplicationTests.java @@ -0,0 +1,108 @@ +package com.example; + +import com.example.api.ApiResponse; +import com.example.api.Pet; +import com.example.client.LoopbackClient; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; + +import java.util.Collection; + +import static com.example.api.ApiErrorCode.PET_STORE_UNAVAILABLE; +import static com.example.api.RepositoryType.*; +import static com.leakyabstractions.result.assertj.InstanceOfResultAssertFactories.LIST; +import static com.leakyabstractions.result.assertj.InstanceOfResultAssertFactories.RESULT; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.http.RequestEntity.get; + +@SpringBootTest(webEnvironment = RANDOM_PORT) +class ExampleApplicationTests { + + static final ParameterizedTypeReference> PET = new ParameterizedTypeReference<>() { }; + static final ParameterizedTypeReference>> PETS = new ParameterizedTypeReference<>() { }; + + @Autowired + TestRestTemplate rest; + + @Test + void contextLoads() { + } + + @Test + void testIndexController() { + assertThat(rest.getForEntity("/", String.class).getBody()) + .contains("swagger-ui.css"); + } + + @Test + void testPetControllerLocal() { + assertThat(rest.exchange(get("/pet").header("X-Type", LOCAL.name()).build(), PETS)) + .extracting(HttpEntity::getBody) + .extracting(ApiResponse::getResult) + .asInstanceOf(RESULT) + .hasSuccessThat(LIST) + .hasSize(3); + } + + @Test + void testPetControllerLoopback() { + assertThat(rest.exchange(get("/pet/0").header("X-Type", LOOPBACK.name()).build(), PET)) + .extracting(HttpEntity::getBody) + .extracting(ApiResponse::getResult) + .asInstanceOf(RESULT) + .hasSuccessSatisfying(pet -> assertThat(pet).hasFieldOrPropertyWithValue("name", "Rocky")); + } + + @Test + void testPetControllerSpecial() { + assertThat(rest.exchange(get("/pet").header("X-Type", SPECIAL.name()).build(), PETS)) + .extracting(HttpEntity::getBody) + .extracting(ApiResponse::getResult) + .asInstanceOf(RESULT) + .hasFailureSatisfying(error -> assertThat(error).hasFieldOrPropertyWithValue("code", PET_STORE_UNAVAILABLE)); + } + + @TestConfiguration + static class TestConfig { + @Bean + @Primary + LoopbackClient loopbackClient(TestRestTemplate rest) { + return new LoopbackClient() { + @Override + public ApiResponse remoteFindById(Long id) { + return rest + .exchange(get("/pet/" + id).header("X-Type", LOCAL.name()).build(), PET) + .getBody(); + } + + @Override + public ApiResponse> remoteList() { + throw new RuntimeException("Not implemented"); + } + + @Override + public ApiResponse remoteDeleteById(Long id) { + throw new RuntimeException("Not implemented"); + } + + @Override + public ApiResponse remoteCreate(Pet pet) { + throw new RuntimeException("Not implemented"); + } + + @Override + public ApiResponse remoteUpdate(Pet pet) { + throw new RuntimeException("Not implemented"); + } + }; + } + } +} diff --git a/src/test/resources/static/1.json b/src/test/resources/static/1.json new file mode 100644 index 0000000..dd14d35 --- /dev/null +++ b/src/test/resources/static/1.json @@ -0,0 +1,10 @@ +{ + "version": 1, + "result": { + "success": { + "id": 1, + "name": "Foo", + "status": "available" + } + } +} diff --git a/src/test/resources/static/2.json b/src/test/resources/static/2.json new file mode 100644 index 0000000..2b87053 --- /dev/null +++ b/src/test/resources/static/2.json @@ -0,0 +1,10 @@ +{ + "version": 1, + "result": { + "success": { + "id": 2, + "name": "Bar", + "status": "sold" + } + } +} diff --git a/src/test/resources/static/3.json b/src/test/resources/static/3.json new file mode 100644 index 0000000..6f1ae34 --- /dev/null +++ b/src/test/resources/static/3.json @@ -0,0 +1,10 @@ +{ + "version": 1, + "result": { + "success": { + "id": 3, + "name": "Foobar", + "status": "pending" + } + } +} diff --git a/src/test/resources/static/all.json b/src/test/resources/static/all.json new file mode 100644 index 0000000..55e0b02 --- /dev/null +++ b/src/test/resources/static/all.json @@ -0,0 +1,22 @@ +{ + "version": 1, + "result": { + "success": [ + { + "id": 1, + "name": "Foo", + "status": "available" + }, + { + "id": 2, + "name": "Bar", + "status": "sold" + }, + { + "id": 3, + "name": "Foobar", + "status": "pending" + } + ] + } +} diff --git a/swagger-ui.png b/swagger-ui.png new file mode 100644 index 0000000..44fff45 Binary files /dev/null and b/swagger-ui.png differ