aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFiete Ostkamp <Fiete.Ostkamp@telekom.de>2023-04-14 11:44:19 +0000
committerFiete Ostkamp <Fiete.Ostkamp@telekom.de>2023-04-14 11:44:19 +0000
commitcdc670c5a1c25b0b0ab460b1711a0a42f270b1f3 (patch)
tree41ac6c0e7a52505fd1d0de057df6d5328a853cd0
parent1a9b563662e9a9dd1f89e04ce0026e2cc5c4771d (diff)
Upload bff
Issue-ID: PORTAL-1083 Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de> Change-Id: I50f0a2db2dab28354c32c1ebf5a5e22afb0faade
-rw-r--r--.gitignore44
-rw-r--r--Dockerfile23
-rw-r--r--README.md68
-rw-r--r--app/LICENSE201
-rw-r--r--app/LICENSE_HEADER20
-rw-r--r--app/build.gradle68
-rw-r--r--app/src/main/java/org/onap/portal/bff/Application.java36
-rw-r--r--app/src/main/resources/application-access-control.yml23
-rw-r--r--app/src/main/resources/application-development.yml30
-rw-r--r--app/src/main/resources/application-local.yml34
-rw-r--r--app/src/main/resources/application.yml49
-rw-r--r--app/src/main/resources/logback-spring.xml13
-rw-r--r--app/src/test/java/org/onap/portal/bff/ApiDocsIntegrationTest.java40
-rw-r--r--app/src/test/java/org/onap/portal/bff/BaseIntegrationTest.java228
-rw-r--r--app/src/test/java/org/onap/portal/bff/HealthCheckIntegrationTest.java48
-rw-r--r--app/src/test/java/org/onap/portal/bff/TokenGenerator.java123
-rw-r--r--app/src/test/java/org/onap/portal/bff/actions/ActionDto.java39
-rw-r--r--app/src/test/java/org/onap/portal/bff/actions/ActionFixtures.java106
-rw-r--r--app/src/test/java/org/onap/portal/bff/actions/ActionsMocks.java228
-rw-r--r--app/src/test/java/org/onap/portal/bff/actions/CreateActionsIntegrationTest.java85
-rw-r--r--app/src/test/java/org/onap/portal/bff/actions/GetActionsIntegrationTest.java79
-rw-r--r--app/src/test/java/org/onap/portal/bff/actions/ListActionsIntegrationTest.java78
-rw-r--r--app/src/test/java/org/onap/portal/bff/headers/XRequestIdHeaderTest.java76
-rw-r--r--app/src/test/java/org/onap/portal/bff/idtoken/IdTokenExchangeFilterFunctionTest.java89
-rw-r--r--app/src/test/java/org/onap/portal/bff/preferences/CreatePreferencesIntegrationTest.java115
-rw-r--r--app/src/test/java/org/onap/portal/bff/preferences/GetPreferencesIntegrationTest.java77
-rw-r--r--app/src/test/java/org/onap/portal/bff/preferences/PreferencesMocks.java182
-rw-r--r--app/src/test/java/org/onap/portal/bff/preferences/UpdatePreferencesIntegrationTest.java114
-rw-r--r--app/src/test/java/org/onap/portal/bff/roles/ListRealmRolesIntegrationTest.java88
-rw-r--r--app/src/test/java/org/onap/portal/bff/roles/RolesMocks.java57
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/CreateUserIntegrationTest.java308
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/DeleteUserIntegrationTest.java83
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/GetUserDetailIntegrationTest.java126
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/ListAssignedRolesIntegrationTest.java111
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/ListAvailableRolesIntegrationTest.java113
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/ListUsersIntegrationTest.java238
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/UpdateAssignedRolesIntegrationTest.java452
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/UpdateUserIntegrationTest.java134
-rw-r--r--app/src/test/java/org/onap/portal/bff/users/UpdateUserPasswordIntegrationTest.java107
-rw-r--r--app/src/test/java/org/onap/portal/bff/utils/SortingChainResolverTest.java141
-rw-r--r--app/src/test/java/org/onap/portal/bff/utils/SortingParserTest.java50
-rw-r--r--app/src/test/java/org/onap/portal/bff/utils/VersionComparatorTest.java41
-rw-r--r--app/src/test/resources/application-access-control.yml22
-rw-r--r--app/src/test/resources/application-development.yml33
-rw-r--r--app/src/test/resources/application.yml34
-rw-r--r--app/src/test/resources/logback-spring.xml18
-rw-r--r--app/src/test/resources/preferences/preferencesProperties.json80
-rwxr-xr-xbin/build.sh3
-rwxr-xr-xbin/compile.sh3
-rwxr-xr-xbin/generate-openapi.sh3
-rwxr-xr-xbin/sonarqube.sh3
-rwxr-xr-xbin/test.sh3
-rwxr-xr-xbuild.gradle81
-rw-r--r--development/.env40
-rw-r--r--development/config/onap-realm.json221
-rw-r--r--development/docker-compose.yml77
-rw-r--r--development/requests-code.http109
-rw-r--r--development/requests.http119
-rwxr-xr-xdevelopment/run.sh6
-rwxr-xr-xdevelopment/stop.sh8
-rw-r--r--gradle/wrapper/gradle-wrapper.jarbin0 -> 60756 bytes
-rw-r--r--gradle/wrapper/gradle-wrapper.properties5
-rwxr-xr-xgradlew240
-rw-r--r--gradlew.bat91
-rw-r--r--lib/LICENSE201
-rw-r--r--lib/LICENSE_HEADER20
-rw-r--r--lib/build.gradle91
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/BeansConfig.java191
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/ConversionServiceConfig.java59
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/IdTokenExchangeFilterFunction.java125
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/LoggerInterceptor.java52
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/MapperSpringConfig.java28
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/PortalBffConfig.java63
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/SecurityConfig.java77
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/clients/AbstractClientConfig.java87
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/clients/KeycloakConfig.java104
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/clients/PortalHistoryConfig.java97
-rw-r--r--lib/src/main/java/org/onap/portal/bff/config/clients/PortalPrefsConfig.java96
-rw-r--r--lib/src/main/java/org/onap/portal/bff/controller/AbstractBffController.java46
-rw-r--r--lib/src/main/java/org/onap/portal/bff/controller/ActionsController.java84
-rw-r--r--lib/src/main/java/org/onap/portal/bff/controller/BffControllerAdvice.java28
-rw-r--r--lib/src/main/java/org/onap/portal/bff/controller/PreferencesController.java77
-rw-r--r--lib/src/main/java/org/onap/portal/bff/controller/RolesController.java56
-rw-r--r--lib/src/main/java/org/onap/portal/bff/controller/UsersController.java145
-rw-r--r--lib/src/main/java/org/onap/portal/bff/exceptions/DownstreamApiProblemException.java65
-rw-r--r--lib/src/main/java/org/onap/portal/bff/mappers/ActionsMapper.java37
-rw-r--r--lib/src/main/java/org/onap/portal/bff/mappers/CredentialMapper.java33
-rw-r--r--lib/src/main/java/org/onap/portal/bff/mappers/PreferencesMapper.java37
-rw-r--r--lib/src/main/java/org/onap/portal/bff/mappers/RolesMapper.java36
-rw-r--r--lib/src/main/java/org/onap/portal/bff/mappers/UsersMapper.java48
-rw-r--r--lib/src/main/java/org/onap/portal/bff/services/ActionService.java125
-rw-r--r--lib/src/main/java/org/onap/portal/bff/services/KeycloakService.java389
-rw-r--r--lib/src/main/java/org/onap/portal/bff/services/PreferencesService.java91
-rw-r--r--lib/src/main/java/org/onap/portal/bff/utils/ErrorHandler.java65
-rw-r--r--lib/src/main/java/org/onap/portal/bff/utils/Logger.java61
-rw-r--r--lib/src/main/java/org/onap/portal/bff/utils/SortingChainResolver.java55
-rw-r--r--lib/src/main/java/org/onap/portal/bff/utils/SortingParser.java57
-rw-r--r--lib/src/main/java/org/onap/portal/bff/utils/VersionComparator.java48
-rw-r--r--lombok.config1
-rw-r--r--openapi/build.gradle27
-rw-r--r--openapi/client-portal-history/LICENSE201
-rw-r--r--openapi/client-portal-history/build.gradle25
-rw-r--r--openapi/client-portal-history/src/portal_history_openapi.yaml457
-rw-r--r--openapi/client-portal-keycloak/LICENSE201
-rw-r--r--openapi/client-portal-keycloak/build.gradle25
-rw-r--r--openapi/client-portal-keycloak/src/portal_keycloak_openapi.yaml651
-rw-r--r--openapi/client-portal-prefs/LICENSE201
-rw-r--r--openapi/client-portal-prefs/build.gradle25
-rw-r--r--openapi/client-portal-prefs/src/portal_prefs_openapi.yaml341
-rw-r--r--openapi/server/LICENSE201
-rw-r--r--openapi/server/build.gradle48
-rw-r--r--openapi/server/src/main/resources/static/api-docs.html20
-rw-r--r--openapi/server/src/main/resources/static/api.yaml969
-rw-r--r--settings.gradle10
-rw-r--r--spotbugs-exclude.xml6
-rw-r--r--version1
116 files changed, 11848 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..1ce5355
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,44 @@
+HELP.md
+.gradle
+gradle.properties
+build/
+app/bin/
+openapi/**/bin/
+!gradle/wrapper/gradle-wrapper.jar
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+!**/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/
+
+### Stoplight on Mac ###
+**/.DS_Store
+
+/lib/bin/ \ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..3e2f704
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,23 @@
+FROM openjdk:17 as builder
+COPY . ./portalbff
+WORKDIR /portalbff
+
+# assemble does not run tests (as opposed to build)
+RUN ./gradlew assemble
+
+# Run locally (docker build --target=prod -t <tag> .)
+FROM openjdk:17 as prod
+ARG JAR_FILE=/portalbff/app/build/libs/app.jar
+COPY --from=builder ${JAR_FILE} app.jar
+EXPOSE 9080
+ENTRYPOINT [ "java","-jar","app.jar" ]
+
+# Run in pipeline (docker build --target=pipeline -t <tag> .)
+FROM openjdk:17 as pipeline
+WORKDIR /app
+
+ARG JAR_FILE=app/build/libs/app.jar
+COPY ${JAR_FILE} app.jar
+
+ENTRYPOINT [ "java","-jar","app.jar" ]
+EXPOSE 9080 \ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..48f023d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,68 @@
+# Portal BFF
+Backend for Frontend (BFF) component of the portal-ng.
+
+## Build
+You can build and test the application with:
+``` sh
+# Windows
+gradlew clean build
+# Unix
+./gradlew clean build
+```
+
+## Test
+``` sh
+# run all tests
+./gradlew test
+# run all tests in a test class
+./gradlew test --tests GetTileIntegrationTest
+# run individual test in a test class
+./gradlew test --tests GetTileIntegrationTest.thatTileCanBeRetrieved
+# run individual test in a test-class with debug info
+./gradlew test --tests GetTileIntegrationTest.thatTileCanBeRetrieved --info
+```
+
+## Generate JAR
+To generate one JAR file including also the open-api part the following command can be used
+```sh
+# generate JAR to /library/build/libs
+./gradlew shadowJar
+```
+
+## Publish JAR
+To publish the generated JAR file run
+```sh
+# publish JAR to target repository
+./gradlew publish
+```
+
+## Run locally
+Currently there are three spring profiles that can be used to run the application (`application.yml`, `application-local.yml` and `application-development.yml`).
+
+To launch the application with a specific profile run
+``` sh
+SPRING_PROFILES_ACTIVE=local ./gradlew bootRun
+# or
+export SPRING_PROFILES_ACTIVE=local
+./gradlew bootRun
+```
+
+## Development
+You can run the service locally for evaluation or development purposes using the provided `docker-compose.yml` file in the development folder. This will launch a Keycloak and a Postgres db in the background.
+
+To start the service execute the `run.sh` in the development folder:
+```sh
+development/run.sh
+```
+
+Example request against the portal-prefs service can be run in your preferred IDE with the `request.http` file from the development folder.
+
+You can access the Keycloak UI via browser.
+URL: http://localhost:8080
+**username:** admin
+**password:** password
+
+To stop the portal-prefs service, Keycloak and the databases run:
+```sh
+development/stop.sh
+```
diff --git a/app/LICENSE b/app/LICENSE
new file mode 100644
index 0000000..abe3069
--- /dev/null
+++ b/app/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 2021 TNAP / development / system-team
+
+ 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/app/LICENSE_HEADER b/app/LICENSE_HEADER
new file mode 100644
index 0000000..66e028a
--- /dev/null
+++ b/app/LICENSE_HEADER
@@ -0,0 +1,20 @@
+/*
+ *
+ * Copyright (c) ${year}. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
diff --git a/app/build.gradle b/app/build.gradle
new file mode 100644
index 0000000..2c766cf
--- /dev/null
+++ b/app/build.gradle
@@ -0,0 +1,68 @@
+apply plugin: 'application'
+apply plugin: 'org.springframework.boot'
+apply plugin: 'com.gorylenko.gradle-git-properties'
+apply plugin: 'jacoco'
+
+dependencyManagement {
+ imports {
+ mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:$springCloudVersion"
+ }
+}
+
+dependencies {
+ implementation project(':openapi:server')
+ implementation project(':openapi:client-portal-prefs')
+ implementation project(':openapi:client-portal-history')
+ implementation project(':openapi:client-portal-keycloak')
+
+ implementation project(':lib')
+
+ implementation 'org.springframework.boot:spring-boot-starter-webflux'
+ implementation 'org.springframework.boot:spring-boot-starter-actuator'
+ implementation 'org.springframework.boot:spring-boot-starter-validation'
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
+ implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
+ implementation "org.zalando:problem:$problemVersion"
+ implementation "org.zalando:jackson-datatype-problem:$problemVersion"
+ implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
+ implementation "org.zalando:problem-spring-webflux:$problemSpringVersion"
+
+ implementation "org.mapstruct:mapstruct:$mapStructVersion"
+ annotationProcessor "org.mapstruct:mapstruct-processor:$mapStructVersion"
+ implementation "org.mapstruct.extensions.spring:mapstruct-spring-annotations:$mapStructExtensionsVersion"
+ implementation "org.mapstruct.extensions.spring:mapstruct-spring-extensions:$mapStructExtensionsVersion"
+
+ testImplementation 'io.projectreactor:reactor-test'
+ testImplementation 'org.springframework.cloud:spring-cloud-contract-wiremock'
+ testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ testImplementation 'io.rest-assured:rest-assured'
+}
+
+mainClassName = 'org.onap.portal.bff.Application'
+
+bootJar {
+ launchScript()
+ enabled = true
+ excludes = ['**/application-local.yml', '**/application-development.yml', '**/log4j.xml']
+}
+
+springBoot {
+ buildInfo {
+ properties {
+ artifact = 'org-onap-portal-bff'
+ version = getVersion()
+ group = rootProject.group
+ name = 'ONAP portal backend for frontend community edition'
+ }
+ }
+}
+
+jacocoTestReport {
+ reports {
+ xml.enabled true
+ }
+}
+test.finalizedBy jacocoTestReport
+
+configurations.implementation.setCanBeResolved(true)
diff --git a/app/src/main/java/org/onap/portal/bff/Application.java b/app/src/main/java/org/onap/portal/bff/Application.java
new file mode 100644
index 0000000..32a07e8
--- /dev/null
+++ b/app/src/main/java/org/onap/portal/bff/Application.java
@@ -0,0 +1,36 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff;
+
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+
+@EnableConfigurationProperties(PortalBffConfig.class)
+@SpringBootApplication
+public class Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+}
diff --git a/app/src/main/resources/application-access-control.yml b/app/src/main/resources/application-access-control.yml
new file mode 100644
index 0000000..d967c53
--- /dev/null
+++ b/app/src/main/resources/application-access-control.yml
@@ -0,0 +1,23 @@
+portal-bff.access-control:
+ ACTIONS_CREATE: [ onap_admin, onap_designer, onap_operator ]
+ ACTIONS_GET: [ onap_admin, onap_designer, onap_operator ]
+ ACTIONS_LIST: [ onap_admin, onap_designer, onap_operator ]
+ ACTIVE_ALARM_LIST: [onap_admin, onap_designer, onap_operator]
+ KEY_ENCRYPT_BY_USER: [onap_admin, onap_designer, onap_operator]
+ KEY_ENCRYPT_BY_VALUE: [onap_admin, onap_designer, onap_operator]
+ PREFERENCES_CREATE: [onap_admin, onap_designer, onap_operator]
+ PREFERENCES_GET: [onap_admin, onap_designer, onap_operator]
+ PREFERENCES_UPDATE: [onap_admin, onap_designer, onap_operator]
+ ROLE_LIST: ["*"]
+ TILE_GET: [onap_admin, onap_designer, onap_operator]
+ TILE_LIST: [onap_admin, onap_designer, onap_operator]
+ USER_CREATE: [onap_admin, onap_designer, onap_operator]
+ USER_DELETE: [onap_admin, onap_designer, onap_operator]
+ USER_GET: [onap_admin, onap_designer, onap_operator]
+ USER_LIST_AVAILABLE_ROLES: [onap_admin, onap_designer, onap_operator]
+ USER_LIST_ROLES: [onap_admin, onap_designer, onap_operator]
+ USER_LIST: [onap_admin, onap_designer, onap_operator]
+ USER_UPDATE_PASSWORD: [onap_admin, onap_designer, onap_operator]
+ USER_UPDATE_ROLES: [onap_admin, onap_designer, onap_operator]
+ USER_UPDATE: [onap_admin, onap_designer, onap_operator]
+
diff --git a/app/src/main/resources/application-development.yml b/app/src/main/resources/application-development.yml
new file mode 100644
index 0000000..50dfb51
--- /dev/null
+++ b/app/src/main/resources/application-development.yml
@@ -0,0 +1,30 @@
+spring:
+ security:
+ oauth2:
+ client:
+ provider:
+ keycloak:
+ token-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/token
+ jwk-set-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/certs
+ registration:
+ keycloak:
+ provider: keycloak
+ client-id: portal-bff
+ client-secret: 5933482a-9f4c-44e0-9814-dca17e0a9137
+ authorization-grant-type: client_credentials
+ resourceserver:
+ jwt:
+ jwk-set-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/certs
+
+management:
+ endpoints:
+ web:
+ exposure:
+ include: "*"
+
+portal-bff:
+ realm: ONAP
+ portal-prefs-url: ${PORTAL_PREFS_URL}
+ portal-history-url: ${PORTAL_HISTORY_URL}
+ keycloak-url: ${KEYCLOAK_URL}
+ instance-id: PORTAL
diff --git a/app/src/main/resources/application-local.yml b/app/src/main/resources/application-local.yml
new file mode 100644
index 0000000..e90a13b
--- /dev/null
+++ b/app/src/main/resources/application-local.yml
@@ -0,0 +1,34 @@
+spring:
+ security:
+ oauth2:
+ client:
+ provider:
+ keycloak:
+ token-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/token
+ jwk-set-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/certs
+ registration:
+ keycloak:
+ provider: keycloak
+ client-id: portal-bff
+ client-secret: pKOuVH1bwRZoNzp5P5t4GV8CqcCJYVtr
+ authorization-grant-type: client_credentials
+ resourceserver:
+ jwt:
+ jwk-set-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/certs
+
+management:
+ endpoints:
+ web:
+ exposure:
+ include: "*"
+
+portal-bff:
+ realm: ONAP
+ portal-prefs-url: http://localhost:9001
+ portal-history-url: http://localhost:9002
+ keycloak-url: http://localhost:8080/
+ instance-id: PORTAL
+
+logging:
+ level:
+ root: debug
diff --git a/app/src/main/resources/application.yml b/app/src/main/resources/application.yml
new file mode 100644
index 0000000..83686b5
--- /dev/null
+++ b/app/src/main/resources/application.yml
@@ -0,0 +1,49 @@
+# List of common application properties:
+# https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
+server:
+ port: 9080
+ address: 0.0.0.0
+
+logging:
+ level:
+ org.springframework.web: TRACE
+
+management:
+ endpoints:
+ web:
+ exposure:
+ include: "*"
+
+spring:
+ application:
+ name: portal-bff
+ profiles:
+ include:
+ - access-control
+ security:
+ oauth2:
+ client:
+ provider:
+ keycloak:
+ token-uri: ${KEYCLOAK_URL}/auth/realms/${KEYCLOAK_REALM}/protocol/openid-connect/token
+ jwk-set-uri: ${KEYCLOAK_URL}/auth/realms/${KEYCLOAK_REALM}/protocol/openid-connect/certs
+ registration:
+ keycloak:
+ provider: keycloak
+ client-id: ${KEYCLOAK_CLIENT_ID}
+ client-secret: ${KEYCLOAK_CLIENT_SECRET}
+ authorization-grant-type: client_credentials
+ resourceserver:
+ jwt:
+ jwk-set-uri: ${KEYCLOAK_URL}/auth/realms/${KEYCLOAK_REALM}/protocol/openid-connect/certs
+ jackson:
+ serialization:
+ FAIL_ON_EMPTY_BEANS: false
+
+portal-bff:
+ realm: ${KEYCLOAK_REALM}
+ portal-prefs-url: ${PORTAL_PREFS_URL}
+ portal-history-url: ${PORTAL_HISTORY_URL}
+ keycloak-url: ${KEYCLOAK_URL}
+ instance-id: PORTAL
+
diff --git a/app/src/main/resources/logback-spring.xml b/app/src/main/resources/logback-spring.xml
new file mode 100644
index 0000000..05503bc
--- /dev/null
+++ b/app/src/main/resources/logback-spring.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration scan="true">
+ <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
+ <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+ <level>${LOGBACK_LEVEL:-info}</level>
+ </filter>
+ <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
+ </appender>
+
+ <root level="all">
+ <appender-ref ref="stdout"/>
+ </root>
+</configuration>
diff --git a/app/src/test/java/org/onap/portal/bff/ApiDocsIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/ApiDocsIntegrationTest.java
new file mode 100644
index 0000000..66edfee
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/ApiDocsIntegrationTest.java
@@ -0,0 +1,40 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class ApiDocsIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void apiDocsAreAvailable() {
+ unauthenticatedRequestSpecification()
+ .given()
+ .accept(MediaType.TEXT_HTML_VALUE)
+ .when()
+ .get("/api-docs.html")
+ .then()
+ .statusCode(HttpStatus.OK.value());
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/BaseIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/BaseIntegrationTest.java
new file mode 100644
index 0000000..f310850
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/BaseIntegrationTest.java
@@ -0,0 +1,228 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff;
+
+import static io.vavr.API.None;
+import static io.vavr.API.Some;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
+import com.nimbusds.jose.jwk.JWKSet;
+import io.restassured.RestAssured;
+import io.restassured.filter.log.RequestLoggingFilter;
+import io.restassured.filter.log.ResponseLoggingFilter;
+import io.restassured.specification.RequestSpecification;
+import io.vavr.collection.List;
+import io.vavr.control.Option;
+import java.time.Clock;
+import java.time.OffsetDateTime;
+import java.util.UUID;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.onap.portal.bff.config.IdTokenExchangeFilterFunction;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
+import org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.MediaType;
+
+/** Base class for all tests that has the common config including port, realm, logging and auth. */
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public abstract class BaseIntegrationTest {
+
+ @TestConfiguration
+ public static class Config {
+ @Bean
+ WireMockConfigurationCustomizer optionsCustomizer() {
+ return options -> options.extensions(new ResponseTemplateTransformer(true));
+ }
+ }
+
+ @LocalServerPort protected int port;
+
+ @Value("${portal-bff.realm}")
+ protected String realm;
+
+ @Autowired protected ObjectMapper objectMapper;
+ @Autowired private TokenGenerator tokenGenerator;
+
+ @Autowired protected PortalBffConfig portalBffConfig;
+
+ @BeforeAll
+ public static void setup() {
+ RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter());
+ }
+
+ /** Mocks the OIDC auth flow. */
+ @BeforeEach
+ public void mockAuth() {
+ WireMock.reset();
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/realms/%s/protocol/openid-connect/certs", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", JWKSet.MIME_TYPE)
+ .withBody(tokenGenerator.getJwkSet().toString())));
+
+ final TokenGenerator.TokenGeneratorConfig config =
+ TokenGenerator.TokenGeneratorConfig.builder().port(port).realm(realm).build();
+
+ WireMock.stubFor(
+ WireMock.post(
+ WireMock.urlMatching(
+ String.format("/auth/realms/%s/protocol/openid-connect/token", realm)))
+ .withBasicAuth("test", "test")
+ .withRequestBody(WireMock.containing("grant_type=client_credentials"))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(
+ objectMapper
+ .createObjectNode()
+ .put("token_type", "bearer")
+ .put("access_token", tokenGenerator.generateToken(config))
+ .put("expires_in", config.getExpireIn().getSeconds())
+ .put("refresh_token", tokenGenerator.generateToken(config))
+ .put("refresh_expires_in", config.getExpireIn().getSeconds())
+ .put("not-before-policy", 0)
+ .put("session_state", UUID.randomUUID().toString())
+ .put("scope", "email profile")
+ .toString())));
+ }
+
+ /**
+ * Object to store common attributes of requests that are going to be made. Adds an Identity
+ * header for the <code>onap_admin</code> role to the request.
+ */
+ protected RequestSpecification requestSpecification() {
+ final String idToken = tokenGenerator.generateToken(getTokenGeneratorConfig("onap_admin"));
+
+ return unauthenticatedRequestSpecification()
+ .auth()
+ .preemptive()
+ .oauth2(idToken)
+ .header(IdTokenExchangeFilterFunction.X_AUTH_IDENTITY_HEADER, "Bearer " + idToken);
+ }
+
+ /**
+ * Object to store common attributes of requests that are going to be made. Adds an Identity
+ * header for the given role to the request.
+ *
+ * @param role the role used for RBAC
+ * @return the templated request
+ */
+ protected RequestSpecification requestSpecification(String role) {
+ final String idToken = tokenGenerator.generateToken(getTokenGeneratorConfig(role));
+
+ return unauthenticatedRequestSpecification()
+ .auth()
+ .preemptive()
+ .oauth2(idToken)
+ .header(IdTokenExchangeFilterFunction.X_AUTH_IDENTITY_HEADER, "Bearer " + idToken);
+ }
+
+ /**
+ * Object to store common attributes of requests that are going to be made. Adds an Identity
+ * header for the given roles to the request.
+ *
+ * @param roles the roles used for RBAC
+ * @return the templated request
+ */
+ protected RequestSpecification requestSpecification(List<String> roles) {
+ final String idToken = tokenGenerator.generateToken(getTokenGeneratorConfig(roles));
+
+ return unauthenticatedRequestSpecification()
+ .auth()
+ .preemptive()
+ .oauth2(idToken)
+ .header(IdTokenExchangeFilterFunction.X_AUTH_IDENTITY_HEADER, "Bearer " + idToken);
+ }
+
+ /** Get a RequestSpecification that does not have an Identity header. */
+ protected RequestSpecification unauthenticatedRequestSpecification() {
+ return RestAssured.given().port(port);
+ }
+
+ /**
+ * Builds an OAuth2 configuration including the role, port and realm. This config can be used to
+ * generate OAuth2 access tokens.
+ *
+ * @param role the role used for RBAC
+ * @return the OAuth2 configuration
+ */
+ protected TokenGenerator.TokenGeneratorConfig getTokenGeneratorConfig(String role) {
+ return TokenGenerator.TokenGeneratorConfig.builder()
+ .port(port)
+ .realm(realm)
+ .roles(List.of(role))
+ .build();
+ }
+
+ /**
+ * Builds an OAuth2 configuration including the roles, port and realm. This config can be used to
+ * generate OAuth2 access tokens.
+ *
+ * @param roles the roles used for RBAC
+ * @return the OAuth2 configuration
+ */
+ protected TokenGenerator.TokenGeneratorConfig getTokenGeneratorConfig(List<String> roles) {
+ return TokenGenerator.TokenGeneratorConfig.builder()
+ .port(port)
+ .realm(realm)
+ .roles(roles)
+ .build();
+ }
+
+ public static OffsetDateTime offsetNow() {
+ return OffsetDateTime.now(Clock.systemUTC());
+ }
+
+ public static String randomUUID() {
+ return UUID.randomUUID().toString();
+ }
+
+ public static String adjustPath(String basePath, Option<Integer> page, Option<Integer> pageSize) {
+ return adjustPath(basePath, page, pageSize, None());
+ }
+
+ public static String adjustPath(
+ String basePath, Option<Integer> page, Option<Integer> pageSize, Option<String> filter) {
+ return page.map(pg -> basePath + "?page=" + pg)
+ .fold(
+ () -> pageSize.map(pgs -> basePath + "?pageSize=" + pgs),
+ pth -> pageSize.map(pgs -> pth + "&pageSize=" + pgs).orElse(Some(pth)))
+ .fold(
+ () -> filter.map(f -> basePath + "?filter=" + f),
+ pth -> filter.map(f -> pth + "&filter=" + f).orElse(Some(pth)))
+ .getOrElse(basePath);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/HealthCheckIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/HealthCheckIntegrationTest.java
new file mode 100644
index 0000000..cef85e1
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/HealthCheckIntegrationTest.java
@@ -0,0 +1,48 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.availability.ApplicationAvailability;
+import org.springframework.boot.availability.LivenessState;
+import org.springframework.boot.availability.ReadinessState;
+
+class HealthCheckIntegrationTest extends BaseIntegrationTest {
+
+ @Autowired private ApplicationAvailability applicationAvailability;
+
+ @Test
+ void livenessProbeIsAvailable() {
+
+ assertThat(applicationAvailability.getLivenessState()).isEqualTo(LivenessState.CORRECT);
+ }
+
+ @Test
+ void readinessProbeIsAvailable() {
+
+ assertThat(applicationAvailability.getReadinessState())
+ .isEqualTo(ReadinessState.ACCEPTING_TRAFFIC);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/TokenGenerator.java b/app/src/test/java/org/onap/portal/bff/TokenGenerator.java
new file mode 100644
index 0000000..d438d95
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/TokenGenerator.java
@@ -0,0 +1,123 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff;
+
+import com.nimbusds.jose.JOSEObjectType;
+import com.nimbusds.jose.JWSAlgorithm;
+import com.nimbusds.jose.JWSHeader;
+import com.nimbusds.jose.JWSSigner;
+import com.nimbusds.jose.crypto.RSASSASigner;
+import com.nimbusds.jose.jwk.JWKSet;
+import com.nimbusds.jose.jwk.KeyUse;
+import com.nimbusds.jose.jwk.RSAKey;
+import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.SignedJWT;
+import io.vavr.collection.List;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.UUID;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NonNull;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class TokenGenerator {
+
+ private static final String ROLES_CLAIM = "roles";
+
+ private final Clock clock;
+ private final RSAKey jwk;
+ private final JWKSet jwkSet;
+ private final JWSSigner signer;
+
+ @Autowired
+ public TokenGenerator(Clock clock) {
+ try {
+ this.clock = clock;
+ jwk =
+ new RSAKeyGenerator(2048)
+ .keyUse(KeyUse.SIGNATURE)
+ .keyID(UUID.randomUUID().toString())
+ .generate();
+ jwkSet = new JWKSet(jwk);
+ signer = new RSASSASigner(jwk);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public JWKSet getJwkSet() {
+ return jwkSet;
+ }
+
+ public String generateToken(TokenGeneratorConfig config) {
+ final Instant iat = clock.instant();
+ final Instant exp = iat.plus(config.expireIn);
+
+ final JWTClaimsSet claims =
+ new JWTClaimsSet.Builder()
+ .jwtID(UUID.randomUUID().toString())
+ .subject(UUID.randomUUID().toString())
+ .issuer(config.issuer())
+ .issueTime(Date.from(iat))
+ .expirationTime(Date.from(exp))
+ .claim(ROLES_CLAIM, config.getRoles())
+ .build();
+
+ final SignedJWT jwt =
+ new SignedJWT(
+ new JWSHeader.Builder(JWSAlgorithm.RS256)
+ .keyID(jwk.getKeyID())
+ .type(JOSEObjectType.JWT)
+ .build(),
+ claims);
+
+ try {
+ jwt.sign(signer);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return jwt.serialize();
+ }
+
+ @Getter
+ @Builder
+ public static class TokenGeneratorConfig {
+ private final int port;
+
+ @NonNull private final String realm;
+
+ @NonNull @Builder.Default private final Duration expireIn = Duration.ofMinutes(5);
+
+ @Builder.Default private final List<String> roles = List.empty();
+
+ public String issuer() {
+ return String.format("http://localhost:%d/auth/realms/%s", port, realm);
+ }
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/actions/ActionDto.java b/app/src/test/java/org/onap/portal/bff/actions/ActionDto.java
new file mode 100644
index 0000000..c88a0db
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/actions/ActionDto.java
@@ -0,0 +1,39 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.actions;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+@Getter
+@Setter
+@AllArgsConstructor
+@NoArgsConstructor
+public class ActionDto {
+ String type;
+ String action;
+ String message;
+ String downStreamSystem;
+ String downStreamId;
+}
diff --git a/app/src/test/java/org/onap/portal/bff/actions/ActionFixtures.java b/app/src/test/java/org/onap/portal/bff/actions/ActionFixtures.java
new file mode 100644
index 0000000..3e7c917
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/actions/ActionFixtures.java
@@ -0,0 +1,106 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.actions;
+
+import java.time.OffsetDateTime;
+import java.time.temporal.ChronoUnit;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionsListResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.client_portal_history.model.CreateActionRequestPortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.CreateActionRequestApiDto;
+
+public class ActionFixtures {
+
+ public static ActionsListResponsePortalHistoryDto generateActionsListResponse(
+ Integer numberOfActions, Integer totalCount, OffsetDateTime createdAt) {
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto =
+ new ActionsListResponsePortalHistoryDto();
+ for (Integer i = 0; i < numberOfActions; i++) {
+ actionsListResponsePortalHistoryDto.addActionsListItem(
+ generateActionResponse(
+ "Instantiation", "create", null, i.toString(), "SO", i, createdAt));
+ }
+ actionsListResponsePortalHistoryDto.setTotalCount(totalCount);
+ return actionsListResponsePortalHistoryDto;
+ }
+
+ public static ActionResponsePortalHistoryDto generateActionResponse(
+ String type,
+ String action,
+ String message,
+ String id,
+ String downStreamSystem,
+ Integer deltaHours,
+ OffsetDateTime createdAt) {
+ ActionDto actionDto = new ActionDto();
+ actionDto.setType(type);
+ actionDto.setAction(action);
+ actionDto.setMessage(message);
+ actionDto.setDownStreamSystem(downStreamSystem);
+ actionDto.setDownStreamId(id);
+
+ return new ActionResponsePortalHistoryDto()
+ .action(actionDto)
+ .actionCreatedAt(createdAt.minus(deltaHours, ChronoUnit.HOURS));
+ }
+
+ public static CreateActionRequestPortalHistoryDto generateActionRequestPortalHistoryDto(
+ String type,
+ String action,
+ String message,
+ String id,
+ String downStreamSystem,
+ String userId,
+ OffsetDateTime createdAt) {
+ ActionDto actionDto = new ActionDto();
+ actionDto.setType(type);
+ actionDto.setAction(action);
+ actionDto.setMessage(message);
+ actionDto.setDownStreamSystem(downStreamSystem);
+ actionDto.setDownStreamId(id);
+ return new CreateActionRequestPortalHistoryDto()
+ .action(actionDto)
+ .actionCreatedAt(createdAt)
+ .userId(userId);
+ }
+
+ public static CreateActionRequestApiDto generateCreateActionRequestApiDto(
+ String type,
+ String action,
+ String message,
+ String id,
+ String downStreamSystem,
+ String userId,
+ OffsetDateTime createdAt) {
+ ActionDto actionDto = new ActionDto();
+ actionDto.setType(type);
+ actionDto.setAction(action);
+ actionDto.setMessage(message);
+ actionDto.setDownStreamSystem(downStreamSystem);
+ actionDto.setDownStreamId(id);
+
+ return new CreateActionRequestApiDto()
+ .action(actionDto)
+ .actionCreatedAt(createdAt)
+ .userId(userId);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/actions/ActionsMocks.java b/app/src/test/java/org/onap/portal/bff/actions/ActionsMocks.java
new file mode 100644
index 0000000..0bb27d7
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/actions/ActionsMocks.java
@@ -0,0 +1,228 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.actions;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.matching.EqualToPattern;
+import io.restassured.http.Header;
+import org.apache.http.HttpHeaders;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionsListResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.client_portal_history.model.ProblemPortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ActionsListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ActionsResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.CreateActionRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+public class ActionsMocks extends BaseIntegrationTest {
+ protected static final String X_REQUEST_ID = "addf6005-3075-4c80-b7bc-2c70b7d42b00";
+
+ // used for test thatActionsListCanBeRetrieved
+ protected ActionsListResponseApiDto listActions() {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .when()
+ .get("/actions")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(ActionsListResponseApiDto.class);
+ }
+
+ // used for test thatActionsListCanBeRetrieved
+ protected void mockListActions(
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlEqualTo("/v1/actions?page=1&pageSize=10"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withBody(
+ objectMapper.writeValueAsString(actionsListResponsePortalHistoryDto))));
+ }
+
+ // used for test thatActionsListCanNotBeRetrieved
+ protected ProblemApiDto listActionsProblem() {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .when()
+ .get("/actions")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+ }
+
+ // used for test thatActionsListCanNotBeRetrieved
+ protected void mockListActionsProblem(ProblemPortalHistoryDto problemPortalHistoryDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlEqualTo("/v1/actions?page=1&pageSize=10"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PROBLEM_JSON_VALUE)
+ .withStatus(HttpStatus.INTERNAL_SERVER_ERROR.value())
+ .withBody(objectMapper.writeValueAsString(problemPortalHistoryDto))));
+ }
+
+ // used for test thatActionCanBeRetrieved
+ protected void mockGetActions(
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto,
+ String userId,
+ Integer showLastHours)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlEqualTo(
+ "/v1/actions/"
+ + userId
+ + "?page=1&pageSize=10"
+ + "&showLastHours="
+ + showLastHours))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withBody(
+ objectMapper.writeValueAsString(actionsListResponsePortalHistoryDto))));
+ }
+ // used for test thatActionCanBeRetrieved
+ protected ActionsListResponseApiDto getActions(String userId) {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .when()
+ .get("/actions/" + userId + "?page=1&pageSize=10&showLastHours=2")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(ActionsListResponseApiDto.class);
+ }
+
+ // used for test thatActionCanBeRetrievedWithoutParameterShowLastHours
+ protected void mockGetActionsWithoutParameterShowLastHours(
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto, String userId)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlEqualTo("/v1/actions/" + userId + "?page=1&pageSize=10"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withBody(
+ objectMapper.writeValueAsString(actionsListResponsePortalHistoryDto))));
+ }
+ // used for test thatActionCanBeRetrievedWithoutParameterShowLastHours
+ protected ActionsListResponseApiDto getActionsWithoutParameterShowLastHours(String userId) {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .when()
+ .get("/actions/" + userId + "?page=1&pageSize=10")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(ActionsListResponseApiDto.class);
+ }
+
+ // Used for thatActionCanBeCreated
+ protected void mockCreateActions(
+ String userId, ActionResponsePortalHistoryDto actionResponsePortalHistoryDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.post(WireMock.urlEqualTo("/v1/actions/" + userId))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .withRequestBody(WireMock.matchingJsonPath("$.action"))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(200)
+ .withBody(objectMapper.writeValueAsString(actionResponsePortalHistoryDto))));
+ }
+
+ // Used for thatActionCanBeCreated
+ protected ActionsResponseApiDto createAction(
+ CreateActionRequestApiDto createActionRequestApiDto, String userId) throws Exception {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .body(objectMapper.writeValueAsString(createActionRequestApiDto))
+ .when()
+ .post("/actions/" + userId)
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(ActionsResponseApiDto.class);
+ }
+
+ // Used for thatActionCanNotBeCreated
+ protected void mockCreateActionsProblem(
+ String userId, ProblemPortalHistoryDto problemPortalHistoryDto)
+ throws JsonProcessingException {
+ WireMock.stubFor(
+ WireMock.post(WireMock.urlEqualTo("/v1/actions/" + userId))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .withRequestBody(WireMock.matchingJsonPath("$.action"))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PROBLEM_JSON_VALUE)
+ .withStatus(500)
+ .withBody(objectMapper.writeValueAsString(problemPortalHistoryDto))));
+ }
+ // Used for thatActionCanNotBeCreated
+ protected ProblemApiDto createActionProblem(
+ CreateActionRequestApiDto createActionRequestApiDto, String userId)
+ throws JsonProcessingException {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .body(objectMapper.writeValueAsString(createActionRequestApiDto))
+ .when()
+ .post("/actions/" + userId)
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/actions/CreateActionsIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/actions/CreateActionsIntegrationTest.java
new file mode 100644
index 0000000..0b6ec57
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/actions/CreateActionsIntegrationTest.java
@@ -0,0 +1,85 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.actions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.OffsetDateTime;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.client_portal_history.model.ProblemPortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ActionsResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.CreateActionRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+
+class CreateActionsIntegrationTest extends ActionsMocks {
+
+ @Test
+ void thatActionCanBeCreated() throws Exception {
+ String userId = "22-33-44-55";
+ OffsetDateTime createdAt = OffsetDateTime.now();
+ ActionResponsePortalHistoryDto actionResponsePortalHistoryDto =
+ ActionFixtures.generateActionResponse(
+ "Instantiation", "create", "no detail message", "223344", "SO", 0, createdAt);
+ CreateActionRequestApiDto createActionDto =
+ ActionFixtures.generateCreateActionRequestApiDto(
+ "Instantiation", "create", "no detail message", "223344", "SO", userId, createdAt);
+
+ mockCreateActions(userId, actionResponsePortalHistoryDto);
+
+ final ActionsResponseApiDto response = createAction(createActionDto, userId);
+
+ assertThat(response.getActionCreatedAt())
+ .isEqualTo(actionResponsePortalHistoryDto.getActionCreatedAt());
+ Assertions.assertThat(objectMapper.writeValueAsString(response.getAction()))
+ .isEqualTo(objectMapper.writeValueAsString(actionResponsePortalHistoryDto.getAction()));
+ }
+
+ @Test
+ void thatActionCanNotBeCreated() throws Exception {
+ String userId = "22-33-44-55";
+ OffsetDateTime createdAt = OffsetDateTime.now();
+
+ ProblemPortalHistoryDto problemPortalHistoryDto =
+ new ProblemPortalHistoryDto()
+ .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
+ .detail("Internal database error")
+ .title("Internal Server Error")
+ .instance("portal-history");
+
+ CreateActionRequestApiDto createActionDto =
+ ActionFixtures.generateCreateActionRequestApiDto(
+ "Instantiation", "create", "no detail message", "223344", "SO", userId, createdAt);
+
+ mockCreateActionsProblem(userId, problemPortalHistoryDto);
+
+ final ProblemApiDto response = createActionProblem(createActionDto, userId);
+
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY);
+
+ assertThat(response.getDownstreamStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
+ assertThat(response.getDetail()).isEqualTo(problemPortalHistoryDto.getDetail());
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/actions/GetActionsIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/actions/GetActionsIntegrationTest.java
new file mode 100644
index 0000000..1f77036
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/actions/GetActionsIntegrationTest.java
@@ -0,0 +1,79 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.actions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.OffsetDateTime;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionsListResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ActionsListResponseApiDto;
+
+class GetActionsIntegrationTest extends ActionsMocks {
+
+ @Test
+ void thatActionCanBeRetrievedWithParameterShowLastHours() throws Exception {
+ int numberOfActions = 10;
+ Integer showLastHours = 2;
+ String userId = "22-33-44-55";
+ OffsetDateTime createdAt = OffsetDateTime.now();
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto =
+ ActionFixtures.generateActionsListResponse(numberOfActions, 30, createdAt);
+
+ mockGetActions(actionsListResponsePortalHistoryDto, userId, showLastHours);
+
+ final ActionsListResponseApiDto response = getActions(userId);
+
+ assertThat(response.getTotalCount()).isEqualTo(30);
+ assertThat(response.getItems()).hasSize(numberOfActions);
+ assertThat(response.getItems().get(0).getActionCreatedAt())
+ .isEqualTo(
+ actionsListResponsePortalHistoryDto.getActionsList().get(0).getActionCreatedAt());
+ assertThat(objectMapper.writeValueAsString(response.getItems().get(0).getAction()))
+ .isEqualTo(
+ objectMapper.writeValueAsString(
+ actionsListResponsePortalHistoryDto.getActionsList().get(0).getAction()));
+ }
+
+ @Test
+ void thatActionCanBeRetrievedWithoutParameterShowLastHours() throws Exception {
+ int numberOfActions = 10;
+ String userId = "22-33-44-55";
+ OffsetDateTime createdAt = OffsetDateTime.now();
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto =
+ ActionFixtures.generateActionsListResponse(numberOfActions, 30, createdAt);
+
+ mockGetActionsWithoutParameterShowLastHours(actionsListResponsePortalHistoryDto, userId);
+
+ final ActionsListResponseApiDto response = getActionsWithoutParameterShowLastHours(userId);
+
+ assertThat(response.getTotalCount()).isEqualTo(30);
+ assertThat(response.getItems()).hasSize(numberOfActions);
+ assertThat(response.getItems().get(0).getActionCreatedAt())
+ .isEqualTo(
+ actionsListResponsePortalHistoryDto.getActionsList().get(0).getActionCreatedAt());
+ assertThat(objectMapper.writeValueAsString(response.getItems().get(0).getAction()))
+ .isEqualTo(
+ objectMapper.writeValueAsString(
+ actionsListResponsePortalHistoryDto.getActionsList().get(0).getAction()));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/actions/ListActionsIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/actions/ListActionsIntegrationTest.java
new file mode 100644
index 0000000..7eb7078
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/actions/ListActionsIntegrationTest.java
@@ -0,0 +1,78 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.actions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.OffsetDateTime;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionsListResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.client_portal_history.model.ProblemPortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ActionsListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+
+class ListActionsIntegrationTest extends ActionsMocks {
+
+ @Test
+ void thatActionsListCanBeRetrieved() throws Exception {
+ int numberOfActions = 10;
+ OffsetDateTime createdAt = OffsetDateTime.now();
+ ActionsListResponsePortalHistoryDto actionsListResponsePortalHistoryDto =
+ ActionFixtures.generateActionsListResponse(numberOfActions, 1000, createdAt);
+
+ mockListActions(actionsListResponsePortalHistoryDto);
+
+ final ActionsListResponseApiDto response = listActions();
+
+ assertThat(response.getTotalCount()).isEqualTo(1000);
+ assertThat(response.getItems()).hasSize(numberOfActions);
+ assertThat(response.getItems().get(0).getActionCreatedAt())
+ .isEqualTo(
+ actionsListResponsePortalHistoryDto.getActionsList().get(0).getActionCreatedAt());
+ Assertions.assertThat(objectMapper.writeValueAsString(response.getItems().get(0).getAction()))
+ .isEqualTo(
+ objectMapper.writeValueAsString(
+ actionsListResponsePortalHistoryDto.getActionsList().get(0).getAction()));
+ }
+
+ @Test
+ void thatActionsListCanNotBeRetrieved() throws Exception {
+
+ ProblemPortalHistoryDto problemPortalHistoryDto =
+ new ProblemPortalHistoryDto()
+ .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
+ .detail("Internal database error")
+ .title("Internal Server Error")
+ .instance("portal-history");
+
+ mockListActionsProblem(problemPortalHistoryDto);
+
+ final ProblemApiDto response = listActionsProblem();
+
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY);
+ assertThat(response.getDownstreamStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
+ assertThat(response.getDetail()).isEqualTo(problemPortalHistoryDto.getDetail());
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/headers/XRequestIdHeaderTest.java b/app/src/test/java/org/onap/portal/bff/headers/XRequestIdHeaderTest.java
new file mode 100644
index 0000000..ad54c82
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/headers/XRequestIdHeaderTest.java
@@ -0,0 +1,76 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.headers;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.matching.EqualToPattern;
+import io.restassured.http.Header;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class XRequestIdHeaderTest extends BaseIntegrationTest {
+ protected static final String X_REQUEST_ID = "addf6005-3075-4c80-b7bc-2c70b7d42b57";
+
+ @Test
+ void xRequestIdHeaderIsCorrectlySetInResponse() throws Exception {
+ // use preferences endpoint for testing the header
+ final PreferencesPortalPrefsDto preferencesPortalPrefsDto =
+ new PreferencesPortalPrefsDto();
+
+ //mockGetTile(tileDetailResponsePortalServiceDto, X_REQUEST_ID);
+ mockGetPreferences(preferencesPortalPrefsDto, X_REQUEST_ID);
+
+ final String response = getPreferencesExtractHeader(X_REQUEST_ID);
+ assertThat(response).isEqualTo(X_REQUEST_ID);
+ }
+
+ protected void mockGetPreferences(PreferencesPortalPrefsDto preferencesPortalPrefsDto, String xRequestId)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlEqualTo("/v1/preferences"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withHeader("X-Request-Id", xRequestId)
+ .withBody(objectMapper.writeValueAsString(preferencesPortalPrefsDto))));
+ }
+
+ protected String getPreferencesExtractHeader(String xRequestId) {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", xRequestId))
+ .when()
+ .get("/preferences")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .header("X-Request-Id");
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/idtoken/IdTokenExchangeFilterFunctionTest.java b/app/src/test/java/org/onap/portal/bff/idtoken/IdTokenExchangeFilterFunctionTest.java
new file mode 100644
index 0000000..7d65849
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/idtoken/IdTokenExchangeFilterFunctionTest.java
@@ -0,0 +1,89 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.idtoken;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+
+import java.net.URI;
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.config.IdTokenExchangeFilterFunction;
+import org.springframework.http.HttpMethod;
+import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
+import org.springframework.mock.web.server.MockServerWebExchange;
+import org.springframework.web.reactive.function.client.ClientRequest;
+import org.springframework.web.reactive.function.client.ClientResponse;
+import org.springframework.web.reactive.function.client.ExchangeFunction;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+class IdTokenExchangeFilterFunctionTest extends BaseIntegrationTest {
+
+ @Test
+ void idTokenIsCorrectlyPropagated() {
+ final IdTokenExchangeFilterFunction filterFunction = new IdTokenExchangeFilterFunction();
+
+ final String idToken = UUID.randomUUID().toString();
+ final ServerWebExchange serverWebExchange =
+ MockServerWebExchange.builder(
+ MockServerHttpRequest.get("http://localhost:8000")
+ .header(IdTokenExchangeFilterFunction.X_AUTH_IDENTITY_HEADER, idToken))
+ .build();
+
+ final ClientRequest request =
+ ClientRequest.create(HttpMethod.GET, URI.create("http://api-server:9000"))
+ .attribute(ServerWebExchange.class.getName(), serverWebExchange)
+ .build();
+ final ClientResponse response = mock(ClientResponse.class);
+
+ final ExchangeFunction exchange =
+ r -> {
+ assertThat(r.headers().getOrEmpty(IdTokenExchangeFilterFunction.X_AUTH_IDENTITY_HEADER))
+ .containsExactly(idToken);
+
+ return Mono.just(response);
+ };
+
+ final ClientResponse result = filterFunction.filter(request, exchange).block();
+ assertThat(result).isEqualTo(response);
+ }
+
+ @Test
+ void exceptionIsThrownWhenIdTokenIsMissingInRequest() {
+ final IdTokenExchangeFilterFunction filterFunction = new IdTokenExchangeFilterFunction();
+
+ final ServerWebExchange serverWebExchange =
+ MockServerWebExchange.builder(MockServerHttpRequest.get("http://localhost:8000")).build();
+
+ final ClientRequest request =
+ ClientRequest.create(HttpMethod.GET, URI.create("http://api-server:9000"))
+ .attribute(ServerWebExchange.class.getName(), serverWebExchange)
+ .build();
+ final ExchangeFunction exchange = r -> Mono.just(mock(ClientResponse.class));
+
+ assertThatThrownBy(() -> filterFunction.filter(request, exchange).block())
+ .hasMessage("Forbidden: ID token is missing");
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/preferences/CreatePreferencesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/preferences/CreatePreferencesIntegrationTest.java
new file mode 100644
index 0000000..5259de8
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/preferences/CreatePreferencesIntegrationTest.java
@@ -0,0 +1,115 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.preferences;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+import io.restassured.http.Header;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.ProblemPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.CreatePreferencesRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class CreatePreferencesIntegrationTest extends PreferencesMocks {
+ @Test
+ void thatPreferencesCanBeCreated() throws Exception {
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto = new PreferencesPortalPrefsDto();
+ preferencesPortalPrefsDto.setProperties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ mockCreatePreferences(preferencesPortalPrefsDto);
+
+ final CreatePreferencesRequestApiDto request =
+ new CreatePreferencesRequestApiDto()
+ .properties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ final PreferencesResponseApiDto response = createPreferences(request);
+ assertThat(response).isNotNull();
+ assertThat(response.getProperties()).isEqualTo(preferencesPortalPrefsDto.getProperties());
+ }
+
+ @Test
+ void thatPreferencesCanNotBeCreated() throws Exception {
+ final var problemPortalPrefsDto = new ProblemPortalPrefsDto();
+ problemPortalPrefsDto.setStatus(HttpStatus.BAD_REQUEST.value());
+ problemPortalPrefsDto.setTitle(HttpStatus.BAD_REQUEST.toString());
+ problemPortalPrefsDto.setDetail("Some details");
+
+ final PreferencesPortalPrefsDto preferencesPortalPrefsDto =
+ new PreferencesPortalPrefsDto()
+ .properties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ mockCreatePreferencesError(preferencesPortalPrefsDto, problemPortalPrefsDto);
+
+ CreatePreferencesRequestApiDto responseBody =
+ new CreatePreferencesRequestApiDto()
+ .properties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_PROBLEM_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .body(responseBody)
+ .when()
+ .post("/preferences")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDetail()).isEqualTo(problemPortalPrefsDto.getDetail());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.PORTAL_PREFS);
+ assertThat(response.getDownstreamStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/preferences/GetPreferencesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/preferences/GetPreferencesIntegrationTest.java
new file mode 100644
index 0000000..1e1317b
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/preferences/GetPreferencesIntegrationTest.java
@@ -0,0 +1,77 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.preferences;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.http.Header;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.ProblemPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class GetPreferencesIntegrationTest extends PreferencesMocks {
+
+ @Test
+ void thatPreferencesCanBeRetrieved() throws Exception {
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto = new PreferencesPortalPrefsDto();
+ preferencesPortalPrefsDto.setProperties(getFixture(PREF_PROPERTIES_FILE, Object.class));
+ mockGetPreferences(preferencesPortalPrefsDto);
+
+ final PreferencesResponseApiDto response = getPreferences();
+ assertThat(response).isNotNull();
+ }
+
+ @Test
+ void thatPreferencesCanNotBeRetrieved() throws Exception {
+ final ProblemPortalPrefsDto problemResponse =
+ new ProblemPortalPrefsDto()
+ .title("Unauthorized")
+ .status(HttpStatus.UNAUTHORIZED.value())
+ .detail("Unauthorized error detail")
+ .instance("instance")
+ .type("type");
+
+ mockGetPreferencesError(problemResponse);
+
+ final ProblemApiDto errorResponse =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/preferences")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .contentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE)
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(errorResponse.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(errorResponse.getTitle()).isEqualTo(HttpStatus.UNAUTHORIZED.toString());
+ assertThat(errorResponse.getDetail()).isEqualTo("Unauthorized error detail");
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/preferences/PreferencesMocks.java b/app/src/test/java/org/onap/portal/bff/preferences/PreferencesMocks.java
new file mode 100644
index 0000000..e08c690
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/preferences/PreferencesMocks.java
@@ -0,0 +1,182 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.preferences;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.matching.EqualToPattern;
+import io.restassured.http.Header;
+import java.io.File;
+import java.io.IOException;
+import org.apache.http.HttpHeaders;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.ProblemPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.CreatePreferencesRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+public class PreferencesMocks extends BaseIntegrationTest {
+ protected static final String X_REQUEST_ID = "addf6005-3075-4c80-b7bc-2c70b7d42b57";
+
+ protected static final String PREF_PROPERTIES_FILE =
+ "src/test/resources/preferences/preferencesProperties.json";
+
+ protected static final ObjectMapper objectMapper =
+ new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
+
+ protected static <T> T getFixture(final String fileName, Class<T> type) throws IOException {
+ return objectMapper.readValue(new File(fileName), type);
+ }
+
+ protected PreferencesResponseApiDto getPreferences() {
+
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .when()
+ .get("/preferences")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(PreferencesResponseApiDto.class);
+ }
+
+ protected void mockGetPreferences(PreferencesPortalPrefsDto preferencesPortalPrefsDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlEqualTo("/v1/preferences"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(preferencesPortalPrefsDto))));
+ }
+
+ protected void mockGetPreferencesError(ProblemPortalPrefsDto problem) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlEqualTo("/v1/preferences"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(
+ org.springframework.http.HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_PROBLEM_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(problem))
+ .withStatus(HttpStatus.UNAUTHORIZED.value())));
+ }
+
+ protected PreferencesResponseApiDto createPreferences(CreatePreferencesRequestApiDto request) {
+ return requestSpecification()
+ .given()
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .body(request)
+ .when()
+ .post("/preferences")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(PreferencesResponseApiDto.class);
+ }
+
+ protected void mockCreatePreferences(PreferencesPortalPrefsDto preferencesPortalPrefsDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.post(WireMock.urlEqualTo("/v1/preferences"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .withRequestBody(
+ WireMock.equalToJson(
+ objectMapper.writeValueAsString(preferencesPortalPrefsDto), true, false))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(preferencesPortalPrefsDto))));
+ }
+
+ protected void mockCreatePreferencesError(
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto,
+ ProblemPortalPrefsDto problemPortalPrefsDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.post(WireMock.urlEqualTo("/v1/preferences"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .withRequestBody(
+ WireMock.equalToJson(
+ objectMapper.writeValueAsString(preferencesPortalPrefsDto), true, false))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(HttpStatus.BAD_REQUEST.value())
+ .withBody(objectMapper.writeValueAsString(problemPortalPrefsDto))));
+ }
+
+ protected PreferencesResponseApiDto updatePreferences(CreatePreferencesRequestApiDto request) {
+ return requestSpecification()
+ .given()
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .body(request)
+ .when()
+ .put("/preferences")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(PreferencesResponseApiDto.class);
+ }
+
+ protected void mockUpdatePreferences(PreferencesPortalPrefsDto preferencesPortalPrefsDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.put(WireMock.urlEqualTo("/v1/preferences"))
+ .withHeader("X-Request-Id", new EqualToPattern(X_REQUEST_ID))
+ .withRequestBody(
+ WireMock.equalToJson(
+ objectMapper.writeValueAsString(preferencesPortalPrefsDto), true, false))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(preferencesPortalPrefsDto))));
+ }
+
+ protected void mockUpdatePreferencesError(
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto,
+ ProblemPortalPrefsDto problemPortalPrefsDto)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.put(WireMock.urlEqualTo("/v1/preferences"))
+ .withRequestBody(
+ WireMock.equalToJson(
+ objectMapper.writeValueAsString(preferencesPortalPrefsDto), true, false))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(HttpStatus.BAD_REQUEST.value())
+ .withBody(objectMapper.writeValueAsString(problemPortalPrefsDto))));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/preferences/UpdatePreferencesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/preferences/UpdatePreferencesIntegrationTest.java
new file mode 100644
index 0000000..74d902c
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/preferences/UpdatePreferencesIntegrationTest.java
@@ -0,0 +1,114 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.preferences;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+import io.restassured.http.Header;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.ProblemPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.CreatePreferencesRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class UpdatePreferencesIntegrationTest extends PreferencesMocks {
+ @Test
+ void thatPreferencesCanBeUpdated() throws Exception {
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto = new PreferencesPortalPrefsDto();
+ preferencesPortalPrefsDto.setProperties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ mockUpdatePreferences(preferencesPortalPrefsDto);
+
+ final CreatePreferencesRequestApiDto requestApiDto =
+ new CreatePreferencesRequestApiDto()
+ .properties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ final PreferencesResponseApiDto response = updatePreferences(requestApiDto);
+ assertThat(response).isNotNull();
+ assertThat(response.getProperties()).isEqualTo(preferencesPortalPrefsDto.getProperties());
+ }
+
+ @Test
+ void thatPreferencesCanNotBeUpdated() throws Exception {
+ final var problemPortalPrefsDto = new ProblemPortalPrefsDto();
+ problemPortalPrefsDto.setStatus(HttpStatus.BAD_REQUEST.value());
+ problemPortalPrefsDto.setTitle(HttpStatus.BAD_REQUEST.toString());
+ problemPortalPrefsDto.setDetail("Some details");
+
+ final PreferencesPortalPrefsDto preferencesPortalPrefsDto =
+ new PreferencesPortalPrefsDto()
+ .properties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ mockUpdatePreferencesError(preferencesPortalPrefsDto, problemPortalPrefsDto);
+
+ CreatePreferencesRequestApiDto requestApiDto =
+ new CreatePreferencesRequestApiDto()
+ .properties(
+ "{\n"
+ + "\"properties\": {\n"
+ + "\"appStarter\": \"value1\",\n"
+ + "\"dashboard\": {\"key1:\" : \"value2\"}\n"
+ + "}\n"
+ + "\n"
+ + "}");
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_PROBLEM_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", X_REQUEST_ID))
+ .body(requestApiDto)
+ .when()
+ .put("/preferences")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.PORTAL_PREFS);
+ assertThat(response.getDownstreamStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/roles/ListRealmRolesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/roles/ListRealmRolesIntegrationTest.java
new file mode 100644
index 0000000..03f39db
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/roles/ListRealmRolesIntegrationTest.java
@@ -0,0 +1,88 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.roles;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class ListRealmRolesIntegrationTest extends RolesMocks {
+
+ @Test
+ void thatListOfRealmRolesCanBeProvided() throws Exception {
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+ final List<RoleKeycloakDto> keycloakRoles = List.of(keycloakRole1, keycloakRole2);
+ mockListRealmRoles(keycloakRoles);
+
+ final RoleApiDto role1 = new RoleApiDto().id("1").name("role1");
+ final RoleApiDto role2 = new RoleApiDto().id("2").name("role2");
+
+ final RoleListResponseApiDto response = listRoles();
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(response.getItems().size());
+ assertThat(response.getItems()).containsExactly(role1, role2);
+ }
+
+ @Test
+ void thatListOfRealmRolesCanNotBeProvided() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlMatching(String.format("/auth/admin/realms/%s/roles", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/roles")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/roles/RolesMocks.java b/app/src/test/java/org/onap/portal/bff/roles/RolesMocks.java
new file mode 100644
index 0000000..fa43302
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/roles/RolesMocks.java
@@ -0,0 +1,57 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.roles;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+public class RolesMocks extends BaseIntegrationTest {
+
+ protected RoleListResponseApiDto listRoles() {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/roles")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+ }
+
+ protected void mockListRealmRoles(List<RoleKeycloakDto> roles) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlMatching(String.format("/auth/admin/realms/%s/roles", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(roles))));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/CreateUserIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/CreateUserIntegrationTest.java
new file mode 100644
index 0000000..641724e
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/CreateUserIntegrationTest.java
@@ -0,0 +1,308 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static io.vavr.API.List;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.API;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RequiredActionsKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.UserKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.CreateUserRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.UserResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class CreateUserIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void userCanBeCreated() throws Exception {
+ String xRequestID = "addf6005-3075-4c80-b7bc-2c70b7d42b57";
+
+ final UserKeycloakDto keycloakRequest =
+ new UserKeycloakDto()
+ .username("user1")
+ .email("user1@localhost.com")
+ .enabled(true)
+ .requiredActions(List(RequiredActionsKeycloakDto.UPDATE_PASSWORD).toJavaList());
+ final String userId = randomUUID();
+ mockCreateUser(keycloakRequest, userId);
+
+ final UserKeycloakDto keycloakResponse =
+ new UserKeycloakDto()
+ .id(userId)
+ .username(keycloakRequest.getUsername())
+ .email(keycloakRequest.getEmail())
+ .firstName(keycloakRequest.getFirstName())
+ .lastName(keycloakRequest.getLastName())
+ .enabled(keycloakRequest.getEnabled());
+ mockGetUser(userId, keycloakResponse);
+
+ final RoleKeycloakDto onapAdmin = new RoleKeycloakDto().id(randomUUID()).name("onap_admin");
+ mockAddRoles(userId, List(onapAdmin));
+ mockAssignedRoles(userId, List(onapAdmin));
+ mockListRealmRoles(List(onapAdmin));
+
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", xRequestID))
+ .when()
+ .get(String.format("/users/%s/roles", userId))
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+ mockSendUpdateEmail(userId, API.List(RequiredActionsKeycloakDto.UPDATE_PASSWORD));
+
+ final CreateUserRequestApiDto request =
+ new CreateUserRequestApiDto()
+ .username("user1")
+ .email("user1@localhost.com")
+ .firstName(null)
+ .lastName(null)
+ .enabled(true)
+ .addRolesItem(new RoleApiDto().id(onapAdmin.getId()).name("onap_admin"));
+
+ final UserResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", xRequestID))
+ .body(request)
+ .when()
+ .post("/users")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(UserResponseApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getId()).isEqualTo(userId);
+ assertThat(response.getUsername()).isEqualTo(request.getUsername());
+ assertThat(response.getEmail()).isEqualTo(request.getEmail());
+ assertThat(response.getFirstName()).isEqualTo(request.getFirstName());
+ assertThat(response.getLastName()).isEqualTo(request.getLastName());
+ assertThat(response.getEnabled()).isEqualTo(request.getEnabled());
+ assertThat(response.getRealmRoles()).containsExactly("onap_admin");
+ }
+
+ @Test
+ void userCanNotBeCreated() throws Exception {
+ final UserKeycloakDto keycloakRequest =
+ new UserKeycloakDto()
+ .username("user1")
+ .email("user1@localhost.com")
+ .enabled(true)
+ .requiredActions(List(RequiredActionsKeycloakDto.UPDATE_PASSWORD).toJavaList());
+ final String userId = randomUUID();
+ mockCreateUser(keycloakRequest, userId);
+
+ final UserKeycloakDto keycloakResponse =
+ new UserKeycloakDto()
+ .id(userId)
+ .username(keycloakRequest.getUsername())
+ .email(keycloakRequest.getEmail())
+ .firstName(keycloakRequest.getFirstName())
+ .lastName(keycloakRequest.getLastName())
+ .enabled(keycloakRequest.getEnabled());
+ mockGetUser(userId, keycloakResponse);
+
+ final RoleKeycloakDto onapAdmin = new RoleKeycloakDto().id(randomUUID()).name("onap_admin");
+ mockAddRoles(userId, List(onapAdmin));
+ mockListRealmRoles(List(onapAdmin));
+
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ mockSendUpdateEmailWithProblem(
+ userId, API.List(RequiredActionsKeycloakDto.UPDATE_PASSWORD), keycloakErrorResponse);
+
+ final CreateUserRequestApiDto request =
+ new CreateUserRequestApiDto()
+ .username("user1")
+ .email("user1@localhost.com")
+ .firstName(null)
+ .lastName(null)
+ .enabled(true)
+ .addRolesItem(new RoleApiDto().id(onapAdmin.getId()).name("onap_admin"));
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(request)
+ .when()
+ .post("/users")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+
+ @Test
+ void userCanNotBeCreatedWithNonexistentRoles() throws Exception {
+ String xRequestID = "addf6005-3075-4c80-b7bc-2c70b7d42b57";
+
+ mockListRealmRoles(List());
+
+ final CreateUserRequestApiDto request =
+ new CreateUserRequestApiDto()
+ .username("user1")
+ .email("user1@localhost.com")
+ .firstName(null)
+ .lastName(null)
+ .enabled(true)
+ .addRolesItem(new RoleApiDto().id("nonexistent_id").name("nonexistent_role"));
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", xRequestID))
+ .body(request)
+ .when()
+ .post("/users")
+ .then()
+ .statusCode(HttpStatus.NOT_FOUND.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.NOT_FOUND.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+
+ protected void mockCreateUser(UserKeycloakDto request, String userId) throws Exception {
+ WireMock.stubFor(
+ WireMock.post(WireMock.urlMatching(String.format("/auth/admin/realms/%s/users", realm)))
+ .withRequestBody(WireMock.equalToJson(objectMapper.writeValueAsString(request)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withHeader(
+ "location",
+ String.format("/auth/admin/realms/%s/users/%s", realm, userId))));
+ }
+
+ protected void mockGetUser(String userId, UserKeycloakDto response) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/%s", realm, userId)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(response))));
+ }
+
+ protected void mockAddRoles(String userId, List<RoleKeycloakDto> response) throws Exception {
+ WireMock.stubFor(
+ WireMock.post(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/%s/role-mappings/realm", realm, userId)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(response))));
+ }
+
+ protected void mockSendUpdateEmailWithProblem(
+ String userId,
+ List<RequiredActionsKeycloakDto> request,
+ ErrorResponseKeycloakDto keycloakErrorResponse)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.put(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/%s/execute-actions-email", realm, userId)))
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(request)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+ }
+
+ protected void mockAssignedRoles(String userID, List<RoleKeycloakDto> keycloakRoles)
+ throws JsonProcessingException {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/%s/role-mappings/realm", realm, userID)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakRoles))));
+ }
+
+ protected void mockSendUpdateEmail(String userId, List<RequiredActionsKeycloakDto> request)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.put(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/%s/execute-actions-email", realm, userId)))
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(request)))
+ .willReturn(
+ WireMock.aResponse().withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)));
+ }
+
+ protected void mockListRealmRoles(List<RoleKeycloakDto> roles) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlMatching(String.format("/auth/admin/realms/%s/roles", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(roles))));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/DeleteUserIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/DeleteUserIntegrationTest.java
new file mode 100644
index 0000000..69f6906
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/DeleteUserIntegrationTest.java
@@ -0,0 +1,83 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class DeleteUserIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void userCanBeDeleted() {
+ WireMock.stubFor(
+ WireMock.delete(WireMock.urlMatching(String.format("/auth/admin/realms/%s/users/1", realm)))
+ .willReturn(WireMock.aResponse().withStatus(204)));
+
+ requestSpecification()
+ .given()
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .delete("/users/1")
+ .then()
+ .statusCode(HttpStatus.NO_CONTENT.value());
+ }
+
+ @Test
+ void userCanNotBeDeleted() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ WireMock.stubFor(
+ WireMock.delete(WireMock.urlMatching(String.format("/auth/admin/realms/%s/users/1", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .delete("/users/1")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/GetUserDetailIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/GetUserDetailIntegrationTest.java
new file mode 100644
index 0000000..1bca58c
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/GetUserDetailIntegrationTest.java
@@ -0,0 +1,126 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.UserKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.UserResponseApiDto;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class GetUserDetailIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void detailOfUserCanBeProvided() throws Exception {
+ final UserKeycloakDto keycloakUser =
+ new UserKeycloakDto().id("1").username("user1").email("user1@localhost").enabled(true);
+
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlMatching(String.format("/auth/admin/realms/%s/users/1", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakUser))));
+
+ final RoleKeycloakDto keycloackRole = new RoleKeycloakDto().id(randomUUID()).name("onap_admin");
+ mockAssignedRoles(keycloakUser.getId(), List.of(keycloackRole));
+
+ final UserResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/users/1")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(UserResponseApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getId()).isEqualTo("1");
+ assertThat(response.getUsername()).isEqualTo("user1");
+ assertThat(response.getEmail()).isEqualTo("user1@localhost");
+ assertThat(response.getFirstName()).isNull();
+ assertThat(response.getLastName()).isNull();
+ assertThat(response.getRealmRoles()).containsExactly(keycloackRole.getName());
+ }
+
+ @Test
+ void detailOfNonExistentUserCanNotBeProvided() throws Exception {
+
+ ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlMatching(String.format("/auth/admin/realms/%s/users/1", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/users/1")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+
+ protected void mockAssignedRoles(String userID, List<RoleKeycloakDto> keycloakRoles)
+ throws JsonProcessingException {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/%s/role-mappings/realm", realm, userID)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakRoles))));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/ListAssignedRolesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/ListAssignedRolesIntegrationTest.java
new file mode 100644
index 0000000..6564577
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/ListAssignedRolesIntegrationTest.java
@@ -0,0 +1,111 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class ListAssignedRolesIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void listOfAssignedRolesCanBeProvided() throws Exception {
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+ final List<RoleKeycloakDto> keycloakRoles = List.of(keycloakRole1, keycloakRole2);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakRoles))));
+
+ final RoleListResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+
+ final RoleApiDto role1 = new RoleApiDto().id("1").name("role1");
+ final RoleApiDto role2 = new RoleApiDto().id("2").name("role2");
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(response.getItems().size());
+ assertThat(response.getItems()).containsExactly(role1, role2);
+ }
+
+ @Test
+ void listOfAssignedRolesCanNotBeProvided() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/ListAvailableRolesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/ListAvailableRolesIntegrationTest.java
new file mode 100644
index 0000000..b5ca3c6
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/ListAvailableRolesIntegrationTest.java
@@ -0,0 +1,113 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class ListAvailableRolesIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void listOfAvailableRolesCanBeProvided() throws Exception {
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+ final List<RoleKeycloakDto> keycloakRoles = List.of(keycloakRole1, keycloakRole2);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakRoles))));
+
+ final RoleListResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/users/1/roles/available")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+
+ final RoleApiDto role1 = new RoleApiDto().id("1").name("role1");
+ final RoleApiDto role2 = new RoleApiDto().id("2").name("role2");
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(response.getItems().size());
+ assertThat(response.getItems()).containsExactly(role1, role2);
+ }
+
+ @Test
+ void listOfAvailableRolesCanNotBeProvided() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get("/users/1/roles/available")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/ListUsersIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/ListUsersIntegrationTest.java
new file mode 100644
index 0000000..1df7b69
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/ListUsersIntegrationTest.java
@@ -0,0 +1,238 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static io.vavr.API.*;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import io.vavr.control.Option;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.UserKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.UserListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.UserResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class ListUsersIntegrationTest extends BaseIntegrationTest {
+ private final RoleKeycloakDto ONAP_ADMIN =
+ new RoleKeycloakDto().id(randomUUID()).name("onap_admin");
+ private final RoleKeycloakDto OFFLINE_ACCESS =
+ new RoleKeycloakDto().id(randomUUID()).name("offline_access");
+
+ @Test
+ void listOfUsersWithDefaultPaginationCanBeProvided() throws Exception {
+ final UserKeycloakDto tAdmin =
+ new UserKeycloakDto()
+ .id("8f05caaf-0e36-4bcd-b9b3-0ae3d531acc2")
+ .username("t-admin")
+ .email("t-admin@example.xyz")
+ .firstName("FirstName4t-admin")
+ .lastName("LastName4t-admin")
+ .enabled(true);
+
+ final UserKeycloakDto tDesigner =
+ new UserKeycloakDto()
+ .id("04ed5525-740d-42da-bc4c-2d3fcf955ee9")
+ .username("t-designer")
+ .email("t-designer@example.xyz")
+ .firstName("FirstName4t-designer")
+ .lastName("LastName4t-designer")
+ .enabled(true);
+
+ mockGetUserCount(2);
+ mockListUsers(List.of(tAdmin, tDesigner), 0, 10);
+ mockListRealmRoles(List(ONAP_ADMIN, OFFLINE_ACCESS));
+ mockListRoleUsers(OFFLINE_ACCESS.getName(), List(tAdmin, tDesigner));
+ mockListRoleUsers(ONAP_ADMIN.getName(), List(tAdmin));
+
+ final UserResponseApiDto expectedTAdmin =
+ new UserResponseApiDto()
+ .id("8f05caaf-0e36-4bcd-b9b3-0ae3d531acc2")
+ .username("t-admin")
+ .email("t-admin@example.xyz")
+ .firstName("FirstName4t-admin")
+ .lastName("LastName4t-admin")
+ .enabled(true)
+ .addRealmRolesItem("onap_admin")
+ .addRealmRolesItem("offline_access");
+ final UserResponseApiDto expectedTDesigner =
+ new UserResponseApiDto()
+ .id("04ed5525-740d-42da-bc4c-2d3fcf955ee9")
+ .username("t-designer")
+ .email("t-designer@example.xyz")
+ .firstName("FirstName4t-designer")
+ .lastName("LastName4t-designer")
+ .enabled(true)
+ .addRealmRolesItem("offline_access");
+
+ final UserListResponseApiDto response = listUsers();
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(2);
+ assertThat(response.getItems().get(0).getRealmRoles())
+ .containsExactlyInAnyOrder(
+ expectedTAdmin.getRealmRoles().get(0), expectedTAdmin.getRealmRoles().get(1));
+ assertThat(response.getItems().get(1).getRealmRoles())
+ .containsExactly(expectedTDesigner.getRealmRoles().get(0));
+ }
+
+ @Test
+ void listOfUsersWithSpecifiedPaginationCanBeProvided() throws Exception {
+ final UserKeycloakDto keycloakUser =
+ new UserKeycloakDto()
+ .id("1")
+ .username("user1")
+ .email("user1@localhost")
+ .firstName("User1")
+ .lastName("Test")
+ .enabled(true);
+
+ mockGetUserCount(1);
+ mockListUsers(List.of(keycloakUser), 60, 30);
+ mockListRealmRoles(List());
+
+ final UserListResponseApiDto response = listUsers(Some(3), Some(30));
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(1);
+ assertThat(response.getItems())
+ .containsExactly(
+ new UserResponseApiDto()
+ .id("1")
+ .username("user1")
+ .enabled(true)
+ .email("user1@localhost")
+ .firstName("User1")
+ .lastName("Test")
+ .realmRoles(java.util.List.of()));
+ }
+
+ @Test
+ void listOfUsersWithSpecifiedPaginationCanNotBeProvided() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ mockGetUserCount(55);
+ mockListUsersWithProblems(keycloakErrorResponse, 60, 30);
+ mockListRealmRoles(List());
+
+ ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get(adjustPath("/users", Some(3), Some(30)))
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+
+ protected void mockGetUserCount(Integer userCount) {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(String.format("/auth/admin/realms/%s/users/count", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(userCount.toString())));
+ }
+
+ protected void mockListUsers(List<UserKeycloakDto> keycloakUsers, Integer first, Integer max)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users\\?first=%s&max=%s", realm, first, max)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakUsers))));
+ }
+
+ protected void mockListRealmRoles(List<RoleKeycloakDto> roles) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(WireMock.urlMatching(String.format("/auth/admin/realms/%s/roles", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(roles))));
+ }
+
+ protected void mockListRoleUsers(String roleName, List<UserKeycloakDto> response)
+ throws Exception {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/roles/%s/users", realm, roleName)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(response))));
+ }
+
+ protected UserListResponseApiDto listUsers() {
+ return listUsers(None(), None());
+ }
+
+ protected UserListResponseApiDto listUsers(Option<Integer> page, Option<Integer> pageSize) {
+ return requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .when()
+ .get(adjustPath("/users", page, pageSize))
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(UserListResponseApiDto.class);
+ }
+
+ protected void mockListUsersWithProblems(
+ ErrorResponseKeycloakDto keycloakErrorResponse, Integer first, Integer max) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users\\?first=%s&max=%s", realm, first, max)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/UpdateAssignedRolesIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/UpdateAssignedRolesIntegrationTest.java
new file mode 100644
index 0000000..54afdcd
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/UpdateAssignedRolesIntegrationTest.java
@@ -0,0 +1,452 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.stubbing.Scenario;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class UpdateAssignedRolesIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void listOfAssignedRolesCanBeUpdatedWhenPreviousAssignedRolesAreEmpty() throws Exception {
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+
+ final List<RoleKeycloakDto> keycloakAvailableRoles = List.of(keycloakRole1, keycloakRole2);
+ final List<RoleKeycloakDto> keycloakInitialAssignedRoles = List.of();
+ final List<RoleKeycloakDto> keycloakUpdatedAssignedRoles = List.of(keycloakRole1);
+
+ final List<RoleKeycloakDto> keycloakRolesToAdd = List.of(keycloakRole1);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakAvailableRoles))));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakInitialAssignedRoles))));
+
+ WireMock.stubFor(
+ WireMock.post(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToAdd)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value()))
+ .willSetStateTo("rolesUpdated"));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs("rolesUpdated")
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakUpdatedAssignedRoles))));
+
+ final RoleApiDto roleToAssign = new RoleApiDto().id("1").name("role1");
+ final List<RoleApiDto> rolesToAssign = List.of(roleToAssign);
+
+ final RoleListResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(rolesToAssign)
+ .when()
+ .put("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+
+ final RoleApiDto role = new RoleApiDto().id("1").name("role1");
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(response.getItems().size());
+ assertThat(response.getItems()).containsExactly(role);
+ }
+
+ @Test
+ void listOfAssignedRolesCanBeUpdatedWhenPreviousAssignedRolesAreNotEmpty() throws Exception {
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+ final RoleKeycloakDto keycloakRole3 = new RoleKeycloakDto().id("3").name("role3");
+
+ final List<RoleKeycloakDto> keycloakAvailableRoles =
+ List.of(keycloakRole1, keycloakRole2, keycloakRole3);
+ final List<RoleKeycloakDto> keycloakInitialAssignedRoles =
+ List.of(keycloakRole1, keycloakRole2);
+ final List<RoleKeycloakDto> keycloakUpdatedAssignedRoles = List.of(keycloakRole1);
+
+ final List<RoleKeycloakDto> keycloakRolesToRemove = List.of(keycloakRole1, keycloakRole2);
+ final List<RoleKeycloakDto> keycloakRolesToAdd = List.of(keycloakRole1);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakAvailableRoles))));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakInitialAssignedRoles))));
+
+ WireMock.stubFor(
+ WireMock.delete(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .withRequestBody(
+ WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToRemove)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value())));
+
+ WireMock.stubFor(
+ WireMock.post(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToAdd)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value()))
+ .willSetStateTo("rolesUpdated"));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs("rolesUpdated")
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakUpdatedAssignedRoles))));
+
+ final RoleApiDto roleToAssign = new RoleApiDto().id("1").name("role1");
+ final List<RoleApiDto> rolesToAssign = List.of(roleToAssign);
+
+ final RoleListResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(rolesToAssign)
+ .when()
+ .put("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+
+ final RoleApiDto role = new RoleApiDto().id("1").name("role1");
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(response.getItems().size());
+ assertThat(response.getItems()).containsExactly(role);
+ }
+
+ @Test
+ void listOfAssignedRolesCanBeCleared() throws Exception {
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+
+ final List<RoleKeycloakDto> keycloakAvailableRoles = List.of(keycloakRole1, keycloakRole2);
+ final List<RoleKeycloakDto> keycloakAssignedRoles = List.empty();
+ final List<RoleKeycloakDto> keycloakRolesToRemove = List.of(keycloakRole1, keycloakRole2);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakAvailableRoles))));
+
+ WireMock.stubFor(
+ WireMock.delete(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .withRequestBody(
+ WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToRemove)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value())));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakAssignedRoles))));
+
+ final List<RoleApiDto> rolesToAssign = List.empty();
+
+ final RoleListResponseApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(rolesToAssign)
+ .when()
+ .put("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.OK.value())
+ .extract()
+ .body()
+ .as(RoleListResponseApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTotalCount()).isEqualTo(response.getItems().size());
+ assertThat(response.getItems()).isEmpty();
+ }
+
+ @Test
+ void listOfAssignedRolesCanNotBeUpdatedWhenPreviousAssignedRolesAreEmpty() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+
+ final List<RoleKeycloakDto> keycloakAvailableRoles = List.of(keycloakRole1, keycloakRole2);
+ final List<RoleKeycloakDto> keycloakInitialAssignedRoles = List.of();
+
+ final List<RoleKeycloakDto> keycloakRolesToAdd = List.of(keycloakRole1);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakAvailableRoles))));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakInitialAssignedRoles))));
+
+ WireMock.stubFor(
+ WireMock.post(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToAdd)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value()))
+ .willSetStateTo("rolesUpdated"));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs("rolesUpdated")
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ final RoleApiDto roleToAssign = new RoleApiDto().id("1").name("role1");
+ final List<RoleApiDto> rolesToAssign = List.of(roleToAssign);
+
+ ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(rolesToAssign)
+ .when()
+ .put("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+
+ @Test
+ void listOfAssignedRolesCanNotBeUpdatedWhenPreviousAssignedRolesAreNotEmpty() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ final RoleKeycloakDto keycloakRole1 = new RoleKeycloakDto().id("1").name("role1");
+ final RoleKeycloakDto keycloakRole2 = new RoleKeycloakDto().id("2").name("role2");
+ final RoleKeycloakDto keycloakRole3 = new RoleKeycloakDto().id("3").name("role3");
+
+ final List<RoleKeycloakDto> keycloakAvailableRoles =
+ List.of(keycloakRole1, keycloakRole2, keycloakRole3);
+ final List<RoleKeycloakDto> keycloakUpdatedAssignedRoles = List.of(keycloakRole1);
+
+ final List<RoleKeycloakDto> keycloakRolesToRemove = List.of(keycloakRole1, keycloakRole2);
+ final List<RoleKeycloakDto> keycloakRolesToAdd = List.of(keycloakRole1);
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/1/role-mappings/realm/available", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakAvailableRoles))));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ WireMock.stubFor(
+ WireMock.delete(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .withRequestBody(
+ WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToRemove)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value())));
+
+ WireMock.stubFor(
+ WireMock.post(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs(Scenario.STARTED)
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRolesToAdd)))
+ .willReturn(WireMock.aResponse().withStatus(HttpStatus.NO_CONTENT.value()))
+ .willSetStateTo("rolesUpdated"));
+
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/role-mappings/realm", realm)))
+ .inScenario("test")
+ .whenScenarioStateIs("rolesUpdated")
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakUpdatedAssignedRoles))));
+
+ final RoleApiDto roleToAssign = new RoleApiDto().id("1").name("role1");
+ final List<RoleApiDto> rolesToAssign = List.of(roleToAssign);
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .accept(MediaType.APPLICATION_JSON_VALUE)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(rolesToAssign)
+ .when()
+ .put("/users/1/roles")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/UpdateUserIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/UpdateUserIntegrationTest.java
new file mode 100644
index 0000000..74f0438
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/UpdateUserIntegrationTest.java
@@ -0,0 +1,134 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.UserKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.UpdateUserRequestApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class UpdateUserIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void userCanBeUpdated() throws Exception {
+ final UserKeycloakDto keycloakRequest = new UserKeycloakDto().firstName("User1").enabled(false);
+ mockUpdateUser(keycloakRequest, "1");
+
+ final UpdateUserRequestApiDto request =
+ new UpdateUserRequestApiDto().email(null).firstName("User1").lastName(null).enabled(false);
+
+ requestSpecification()
+ .given()
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(request)
+ .when()
+ .put("/users/1")
+ .then()
+ .statusCode(HttpStatus.OK.value());
+ }
+
+ @Test
+ void userCanNotBeUpdated() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ final UserKeycloakDto keycloakRequest = new UserKeycloakDto().firstName("User1").enabled(false);
+
+ WireMock.stubFor(
+ WireMock.put(WireMock.urlMatching(String.format("/auth/admin/realms/%s/users/1", realm)))
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRequest)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ final UpdateUserRequestApiDto request =
+ new UpdateUserRequestApiDto().email(null).firstName("User1").lastName(null).enabled(false);
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(request)
+ .when()
+ .put("/users/1")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+
+ protected void mockUpdateUser(UserKeycloakDto request, String userId) throws Exception {
+ WireMock.stubFor(
+ WireMock.put(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/%s", realm, userId)))
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(request)))
+ .willReturn(
+ WireMock.aResponse().withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)));
+ }
+
+ protected void mockGetUser(String userId, UserKeycloakDto response) throws Exception {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/%s", realm, userId)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(response))));
+ }
+
+ protected void mockAssignedRoles(String userID, List<RoleKeycloakDto> keycloakRoles)
+ throws JsonProcessingException {
+ WireMock.stubFor(
+ WireMock.get(
+ WireMock.urlMatching(
+ String.format(
+ "/auth/admin/realms/%s/users/%s/role-mappings/realm", realm, userID)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withBody(objectMapper.writeValueAsString(keycloakRoles))));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/users/UpdateUserPasswordIntegrationTest.java b/app/src/test/java/org/onap/portal/bff/users/UpdateUserPasswordIntegrationTest.java
new file mode 100644
index 0000000..200ad69
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/users/UpdateUserPasswordIntegrationTest.java
@@ -0,0 +1,107 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.users;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import io.restassured.http.Header;
+import org.junit.jupiter.api.Test;
+import org.onap.portal.bff.BaseIntegrationTest;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.CredentialKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.openapi.server.model.UpdateUserPasswordRequestApiDto;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+class UpdateUserPasswordIntegrationTest extends BaseIntegrationTest {
+
+ @Test
+ void userPasswordCanBeUpdated() throws Exception {
+ final CredentialKeycloakDto keycloakRequest =
+ new CredentialKeycloakDto().temporary(true).value("pswd");
+
+ WireMock.stubFor(
+ WireMock.put(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/reset-password", realm)))
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRequest)))
+ .willReturn(WireMock.aResponse().withStatus(204)));
+
+ final UpdateUserPasswordRequestApiDto request =
+ new UpdateUserPasswordRequestApiDto().temporary(true).value("pswd");
+
+ requestSpecification()
+ .given()
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(request)
+ .when()
+ .put("/users/1/password")
+ .then()
+ .statusCode(HttpStatus.NO_CONTENT.value());
+ }
+
+ @Test
+ void userPasswordCanNotBeUpdated() throws Exception {
+ final ErrorResponseKeycloakDto keycloakErrorResponse =
+ new ErrorResponseKeycloakDto().errorMessage("Some error message");
+
+ final CredentialKeycloakDto keycloakRequest =
+ new CredentialKeycloakDto().temporary(true).value("pswd");
+
+ WireMock.stubFor(
+ WireMock.put(
+ WireMock.urlMatching(
+ String.format("/auth/admin/realms/%s/users/1/reset-password", realm)))
+ .withRequestBody(WireMock.equalTo(objectMapper.writeValueAsString(keycloakRequest)))
+ .willReturn(
+ WireMock.aResponse()
+ .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
+ .withStatus(400)
+ .withBody(objectMapper.writeValueAsString(keycloakErrorResponse))));
+
+ final UpdateUserPasswordRequestApiDto request =
+ new UpdateUserPasswordRequestApiDto().temporary(true).value("pswd");
+
+ final ProblemApiDto response =
+ requestSpecification()
+ .given()
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .header(new Header("X-Request-Id", "addf6005-3075-4c80-b7bc-2c70b7d42b57"))
+ .body(request)
+ .when()
+ .put("/users/1/password")
+ .then()
+ .statusCode(HttpStatus.BAD_GATEWAY.value())
+ .extract()
+ .body()
+ .as(ProblemApiDto.class);
+
+ assertThat(response).isNotNull();
+ assertThat(response.getTitle()).isEqualTo(HttpStatus.BAD_REQUEST.toString());
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_GATEWAY.value());
+ assertThat(response.getDownstreamSystem())
+ .isEqualTo(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK);
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/utils/SortingChainResolverTest.java b/app/src/test/java/org/onap/portal/bff/utils/SortingChainResolverTest.java
new file mode 100644
index 0000000..c12b01f
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/utils/SortingChainResolverTest.java
@@ -0,0 +1,141 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.vavr.collection.HashMap;
+import io.vavr.collection.List;
+import io.vavr.control.Option;
+import java.util.Comparator;
+import lombok.Data;
+import lombok.NonNull;
+import org.junit.jupiter.api.Test;
+
+class SortingChainResolverTest {
+
+ @Test
+ void emptySortIsCorrectlyResolved() {
+ final SortingChainResolver<DummyPerson> resolver =
+ new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
+
+ final Option<Comparator<DummyPerson>> comparatorOption =
+ resolver.resolve(SortingParser.parse(""));
+ assertThat(comparatorOption.isEmpty()).isTrue();
+ }
+
+ @Test
+ void sortWithUnknownPropertyIsCorrectlyResolved() {
+ final SortingChainResolver<DummyPerson> resolver =
+ new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
+
+ final Option<Comparator<DummyPerson>> comparatorOption =
+ resolver.resolve(SortingParser.parse("unknown"));
+ assertThat(comparatorOption.isEmpty()).isTrue();
+ }
+
+ @Test
+ void sortWithSingleAscendingPropertyIsCorrectlyResolved() {
+ final SortingChainResolver<DummyPerson> resolver =
+ new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
+
+ final Option<Comparator<DummyPerson>> comparatorOption =
+ resolver.resolve(SortingParser.parse("age"));
+ assertThat(comparatorOption.isDefined()).isTrue();
+
+ final List<DummyPerson> list =
+ List.of(new DummyPerson("Albert", 10), new DummyPerson("Bernard", 7));
+ final List<DummyPerson> expectedList =
+ List.of(new DummyPerson("Bernard", 7), new DummyPerson("Albert", 10));
+ assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
+ }
+
+ @Test
+ void sortWithSingleDescendingPropertyIsCorrectlyResolved() {
+ final SortingChainResolver<DummyPerson> resolver =
+ new SortingChainResolver<>(HashMap.of("age", Comparator.comparing(DummyPerson::getAge)));
+
+ final Option<Comparator<DummyPerson>> comparatorOption =
+ resolver.resolve(SortingParser.parse("-age"));
+ assertThat(comparatorOption.isDefined()).isTrue();
+
+ final List<DummyPerson> list =
+ List.of(new DummyPerson("Charles", 23), new DummyPerson("Dominick", 31));
+ final List<DummyPerson> expectedList =
+ List.of(new DummyPerson("Dominick", 31), new DummyPerson("Charles", 23));
+ assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
+ }
+
+ @Test
+ void sortWithMultiplePropertiesIsCorrectlyResolved() {
+ final SortingChainResolver<DummyPerson> resolver =
+ new SortingChainResolver<>(
+ HashMap.of("age", Comparator.comparing(DummyPerson::getAge))
+ .put("name", Comparator.comparing(DummyPerson::getName)));
+
+ final Option<Comparator<DummyPerson>> comparatorOption =
+ resolver.resolve(SortingParser.parse("age,name"));
+ assertThat(comparatorOption.isDefined()).isTrue();
+
+ final List<DummyPerson> list =
+ List.of(
+ new DummyPerson("Harold", 27),
+ new DummyPerson("Diego", 70),
+ new DummyPerson("David", 27));
+ final List<DummyPerson> expectedList =
+ List.of(
+ new DummyPerson("David", 27),
+ new DummyPerson("Harold", 27),
+ new DummyPerson("Diego", 70));
+ assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
+ }
+
+ @Test
+ void sortWithMultiplePropertiesInDifferentOrderIsCorrectlyResolved() {
+ final SortingChainResolver<DummyPerson> resolver =
+ new SortingChainResolver<>(
+ HashMap.of("age", Comparator.comparing(DummyPerson::getAge))
+ .put("name", Comparator.comparing(DummyPerson::getName)));
+
+ final Option<Comparator<DummyPerson>> comparatorOption =
+ resolver.resolve(SortingParser.parse("name,age"));
+ assertThat(comparatorOption.isDefined()).isTrue();
+
+ final List<DummyPerson> list =
+ List.of(
+ new DummyPerson("Harold", 27),
+ new DummyPerson("Diego", 70),
+ new DummyPerson("David", 27));
+ final List<DummyPerson> expectedList =
+ List.of(
+ new DummyPerson("David", 27),
+ new DummyPerson("Diego", 70),
+ new DummyPerson("Harold", 27));
+ assertThat(list.sorted(comparatorOption.get())).containsExactlyElementsOf(expectedList);
+ }
+
+ @Data
+ private static class DummyPerson {
+ @NonNull private final String name;
+ private final int age;
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/utils/SortingParserTest.java b/app/src/test/java/org/onap/portal/bff/utils/SortingParserTest.java
new file mode 100644
index 0000000..6412a25
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/utils/SortingParserTest.java
@@ -0,0 +1,50 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class SortingParserTest {
+
+ @Test
+ void emptySortIsCorrectlyParsed() {
+ assertThat(SortingParser.parse("")).isEmpty();
+ }
+
+ @Test
+ void sortIsCorrectlyParsed() {
+ assertThat(SortingParser.parse("age,-name"))
+ .containsExactly(
+ new SortingParser.SortingParam("age", false),
+ new SortingParser.SortingParam("name", true));
+ }
+
+ @Test
+ void sortWithInvalidPartsIsCorrectlyParsed() {
+ assertThat(SortingParser.parse("age,,name,-"))
+ .containsExactly(
+ new SortingParser.SortingParam("age", false),
+ new SortingParser.SortingParam("name", false));
+ }
+}
diff --git a/app/src/test/java/org/onap/portal/bff/utils/VersionComparatorTest.java b/app/src/test/java/org/onap/portal/bff/utils/VersionComparatorTest.java
new file mode 100644
index 0000000..af99f50
--- /dev/null
+++ b/app/src/test/java/org/onap/portal/bff/utils/VersionComparatorTest.java
@@ -0,0 +1,41 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.vavr.collection.List;
+import org.junit.jupiter.api.Test;
+
+class VersionComparatorTest {
+
+ @Test
+ void versionsAreCorrectlySorted() {
+ final VersionComparator comparator = new VersionComparator();
+
+ final List<String> expectedVersions =
+ List.of("1.0", "1.0.1", "1.1", "1.1.1", "1.2", "1.2.1", "1.10", "2.0");
+ final List<String> versions = expectedVersions.shuffle().shuffle();
+
+ assertThat(versions.sorted(comparator)).containsExactlyElementsOf(expectedVersions);
+ }
+}
diff --git a/app/src/test/resources/application-access-control.yml b/app/src/test/resources/application-access-control.yml
new file mode 100644
index 0000000..5454a15
--- /dev/null
+++ b/app/src/test/resources/application-access-control.yml
@@ -0,0 +1,22 @@
+portal-bff.access-control:
+ ACTIONS_CREATE: [ onap_admin, onap_designer, onap_operator ]
+ ACTIONS_GET: [ onap_admin, onap_designer, onap_operator ]
+ ACTIONS_LIST: [ onap_admin, onap_designer, onap_operator ]
+ ACTIVE_ALARM_LIST: [onap_admin, onap_designer, onap_operator]
+ KEY_ENCRYPT_BY_USER: [onap_admin, onap_designer, onap_operator]
+ KEY_ENCRYPT_BY_VALUE: [onap_admin, onap_designer, onap_operator]
+ PREFERENCES_CREATE: [onap_admin, onap_designer, onap_operator]
+ PREFERENCES_GET: [onap_admin, onap_designer, onap_operator]
+ PREFERENCES_UPDATE: [onap_admin, onap_designer, onap_operator]
+ ROLE_LIST: ["*"]
+ TILE_GET: [onap_admin, onap_designer, onap_operator]
+ TILE_LIST: [onap_admin, onap_designer, onap_operator]
+ USER_CREATE: [onap_admin, onap_designer, onap_operator]
+ USER_DELETE: [onap_admin, onap_designer, onap_operator]
+ USER_GET: [onap_admin, onap_designer, onap_operator]
+ USER_LIST_AVAILABLE_ROLES: [onap_admin, onap_designer, onap_operator]
+ USER_LIST_ROLES: [onap_admin, onap_designer, onap_operator]
+ USER_LIST: [onap_admin, onap_designer, onap_operator]
+ USER_UPDATE_PASSWORD: [onap_admin, onap_designer, onap_operator]
+ USER_UPDATE_ROLES: [onap_admin, onap_designer, onap_operator]
+ USER_UPDATE: [onap_admin, onap_designer, onap_operator]
diff --git a/app/src/test/resources/application-development.yml b/app/src/test/resources/application-development.yml
new file mode 100644
index 0000000..8e97b45
--- /dev/null
+++ b/app/src/test/resources/application-development.yml
@@ -0,0 +1,33 @@
+logging:
+ level:
+ org.springframework.web: TRACE
+
+spring:
+ profiles:
+ include: access-control
+ security:
+ oauth2:
+ client:
+ provider:
+ keycloak:
+ token-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/token
+ jwk-set-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/certs
+ registration:
+ keycloak:
+ provider: keycloak
+ client-id: test
+ client-secret: test
+ authorization-grant-type: client_credentials
+ resourceserver:
+ jwt:
+ jwk-set-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/certs
+ jackson:
+ serialization:
+ FAIL_ON_EMPTY_BEANS: false
+
+portal-bff:
+ realm: ONAP
+ portal-prefs-url: http://localhost:${wiremock.server.port}
+ portal-history-url: http://localhost:${wiremock.server.port}
+ keycloak-url: http://localhost:${wiremock.server.port}
+ instance-id: PORTAL
diff --git a/app/src/test/resources/application.yml b/app/src/test/resources/application.yml
new file mode 100644
index 0000000..f9a82d8
--- /dev/null
+++ b/app/src/test/resources/application.yml
@@ -0,0 +1,34 @@
+logging:
+ level:
+ org.springframework.web: TRACE
+
+spring:
+ profiles:
+ include:
+ - access-control
+ security:
+ oauth2:
+ client:
+ provider:
+ keycloak:
+ token-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/token
+ jwk-set-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/certs
+ registration:
+ keycloak:
+ provider: keycloak
+ client-id: test
+ client-secret: test
+ authorization-grant-type: client_credentials
+ resourceserver:
+ jwt:
+ jwk-set-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/certs
+ jackson:
+ serialization:
+ FAIL_ON_EMPTY_BEANS: false
+
+portal-bff:
+ realm: ONAP
+ portal-prefs-url: http://localhost:${wiremock.server.port}
+ portal-history-url: http://localhost:${wiremock.server.port}
+ keycloak-url: http://localhost:${wiremock.server.port}
+ instance-id: PORTAL
diff --git a/app/src/test/resources/logback-spring.xml b/app/src/test/resources/logback-spring.xml
new file mode 100644
index 0000000..45bd7e2
--- /dev/null
+++ b/app/src/test/resources/logback-spring.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration scan="true">
+ <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
+
+ <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
+ <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+ <level>${LOGBACK_LEVEL:-info}</level>
+ </filter>
+ <encoder>
+ <pattern>${CONSOLE_LOG_PATTERN}</pattern>
+ <charset>utf8</charset>
+ </encoder>
+ </appender>
+
+ <root level="all">
+ <appender-ref ref="stdout"/>
+ </root>
+</configuration> \ No newline at end of file
diff --git a/app/src/test/resources/preferences/preferencesProperties.json b/app/src/test/resources/preferences/preferencesProperties.json
new file mode 100644
index 0000000..dc094ec
--- /dev/null
+++ b/app/src/test/resources/preferences/preferencesProperties.json
@@ -0,0 +1,80 @@
+{
+ "dashboard": {
+ "apps": {
+ "availableTiles": [
+ {
+ "type": "ALARM_COUNT_TILE",
+ "displayed": true
+ },
+ {
+ "type": "KPI_GRAPH_TILE",
+ "displayed": true
+ },
+ {
+ "type": "K8S_RESOURCE_STATUS_TILE",
+ "displayed": true
+ },
+ {
+ "type": "USER_LAST_ACTION_TILE",
+ "displayed": true
+ }
+ ],
+ "k8sResourceStatus": "pod",
+ "kpiSettings": {
+ "primaryGraph": "erabDropRatio",
+ "secondaryGraph": "erabDropData",
+ "expanded": false
+ },
+ "alarmTileGraphEnabled": false,
+ "lastUserAction": {
+ "interval": "1H",
+ "filterType": "ALL"
+ }
+ }
+ },
+ "alarms": {
+ "showEmptyProperties": false
+ },
+ "columns": [
+ "id",
+ "baseType",
+ "ackState",
+ "alarmedObjectType",
+ "sourceSystemId",
+ "alarmedObject",
+ "perceivedSeverity",
+ "specificProblem",
+ "eventCategory",
+ "probableCause",
+ "proposedRepairedActions",
+ "comment",
+ "alarmRaisedTime",
+ "alarmReportingTime"
+ ],
+ "columnsOrder": [
+ "id",
+ "baseType",
+ "ackState",
+ "alarmedObjectType",
+ "sourceSystemId",
+ "alarmedObject",
+ "perceivedSeverity",
+ "specificProblem",
+ "eventCategory",
+ "probableCause",
+ "proposedRepairedActions",
+ "comment",
+ "alarmRaisedTime",
+ "alarmReportingTime"
+ ],
+ "refreshInterval": "1",
+ "serviceInstanceSettings": {
+ "showAll": false
+ },
+ "topologySettings": {
+ "showAll": false
+ },
+ "treeViewSettings": {
+ "showAll": false
+ }
+} \ No newline at end of file
diff --git a/bin/build.sh b/bin/build.sh
new file mode 100755
index 0000000..b402ba6
--- /dev/null
+++ b/bin/build.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+./gradlew build
diff --git a/bin/compile.sh b/bin/compile.sh
new file mode 100755
index 0000000..3605462
--- /dev/null
+++ b/bin/compile.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+./gradlew compileJava -x spotbugsMain -x spotbugsTest -x spotlessJava
diff --git a/bin/generate-openapi.sh b/bin/generate-openapi.sh
new file mode 100755
index 0000000..3306f4a
--- /dev/null
+++ b/bin/generate-openapi.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+./gradlew -p openapi clean compileJava -x spotbugsMain -x spotbugsTest -x spotlessJava
diff --git a/bin/sonarqube.sh b/bin/sonarqube.sh
new file mode 100755
index 0000000..0047966
--- /dev/null
+++ b/bin/sonarqube.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+./gradlew sonarqube -Dsonar.branch.name=local-ce -Dsonar.host.url=https://sonarqube.devops.telekom.de -Dsonar.login=5392bed06c65e0bbce329ad625cf8554ce467052
diff --git a/bin/test.sh b/bin/test.sh
new file mode 100755
index 0000000..ca731bf
--- /dev/null
+++ b/bin/test.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+./gradlew test -x spotbugsMain -x spotbugsTest -x spotlessJava
diff --git a/build.gradle b/build.gradle
new file mode 100755
index 0000000..9ce6023
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,81 @@
+import org.springframework.boot.gradle.plugin.SpringBootPlugin
+
+buildscript {
+ repositories {
+ mavenCentral()
+ maven {
+ url "https://plugins.gradle.org/m2/"
+ }
+ }
+
+ ext {
+ springBootVersion = '2.7.3'
+ springCloudVersion = '3.1.3'
+ vavrVersion = '0.10.4'
+ vavrJacksonVersion = '0.10.3'
+ lombokVersion = '1.18.24'
+ openapiVersion = '6.0.1'
+ redocVersion = '2.0.0-rc.65'
+ spotlessVersion = '6.10.0'
+ spotbugsVersion = '5.0.10'
+ sonarqubeVersion = '3.4.0.2513'
+ problemVersion = '0.27.1'
+ problemSpringVersion = '0.27.0'
+ logstashLogbackVersion = '7.2'
+ mapStructVersion = '1.5.2.Final'
+ mapStructExtensionsVersion = '0.1.2'
+ gorylenkoVersion= '2.4.1'
+ licenseVersion = '0.16.1'
+ shadowVersion = '7.1.2'
+ }
+
+ dependencies {
+ classpath "com.diffplug.spotless:spotless-plugin-gradle:$spotlessVersion"
+ classpath "com.github.spotbugs.snom:spotbugs-gradle-plugin:$spotbugsVersion"
+ classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
+ classpath "org.openapitools:openapi-generator-gradle-plugin:$openapiVersion"
+ classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:$sonarqubeVersion"
+ classpath "com.gorylenko.gradle-git-properties:gradle-git-properties:$gorylenkoVersion"
+ classpath "gradle.plugin.com.hierynomus.gradle.plugins:license-gradle-plugin:$licenseVersion"
+ classpath "gradle.plugin.com.github.johnrengelman:shadow:$shadowVersion"
+ }
+}
+
+group = 'org.onap'
+version = rootProject.file('version').text.trim()
+
+allprojects {
+ apply plugin: 'java'
+ apply plugin: 'idea'
+ apply plugin: 'io.spring.dependency-management'
+
+
+ sourceCompatibility = 17
+ targetCompatibility = 17
+
+ dependencyManagement {
+ imports {
+ mavenBom SpringBootPlugin.BOM_COORDINATES
+ }
+ }
+
+ repositories {
+ mavenCentral()
+ }
+
+ test {
+ useJUnitPlatform()
+ }
+
+ dependencies {
+ implementation "io.vavr:vavr:$vavrVersion"
+ implementation "io.vavr:vavr-jackson:$vavrJacksonVersion"
+ implementation "org.springframework.boot:spring-boot-starter-logging"
+ implementation "net.logstash.logback:logstash-logback-encoder:$logstashLogbackVersion"
+
+ compileOnly "org.projectlombok:lombok:$lombokVersion"
+ annotationProcessor "org.projectlombok:lombok:$lombokVersion"
+ testCompileOnly "org.projectlombok:lombok:$lombokVersion"
+ testAnnotationProcessor "org.projectlombok:lombok:$lombokVersion"
+ }
+} \ No newline at end of file
diff --git a/development/.env b/development/.env
new file mode 100644
index 0000000..9bb9dd3
--- /dev/null
+++ b/development/.env
@@ -0,0 +1,40 @@
+# General image repository
+IMAGE_REPOSITORY=tbd
+
+# Keycloak
+KEYCLOAK_IMAGE=quay.io/keycloak/keycloak
+KEYCLOAK_VERSION=18.0.2-legacy
+KEYCLOAK_USER=admin
+KEYCLOAK_PASSWORD=password
+KEYCLOAK_DB=keycloak
+KEYCLOAK_DB_USER=keycloak
+KEYCLOAK_DB_PASSWORD=password
+KEYCLOAK_URL:http://keycloak-bff:8080
+KEYCLOAK_REALM:ONAP
+
+# Postgres for Keycloak
+POSTGRES_IMAGE=postgres
+POSTGRES_VERSION=15rc1
+
+# mongo data base
+MONGO_IMAGE=mongo
+MONGO_VERSION=latest
+
+# portal-prefs
+PORTAL_PREFS_IMAGE_NAME=portal-prefs
+PORTAL_PREFS_IMAGE_TAG=0.1.0-master-faef0c0e
+PORTALPREFS_USERNAME:root
+PORTALPREFS_PASSWORD:password
+PORTALPREFS_DATABASE:Portalprefs
+PORTALPREFS_HOST:mongo-prefs
+PORTALPREFS_PORT:27017
+
+# portal-history
+PORTAL_HISTORY_IMAGE_NAME=portal-history
+PORTAL_HISTORY_IMAGE_TAG=0.1.1-de369ace
+PORTALHISTORY_USERNAME:root
+PORTALHISTORY_PASSWORD:password
+PORTALHISTORY_DATABASE:Portalhist
+PORTALHISTORY_HOST:mongo-history
+PORTALHISTORY_PORT:27017
+
diff --git a/development/config/onap-realm.json b/development/config/onap-realm.json
new file mode 100644
index 0000000..e47136b
--- /dev/null
+++ b/development/config/onap-realm.json
@@ -0,0 +1,221 @@
+{
+ "id": "ONAP",
+ "realm": "ONAP",
+ "enabled": true,
+ "clients": [
+ {
+ "clientId": "portal-app",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "redirectUris": [],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": true,
+ "serviceAccountsEnabled": false,
+ "publicClient": true,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {
+ "backchannel.logout.session.required": "true",
+ "backchannel.logout.revoke.offline.tokens": "false"
+ },
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": true,
+ "nodeReRegistrationTimeout": -1,
+ "protocolMappers": [
+ {
+ "name": "User-Roles",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-realm-role-mapper",
+ "consentRequired": false,
+ "config": {
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "roles",
+ "multivalued": "true",
+ "userinfo.token.claim": "true"
+ }
+ },
+ {
+ "name": "SDC-User",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "sdc_user",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "sdc_user",
+ "jsonType.label": "String"
+ }
+ }
+ ],
+ "defaultClientScopes": [
+ "web-origins",
+ "acr",
+ "profile",
+ "roles",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ }, {
+ "clientId" : "portal-bff",
+ "surrogateAuthRequired" : false,
+ "enabled" : true,
+ "alwaysDisplayInConsole" : false,
+ "clientAuthenticatorType" : "client-secret",
+ "secret" : "pKOuVH1bwRZoNzp5P5t4GV8CqcCJYVtr",
+ "redirectUris" : [ ],
+ "webOrigins" : [ ],
+ "notBefore" : 0,
+ "bearerOnly" : false,
+ "consentRequired" : false,
+ "standardFlowEnabled" : false,
+ "implicitFlowEnabled" : false,
+ "directAccessGrantsEnabled" : false,
+ "serviceAccountsEnabled" : true,
+ "publicClient" : false,
+ "frontchannelLogout" : false,
+ "protocol" : "openid-connect",
+ "attributes" : {
+ "saml.force.post.binding" : "false",
+ "saml.multivalued.roles" : "false",
+ "frontchannel.logout.session.required" : "false",
+ "oauth2.device.authorization.grant.enabled" : "false",
+ "backchannel.logout.revoke.offline.tokens" : "false",
+ "saml.server.signature.keyinfo.ext" : "false",
+ "use.refresh.tokens" : "true",
+ "oidc.ciba.grant.enabled" : "false",
+ "backchannel.logout.session.required" : "true",
+ "client_credentials.use_refresh_token" : "false",
+ "require.pushed.authorization.requests" : "false",
+ "saml.client.signature" : "false",
+ "saml.allow.ecp.flow" : "false",
+ "id.token.as.detached.signature" : "false",
+ "saml.assertion.signature" : "false",
+ "client.secret.creation.time" : "1665048112",
+ "saml.encrypt" : "false",
+ "saml.server.signature" : "false",
+ "exclude.session.state.from.auth.response" : "false",
+ "saml.artifact.binding" : "false",
+ "saml_force_name_id_format" : "false",
+ "acr.loa.map" : "{}",
+ "tls.client.certificate.bound.access.tokens" : "false",
+ "saml.authnstatement" : "false",
+ "display.on.consent.screen" : "false",
+ "token.response.type.bearer.lower-case" : "false",
+ "saml.onetimeuse.condition" : "false"
+ },
+ "authenticationFlowBindingOverrides" : { },
+ "fullScopeAllowed" : true,
+ "nodeReRegistrationTimeout" : -1,
+ "protocolMappers" : [ {
+ "name" : "Client Host",
+ "protocol" : "openid-connect",
+ "protocolMapper" : "oidc-usersessionmodel-note-mapper",
+ "consentRequired" : false,
+ "config" : {
+ "user.session.note" : "clientHost",
+ "id.token.claim" : "true",
+ "access.token.claim" : "true",
+ "claim.name" : "clientHost",
+ "jsonType.label" : "String"
+ }
+ }, {
+ "name" : "Client IP Address",
+ "protocol" : "openid-connect",
+ "protocolMapper" : "oidc-usersessionmodel-note-mapper",
+ "consentRequired" : false,
+ "config" : {
+ "user.session.note" : "clientAddress",
+ "id.token.claim" : "true",
+ "access.token.claim" : "true",
+ "claim.name" : "clientAddress",
+ "jsonType.label" : "String"
+ }
+ } ],
+ "defaultClientScopes" : [ "web-origins", "acr", "profile", "roles", "email" ],
+ "optionalClientScopes" : [ "address", "phone", "offline_access", "microprofile-jwt" ]
+ }],
+ "users": [
+ {
+ "createdTimestamp" : 1664965113698,
+ "username" : "onap-admin",
+ "enabled" : true,
+ "totp" : false,
+ "emailVerified" : false,
+ "attributes" : {
+ "sdc_user" : [ "cs0008" ]
+ },
+ "credentials" : [ {
+ "type" : "password",
+ "createdDate" : 1664965134586,
+ "secretData" : "{\"value\":\"nD4K4x8HEgk6xlWIAgzZOE+EOjdbovJfEa7N3WXwIMCWCfdXpn7Riys7hZhI1NbKcc9QPI9j8LQB/JSuZVcXKA==\",\"salt\":\"T8X9A9tT2cyLvEjHFo+zuQ==\",\"additionalParameters\":{}}",
+ "credentialData" : "{\"hashIterations\":27500,\"algorithm\":\"pbkdf2-sha256\",\"additionalParameters\":{}}"
+ } ],
+ "disableableCredentialTypes" : [ ],
+ "requiredActions" : [ ],
+ "realmRoles" : [ "default-roles-onap", "onap_admin" ],
+ "notBefore" : 0,
+ "groups" : [ ]
+ }, {
+ "createdTimestamp" : 1665048354760,
+ "username" : "onap-designer",
+ "enabled" : true,
+ "totp" : false,
+ "emailVerified" : false,
+ "attributes" : {
+ "sec_user" : [ "cs0008" ]
+ },
+ "credentials" : [ ],
+ "disableableCredentialTypes" : [ ],
+ "requiredActions" : [ ],
+ "realmRoles" : [ "default-roles-onap", "onap_designer" ],
+ "notBefore" : 0,
+ "groups" : [ ]
+ }, {
+ "createdTimestamp" : 1665048547054,
+ "username" : "onap-operator",
+ "enabled" : true,
+ "totp" : false,
+ "emailVerified" : false,
+ "attributes" : {
+ "sdc_user" : [ "cs0008" ]
+ },
+ "credentials" : [ ],
+ "disableableCredentialTypes" : [ ],
+ "requiredActions" : [ ],
+ "realmRoles" : [ "default-roles-onap", "onap_operator" ],
+ "notBefore" : 0,
+ "groups" : [ ]
+ }, {
+ "createdTimestamp" : 1665048112458,
+ "username" : "service-account-portal-bff",
+ "enabled" : true,
+ "totp" : false,
+ "emailVerified" : false,
+ "serviceAccountClientId" : "portal-bff",
+ "credentials" : [ ],
+ "disableableCredentialTypes" : [ ],
+ "requiredActions" : [ ],
+ "realmRoles" : [ "default-roles-onap" ],
+ "clientRoles" : {
+ "realm-management" : [ "manage-realm", "manage-users" ]
+ },
+ "notBefore" : 0,
+ "groups" : [ ]
+ }
+ ]
+} \ No newline at end of file
diff --git a/development/docker-compose.yml b/development/docker-compose.yml
new file mode 100644
index 0000000..4794ff3
--- /dev/null
+++ b/development/docker-compose.yml
@@ -0,0 +1,77 @@
+version: '3'
+
+volumes:
+ postgres_data:
+ driver: local
+
+services:
+ postgres:
+ container_name: postgres-keycloak
+ image: "${POSTGRES_IMAGE}:${POSTGRES_VERSION}"
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ environment:
+ POSTGRES_DB: keycloak
+ POSTGRES_USER: keycloak
+ POSTGRES_PASSWORD: ${KEYCLOAK_DB_PASSWORD}
+ keycloak:
+ container_name: keycloak-bff
+ image: "quay.io/keycloak/keycloak:18.0.2-legacy"
+ environment:
+ DB_VENDOR: POSTGRES
+ DB_ADDR: postgres-keycloak
+ DB_DATABASE: keycloak
+ DB_USER: keycloak
+ DB_SCHEMA: public
+ DB_PASSWORD: ${KEYCLOAK_DB_PASSWORD}
+ KEYCLOAK_USER: ${KEYCLOAK_USER}
+ KEYCLOAK_PASSWORD: ${KEYCLOAK_PASSWORD}
+ KEYCLOAK_IMPORT: /config/onap-realm.json
+ ports:
+ - 8080:8080
+ volumes:
+ - ./config:/config
+ depends_on:
+ - postgres
+ mongo-history:
+ container_name: mongo-history
+ image: "${MONGO_IMAGE}:${MONGO_VERSION}"
+ environment:
+ MONGO_INITDB_ROOT_USERNAME: ${PORTALHISTORY_USERNAME}
+ MONGO_INITDB_ROOT_PASSWORD: ${PORTALHISTORY_PASSWORD}
+ portal-history:
+ container_name: portal-history
+ image: "${IMAGE_REPOSITORY}/${PORTAL_HISTORY_IMAGE_NAME}:${PORTAL_HISTORY_IMAGE_TAG}"
+ ports:
+ - 9002:9002
+ environment:
+ PORTALHISTORY_USERNAME: ${PORTALHISTORY_USERNAME}
+ PORTALHISTORY_PASSWORD: ${PORTALHISTORY_PASSWORD}
+ PORTALHISTORY_DATABASE: ${PORTALHISTORY_DATABASE}
+ KEYCLOAK_URL: ${KEYCLOAK_URL}
+ KEYCLOAK_REALM: ${KEYCLOAK_REALM}
+ PORTALHISTORY_HOST: ${PORTALHISTORY_HOST}
+ PORTALHISTORY_PORT: ${PORTALHISTORY_PORT}
+ depends_on:
+ - mongo-history
+ mongo-prefs:
+ container_name: mongo-prefs
+ image: "${MONGO_IMAGE}:${MONGO_VERSION}"
+ environment:
+ MONGO_INITDB_ROOT_USERNAME: ${PORTALPREFS_USERNAME}
+ MONGO_INITDB_ROOT_PASSWORD: ${PORTALPREFS_PASSWORD}
+ portal-prefs:
+ container_name: portal-prefs
+ image: "${IMAGE_REPOSITORY}/${PORTAL_PREFS_IMAGE_NAME}:${PORTAL_PREFS_IMAGE_TAG}"
+ ports:
+ - 9001:9001
+ environment:
+ PORTALPREFS_USERNAME: ${PORTALPREFS_USERNAME}
+ PORTALPREFS_PASSWORD: ${PORTALPREFS_PASSWORD}
+ PORTALPREFS_DATABASE: ${PORTALPREFS_DATABASE}
+ KEYCLOAK_URL: ${KEYCLOAK_URL}
+ KEYCLOAK_REALM: ${KEYCLOAK_REALM}
+ PORTALPREFS_HOST: ${PORTALPREFS_HOST}
+ PORTALPREFS_PORT: ${PORTALPREFS_PORT}
+ depends_on:
+ - mongo-prefs \ No newline at end of file
diff --git a/development/requests-code.http b/development/requests-code.http
new file mode 100644
index 0000000..cec50e9
--- /dev/null
+++ b/development/requests-code.http
@@ -0,0 +1,109 @@
+# Use this with the REST Client extension in VSCode
+###
+# @name login
+@access_token = {{login.response.body.access_token}}
+@id_token = {{login.response.body.id_token}}
+POST http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/token
+Content-Type: application/x-www-form-urlencoded
+Authorization: Basic admin:password
+
+grant_type=password&scope=openid&client_id=portal-app&username=onap-admin&password=password
+
+###
+# @name userinfo
+@user_id = {{userinfo.response.body.sub}}
+@user_name = {{userinfo.response.body.preferred_username}}
+GET http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/userinfo
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+
+POST http://localhost:9080/preferences
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Content-Type: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+{
+ "properties": {
+ "dashboard": {
+ "apps": {
+ "availableTiles": [
+ {
+ "type": "USER_LAST_ACTION_TILE",
+ "displayed": false
+ }
+ ],
+ "lastUserAction": {
+ "interval": "1H",
+ "filterType": "ALL"
+ }
+ }
+ }
+ }
+}
+
+###
+GET http://localhost:9080/preferences
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+X-Request-Id: {{$uuid}}
+
+###
+POST http://localhost:9080/actions/{{user_id}}
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+Content-Type: application/json
+
+{
+ "userId": "{{user_id}}",
+ "actionCreatedAt": "{{$timestamp}}",
+ "action": {
+ "type": "DELETE",
+ "entity": "USERADMINISTRATION",
+ "entityParams": {
+ "userName": "uli",
+ "userId": "{{$randomInt}}"
+ }
+ }
+}
+
+###
+GET http://localhost:9080/actions/{{user_id}}?page=1&pageSize=10&showLastHours=1
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+GET http://localhost:9080/actions?page=1&pageSize=10&showLastHours=1
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+### requests to keycloak
+GET http://localhost:9080/users
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+GET http://localhost:9080/users/{{user_id}}
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+GET http://localhost:9080/users/{{user_id}}/roles
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
diff --git a/development/requests.http b/development/requests.http
new file mode 100644
index 0000000..6b9d12c
--- /dev/null
+++ b/development/requests.http
@@ -0,0 +1,119 @@
+# To be used with IntelliJ. Use the requests-code.http with the REST Client Extension if you are using VSCode
+POST http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/token
+Content-Type: application/x-www-form-urlencoded
+
+client_id=portal-app&client_secret=&scope=openid&grant_type=password&username=onap-admin&password=password
+> {%
+ client.global.set("access_token", response.body.access_token);
+ client.global.set("id_token", response.body.id_token);
+ %}
+
+###
+
+GET http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/userinfo
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+> {%
+ client.global.set("user_id", response.body.sub);
+ client.global.set("user_name", response.body.preferred_username);
+ %}
+
+###
+
+POST http://localhost:9080/preferences
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Content-Type: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+
+{
+ "properties": {
+ "dashboard": {
+ "apps": {
+ "availableTiles": [
+ {
+ "type": "USER_LAST_ACTION_TILE",
+ "displayed": false
+ }
+ ],
+ "lastUserAction": {
+ "interval": "1H",
+ "filterType": "ALL"
+ }
+ }
+ }
+ }
+}
+
+###
+
+GET http://localhost:9080/preferences
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+X-Request-Id: {{$uuid}}
+
+###
+
+POST http://localhost:9080/actions/{{user_id}}
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+Content-Type: application/json
+
+{
+ "userId": "{{user_id}}",
+ "actionCreatedAt": "{{$timestamp}}",
+ "action": {
+ "type": "DELETE",
+ "entity": "USERADMINISTRATION",
+ "entityParams": {
+ "userName": "uli",
+ "userId": "{{$randomInt}}"
+ }
+ }
+}
+
+###
+
+GET http://localhost:9080/actions/{{user_id}}?page=1&pageSize=10&showLastHours=1
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+
+GET http://localhost:9080/actions?page=1&pageSize=10&showLastHours=1
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+### requests to keycloak
+
+GET http://localhost:9080/users
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+
+GET http://localhost:9080/users/{{user_id}}
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
+
+###
+
+GET http://localhost:9080/users/{{user_id}}/roles
+X-Request-Id: {{$uuid}}
+Accept: application/json
+Authorization: Bearer {{access_token}}
+X-Auth-Identity: Bearer {{id_token}}
diff --git a/development/run.sh b/development/run.sh
new file mode 100755
index 0000000..020889f
--- /dev/null
+++ b/development/run.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
+
+docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d
+cd $SCRIPT_DIR/..
+SPRING_PROFILES_ACTIVE=local ./gradlew bootRun \ No newline at end of file
diff --git a/development/stop.sh b/development/stop.sh
new file mode 100755
index 0000000..9752a7f
--- /dev/null
+++ b/development/stop.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
+
+# shutdown all docker container
+docker compose -f "$SCRIPT_DIR/docker-compose.yml" down -v
+
+cd $SCRIPT_DIR/..
+./gradlew -stop \ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..249e583
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..070cb70
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..a69d9cb
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,240 @@
+#!/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.
+#
+
+##############################################################################
+#
+# 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/master/subprojects/plugins/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
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${0##*/}
+
+# 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"'
+
+# 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
+ which java >/dev/null 2>&1 || 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
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ 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
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+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..53a6b23
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,91 @@
+@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
+
+@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=.
+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.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+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/lib/LICENSE b/lib/LICENSE
new file mode 100644
index 0000000..abe3069
--- /dev/null
+++ b/lib/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 2021 TNAP / development / system-team
+
+ 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/lib/LICENSE_HEADER b/lib/LICENSE_HEADER
new file mode 100644
index 0000000..66e028a
--- /dev/null
+++ b/lib/LICENSE_HEADER
@@ -0,0 +1,20 @@
+/*
+ *
+ * Copyright (c) ${year}. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
diff --git a/lib/build.gradle b/lib/build.gradle
new file mode 100644
index 0000000..0e2a413
--- /dev/null
+++ b/lib/build.gradle
@@ -0,0 +1,91 @@
+apply plugin: 'com.gorylenko.gradle-git-properties'
+apply plugin: 'jacoco'
+apply plugin: 'com.github.johnrengelman.shadow'
+apply plugin: 'maven-publish'
+apply plugin: 'java-library'
+apply plugin: 'com.diffplug.spotless'
+apply plugin: 'com.github.spotbugs'
+apply plugin: 'org.sonarqube'
+
+group 'org.onap'
+version rootProject.file('version').text.trim()
+
+dependencies {
+ implementation project(':openapi:server')
+ implementation project(':openapi:client-portal-prefs')
+ implementation project(':openapi:client-portal-history')
+ implementation project(':openapi:client-portal-keycloak')
+
+ implementation 'org.springframework.boot:spring-boot-starter-webflux'
+ implementation 'org.springframework.boot:spring-boot-starter-actuator'
+ implementation 'org.springframework.boot:spring-boot-starter-validation'
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
+ implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
+ implementation "org.zalando:problem:$problemVersion"
+ implementation "org.zalando:jackson-datatype-problem:$problemVersion"
+ implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
+ implementation "org.zalando:problem-spring-webflux:$problemSpringVersion"
+ implementation "org.mapstruct:mapstruct:$mapStructVersion"
+ implementation "org.mapstruct.extensions.spring:mapstruct-spring-annotations:$mapStructExtensionsVersion"
+ implementation "org.mapstruct.extensions.spring:mapstruct-spring-extensions:$mapStructExtensionsVersion"
+
+ annotationProcessor "org.mapstruct:mapstruct-processor:$mapStructVersion"
+ annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
+}
+
+shadowJar {
+ archiveBaseName.set('portal-bff')
+ dependencies {
+ include(project(':openapi:server'))
+ include(project(':openapi:client-portal-history'))
+ include(project(':openapi:client-portal-prefs'))
+ include(project(':openapi:client-portal-keycloak'))
+ }
+}
+
+publishing {
+ publications {
+ myLibrary(MavenPublication) {
+ artifactId = rootProject.name
+ groupId = group
+ version = version
+ artifacts = ["build/libs/portal-bff-$version-all.jar"]
+ pom {
+ name = rootProject.name
+ description = 'ONAP community edition of portal-bff'
+ }
+ }
+ }
+ repositories{
+ mavenCentral()
+ }
+}
+
+spotless {
+ java {
+ target project.fileTree(project.projectDir) {
+ include '**/*.java'
+ exclude '**/build/**'
+ }
+ removeUnusedImports()
+ trimTrailingWhitespace()
+ googleJavaFormat('1.15.0')
+ }
+}
+
+spotbugs {
+ ignoreFailures = false
+ effort = "max"
+ reportLevel = "high"
+ excludeFilter = file("$rootProject.projectDir/spotbugs-exclude.xml")
+}
+
+sonarqube {
+ properties {
+ property "sonar.projectKey", "tnap.SONAR.portal.portal-bff-ce"
+ property "sonar.projectName", "portal-bff-ce"
+ property "sonar.projectDescription", "Community edition of the the ONAP portal"
+ property "sonar.exclusions", "**/build**"
+ }
+} \ No newline at end of file
diff --git a/lib/src/main/java/org/onap/portal/bff/config/BeansConfig.java b/lib/src/main/java/org/onap/portal/bff/config/BeansConfig.java
new file mode 100644
index 0000000..a0d0555
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/BeansConfig.java
@@ -0,0 +1,191 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.xml.XmlMapper;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import io.vavr.jackson.datatype.VavrModule;
+import java.time.Clock;
+import java.util.List;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.utils.Logger;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.config.ConfigurableBeanFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Scope;
+import org.springframework.http.codec.ClientCodecConfigurer;
+import org.springframework.http.codec.json.Jackson2JsonDecoder;
+import org.springframework.http.codec.json.Jackson2JsonEncoder;
+import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
+import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
+import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.ExchangeStrategies;
+import org.springframework.web.reactive.function.client.WebClient;
+import org.zalando.problem.jackson.ProblemModule;
+import reactor.core.publisher.Mono;
+
+@Slf4j
+@Configuration
+public class BeansConfig {
+
+ public static final String OAUTH2_EXCHANGE_FILTER_FUNCTION = "oauth2ExchangeFilterFunction";
+ private static final String ID_TOKEN_EXCHANGE_FILTER_FUNCTION = "idTokenExchangeFilterFunction";
+ private static final String ERROR_HANDLING_EXCHANGE_FILTER_FUNCTION =
+ "errorHandlingExchangeFilterFunction";
+ private static final String LOG_REQUEST_EXCHANGE_FILTER_FUNCTION =
+ "logRequestExchangeFilterFunction";
+ private static final String LOG_RESPONSE_EXCHANGE_FILTER_FUNCTION =
+ "logResponseExchangeFilterFunction";
+ private static final String CLIENT_REGISTRATION_ID = "keycloak";
+ public static final String X_REQUEST_ID = "X-Request-Id";
+
+ @Bean(name = OAUTH2_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction oauth2ExchangeFilterFunction(
+ ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
+ final ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Filter =
+ new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
+ oauth2Filter.setDefaultClientRegistrationId(CLIENT_REGISTRATION_ID);
+
+ return oauth2Filter;
+ }
+
+ @Bean(name = ID_TOKEN_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction idTokenExchangeFilterFunction() {
+ return new IdTokenExchangeFilterFunction();
+ }
+
+ @Bean(name = ERROR_HANDLING_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction errorHandlingExchangeFilterFunction() {
+ return ExchangeFilterFunction.ofResponseProcessor(
+ clientResponse -> {
+ if (clientResponse.statusCode().isError()) {
+ return clientResponse
+ .bodyToMono(String.class)
+ .doOnNext(s -> log.error("Received error response from downstream: {}", s))
+ .flatMap(
+ downstreamExceptionBody -> {
+ try {
+ return Mono.error(
+ new ObjectMapper()
+ .readValue(
+ downstreamExceptionBody, DownstreamApiProblemException.class));
+ } catch (JsonProcessingException e) {
+ return Mono.error(DownstreamApiProblemException.builder().build());
+ }
+ });
+ }
+ return Mono.just(clientResponse);
+ });
+ }
+
+ //
+ // Don't use this. Log will is written in the LoggerInterceptor
+ //
+ @Bean(name = LOG_REQUEST_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction logRequestExchangeFilterFunction() {
+ return ExchangeFilterFunction.ofRequestProcessor(
+ clientRequest -> {
+ List<String> xRequestIdList = clientRequest.headers().get(X_REQUEST_ID);
+ if (xRequestIdList != null && !xRequestIdList.isEmpty()) {
+ String xRequestId = xRequestIdList.get(0);
+ Logger.requestLog(xRequestId, clientRequest.method(), clientRequest.url());
+ }
+ return Mono.just(clientRequest);
+ });
+ }
+
+ @Bean(name = LOG_RESPONSE_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction logResponseExchangeFilterFunction() {
+ return ExchangeFilterFunction.ofResponseProcessor(
+ clientResponse -> {
+ String xRequestId = "not set";
+ List<String> xRequestIdList = clientResponse.headers().header(X_REQUEST_ID);
+ if (xRequestIdList != null && !xRequestIdList.isEmpty())
+ xRequestId = xRequestIdList.get(0);
+ Logger.responseLog(xRequestId, clientResponse.statusCode());
+ return Mono.just(clientResponse);
+ });
+ }
+
+ @Bean
+ ExchangeStrategies exchangeStrategies(ObjectMapper objectMapper) {
+ return ExchangeStrategies.builder()
+ .codecs(
+ configurer -> {
+ final ClientCodecConfigurer.ClientDefaultCodecs defaultCodecs =
+ configurer.defaultCodecs();
+
+ defaultCodecs.maxInMemorySize(16 * 1024 * 1024); // 16MB
+ defaultCodecs.jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper));
+ defaultCodecs.jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper));
+ })
+ .build();
+ }
+
+ // we need to use prototype scope to always create new instance of the bean
+ // because internally WebClient.Builder is mutable
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ WebClient.Builder webClientBuilder(
+ ExchangeStrategies exchangeStrategies,
+ @Qualifier(ID_TOKEN_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction idTokenExchangeFilterFunction,
+ @Qualifier(ERROR_HANDLING_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction errorHandlingExchangeFilterFunction,
+ @Qualifier(LOG_RESPONSE_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction logResponseExchangeFilterFunction) {
+ return WebClient.builder()
+ .exchangeStrategies(exchangeStrategies)
+ .filter(idTokenExchangeFilterFunction)
+ .filter(errorHandlingExchangeFilterFunction)
+ .filter(logResponseExchangeFilterFunction);
+ }
+
+ @Bean
+ Clock clock() {
+ return Clock.systemUTC();
+ }
+
+ @Bean
+ public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
+ return builder
+ .modules(new VavrModule(), new ProblemModule(), new JavaTimeModule())
+ .build()
+ .setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ }
+
+ @Bean
+ public XmlMapper xmlMapper() {
+ return XmlMapper.builder()
+ .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
+ .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
+ .build();
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/ConversionServiceConfig.java b/lib/src/main/java/org/onap/portal/bff/config/ConversionServiceConfig.java
new file mode 100644
index 0000000..09a8d53
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/ConversionServiceConfig.java
@@ -0,0 +1,59 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import io.vavr.collection.List;
+import org.onap.portal.bff.mappers.ActionsMapper;
+import org.onap.portal.bff.mappers.PreferencesMapper;
+import org.onap.portal.bff.mappers.RolesMapper;
+import org.onap.portal.bff.mappers.UsersMapper;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.convert.converter.Converter;
+import org.springframework.core.convert.support.ConfigurableConversionService;
+import org.springframework.core.convert.support.DefaultConversionService;
+
+@SuppressWarnings("rawtypes")
+@Configuration
+public class ConversionServiceConfig {
+
+ @Bean
+ public ConfigurableConversionService conversionService(
+ ActionsMapper actionsMapper,
+ PreferencesMapper preferencesMapper,
+ RolesMapper rolesMapper,
+ UsersMapper usersMapper) {
+ final List<Converter> converters =
+ List.of(
+ actionsMapper,
+ preferencesMapper,
+ preferencesMapper,
+ actionsMapper,
+ rolesMapper,
+ usersMapper);
+
+ final ConfigurableConversionService conversionService = new DefaultConversionService();
+ converters.forEach(conversionService::addConverter);
+
+ return conversionService;
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/IdTokenExchangeFilterFunction.java b/lib/src/main/java/org/onap/portal/bff/config/IdTokenExchangeFilterFunction.java
new file mode 100644
index 0000000..be3493d
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/IdTokenExchangeFilterFunction.java
@@ -0,0 +1,125 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import com.nimbusds.jwt.JWTParser;
+import io.vavr.control.Option;
+import io.vavr.control.Try;
+import java.util.List;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.web.reactive.function.client.ClientRequest;
+import org.springframework.web.reactive.function.client.ClientResponse;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.ExchangeFunction;
+import org.springframework.web.server.ServerWebExchange;
+import org.zalando.problem.Problem;
+import org.zalando.problem.Status;
+import reactor.core.publisher.Mono;
+
+public class IdTokenExchangeFilterFunction implements ExchangeFilterFunction {
+
+ public static final String X_AUTH_IDENTITY_HEADER = "X-Auth-Identity";
+ public static final String CLAIM_NAME_ROLES = "roles";
+
+ private static final List<String> EXCLUDED_PATHS_PATTERNS =
+ List.of(
+ "/actuator/**", "**/actuator/**", "*/actuator/**", "/**/actuator/**", "/*/actuator/**");
+
+ private static final Mono<ServerWebExchange> serverWebExchangeFromContext =
+ Mono.deferContextual(Mono::just)
+ .filter(context -> context.hasKey(ServerWebExchange.class))
+ .map(context -> context.get(ServerWebExchange.class));
+
+ @Override
+ public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
+ boolean shouldNotFilter =
+ EXCLUDED_PATHS_PATTERNS.stream()
+ .anyMatch(
+ excludedPath ->
+ new AntPathMatcher().match(excludedPath, request.url().getRawPath()));
+ if (shouldNotFilter) {
+ return next.exchange(request).switchIfEmpty(Mono.defer(() -> next.exchange(request)));
+ }
+ return extractServerWebExchange(request)
+ .flatMap(IdTokenExchangeFilterFunction::extractIdentityHeader)
+ .flatMap(
+ idToken -> {
+ final ClientRequest requestWithIdToken =
+ ClientRequest.from(request).header(X_AUTH_IDENTITY_HEADER, idToken).build();
+
+ return next.exchange(requestWithIdToken);
+ })
+ .switchIfEmpty(Mono.defer(() -> next.exchange(request)));
+ }
+
+ private Mono<ServerWebExchange> extractServerWebExchange(ClientRequest request) {
+ return Mono.justOrEmpty(request.attribute(ServerWebExchange.class.getName()))
+ .cast(ServerWebExchange.class)
+ .switchIfEmpty(serverWebExchangeFromContext);
+ }
+
+ private static Mono<String> extractIdentityHeader(ServerWebExchange exchange) {
+ return io.vavr.collection.List.ofAll(
+ exchange.getRequest().getHeaders().getOrEmpty(X_AUTH_IDENTITY_HEADER))
+ .headOption()
+ .map(Mono::just)
+ .getOrElse(Mono.error(Problem.valueOf(Status.FORBIDDEN, "ID token is missing")));
+ }
+
+ private static Mono<String> extractIdToken(ServerWebExchange exchange) {
+ return extractIdentityHeader(exchange)
+ .map(identityHeader -> identityHeader.replace("Bearer ", ""));
+ }
+
+ public static Mono<Void> validateAccess(
+ ServerWebExchange exchange, List<String> rolesListForMethod) {
+
+ return extractRoles(exchange)
+ .map(roles -> roles.stream().anyMatch(rolesListForMethod::contains))
+ .flatMap(
+ match -> {
+ if (Boolean.TRUE.equals(match)) {
+ return Mono.empty();
+ } else {
+ return Mono.error(Problem.valueOf(Status.FORBIDDEN));
+ }
+ });
+ }
+
+ private static Mono<List<String>> extractRoles(ServerWebExchange exchange) {
+ return extractIdToken(exchange)
+ .flatMap(
+ token ->
+ Try.of(() -> JWTParser.parse(token))
+ .mapTry(jwt -> Option.of(jwt.getJWTClaimsSet()))
+ .map(
+ optionJwtClaimSet ->
+ optionJwtClaimSet
+ .flatMap(
+ jwtClaimSet ->
+ Option.of(jwtClaimSet.getClaim(CLAIM_NAME_ROLES)))
+ .map(obj -> (List<String>) obj))
+ .map(Mono::just)
+ .getOrElseGet(Mono::error))
+ .map(optionRoles -> optionRoles.getOrElse(List.of()));
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/LoggerInterceptor.java b/lib/src/main/java/org/onap/portal/bff/config/LoggerInterceptor.java
new file mode 100644
index 0000000..4fa2d82
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/LoggerInterceptor.java
@@ -0,0 +1,52 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import java.util.List;
+import org.onap.portal.bff.utils.Logger;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.reactive.ServerWebExchangeContextFilter;
+import org.springframework.web.server.ServerWebExchange;
+import org.springframework.web.server.WebFilterChain;
+import reactor.core.publisher.Mono;
+
+@Component
+public class LoggerInterceptor extends ServerWebExchangeContextFilter {
+ public static final String EXCHANGE_CONTEXT_ATTRIBUTE =
+ ServerWebExchangeContextFilter.class.getName() + ".EXCHANGE_CONTEXT";
+
+ public static final String X_REQUEST_ID = "X-Request-Id";
+
+ @Override
+ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
+ List<String> xRequestIdList = exchange.getRequest().getHeaders().get(X_REQUEST_ID);
+ if (xRequestIdList != null && !xRequestIdList.isEmpty()) {
+ String xRequestId = xRequestIdList.get(0);
+ Logger.requestLog(
+ xRequestId, exchange.getRequest().getMethod(), exchange.getRequest().getURI());
+ exchange.getResponse().getHeaders().add(X_REQUEST_ID, xRequestId);
+ }
+ return chain
+ .filter(exchange)
+ .contextWrite(cxt -> cxt.put(EXCHANGE_CONTEXT_ATTRIBUTE, exchange));
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/MapperSpringConfig.java b/lib/src/main/java/org/onap/portal/bff/config/MapperSpringConfig.java
new file mode 100644
index 0000000..c7e3711
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/MapperSpringConfig.java
@@ -0,0 +1,28 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import org.mapstruct.MapperConfig;
+import org.mapstruct.extensions.spring.converter.ConversionServiceAdapterGenerator;
+
+@MapperConfig(componentModel = "spring", uses = ConversionServiceAdapterGenerator.class)
+public interface MapperSpringConfig {}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/PortalBffConfig.java b/lib/src/main/java/org/onap/portal/bff/config/PortalBffConfig.java
new file mode 100644
index 0000000..42454c8
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/PortalBffConfig.java
@@ -0,0 +1,63 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import io.vavr.control.Option;
+import java.util.List;
+import java.util.Map;
+import javax.validation.Valid;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.context.properties.ConstructorBinding;
+import org.zalando.problem.Problem;
+import org.zalando.problem.Status;
+import reactor.core.publisher.Mono;
+
+/**
+ * Class that contains configuration of the downstream apis. This could be username and password or
+ * urls.
+ */
+@Valid
+@ConstructorBinding
+@ConfigurationProperties("portal-bff")
+@Data
+public class PortalBffConfig {
+
+ @NotBlank private final String realm;
+ @NotBlank private final String portalServiceUrl;
+ @NotBlank private final String portalPrefsUrl;
+ @NotBlank private final String portalHistoryUrl;
+ @NotBlank private final String keycloakUrl;
+
+ @NotNull private final Map<String, List<String>> accessControl;
+
+ public Mono<List<String>> getRoles(String method) {
+ return Option.of(accessControl.get(method))
+ .map(Mono::just)
+ .getOrElse(
+ Mono.error(
+ Problem.valueOf(
+ Status.FORBIDDEN, "The user does not have the necessary access rights")));
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/SecurityConfig.java b/lib/src/main/java/org/onap/portal/bff/config/SecurityConfig.java
new file mode 100644
index 0000000..0d33980
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/SecurityConfig.java
@@ -0,0 +1,77 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
+import org.springframework.security.config.web.server.ServerHttpSecurity;
+import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
+import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider;
+import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder;
+import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
+import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
+import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
+import org.springframework.security.web.server.SecurityWebFilterChain;
+
+@EnableWebFluxSecurity
+@Configuration
+public class SecurityConfig {
+ @Bean
+ public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
+ return http.httpBasic()
+ .disable()
+ .formLogin()
+ .disable()
+ .csrf()
+ .disable()
+ .cors()
+ .and()
+ .authorizeExchange()
+ .pathMatchers(HttpMethod.GET, "/api-docs.html", "/api.yaml", "/webjars/**", "/actuator/**")
+ .permitAll()
+ .anyExchange()
+ .authenticated()
+ .and()
+ .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt)
+ .oauth2Client()
+ .and()
+ .build();
+ }
+
+ @Bean
+ ReactiveOAuth2AuthorizedClientManager reactiveOAuth2AuthorizedClientManager(
+ ReactiveClientRegistrationRepository clientRegistrationRepository,
+ ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
+
+ final ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
+ ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build();
+
+ final DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
+ new DefaultReactiveOAuth2AuthorizedClientManager(
+ clientRegistrationRepository, authorizedClientRepository);
+ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
+
+ return authorizedClientManager;
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/clients/AbstractClientConfig.java b/lib/src/main/java/org/onap/portal/bff/config/clients/AbstractClientConfig.java
new file mode 100644
index 0000000..85ee8ba
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/clients/AbstractClientConfig.java
@@ -0,0 +1,87 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config.clients;
+
+import java.time.Duration;
+import java.util.List;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.client.reactive.ClientHttpConnector;
+import org.springframework.http.client.reactive.ReactorClientHttpConnector;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.WebClient;
+import reactor.core.publisher.Mono;
+import reactor.netty.http.client.HttpClient;
+import reactor.netty.resources.ConnectionProvider;
+
+@Slf4j
+@RequiredArgsConstructor
+public abstract class AbstractClientConfig<E> {
+ private final Class<E> errorResponseTypeClass;
+
+ protected ExchangeFilterFunction errorHandlingExchangeFilterFunction() {
+ return ExchangeFilterFunction.ofResponseProcessor(
+ clientResponse -> {
+ if (clientResponse.statusCode().isError()) {
+ return clientResponse
+ .bodyToMono(errorResponseTypeClass)
+ .doOnNext(s -> log.error("Received error response from downstream: {}", s))
+ .flatMap(
+ problemResponse ->
+ Mono.error(mapException(problemResponse, clientResponse.statusCode())));
+ }
+ return Mono.just(clientResponse);
+ });
+ }
+
+ protected abstract DownstreamApiProblemException mapException(
+ E errorResponse, HttpStatus httpStatus);
+
+ protected ClientHttpConnector getClientHttpConnector() {
+ // ConnectionTimeouts introduced due to
+ // io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by
+ // peer issue
+ // https://github.com/reactor/reactor-netty/issues/1774#issuecomment-908066283
+ ConnectionProvider connectionProvider =
+ ConnectionProvider.builder("fixed")
+ .maxConnections(500)
+ .maxIdleTime(Duration.ofSeconds(20))
+ .maxLifeTime(Duration.ofSeconds(60))
+ .pendingAcquireTimeout(Duration.ofSeconds(60))
+ .evictInBackground(Duration.ofSeconds(120))
+ .build();
+ return new ReactorClientHttpConnector(HttpClient.create(connectionProvider));
+ }
+
+ protected WebClient getWebClient(
+ WebClient.Builder webClientBuilder, List<ExchangeFilterFunction> filters) {
+ if (filters != null) {
+ filters.forEach(webClientBuilder::filter);
+ }
+ return webClientBuilder
+ .filter(errorHandlingExchangeFilterFunction())
+ .clientConnector(getClientHttpConnector())
+ .build();
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/clients/KeycloakConfig.java b/lib/src/main/java/org/onap/portal/bff/config/clients/KeycloakConfig.java
new file mode 100644
index 0000000..0935a00
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/clients/KeycloakConfig.java
@@ -0,0 +1,104 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config.clients;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.List;
+import java.util.function.Function;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.portal.bff.config.BeansConfig;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.openapi.client_portal_keycloak.ApiClient;
+import org.onap.portal.bff.openapi.client_portal_keycloak.api.KeycloakApi;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.ErrorResponseKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.client.reactive.ClientHttpConnector;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.WebClient;
+
+@Slf4j
+@Configuration
+public class KeycloakConfig extends AbstractClientConfig<ErrorResponseKeycloakDto> {
+ private final ObjectMapper objectMapper;
+ private final PortalBffConfig bffConfig;
+ private final ExchangeFilterFunction oauth2ExchangeFilterFunction;
+
+ @Autowired
+ public KeycloakConfig(
+ @Qualifier(BeansConfig.OAUTH2_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction oauth2ExchangeFilterFunction,
+ ObjectMapper objectMapper,
+ PortalBffConfig bffConfig) {
+ super(ErrorResponseKeycloakDto.class);
+ this.objectMapper = objectMapper;
+ this.bffConfig = bffConfig;
+ this.oauth2ExchangeFilterFunction = oauth2ExchangeFilterFunction;
+ }
+
+ @Bean
+ public KeycloakApi keycloakApi(WebClient.Builder webClientBuilder) {
+ return constructApiClient(webClientBuilder, KeycloakApi::new);
+ }
+
+ private <T> T constructApiClient(
+ WebClient.Builder webClientBuilder, Function<ApiClient, T> apiConstructor) {
+ final ApiClient apiClient =
+ new ApiClient(
+ getWebClient(webClientBuilder, List.of(oauth2ExchangeFilterFunction)),
+ objectMapper,
+ objectMapper.getDateFormat());
+
+ // Extract service name and version from BasePath
+ String urlBasePathPrefix =
+ String.format("%s/auth/admin/realms/%s", bffConfig.getKeycloakUrl(), bffConfig.getRealm());
+
+ return apiConstructor.apply(apiClient.setBasePath(urlBasePathPrefix));
+ }
+
+ @Override
+ protected DownstreamApiProblemException mapException(
+ ErrorResponseKeycloakDto errorResponse, HttpStatus httpStatus) {
+ String errorDetail =
+ errorResponse.getErrorMessage() != null
+ ? errorResponse.getErrorMessage()
+ : errorResponse.getError();
+
+ return DownstreamApiProblemException.builder()
+ .title(httpStatus.toString())
+ .detail(errorDetail)
+ .downstreamSystem(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString())
+ .downstreamMessageId("not set by downstream system")
+ .downstreamStatus(httpStatus.value())
+ .build();
+ }
+
+ @Override
+ protected ClientHttpConnector getClientHttpConnector() {
+ return null;
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/clients/PortalHistoryConfig.java b/lib/src/main/java/org/onap/portal/bff/config/clients/PortalHistoryConfig.java
new file mode 100644
index 0000000..b71608f
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/clients/PortalHistoryConfig.java
@@ -0,0 +1,97 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config.clients;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.List;
+import java.util.function.Function;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.portal.bff.config.BeansConfig;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.openapi.client_portal_history.ApiClient;
+import org.onap.portal.bff.openapi.client_portal_history.api.ActionsApi;
+import org.onap.portal.bff.openapi.client_portal_history.model.ProblemPortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.WebClient;
+
+@Slf4j
+@Configuration
+public class PortalHistoryConfig extends AbstractClientConfig<ProblemPortalHistoryDto> {
+ private final ObjectMapper objectMapper;
+ private final PortalBffConfig bffConfig;
+ private final ExchangeFilterFunction oauth2ExchangeFilterFunction;
+
+ @Autowired
+ public PortalHistoryConfig(
+ @Qualifier(BeansConfig.OAUTH2_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction oauth2ExchangeFilterFunction,
+ ObjectMapper objectMapper,
+ PortalBffConfig bffConfig) {
+ super(ProblemPortalHistoryDto.class);
+ this.objectMapper = objectMapper;
+ this.bffConfig = bffConfig;
+ this.oauth2ExchangeFilterFunction = oauth2ExchangeFilterFunction;
+ }
+
+ @Bean
+ public ActionsApi portalHistoryActionApi(WebClient.Builder webClientBuilder) {
+ return constructApiClient(webClientBuilder, ActionsApi::new);
+ }
+
+ private <T> T constructApiClient(
+ WebClient.Builder webClientBuilder, Function<ApiClient, T> apiConstructor) {
+ final ApiClient apiClient =
+ new ApiClient(
+ getWebClient(webClientBuilder, List.of(oauth2ExchangeFilterFunction)),
+ objectMapper,
+ objectMapper.getDateFormat());
+ final String generatedBasePath = apiClient.getBasePath();
+ String basePath = "";
+ try {
+ basePath = bffConfig.getPortalHistoryUrl() + new URL(generatedBasePath).getPath();
+ } catch (MalformedURLException e) {
+ log.error(e.getLocalizedMessage());
+ }
+ return apiConstructor.apply(apiClient.setBasePath(basePath));
+ }
+
+ @Override
+ protected DownstreamApiProblemException mapException(
+ ProblemPortalHistoryDto errorResponse, HttpStatus httpStatus) {
+ return DownstreamApiProblemException.builder()
+ .title(httpStatus.toString())
+ .detail(errorResponse.getDetail())
+ .downstreamMessageId(errorResponse.getType())
+ .downstreamSystem(ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY.toString())
+ .downstreamStatus(httpStatus.value())
+ .build();
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/config/clients/PortalPrefsConfig.java b/lib/src/main/java/org/onap/portal/bff/config/clients/PortalPrefsConfig.java
new file mode 100644
index 0000000..5e23348
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/config/clients/PortalPrefsConfig.java
@@ -0,0 +1,96 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.config.clients;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.List;
+import java.util.function.Function;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.portal.bff.config.BeansConfig;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.openapi.client_portal_prefs.ApiClient;
+import org.onap.portal.bff.openapi.client_portal_prefs.api.PreferencesApi;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.ProblemPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
+import org.springframework.web.reactive.function.client.WebClient;
+
+@Slf4j
+@Configuration
+public class PortalPrefsConfig extends AbstractClientConfig<ProblemPortalPrefsDto> {
+ private final ObjectMapper objectMapper;
+ private final PortalBffConfig bffConfig;
+ private final ExchangeFilterFunction oauth2ExchangeFilterFunction;
+
+ public PortalPrefsConfig(
+ @Qualifier(BeansConfig.OAUTH2_EXCHANGE_FILTER_FUNCTION)
+ ExchangeFilterFunction oauth2ExchangeFilterFunction,
+ ObjectMapper objectMapper,
+ PortalBffConfig bffConfig) {
+ super(ProblemPortalPrefsDto.class);
+ this.objectMapper = objectMapper;
+ this.bffConfig = bffConfig;
+ this.oauth2ExchangeFilterFunction = oauth2ExchangeFilterFunction;
+ }
+
+ @Bean
+ public PreferencesApi portalPrefsApi(WebClient.Builder webClientBuilder) {
+ return constructApiClient(webClientBuilder, PreferencesApi::new);
+ }
+
+ private <T> T constructApiClient(
+ WebClient.Builder webClientBuilder, Function<ApiClient, T> apiConstructor) {
+ final ApiClient apiClient =
+ new ApiClient(
+ getWebClient(webClientBuilder, List.of(oauth2ExchangeFilterFunction)),
+ objectMapper,
+ objectMapper.getDateFormat());
+
+ final String generatedBasePath = apiClient.getBasePath();
+ String basePath = "";
+ try {
+ basePath = bffConfig.getPortalPrefsUrl() + new URL(generatedBasePath).getPath();
+ } catch (MalformedURLException e) {
+ log.error(e.getLocalizedMessage());
+ }
+ return apiConstructor.apply(apiClient.setBasePath(basePath));
+ }
+
+ @Override
+ protected DownstreamApiProblemException mapException(
+ ProblemPortalPrefsDto errorResponse, HttpStatus httpStatus) {
+ return DownstreamApiProblemException.builder()
+ .title(httpStatus.toString())
+ .detail(errorResponse.getDetail())
+ .downstreamMessageId(errorResponse.getType())
+ .downstreamSystem(ProblemApiDto.DownstreamSystemEnum.PORTAL_PREFS.toString())
+ .downstreamStatus(httpStatus.value())
+ .build();
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/controller/AbstractBffController.java b/lib/src/main/java/org/onap/portal/bff/controller/AbstractBffController.java
new file mode 100644
index 0000000..bc92b68
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/controller/AbstractBffController.java
@@ -0,0 +1,46 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.controller;
+
+import org.onap.portal.bff.config.IdTokenExchangeFilterFunction;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+public abstract class AbstractBffController {
+
+ protected PortalBffConfig bffConfig;
+
+ protected AbstractBffController(PortalBffConfig bffConfig) {
+ this.bffConfig = bffConfig;
+ }
+
+ public Mono<Void> checkRoleAccess(String method, ServerWebExchange exchange) {
+ return bffConfig
+ .getRoles(method)
+ .flatMap(
+ roles ->
+ roles.contains("*")
+ ? Mono.empty()
+ : IdTokenExchangeFilterFunction.validateAccess(exchange, roles));
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/controller/ActionsController.java b/lib/src/main/java/org/onap/portal/bff/controller/ActionsController.java
new file mode 100644
index 0000000..ece6683
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/controller/ActionsController.java
@@ -0,0 +1,84 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.controller;
+
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.openapi.server.api.ActionsApi;
+import org.onap.portal.bff.openapi.server.model.ActionsListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ActionsResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.CreateActionRequestApiDto;
+import org.onap.portal.bff.services.ActionService;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+@RestController
+public class ActionsController extends AbstractBffController implements ActionsApi {
+ public static final String CREATE = "ACTIONS_CREATE";
+ public static final String GET = "ACTIONS_GET";
+ public static final String LIST = "ACTIONS_LIST";
+
+ private final ActionService actionService;
+
+ public ActionsController(PortalBffConfig bffConfig, ActionService actionService) {
+ super(bffConfig);
+ this.actionService = actionService;
+ }
+
+ @Override
+ public Mono<ResponseEntity<ActionsResponseApiDto>> createAction(
+ String userId,
+ String xRequestId,
+ Mono<CreateActionRequestApiDto> createActionRequestApiDto,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(CREATE, exchange)
+ .then(createActionRequestApiDto)
+ .flatMap(action -> actionService.createAction(userId, xRequestId, action))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<ActionsListResponseApiDto>> getActions(
+ String userId,
+ Integer page,
+ Integer pageSize,
+ Integer showLastHours,
+ String xRequestId,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(GET, exchange)
+ .then(actionService.getActions(userId, xRequestId, page, pageSize, showLastHours))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<ActionsListResponseApiDto>> listActions(
+ Integer page,
+ Integer pageSize,
+ Integer showLastHours,
+ String xRequestId,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(LIST, exchange)
+ .then(actionService.listActions(xRequestId, page, pageSize, showLastHours))
+ .map(ResponseEntity::ok);
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/controller/BffControllerAdvice.java b/lib/src/main/java/org/onap/portal/bff/controller/BffControllerAdvice.java
new file mode 100644
index 0000000..3580495
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/controller/BffControllerAdvice.java
@@ -0,0 +1,28 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.controller;
+
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+import org.zalando.problem.spring.webflux.advice.ProblemHandling;
+
+@RestControllerAdvice
+public class BffControllerAdvice implements ProblemHandling {}
diff --git a/lib/src/main/java/org/onap/portal/bff/controller/PreferencesController.java b/lib/src/main/java/org/onap/portal/bff/controller/PreferencesController.java
new file mode 100644
index 0000000..625d034
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/controller/PreferencesController.java
@@ -0,0 +1,77 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.controller;
+
+import javax.validation.Valid;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.openapi.server.api.PreferencesApi;
+import org.onap.portal.bff.openapi.server.model.CreatePreferencesRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.onap.portal.bff.services.PreferencesService;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+@RestController
+public class PreferencesController extends AbstractBffController implements PreferencesApi {
+ public static final String CREATE = "PREFERENCES_CREATE";
+ public static final String GET = "PREFERENCES_GET";
+ public static final String UPDATE = "PREFERENCES_UPDATE";
+
+ private final PreferencesService preferencesService;
+
+ public PreferencesController(PortalBffConfig bffConfig, PreferencesService preferencesService) {
+ super(bffConfig);
+ this.preferencesService = preferencesService;
+ }
+
+ @Override
+ public Mono<ResponseEntity<PreferencesResponseApiDto>> getPreferences(
+ String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(GET, exchange)
+ .then(preferencesService.getPreferences(xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<PreferencesResponseApiDto>> savePreferences(
+ @Valid Mono<CreatePreferencesRequestApiDto> preferencesApiDto,
+ String xRequestId,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(CREATE, exchange)
+ .then(preferencesApiDto)
+ .flatMap(request -> preferencesService.createPreferences(xRequestId, request))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<PreferencesResponseApiDto>> updatePreferences(
+ @Valid Mono<CreatePreferencesRequestApiDto> preferencesApiDto,
+ String xRequestId,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(UPDATE, exchange)
+ .then(preferencesApiDto)
+ .flatMap(request -> preferencesService.updatePreferences(xRequestId, request))
+ .map(ResponseEntity::ok);
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/controller/RolesController.java b/lib/src/main/java/org/onap/portal/bff/controller/RolesController.java
new file mode 100644
index 0000000..34d495f
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/controller/RolesController.java
@@ -0,0 +1,56 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.controller;
+
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.openapi.server.api.RolesApi;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.onap.portal.bff.services.KeycloakService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+@RestController
+public class RolesController extends AbstractBffController implements RolesApi {
+
+ public static final String LIST = "ROLE_LIST";
+
+ private final KeycloakService keycloakService;
+
+ @Autowired
+ public RolesController(PortalBffConfig bffConfig, KeycloakService keycloakService) {
+ super(bffConfig);
+ this.keycloakService = keycloakService;
+ }
+
+ @Override
+ public Mono<ResponseEntity<RoleListResponseApiDto>> listRoles(
+ String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(LIST, exchange)
+ .thenMany(keycloakService.listRoles(xRequestId))
+ .collectList()
+ .map(roles -> new RoleListResponseApiDto().items(roles).totalCount(roles.size()))
+ .map(ResponseEntity::ok);
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/controller/UsersController.java b/lib/src/main/java/org/onap/portal/bff/controller/UsersController.java
new file mode 100644
index 0000000..f67809b
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/controller/UsersController.java
@@ -0,0 +1,145 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.controller;
+
+import io.vavr.collection.List;
+import org.onap.portal.bff.config.PortalBffConfig;
+import org.onap.portal.bff.openapi.server.api.UsersApi;
+import org.onap.portal.bff.openapi.server.model.CreateUserRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.onap.portal.bff.openapi.server.model.RoleListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.UpdateUserPasswordRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.UpdateUserRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.UserListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.UserResponseApiDto;
+import org.onap.portal.bff.services.KeycloakService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@RestController
+public class UsersController extends AbstractBffController implements UsersApi {
+
+ public static final String CREATE = "USER_CREATE";
+ public static final String GET = "USER_GET";
+ public static final String UPDATE = "USER_UPDATE";
+ public static final String DELETE = "USER_DELETE";
+ public static final String LIST = "USER_LIST";
+ public static final String UPDATE_PASSWORD = "USER_UPDATE_PASSWORD";
+ public static final String UPDATE_ROLES = "USER_UPDATE_ROLES";
+ public static final String LIST_ROLES = "USER_LIST_ROLES";
+ public static final String LIST_AVAILABLE_ROLES = "USER_LIST_AVAILABLE_ROLES";
+
+ private final KeycloakService keycloakService;
+
+ @Autowired
+ public UsersController(PortalBffConfig bffConfig, KeycloakService keycloakService) {
+ super(bffConfig);
+ this.keycloakService = keycloakService;
+ }
+
+ @Override
+ public Mono<ResponseEntity<UserResponseApiDto>> createUser(
+ Mono<CreateUserRequestApiDto> requestMono, String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(CREATE, exchange)
+ .then(requestMono.flatMap(request -> keycloakService.createUser(request, xRequestId)))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<UserResponseApiDto>> getUser(
+ String userId, String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(GET, exchange)
+ .then(keycloakService.getUser(userId, xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<Void>> updateUser(
+ String userId,
+ Mono<UpdateUserRequestApiDto> requestMono,
+ String xRequestId,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(UPDATE, exchange)
+ .then(requestMono)
+ .flatMap(request -> keycloakService.updateUser(userId, request, xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<Void>> deleteUser(
+ String userId, String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(DELETE, exchange)
+ .then(keycloakService.deleteUser(userId, xRequestId))
+ .thenReturn(ResponseEntity.noContent().build());
+ }
+
+ @Override
+ public Mono<ResponseEntity<UserListResponseApiDto>> listUsers(
+ Integer page, Integer pageSize, String xRequestId, ServerWebExchange exchange) {
+
+ return checkRoleAccess(LIST, exchange)
+ .then(keycloakService.listUsers(page, pageSize, xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<Void>> updatePassword(
+ String userId,
+ Mono<UpdateUserPasswordRequestApiDto> requestMono,
+ String xRequestId,
+ ServerWebExchange exchange) {
+ return checkRoleAccess(UPDATE_PASSWORD, exchange)
+ .then(requestMono)
+ .flatMap(request -> keycloakService.updateUserPassword(userId, request))
+ .thenReturn(ResponseEntity.noContent().build());
+ }
+
+ @Override
+ public Mono<ResponseEntity<RoleListResponseApiDto>> listAvailableRoles(
+ String userId, String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(LIST_AVAILABLE_ROLES, exchange)
+ .then(keycloakService.getAvailableRoles(userId, xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<RoleListResponseApiDto>> listAssignedRoles(
+ String userId, String xRequestId, ServerWebExchange exchange) {
+ return checkRoleAccess(LIST_ROLES, exchange)
+ .then(keycloakService.getAssignedRoles(userId, xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<RoleListResponseApiDto>> updateAssignedRoles(
+ String userId, String xRequestId, Flux<RoleApiDto> rolesFlux, ServerWebExchange exchange) {
+ return checkRoleAccess(UPDATE_ROLES, exchange)
+ .then(rolesFlux.collectList())
+ .map(List::ofAll)
+ .flatMap(roles -> keycloakService.updateAssignedRoles(userId, roles, xRequestId))
+ .map(ResponseEntity::ok);
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/exceptions/DownstreamApiProblemException.java b/lib/src/main/java/org/onap/portal/bff/exceptions/DownstreamApiProblemException.java
new file mode 100644
index 0000000..35b895e
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/exceptions/DownstreamApiProblemException.java
@@ -0,0 +1,65 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.exceptions;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.net.URI;
+import java.util.List;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.ToString;
+import org.onap.portal.bff.openapi.server.model.ConstraintViolationApiDto;
+import org.zalando.problem.AbstractThrowableProblem;
+import org.zalando.problem.Problem;
+import org.zalando.problem.Status;
+import org.zalando.problem.StatusType;
+
+/** The default portal-bff exception */
+@Getter
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+@EqualsAndHashCode(callSuper = true)
+@ToString
+@JsonIgnoreProperties
+public class DownstreamApiProblemException extends AbstractThrowableProblem {
+
+ @Builder.Default private final URI type = Problem.DEFAULT_TYPE;
+ @Builder.Default private final String title = "Bad gateway error";
+
+ @JsonIgnore @Builder.Default private final transient StatusType status = Status.BAD_GATEWAY;
+
+ @Builder.Default
+ private final String detail = "Please find more detail under correlationId: 'TODO'";
+
+ @Builder.Default private final String downstreamSystem = null;
+ @Builder.Default private final URI instance = null;
+ @Builder.Default private final Integer downstreamStatus = null;
+ @Builder.Default private final String downstreamMessageId = null;
+
+ @JsonIgnore @Builder.Default
+ private final transient List<ConstraintViolationApiDto> violations = null;
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/mappers/ActionsMapper.java b/lib/src/main/java/org/onap/portal/bff/mappers/ActionsMapper.java
new file mode 100644
index 0000000..588deba
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/mappers/ActionsMapper.java
@@ -0,0 +1,37 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.mappers;
+
+import org.mapstruct.Mapper;
+import org.mapstruct.Mapping;
+import org.onap.portal.bff.config.MapperSpringConfig;
+import org.onap.portal.bff.openapi.client_portal_history.model.ActionsListResponsePortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ActionsListResponseApiDto;
+import org.springframework.core.convert.converter.Converter;
+
+@Mapper(config = MapperSpringConfig.class)
+public interface ActionsMapper
+ extends Converter<ActionsListResponsePortalHistoryDto, ActionsListResponseApiDto> {
+
+ @Mapping(source = "actionsList", target = "items")
+ ActionsListResponseApiDto convert(ActionsListResponsePortalHistoryDto source);
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/mappers/CredentialMapper.java b/lib/src/main/java/org/onap/portal/bff/mappers/CredentialMapper.java
new file mode 100644
index 0000000..e1db8de
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/mappers/CredentialMapper.java
@@ -0,0 +1,33 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.mappers;
+
+import org.mapstruct.Mapper;
+import org.mapstruct.ReportingPolicy;
+import org.onap.portal.bff.config.MapperSpringConfig;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.CredentialKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.UpdateUserPasswordRequestApiDto;
+
+@Mapper(config = MapperSpringConfig.class, unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface CredentialMapper {
+ CredentialKeycloakDto convert(UpdateUserPasswordRequestApiDto source);
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/mappers/PreferencesMapper.java b/lib/src/main/java/org/onap/portal/bff/mappers/PreferencesMapper.java
new file mode 100644
index 0000000..8a554fe
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/mappers/PreferencesMapper.java
@@ -0,0 +1,37 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.mappers;
+
+import org.mapstruct.Mapper;
+import org.mapstruct.Mapping;
+import org.onap.portal.bff.config.MapperSpringConfig;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.springframework.core.convert.converter.Converter;
+
+@Mapper(config = MapperSpringConfig.class)
+public interface PreferencesMapper
+ extends Converter<PreferencesPortalPrefsDto, PreferencesResponseApiDto> {
+
+ @Mapping(source = "properties", target = "properties")
+ PreferencesResponseApiDto convert(PreferencesPortalPrefsDto source);
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/mappers/RolesMapper.java b/lib/src/main/java/org/onap/portal/bff/mappers/RolesMapper.java
new file mode 100644
index 0000000..68d00d8
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/mappers/RolesMapper.java
@@ -0,0 +1,36 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.mappers;
+
+import org.mapstruct.Mapper;
+import org.mapstruct.ReportingPolicy;
+import org.onap.portal.bff.config.MapperSpringConfig;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RoleKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.RoleApiDto;
+import org.springframework.core.convert.converter.Converter;
+
+@Mapper(config = MapperSpringConfig.class, unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface RolesMapper extends Converter<RoleKeycloakDto, RoleApiDto> {
+ RoleApiDto convert(RoleKeycloakDto source);
+
+ RoleKeycloakDto convert(RoleApiDto source);
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/mappers/UsersMapper.java b/lib/src/main/java/org/onap/portal/bff/mappers/UsersMapper.java
new file mode 100644
index 0000000..19cb4c7
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/mappers/UsersMapper.java
@@ -0,0 +1,48 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.mappers;
+
+import java.util.List;
+import org.mapstruct.Mapper;
+import org.mapstruct.Mapping;
+import org.mapstruct.ReportingPolicy;
+import org.onap.portal.bff.config.MapperSpringConfig;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RequiredActionsKeycloakDto;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.UserKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.CreateUserRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.UpdateUserRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.UserResponseApiDto;
+import org.springframework.core.convert.converter.Converter;
+
+@Mapper(config = MapperSpringConfig.class, unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface UsersMapper extends Converter<UserKeycloakDto, UserResponseApiDto> {
+
+ UserResponseApiDto convert(UserKeycloakDto source);
+
+ @Mapping(source = "roles", target = "realmRoles")
+ UserResponseApiDto convert(UserKeycloakDto source, List<String> roles);
+
+ @Mapping(source = "actions", target = "requiredActions")
+ UserKeycloakDto convert(CreateUserRequestApiDto source, List<RequiredActionsKeycloakDto> actions);
+
+ UserKeycloakDto convert(UpdateUserRequestApiDto source);
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/services/ActionService.java b/lib/src/main/java/org/onap/portal/bff/services/ActionService.java
new file mode 100644
index 0000000..0358d29
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/services/ActionService.java
@@ -0,0 +1,125 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.services;
+
+import lombok.RequiredArgsConstructor;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.openapi.client_portal_history.api.ActionsApi;
+import org.onap.portal.bff.openapi.client_portal_history.model.CreateActionRequestPortalHistoryDto;
+import org.onap.portal.bff.openapi.server.model.ActionsListResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.ActionsResponseApiDto;
+import org.onap.portal.bff.openapi.server.model.CreateActionRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.onap.portal.bff.utils.Logger;
+import org.springframework.core.convert.support.ConfigurableConversionService;
+import org.springframework.stereotype.Service;
+import reactor.core.publisher.Mono;
+
+@RequiredArgsConstructor
+@Service
+public class ActionService {
+ private final ActionsApi actionsApi;
+ private final ConfigurableConversionService conversionService;
+
+ public Mono<ActionsResponseApiDto> createAction(
+ String userId, String xRequestId, CreateActionRequestApiDto createActionRequestApiDto) {
+ // First map from server API model to client API model
+ CreateActionRequestPortalHistoryDto createActionRequestPortalHistoryDto =
+ new CreateActionRequestPortalHistoryDto();
+ createActionRequestPortalHistoryDto.setUserId(createActionRequestApiDto.getUserId());
+ createActionRequestPortalHistoryDto.setAction(createActionRequestApiDto.getAction());
+ createActionRequestPortalHistoryDto.setActionCreatedAt(
+ createActionRequestApiDto.getActionCreatedAt());
+
+ return actionsApi
+ .createAction(userId, xRequestId, createActionRequestPortalHistoryDto)
+ .map(
+ action ->
+ new ActionsResponseApiDto()
+ .action(action.getAction())
+ .actionCreatedAt(action.getActionCreatedAt()))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Create actions failed for userId",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<ActionsListResponseApiDto> getActions(
+ String userId, String xRequestId, Integer page, Integer pageSize, Integer showLastHours) {
+
+ return actionsApi
+ .getActions(userId, xRequestId, page, pageSize, showLastHours)
+ .map(actions -> conversionService.convert(actions, ActionsListResponseApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Get actions failed for userId",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<ActionsListResponseApiDto> listActions(
+ String xRequestId, Integer page, Integer pageSize, Integer showLast) {
+ return actionsApi
+ .listActions(xRequestId, page, pageSize, showLast)
+ .map(
+ responseEntity ->
+ conversionService.convert(responseEntity, ActionsListResponseApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "List actions failed",
+ null,
+ ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<Object> deleteActions(String userId, String xRequestId, Integer deleteAfterHours) {
+ return actionsApi
+ .deleteActions(userId, xRequestId, deleteAfterHours)
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Get actions failed for userId because actions cannot be deleted after "
+ + deleteAfterHours
+ + " hours",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.PORTAL_HISTORY.toString());
+ return Mono.error(ex);
+ });
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/services/KeycloakService.java b/lib/src/main/java/org/onap/portal/bff/services/KeycloakService.java
new file mode 100644
index 0000000..ff96b63
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/services/KeycloakService.java
@@ -0,0 +1,389 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.services;
+
+import io.vavr.API;
+import io.vavr.Tuple;
+import io.vavr.Tuple2;
+import io.vavr.collection.List;
+import io.vavr.control.Option;
+import java.net.URI;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.mappers.CredentialMapper;
+import org.onap.portal.bff.mappers.RolesMapper;
+import org.onap.portal.bff.mappers.UsersMapper;
+import org.onap.portal.bff.openapi.client_portal_keycloak.api.KeycloakApi;
+import org.onap.portal.bff.openapi.client_portal_keycloak.model.RequiredActionsKeycloakDto;
+import org.onap.portal.bff.openapi.server.model.*;
+import org.onap.portal.bff.utils.Logger;
+import org.springframework.core.convert.support.ConfigurableConversionService;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.zalando.problem.Status;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class KeycloakService {
+ private final KeycloakApi keycloakApi;
+ private final ConfigurableConversionService conversionService;
+ private final RolesMapper rolesMapper;
+ private final UsersMapper usersMapper;
+ private final CredentialMapper credentialMapper;
+
+ public Mono<UserResponseApiDto> createUser(CreateUserRequestApiDto request, String xRequestId) {
+ log.debug("Create user in keycloak. request=`{}`", request);
+
+ final List<RoleApiDto> rolesToBeAssigned =
+ Option.of(request.getRoles()).fold(List::empty, List::ofAll);
+ return listRoles(xRequestId)
+ .collectList()
+ .flatMap(
+ realmRoles -> {
+ final List<RoleApiDto> absentRoles =
+ rolesToBeAssigned.filter(role -> !realmRoles.contains(role));
+ if (!absentRoles.isEmpty()) {
+ return Mono.error(
+ DownstreamApiProblemException.builder()
+ .status(Status.NOT_FOUND)
+ .detail(
+ String.format(
+ "Roles not found in the realm: %s",
+ absentRoles.map(RoleApiDto::getName).asJava()))
+ .downstreamSystem(ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString())
+ .title(HttpStatus.NOT_FOUND.toString())
+ .build());
+ }
+ return Mono.just(rolesToBeAssigned);
+ })
+ .flatMap(roles -> createUserWithRoles(request, xRequestId, List.ofAll(roles)));
+ }
+
+ private Mono<UserResponseApiDto> createUserWithRoles(
+ CreateUserRequestApiDto request, String xRequestId, List<RoleApiDto> roles) {
+ return keycloakApi
+ .createUserWithHttpInfo(
+ usersMapper.convert(
+ request, List.of(RequiredActionsKeycloakDto.UPDATE_PASSWORD).asJava()))
+ .flatMap(
+ responseEntity ->
+ Option.of(responseEntity.getHeaders().getLocation())
+ .map(URI::toString)
+ .map(location -> location.substring(location.lastIndexOf("/") + 1))
+ .fold(
+ () -> Mono.error(DownstreamApiProblemException.builder().build()),
+ Mono::just))
+ .flatMap(
+ userId -> {
+ if (!roles.isEmpty()) {
+ return assignRoles(userId, roles);
+ }
+ return Mono.just(userId);
+ })
+ .flatMap(
+ userId ->
+ sendActionEmail(
+ userId, API.List(RequiredActionsKeycloakDto.UPDATE_PASSWORD).toJavaList()))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Create user failed at sending update-password email for userName",
+ request.getUsername(),
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ })
+ .flatMap((String userId1) -> getUser(userId1, xRequestId));
+ }
+
+ public Mono<UserResponseApiDto> getUser(String userId, String xRequestId) {
+ log.debug("Get user from keycloak. userId=`{}`", userId);
+ return Mono.zip(
+ keycloakApi
+ .getUser(userId)
+ .map(user -> conversionService.convert(user, UserResponseApiDto.class)),
+ getAssignedRoles(userId, xRequestId))
+ .map(
+ tuple ->
+ new UserResponseApiDto()
+ .username(tuple.getT1().getUsername())
+ .email(tuple.getT1().getEmail())
+ .enabled(tuple.getT1().getEnabled())
+ .id(tuple.getT1().getId())
+ .firstName(tuple.getT1().getFirstName())
+ .lastName(tuple.getT1().getLastName())
+ .realmRoles(
+ tuple.getT2().getItems().stream().map(RoleApiDto::getName).toList()))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Failed to get user",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<UserListResponseApiDto> listUsers(int page, int pageSize, String xRequestId) {
+ log.debug("Get users from keycloak. page=`{}`, pageSize=`{}`", page, pageSize);
+ final int first = (page - 1) * pageSize;
+
+ return Mono.zip(
+ keycloakApi.getUsersCount(null, null, null, null, null, null, null),
+ keycloakApi
+ .getUsers(
+ null, null, null, null, null, null, null, null, first, pageSize, null, null,
+ null, null)
+ .collectList(),
+ listRoles(xRequestId)
+ .flatMap(
+ role ->
+ listUsersByRole(role.getName(), xRequestId)
+ .map(user -> Tuple.of(user.getId(), role.getName())))
+ .collectList()
+ .map(List::ofAll)
+ .map(list -> list.groupBy(t -> t._1).map((k, v) -> Tuple.of(k, v.map(Tuple2::_2)))))
+ .map(
+ tuple -> {
+ final UserListResponseApiDto result = new UserListResponseApiDto();
+ result.setTotalCount(tuple.getT1());
+ result.setItems(
+ List.ofAll(tuple.getT2())
+ .map(
+ user ->
+ usersMapper.convert(
+ user,
+ tuple.getT3().getOrElse(user.getId(), API.List()).toJavaList()))
+ .toJavaList());
+
+ return result;
+ })
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "List users failed",
+ null,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<Void> updateUser(String userId, UpdateUserRequestApiDto request, String xRequestId) {
+ log.debug("Update user in keycloak. userId=`{}`, request=`{}`", userId, request);
+ return keycloakApi
+ .updateUser(userId, usersMapper.convert(request))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Failed to update user",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<Void> updateUserPassword(String userId, UpdateUserPasswordRequestApiDto request) {
+ log.debug(
+ "Update password for user in keycloak. userId=`{}`, temporary=`{}`",
+ userId,
+ request.getTemporary());
+
+ return keycloakApi.resetUserPassword(userId, credentialMapper.convert(request));
+ }
+
+ public Mono<Void> deleteUser(String userId, String xRequestId) {
+ log.debug("Delete user from keycloak. userId=`{}`", userId);
+
+ return keycloakApi
+ .deleteUser(userId)
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Failed to delete user",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<String> assignRoles(String userId, List<RoleApiDto> roles) {
+ log.debug(
+ "Assign roles to user in keycloak. userId=`{}`, roleIds=`{}`",
+ userId,
+ roles.map(RoleApiDto::getId).mkString(", "));
+
+ return keycloakApi
+ .addRealmRoleMappingsToUser(userId, roles.map(rolesMapper::convert).toJavaList())
+ .thenReturn(userId);
+ }
+
+ public Mono<RoleListResponseApiDto> updateAssignedRoles(
+ String userId, List<RoleApiDto> roles, String xRequestId) {
+ log.debug(
+ "Update assigned roles for user in keycloak. userId=`{}`, roleIds=`{}`",
+ userId,
+ roles.map(RoleApiDto::getId).mkString(", "));
+
+ return getAssignedRoles(userId, xRequestId)
+ .map(response -> List.ofAll(response.getItems()))
+ .flatMap(
+ assignedRoles -> {
+ if (assignedRoles.isEmpty()) {
+ return Mono.empty();
+ }
+ return unassignRoles(userId, assignedRoles);
+ })
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Update assigned roles failed for userId",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ })
+ .then(
+ Mono.defer(
+ () -> {
+ if (roles.isEmpty()) {
+ return Mono.empty();
+ }
+ return assignRoles(userId, roles);
+ }))
+ .then(Mono.defer(() -> getAssignedRoles(userId, xRequestId)));
+ }
+
+ public Mono<Void> unassignRoles(String userId, List<RoleApiDto> roles) {
+ log.debug(
+ "Unassign roles from user in keycloak. userId=`{}`, roleIds=`{}`",
+ userId,
+ roles.map(RoleApiDto::getId).mkString(", "));
+
+ return keycloakApi.deleteRealmRoleMappingsByUserId(
+ userId, roles.map(rolesMapper::convert).toJavaList());
+ }
+
+ public Mono<String> sendActionEmail(
+ String userId, java.util.List<RequiredActionsKeycloakDto> requiredActions) {
+ log.debug(
+ "Sending update actions email to user in keycloak. userId=`{}`, actions=`{}`",
+ userId,
+ requiredActions);
+ return keycloakApi
+ .executeActionsEmail(userId, null, null, null, requiredActions)
+ .thenReturn(userId);
+ }
+
+ public Flux<RoleApiDto> listRoles(String xRequestId) {
+ return keycloakApi
+ .getRoles(null, null, null, null)
+ .log()
+ .map(role -> conversionService.convert(role, RoleApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(xRequestId, "Get realm roles failed for ID", xRequestId, "KEYCLOAK");
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<RoleListResponseApiDto> getAssignedRoles(String userId, String xRequestId) {
+ log.debug("Get assigned roles from keycloak. userId=`{}`", userId);
+
+ return keycloakApi
+ .getRealmRoleMappingsByUserId(userId)
+ .map(role -> conversionService.convert(role, RoleApiDto.class))
+ .collectList()
+ .map(
+ items -> {
+ final RoleListResponseApiDto result = new RoleListResponseApiDto();
+ result.setTotalCount(items.size()); // keycloak does not support pagination for roles
+ result.setItems(items);
+ return result;
+ })
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Get assigned roles failed for userId",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<RoleListResponseApiDto> getAvailableRoles(String userId, String xRequestId) {
+ log.debug("Get available roles from keycloak. userId=`{}`", userId);
+
+ return keycloakApi
+ .getAvailableRealmRoleMappingsByUserId(userId)
+ .map(role -> conversionService.convert(role, RoleApiDto.class))
+ .collectList()
+ .map(
+ items -> {
+ final RoleListResponseApiDto result = new RoleListResponseApiDto();
+ result.setTotalCount(items.size()); // keycloak does not support pagination for roles
+ result.setItems(items);
+
+ return result;
+ })
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Get available roles failed for userId",
+ userId,
+ ProblemApiDto.DownstreamSystemEnum.KEYCLOAK.toString());
+ return Mono.error(ex);
+ });
+ }
+
+ public Flux<UserResponseApiDto> listUsersByRole(String roleName, String xRequestId) {
+ return keycloakApi
+ .getUsersByRole(roleName, null, null)
+ .log()
+ .map(user -> conversionService.convert(user, UserResponseApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId, "Get users by realm role failed for ID", xRequestId, "KEYCLOAK");
+ return Mono.error(ex);
+ });
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/services/PreferencesService.java b/lib/src/main/java/org/onap/portal/bff/services/PreferencesService.java
new file mode 100644
index 0000000..ee0a5df
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/services/PreferencesService.java
@@ -0,0 +1,91 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.services;
+
+import lombok.RequiredArgsConstructor;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.openapi.client_portal_prefs.api.PreferencesApi;
+import org.onap.portal.bff.openapi.client_portal_prefs.model.PreferencesPortalPrefsDto;
+import org.onap.portal.bff.openapi.server.model.CreatePreferencesRequestApiDto;
+import org.onap.portal.bff.openapi.server.model.PreferencesResponseApiDto;
+import org.onap.portal.bff.utils.Logger;
+import org.springframework.core.convert.support.ConfigurableConversionService;
+import org.springframework.stereotype.Service;
+import reactor.core.publisher.Mono;
+
+@RequiredArgsConstructor
+@Service
+public class PreferencesService {
+
+ private static final String PREFERENCES_APPLICATION_NAME = "PORTAL_PREFS";
+
+ private final PreferencesApi preferencesApi;
+ private final ConfigurableConversionService conversionService;
+
+ public Mono<PreferencesResponseApiDto> createPreferences(
+ String xRequestId, CreatePreferencesRequestApiDto request) {
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto = new PreferencesPortalPrefsDto();
+ preferencesPortalPrefsDto.setProperties(request.getProperties());
+ return preferencesApi
+ .savePreferences(xRequestId, preferencesPortalPrefsDto)
+ .map(resp -> conversionService.convert(resp, PreferencesResponseApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId, "Preference raise error", xRequestId, PREFERENCES_APPLICATION_NAME);
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<PreferencesResponseApiDto> updatePreferences(
+ String xRequestId, CreatePreferencesRequestApiDto request) {
+ PreferencesPortalPrefsDto preferencesPortalPrefsDto = new PreferencesPortalPrefsDto();
+ preferencesPortalPrefsDto.setProperties(request.getProperties());
+ return preferencesApi
+ .updatePreferences(xRequestId, preferencesPortalPrefsDto)
+ .map(resp -> conversionService.convert(resp, PreferencesResponseApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId, "Preference raise error", xRequestId, PREFERENCES_APPLICATION_NAME);
+ return Mono.error(ex);
+ });
+ }
+
+ public Mono<PreferencesResponseApiDto> getPreferences(String xRequestId) {
+ return preferencesApi
+ .getPreferences(xRequestId)
+ .map(preferences -> conversionService.convert(preferences, PreferencesResponseApiDto.class))
+ .onErrorResume(
+ DownstreamApiProblemException.class,
+ ex -> {
+ Logger.errorLog(
+ xRequestId,
+ "Get preferences failed for ID",
+ xRequestId,
+ PREFERENCES_APPLICATION_NAME);
+ return Mono.error(ex);
+ });
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/utils/ErrorHandler.java b/lib/src/main/java/org/onap/portal/bff/utils/ErrorHandler.java
new file mode 100644
index 0000000..8bec189
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/utils/ErrorHandler.java
@@ -0,0 +1,65 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import java.util.List;
+import java.util.Objects;
+import org.onap.portal.bff.exceptions.DownstreamApiProblemException;
+import org.onap.portal.bff.openapi.server.model.ProblemApiDto;
+import org.springframework.http.HttpStatus;
+
+public class ErrorHandler {
+ /**
+ * Not meant to be instantiated. To prevent Java from adding an implicit public constructor to
+ * every class which does not define at least one explicitly.
+ */
+ private ErrorHandler() {}
+
+ public static String mapVariablesToDetails(List<String> variables, String details) {
+ int i = 0;
+ for (String variable : variables) {
+ i++;
+ details = details.replace("%" + i, variable);
+ }
+ return details;
+ }
+
+ public static DownstreamApiProblemException getDownstreamApiProblemException(
+ HttpStatus httpStatus,
+ List<String> variables,
+ String text,
+ String messageId,
+ ProblemApiDto.DownstreamSystemEnum downStreamSystem) {
+ String errorDetail =
+ variables != null && text != null
+ ? ErrorHandler.mapVariablesToDetails(variables, text)
+ : null;
+
+ return DownstreamApiProblemException.builder()
+ .title(httpStatus.toString())
+ .detail(errorDetail)
+ .downstreamMessageId(Objects.requireNonNullElse(messageId, "not set by downstream system"))
+ .downstreamSystem(downStreamSystem.toString())
+ .downstreamStatus(httpStatus.value())
+ .build();
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/utils/Logger.java b/lib/src/main/java/org/onap/portal/bff/utils/Logger.java
new file mode 100644
index 0000000..b985ad5
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/utils/Logger.java
@@ -0,0 +1,61 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import java.net.URI;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+
+@Slf4j
+public class Logger {
+
+ /**
+ * Not meant to be instantiated. To prevent Java from adding an implicit public constructor to
+ * every class which does not define at least one explicitly.
+ */
+ private Logger() {}
+
+ public static void requestLog(String xRequestId, HttpMethod methode, URI path) {
+ log.info("Portal-bff - request - X-Request-Id {} {} {}", xRequestId, methode, path);
+ }
+
+ public static void responseLog(String xRequestId, HttpStatus code) {
+ log.info("Portal-bff - response - X-Request-Id {} {}", xRequestId, code);
+ }
+
+ public static void errorLog(String xRequestId, String msg, String id, String app) {
+ log.info(
+ "Portal-bff - error - X-Request-Id {} {} {} not found in {}", xRequestId, msg, id, app);
+ }
+
+ public static void errorLog(
+ String xRequestId, String msg, String id, String app, String errorDetails) {
+ log.info(
+ "Portal-bff - error - X-Request-Id {} {} {} not found in {} error message: {}",
+ xRequestId,
+ msg,
+ id,
+ app,
+ errorDetails);
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/utils/SortingChainResolver.java b/lib/src/main/java/org/onap/portal/bff/utils/SortingChainResolver.java
new file mode 100644
index 0000000..d162637
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/utils/SortingChainResolver.java
@@ -0,0 +1,55 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import io.vavr.collection.Map;
+import io.vavr.collection.Seq;
+import io.vavr.control.Option;
+import java.util.Comparator;
+
+public class SortingChainResolver<T> {
+ final Map<String, Comparator<T>> comparators;
+
+ public SortingChainResolver(Map<String, Comparator<T>> comparators) {
+ this.comparators = comparators;
+ }
+
+ public Option<Comparator<T>> resolve(Seq<SortingParser.SortingParam> sortingParams) {
+ final Seq<Comparator<T>> resolvedComparators =
+ sortingParams.flatMap(
+ sortingParam ->
+ comparators
+ .get(sortingParam.getName())
+ .map(
+ comparator -> {
+ if (sortingParam.isDescending()) {
+ return comparator.reversed();
+ }
+ return comparator;
+ }));
+
+ if (resolvedComparators.isEmpty()) {
+ return Option.none();
+ }
+ return Option.some(resolvedComparators.reduceLeft(Comparator::thenComparing));
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/utils/SortingParser.java b/lib/src/main/java/org/onap/portal/bff/utils/SortingParser.java
new file mode 100644
index 0000000..d08f775
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/utils/SortingParser.java
@@ -0,0 +1,57 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import io.vavr.collection.List;
+import io.vavr.collection.Seq;
+import lombok.Builder;
+import lombok.NonNull;
+import lombok.Value;
+
+public class SortingParser {
+ private static final String DESC_PREFIX = "-";
+ private static final String SEPARATOR = ",";
+
+ private SortingParser() {}
+
+ public static Seq<SortingParam> parse(String sort) {
+ return List.of(sort.split(SEPARATOR))
+ .filter(name -> !name.isEmpty() && !name.equals(DESC_PREFIX))
+ .map(
+ name -> {
+ if (name.startsWith(DESC_PREFIX)) {
+ return SortingParam.builder()
+ .name(name.substring(DESC_PREFIX.length()))
+ .isDescending(true)
+ .build();
+ }
+ return SortingParam.builder().name(name).isDescending(false).build();
+ });
+ }
+
+ @Builder
+ @Value
+ public static class SortingParam {
+ @NonNull String name;
+ boolean isDescending;
+ }
+}
diff --git a/lib/src/main/java/org/onap/portal/bff/utils/VersionComparator.java b/lib/src/main/java/org/onap/portal/bff/utils/VersionComparator.java
new file mode 100644
index 0000000..cb8ecf1
--- /dev/null
+++ b/lib/src/main/java/org/onap/portal/bff/utils/VersionComparator.java
@@ -0,0 +1,48 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portal.bff.utils;
+
+import java.util.Comparator;
+import java.util.regex.Pattern;
+
+public class VersionComparator implements Comparator<String> {
+ private static final Pattern SEPARATOR_PATTERN = Pattern.compile("\\.");
+
+ @Override
+ public int compare(String version1, String version2) {
+ final String[] parsedVersion1 = SEPARATOR_PATTERN.split(version1);
+ final String[] parsedVersion2 = SEPARATOR_PATTERN.split(version2);
+ final int maxLength = Math.max(parsedVersion1.length, parsedVersion2.length);
+
+ for (int i = 0; i < maxLength; i++) {
+ final Integer v1 = i < parsedVersion1.length ? Integer.parseInt(parsedVersion1[i]) : 0;
+ final Integer v2 = i < parsedVersion2.length ? Integer.parseInt(parsedVersion2[i]) : 0;
+ final int compare = v1.compareTo(v2);
+
+ if (compare != 0) {
+ return compare;
+ }
+ }
+
+ return 0;
+ }
+}
diff --git a/lombok.config b/lombok.config
new file mode 100644
index 0000000..7a21e88
--- /dev/null
+++ b/lombok.config
@@ -0,0 +1 @@
+lombok.addLombokGeneratedAnnotation = true
diff --git a/openapi/build.gradle b/openapi/build.gradle
new file mode 100644
index 0000000..ee9ac96
--- /dev/null
+++ b/openapi/build.gradle
@@ -0,0 +1,27 @@
+apply plugin: 'org.openapi.generator'
+
+void createOpenApiGenerateClientTask(Project project, String apiDefinition, String packageName, String dtoSuffix) {
+ String taskName = "openApiGenerate_$packageName"
+ tasks.create(taskName, org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
+ generatorName = "java"
+ library = "webclient"
+ inputSpec = "${project.projectDir}/src/$apiDefinition".toString()
+ outputDir = "${project.buildDir}/openapi".toString()
+ configOptions = [
+ openApiNullable : "false",
+ dateLibrary : "java8",
+ serializationLibrary: "jackson"
+ ]
+ typeMappings = [
+ "File": "org.springframework.core.io.buffer.DataBuffer"
+ ]
+ generateApiTests = false
+ generateApiDocumentation = false
+ generateModelTests = false
+ generateModelDocumentation = false
+ invokerPackage = "org.onap.portal.bff.openapi.$packageName"
+ apiPackage = "org.onap.portal.bff.openapi.${packageName}.api"
+ modelPackage = "org.onap.portal.bff.openapi.${packageName}.model"
+ modelNameSuffix = dtoSuffix
+ }
+}
diff --git a/openapi/client-portal-history/LICENSE b/openapi/client-portal-history/LICENSE
new file mode 100644
index 0000000..abe3069
--- /dev/null
+++ b/openapi/client-portal-history/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 2021 TNAP / development / system-team
+
+ 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/openapi/client-portal-history/build.gradle b/openapi/client-portal-history/build.gradle
new file mode 100644
index 0000000..1872713
--- /dev/null
+++ b/openapi/client-portal-history/build.gradle
@@ -0,0 +1,25 @@
+apply plugin: 'org.openapi.generator'
+
+dependencies {
+ implementation "org.springframework.boot:spring-boot-starter-webflux"
+ implementation "org.openapitools:openapi-generator:$openapiVersion"
+}
+
+compileJava {
+ createOpenApiGenerateClientTask(project, "portal_history_openapi.yaml", "client_portal_history", "PortalHistoryDto")
+ dependsOn = [':openapi:openApiGenerate_client_portal_history']
+}
+
+sourceSets {
+ main {
+ java {
+ srcDirs += file("$buildDir/openapi/src/main/java")
+ }
+ }
+}
+
+idea {
+ module {
+ generatedSourceDirs += file("$buildDir/openapi/src/main/java")
+ }
+}
diff --git a/openapi/client-portal-history/src/portal_history_openapi.yaml b/openapi/client-portal-history/src/portal_history_openapi.yaml
new file mode 100644
index 0000000..5057592
--- /dev/null
+++ b/openapi/client-portal-history/src/portal_history_openapi.yaml
@@ -0,0 +1,457 @@
+openapi: 3.0.2
+info:
+ title: Config API
+ version: '1.0'
+ description: API to provide actions for portal-history
+ contact:
+ name: TNAP Team Tesla
+ url: 'https://www.telekom.de'
+ email: info@telekom.de
+servers:
+ - url: 'http://localhost:9002'
+tags:
+ - name: actions
+paths:
+ '/v1/actions/{userId}':
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ get:
+ summary: Retrieve all actions for a specific user
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActionsListResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ operationId: getActions
+ parameters:
+ - $ref: '#/components/parameters/pageQueryParam'
+ - $ref: '#/components/parameters/pageSizeQueryParam'
+ - schema:
+ type: integer
+ format: int32
+ in: query
+ name: showLastHours
+ description: Get all actions within the last X hours.
+ description: Get actions for the given userId
+ tags:
+ - actions
+ post:
+ summary: Create an action for a given user
+ operationId: createAction
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActionResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreateActionRequest'
+ description: Only one action in each POST request
+ description: Create a user action
+ tags:
+ - actions
+ delete:
+ summary: Delete user actions after given time
+ operationId: deleteActions
+ parameters:
+ - schema:
+ type: integer
+ format: int32
+ in: query
+ name: deleteAfterHours
+ description: If parameter is given actions older than value will be deleted for the user
+ required: true
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ tags:
+ - actions
+ description: Delete user actions after given time
+ '/v1/actions':
+ get:
+ summary: Retrieve all actions from the portal with an optional timeframe
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActionsListResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ operationId: listActions
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ - $ref: '#/components/parameters/pageQueryParam'
+ - $ref: '#/components/parameters/pageSizeQueryParam'
+ - schema:
+ type: integer
+ format: int32
+ in: query
+ name: showLastHours
+ description: Get all actions within the last X hours.
+ description: Get portal actions from all users
+ tags:
+ - actions
+ '/actuator/info':
+ get:
+ tags:
+ - actions
+ summary: Retrieve actuator information
+ description: Proxy for actuator info endpoint
+ operationId: getActuatorInfo
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActuatorInfoResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+
+components:
+ parameters:
+ xRequestIdHeader:
+ name: X-Request-Id
+ in: header
+ description: The unique identifier of the request
+ required: true
+ schema:
+ type: string
+ pageQueryParam:
+ name: page
+ in: query
+ description: Page index (1..N)
+ required: false
+ schema:
+ type: integer
+ format: int32
+ minimum: 1
+ default: 1
+ pageSizeQueryParam:
+ name: pageSize
+ in: query
+ description: The size of the page to be returned
+ required: false
+ schema:
+ type: integer
+ format: int32
+ minimum: 1
+ maximum: 5000
+ default: 10
+ userIdPathParam:
+ name: userId
+ in: path
+ description: User ID
+ required: true
+ schema:
+ $ref: '#/components/schemas/ValidString'
+ schemas:
+ ActionResponse:
+ title: ActionResponse
+ type: object
+ properties:
+ actionCreatedAt:
+ type: string
+ format: date-time
+ action:
+ type: object
+ saveInterval:
+ type: integer
+ format: int32
+ required:
+ - action
+ - actionCreatedAt
+ CreateActionRequest:
+ title: CreateActionRequest
+ type: object
+ properties:
+ userId:
+ type: string
+ actionCreatedAt:
+ type: string
+ format: date-time
+ action:
+ type: object
+ required:
+ - userId
+ - actionCreatedAt
+ - action
+ ActionsListResponse:
+ title: ActionsListResponse
+ type: object
+ properties:
+ actionsList:
+ type: array
+ items:
+ $ref: '#/components/schemas/ActionResponse'
+ totalCount:
+ type: integer
+ format: int32
+ description: Total number of items matching criteria
+ required:
+ - actionsList
+ - totalCount
+ ActuatorInfoResponse:
+ title: ActuatorInfoResponse
+ type: object
+ properties:
+ git:
+ $ref: '#/components/schemas/ActuatorGitInfo'
+ build:
+ $ref: '#/components/schemas/ActuatorBuildInfo'
+ java:
+ $ref: '#/components/schemas/ActuatorJavaInfo'
+ ActuatorGitInfo:
+ title: ActuatorGitInfo
+ type: object
+ properties:
+ branch:
+ type: string
+ commit:
+ $ref: '#/components/schemas/GitCommitInfo'
+ ActuatorBuildInfo:
+ title: ActuatorBuildInfo
+ type: object
+ properties:
+ artifact:
+ type: string
+ name:
+ type: string
+ time:
+ type: string
+ version:
+ type: string
+ group:
+ type: string
+ GitCommitInfo:
+ title: GitCommitInfo
+ type: object
+ properties:
+ id:
+ type: string
+ time:
+ type: string
+ ActuatorJavaInfo:
+ title: ActuatorJavaInfo
+ type: object
+ properties:
+ version:
+ type: string
+ vendor:
+ $ref: '#/components/schemas/JavaVendorInfo'
+ runtime:
+ $ref: '#/components/schemas/JavaRuntimeInfo'
+ jvm:
+ $ref: '#/components/schemas/JavaJvmInfo'
+ JavaVendorInfo:
+ title: JavaVendorInfo
+ type: object
+ properties:
+ name:
+ type: string
+ version:
+ type: string
+ JavaRuntimeInfo:
+ title: JavaRuntimeInfo
+ type: object
+ properties:
+ name:
+ type: string
+ version:
+ type: string
+ JavaJvmInfo:
+ title: JavaJvmInfo
+ type: object
+ properties:
+ name:
+ type: string
+ vendor:
+ type: string
+ version:
+ type: string
+ Problem:
+ type: object
+ properties:
+ type:
+ type: string
+ format: uri-reference
+ description: |
+ A URI reference that uniquely identifies the problem type only in the context of the provided API. Opposed to the specification in RFC-7807, it is neither recommended to be dereferencable and point to a human-readable documentation nor globally unique for the problem type.
+ default: 'about:blank'
+ example: /problem/connection-error
+ title:
+ type: string
+ description: |
+ A short summary of the problem type. Written in English and readable for engineers, usually not suited for non technical stakeholders and not localized.
+ example: Service Unavailable
+ status:
+ type: integer
+ format: int32
+ description: |
+ The HTTP status code generated by the origin server for this occurrence of the problem.
+ minimum: 100
+ maximum: 600
+ exclusiveMaximum: true
+ example: 503
+ detail:
+ type: string
+ description: |
+ A human readable explanation specific to this occurrence of the problem that is helpful to locate the problem and give advice on how to proceed. Written in English and readable for engineers, usually not suited for non technical stakeholders and not localized.
+ example: Connection to database timed out
+ instance:
+ type: string
+ format: uri-reference
+ description: |
+ A URI reference that identifies the specific occurrence of the problem, e.g. by adding a fragment identifier or sub-path to the problem type. May be used to locate the root of this problem in the source code.
+ example: /problem/connection-error#token-info-read-timed-out
+ ValidString:
+ type: string
+ pattern: '[\w,/!=§#@€:µ.*+?'' \-\u00C0-\u017F]*'
+ responses:
+ BadRequest:
+ description: '400: Bad Request'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Unauthorized:
+ description: '401: Unauthorized'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Forbidden:
+ description: '403: Forbidden'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ NotFound:
+ description: '404: Not Found'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ NotAllowed:
+ description: '405: Method Not Allowed'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Conflict:
+ description: '409: Conflict'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ InternalServerError:
+ description: Internal Server Error
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ BadGateway:
+ description: Bad Gateway
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
diff --git a/openapi/client-portal-keycloak/LICENSE b/openapi/client-portal-keycloak/LICENSE
new file mode 100644
index 0000000..abe3069
--- /dev/null
+++ b/openapi/client-portal-keycloak/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 2021 TNAP / development / system-team
+
+ 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/openapi/client-portal-keycloak/build.gradle b/openapi/client-portal-keycloak/build.gradle
new file mode 100644
index 0000000..f01cf4b
--- /dev/null
+++ b/openapi/client-portal-keycloak/build.gradle
@@ -0,0 +1,25 @@
+apply plugin: 'org.openapi.generator'
+
+dependencies {
+ implementation "org.springframework.boot:spring-boot-starter-webflux"
+ implementation "org.openapitools:openapi-generator:$openapiVersion"
+}
+
+compileJava {
+ createOpenApiGenerateClientTask(project, "portal_keycloak_openapi.yaml", "client_portal_keycloak", "KeycloakDto")
+ dependsOn = [':openapi:openApiGenerate_client_portal_keycloak']
+}
+
+sourceSets {
+ main {
+ java {
+ srcDirs += file("$buildDir/openapi/src/main/java")
+ }
+ }
+}
+
+idea {
+ module {
+ generatedSourceDirs += file("$buildDir/openapi/src/main/java")
+ }
+}
diff --git a/openapi/client-portal-keycloak/src/portal_keycloak_openapi.yaml b/openapi/client-portal-keycloak/src/portal_keycloak_openapi.yaml
new file mode 100644
index 0000000..a09f0f4
--- /dev/null
+++ b/openapi/client-portal-keycloak/src/portal_keycloak_openapi.yaml
@@ -0,0 +1,651 @@
+openapi: 3.0.2
+info:
+ title: Keycloak API
+ version: '1.0'
+ description: API to provide Keycloak actions
+ contact:
+ name: TNAP Team Tesla
+ url: 'https://www.telekom.de'
+ email: info@telekom.de
+servers:
+ - url: 'http://localhost:9003/{base}/{version}'
+ variables:
+ base:
+ default: 'portal-keycloak'
+ description: Basepath
+ version:
+ default: 'v1'
+ description: Version
+paths:
+ '/roles':
+ get:
+ tags:
+ - keycloak
+ summary: Get all roles
+ description: Retrieves all keycloak roles for the realm or client
+ operationId: getRoles
+ parameters:
+ - name: search
+ in: query
+ schema:
+ type: string
+ - name: first
+ in: query
+ schema:
+ type: integer
+ format: int32
+ - name: max
+ in: query
+ schema:
+ type: integer
+ format: int32
+ - name: briefRepresentation
+ in: query
+ schema:
+ type: boolean
+ responses:
+ 2XX:
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ post:
+ tags:
+ - keycloak
+ summary: Create a new role
+ description: Creates a new role for the realm or client
+ operationId: createRole
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Role'
+ required: true
+ responses:
+ 2XX:
+ description: OK
+ '/roles/{roleName}/users':
+ get:
+ tags:
+ - keycloak
+ summary: Get all users for the role
+ description: Returns a stream of users that have the specified role name
+ operationId: getUsersByRole
+ parameters:
+ - name: first
+ in: query
+ description: 'First result to return. Ignored if negative or {@code null}'
+ schema:
+ type: integer
+ format: int32
+ - name: max
+ in: query
+ description: 'Maximum number of results to return. Ignored if negative or {@code null}'
+ schema:
+ type: integer
+ format: int32
+ responses:
+ 2XX:
+ description: Success
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/User'
+ parameters:
+ - name: roleName
+ in: path
+ description: The role name
+ required: true
+ schema:
+ type: string
+ '/users':
+ post:
+ tags:
+ - keycloak
+ summary: Create a new keycloak user
+ description: Creates a new user in keycloak. Username must be unique
+ operationId: createUser
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ responses:
+ 2XX:
+ description: Success
+ get:
+ tags:
+ - keycloak
+ summary: Get keycloak users
+ description: Returns a stream of users, filtered according to query.
+ operationId: getUsers
+ parameters:
+ - name: search
+ in: query
+ schema:
+ type: string
+ - name: lastName
+ in: query
+ schema:
+ type: string
+ - name: firstName
+ in: query
+ schema:
+ type: string
+ - name: email
+ in: query
+ schema:
+ type: string
+ - name: username
+ in: query
+ schema:
+ type: string
+ - name: emailVerified
+ in: query
+ schema:
+ type: boolean
+ - name: idpAlias
+ in: query
+ schema:
+ type: string
+ - name: idpUserId
+ in: query
+ schema:
+ type: string
+ - name: first
+ in: query
+ schema:
+ type: integer
+ format: int32
+ - name: max
+ in: query
+ schema:
+ type: integer
+ format: int32
+ - name: enabled
+ in: query
+ schema:
+ type: boolean
+ - name: briefRepresentation
+ in: query
+ schema:
+ type: boolean
+ - name: exact
+ in: query
+ schema:
+ type: boolean
+ - name: q
+ in: query
+ schema:
+ type: string
+ responses:
+ 2XX:
+ description: Success
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/User'
+ '/users/count':
+ get:
+ tags:
+ - keycloak
+ summary: Get users count
+ description: Returns the number of users that match the given criteria
+ operationId: getUsersCount
+ parameters:
+ - name: search
+ in: query
+ schema:
+ type: string
+ - name: lastName
+ in: query
+ schema:
+ type: string
+ - name: firstName
+ in: query
+ schema:
+ type: string
+ - name: email
+ in: query
+ schema:
+ type: string
+ - name: emailVerified
+ in: query
+ schema:
+ type: boolean
+ - name: username
+ in: query
+ schema:
+ type: string
+ - name: enabled
+ in: query
+ schema:
+ type: boolean
+ responses:
+ 2XX:
+ description: Success
+ content:
+ application/json:
+ schema:
+ type: integer
+ format: int32
+ '/users/{id}':
+ put:
+ tags:
+ - keycloak
+ summary: Update user
+ description: Updates the user
+ operationId: updateUser
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ responses:
+ 2XX:
+ description: Success
+ get:
+ tags:
+ - keycloak
+ summary: Get user
+ description: Returns representation of the user
+ operationId: getUser
+ responses:
+ 2XX:
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ delete:
+ tags:
+ - keycloak
+ summary: Delete the user
+ description: Deletes the user
+ operationId: deleteUser
+ responses:
+ 2XX:
+ description: Success
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ '/users/{id}/reset-password':
+ put:
+ tags:
+ - keycloak
+ summary: Reset user password
+ description: Sets up a new password for the user
+ operationId: resetUserPassword
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Credential'
+ responses:
+ 2XX:
+ description: Success
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ '/users/{id}/role-mappings/realm':
+ get:
+ tags:
+ - keycloak
+ summary: Get realm role mappings
+ description: Returns realm-level role mappings
+ operationId: getRealmRoleMappingsByUserId
+ responses:
+ 2XX:
+ description: Success
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ post:
+ tags:
+ - keycloak
+ summary: Add realm role mappings
+ description: Adds realm-level role mappings to the user
+ operationId: addRealmRoleMappingsToUser
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ responses:
+ 2XX:
+ description: Success
+ delete:
+ tags:
+ - keycloak
+ summary: Delete realm role mappings
+ description: Deletes realm-level role mappings
+ operationId: deleteRealmRoleMappingsByUserId
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ responses:
+ 2XX:
+ description: Success
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ '/users/{id}/role-mappings/realm/available':
+ get:
+ tags:
+ - keycloak
+ summary: Get available realm roles
+ description: Returns realm-level roles that can be mapped
+ operationId: getAvailableRealmRoleMappingsByUserId
+ responses:
+ 2XX:
+ description: Success
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ '/users/{id}/execute-actions-email':
+ put:
+ tags:
+ - keycloak
+ summary: Execute actions email
+ description: Send an update account email to the user. An email contains a link the user can click to perform a set of required actions. The redirectUri and clientId parameters are optional. If no redirect is given, then there will be no link back to click after actions have completed. Redirect uri must be a valid uri for the particular clientId
+ operationId: executeActionsEmail
+ parameters:
+ - name: OIDCLoginProtocol.REDIRECT_URI_PARAM
+ in: query
+ description: Redirect uri
+ schema:
+ type: string
+ - name: OIDCLoginProtocol.CLIENT_ID_PARAM
+ in: query
+ description: Client id
+ schema:
+ type: string
+ - name: lifespan
+ in: query
+ description: Number of seconds after which the generated token expires
+ schema:
+ type: integer
+ format: int32
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/RequiredActions'
+ responses:
+ 2XX:
+ description: Success
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+components:
+ schemas:
+ Role:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ description:
+ type: string
+ scopeParamRequired:
+ type: boolean
+ composites:
+ $ref: '#/components/schemas/Composites'
+ composite:
+ type: boolean
+ clientRole:
+ type: boolean
+ containerId:
+ type: string
+ attributes:
+ type: object
+ additionalProperties:
+ type: array
+ items:
+ type: string
+ Composites:
+ type: object
+ properties:
+ realm:
+ type: array
+ items:
+ type: string
+ client:
+ type: object
+ additionalProperties:
+ type: array
+ items:
+ type: string
+ application:
+ type: object
+ additionalProperties:
+ type: array
+ items:
+ type: string
+ User:
+ type: object
+ properties:
+ self:
+ type: string
+ id:
+ type: string
+ createdTimestamp:
+ type: integer
+ format: int64
+ firstName:
+ type: string
+ lastName:
+ type: string
+ email:
+ type: string
+ username:
+ type: string
+ enabled:
+ type: boolean
+ totp:
+ type: boolean
+ emailVerified:
+ type: boolean
+ attributes:
+ type: object
+ additionalProperties:
+ type: array
+ items:
+ type: string
+ credentials:
+ type: array
+ items:
+ $ref: '#/components/schemas/Credential'
+ requiredActions:
+ type: array
+ items:
+ $ref: '#/components/schemas/RequiredActions'
+ federatedIdentities:
+ type: array
+ items:
+ $ref: '#/components/schemas/FederatedIdentity'
+ socialLinks:
+ type: array
+ items:
+ $ref: '#/components/schemas/SocialLink'
+ realmRoles:
+ type: array
+ items:
+ type: string
+ clientRoles:
+ type: object
+ additionalProperties:
+ type: array
+ items:
+ type: string
+ clientConsents:
+ type: array
+ items:
+ $ref: '#/components/schemas/UserConsent'
+ notBefore:
+ type: integer
+ format: int32
+ applicationRoles:
+ type: object
+ additionalProperties:
+ type: array
+ items:
+ type: string
+ federationLink:
+ type: string
+ serviceAccountClientId:
+ type: string
+ groups:
+ type: array
+ items:
+ type: string
+ origin:
+ type: string
+ disableableCredentialTypes:
+ type: array
+ items:
+ type: string
+ access:
+ type: object
+ additionalProperties:
+ type: boolean
+ Credential:
+ type: object
+ properties:
+ id:
+ type: string
+ type:
+ type: string
+ userLabel:
+ type: string
+ secretData:
+ type: string
+ credentialData:
+ type: string
+ priority:
+ type: integer
+ format: int32
+ createdDate:
+ type: integer
+ format: int64
+ value:
+ type: string
+ temporary:
+ type: boolean
+ device:
+ type: string
+ hashedSaltedValue:
+ type: string
+ salt:
+ type: string
+ hashIterations:
+ type: integer
+ format: int32
+ counter:
+ type: integer
+ format: int32
+ algorithm:
+ type: string
+ digits:
+ type: integer
+ format: int32
+ period:
+ type: integer
+ format: int32
+ config:
+ type: object
+ additionalProperties:
+ type: string
+ FederatedIdentity:
+ type: object
+ properties:
+ identityProvider:
+ type: string
+ userId:
+ type: string
+ userName:
+ type: string
+ SocialLink:
+ type: object
+ properties:
+ socialProvider:
+ type: string
+ socialUserId:
+ type: string
+ socialUsername:
+ type: string
+ UserConsent:
+ type: object
+ properties:
+ clientId:
+ type: string
+ grantedClientScopes:
+ type: array
+ items:
+ type: string
+ createdDate:
+ type: integer
+ format: int64
+ lastUpdatedDate:
+ type: integer
+ format: int64
+ grantedRealmRoles:
+ type: array
+ items:
+ type: string
+ RequiredActions:
+ type: string
+ enum:
+ - CONFIGURE_TOTP
+ - TERMS_AND_CONDITIONS
+ - UPDATE_PASSWORD
+ - UPDATE_PROFILE
+ - VERIFY_EMAIL
+ ErrorResponse:
+ type: object
+ properties:
+ error:
+ type: string
+ errorMessage:
+ type: string
+
diff --git a/openapi/client-portal-prefs/LICENSE b/openapi/client-portal-prefs/LICENSE
new file mode 100644
index 0000000..abe3069
--- /dev/null
+++ b/openapi/client-portal-prefs/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 2021 TNAP / development / system-team
+
+ 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/openapi/client-portal-prefs/build.gradle b/openapi/client-portal-prefs/build.gradle
new file mode 100644
index 0000000..5201737
--- /dev/null
+++ b/openapi/client-portal-prefs/build.gradle
@@ -0,0 +1,25 @@
+apply plugin: 'org.openapi.generator'
+
+dependencies {
+ implementation "org.springframework.boot:spring-boot-starter-webflux"
+ implementation "org.openapitools:openapi-generator:$openapiVersion"
+}
+
+compileJava {
+ createOpenApiGenerateClientTask(project, "portal_prefs_openapi.yaml", "client_portal_prefs", "PortalPrefsDto")
+ dependsOn = [':openapi:openApiGenerate_client_portal_prefs']
+}
+
+sourceSets {
+ main {
+ java {
+ srcDirs += file("$buildDir/openapi/src/main/java")
+ }
+ }
+}
+
+idea {
+ module {
+ generatedSourceDirs += file("$buildDir/openapi/src/main/java")
+ }
+}
diff --git a/openapi/client-portal-prefs/src/portal_prefs_openapi.yaml b/openapi/client-portal-prefs/src/portal_prefs_openapi.yaml
new file mode 100644
index 0000000..86d9e2b
--- /dev/null
+++ b/openapi/client-portal-prefs/src/portal_prefs_openapi.yaml
@@ -0,0 +1,341 @@
+openapi: 3.0.2
+info:
+ title: Config API
+ version: '1.0'
+servers:
+ - url: 'http://localhost:9001'
+tags:
+ - name: preferences
+paths:
+ '/v1/preferences':
+ get:
+ description: Returns user preferences
+ summary: Get user preferences
+ operationId: getPreferences
+ parameters:
+ - $ref: '#/components/parameters/XRequestIdHeader'
+ tags:
+ - preferences
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Preferences'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ put:
+ description: Updates user preferences
+ summary: Update user preferences
+ operationId: updatePreferences
+ parameters:
+ - $ref: '#/components/parameters/XRequestIdHeader'
+ tags:
+ - preferences
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Preferences'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Preferences'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ post:
+ description: Save user preferences
+ summary: Save user preferences
+ operationId: savePreferences
+ parameters:
+ - $ref: '#/components/parameters/XRequestIdHeader'
+ tags:
+ - preferences
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Preferences'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Preferences'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ '/actuator/info':
+ get:
+ tags:
+ - preferences
+ summary: Retrieve actuator information
+ description: Proxy for actuator info endpoint
+ operationId: getActuatorInfo
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActuatorInfoResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+components:
+ parameters:
+ XRequestIdHeader:
+ name: X-Request-Id
+ in: header
+ description: The unique identifier of the request
+ required: true
+ schema:
+ type: string
+ schemas:
+ Preferences:
+ type: object
+ x-extension-1: null
+ properties:
+ properties:
+ type: object
+ required:
+ - properties
+ ActuatorInfoResponse:
+ title: ActuatorInfoResponse
+ type: object
+ properties:
+ git:
+ $ref: '#/components/schemas/ActuatorGitInfo'
+ build:
+ $ref: '#/components/schemas/ActuatorBuildInfo'
+ java:
+ $ref: '#/components/schemas/ActuatorJavaInfo'
+ ActuatorGitInfo:
+ title: ActuatorGitInfo
+ type: object
+ properties:
+ branch:
+ type: string
+ commit:
+ $ref: '#/components/schemas/GitCommitInfo'
+ ActuatorBuildInfo:
+ title: ActuatorBuildInfo
+ type: object
+ properties:
+ artifact:
+ type: string
+ name:
+ type: string
+ time:
+ type: string
+ version:
+ type: string
+ group:
+ type: string
+ GitCommitInfo:
+ title: GitCommitInfo
+ type: object
+ properties:
+ id:
+ type: string
+ time:
+ type: string
+ ActuatorJavaInfo:
+ title: ActuatorJavaInfo
+ type: object
+ properties:
+ version:
+ type: string
+ vendor:
+ $ref: '#/components/schemas/JavaVendorInfo'
+ runtime:
+ $ref: '#/components/schemas/JavaRuntimeInfo'
+ jvm:
+ $ref: '#/components/schemas/JavaJvmInfo'
+ JavaVendorInfo:
+ title: JavaVendorInfo
+ type: object
+ properties:
+ name:
+ type: string
+ version:
+ type: string
+ JavaRuntimeInfo:
+ title: JavaRuntimeInfo
+ type: object
+ properties:
+ name:
+ type: string
+ version:
+ type: string
+ JavaJvmInfo:
+ title: JavaJvmInfo
+ type: object
+ properties:
+ name:
+ type: string
+ vendor:
+ type: string
+ version:
+ type: string
+ Problem:
+ type: object
+ properties:
+ type:
+ type: string
+ format: uri-reference
+ description: |
+ A URI reference that uniquely identifies the problem type only in the context of the provided API. Opposed to the specification in RFC-7807, it is neither recommended to be dereferencable and point to a human-readable documentation nor globally unique for the problem type.
+ default: 'about:blank'
+ example: /problem/connection-error
+ title:
+ type: string
+ description: |
+ A short summary of the problem type. Written in English and readable for engineers, usually not suited for non technical stakeholders and not localized.
+ example: Service Unavailable
+ status:
+ type: integer
+ format: int32
+ description: |
+ The HTTP status code generated by the origin server for this occurrence of the problem.
+ minimum: 100
+ maximum: 600
+ exclusiveMaximum: true
+ example: 503
+ detail:
+ type: string
+ description: |
+ A human readable explanation specific to this occurrence of the problem that is helpful to locate the problem and give advice on how to proceed. Written in English and readable for engineers, usually not suited for non technical stakeholders and not localized.
+ example: Connection to database timed out
+ instance:
+ type: string
+ format: uri-reference
+ description: |
+ A URI reference that identifies the specific occurrence of the problem, e.g. by adding a fragment identifier or sub-path to the problem type. May be used to locate the root of this problem in the source code.
+ example: /problem/connection-error#token-info-read-timed-out
+ responses:
+ BadRequest:
+ description: '400: Bad Request'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Unauthorized:
+ description: '401: Unauthorized'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Forbidden:
+ description: '403: Forbidden'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ NotFound:
+ description: '404: Not Found'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ NotAllowed:
+ description: '405: Method Not Allowed'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Conflict:
+ description: '409: Conflict'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ InternalServerError:
+ description: Internal Server Error
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ BadGateway:
+ description: Bad Gateway
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
diff --git a/openapi/server/LICENSE b/openapi/server/LICENSE
new file mode 100644
index 0000000..abe3069
--- /dev/null
+++ b/openapi/server/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 2021 TNAP / development / system-team
+
+ 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/openapi/server/build.gradle b/openapi/server/build.gradle
new file mode 100644
index 0000000..d3b4a47
--- /dev/null
+++ b/openapi/server/build.gradle
@@ -0,0 +1,48 @@
+apply plugin: 'org.openapi.generator'
+
+dependencies {
+ implementation "org.springframework.boot:spring-boot-starter-webflux"
+ implementation "org.openapitools:openapi-generator:$openapiVersion"
+ implementation "org.webjars:redoc:$redocVersion"
+}
+
+openApiGenerate {
+ generatorName = "spring"
+ library = "spring-boot"
+ inputSpec = "$projectDir/src/main/resources/static/api.yaml"
+ outputDir = "$buildDir/openapi"
+ configOptions = [
+ openApiNullable: "false",
+ skipDefaultInterface: "true",
+ dateLibrary: "java8",
+ interfaceOnly: "true",
+ useTags: "true",
+ reactive: "true",
+ ]
+ generateApiTests = false
+ generateApiDocumentation = true
+ generateModelTests = false
+ generateModelDocumentation = false
+ invokerPackage = "org.onap.portal.bff.openapi.server"
+ apiPackage = "org.onap.portal.bff.openapi.server.api"
+ modelPackage = "org.onap.portal.bff.openapi.server.model"
+ modelNameSuffix = "ApiDto"
+}
+
+compileJava {
+ dependsOn tasks.openApiGenerate
+}
+
+sourceSets {
+ main {
+ java {
+ srcDirs += file("$buildDir/openapi/src/main/java")
+ }
+ }
+}
+
+idea {
+ module {
+ generatedSourceDirs += file("$buildDir/openapi/src/main/java")
+ }
+}
diff --git a/openapi/server/src/main/resources/static/api-docs.html b/openapi/server/src/main/resources/static/api-docs.html
new file mode 100644
index 0000000..5c52f49
--- /dev/null
+++ b/openapi/server/src/main/resources/static/api-docs.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Portal BFF API</title>
+ <meta charset="utf-8"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
+
+ <style>
+ body {
+ margin: 0;
+ padding: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <redoc spec-url='api.yaml' required-props-first native-scrollbars hide-download-button></redoc>
+ <script src="webjars/redoc/2.0.0-rc.20/redoc.standalone.js"></script>
+ </body>
+</html>
diff --git a/openapi/server/src/main/resources/static/api.yaml b/openapi/server/src/main/resources/static/api.yaml
new file mode 100644
index 0000000..a7d4b74
--- /dev/null
+++ b/openapi/server/src/main/resources/static/api.yaml
@@ -0,0 +1,969 @@
+openapi: 3.0.3
+info:
+ title: Portal BFF
+ version: '1.0'
+ description: Portal BFF API
+ contact:
+ name: Team Tesla
+servers:
+ - url: 'http://localhost:9080'
+tags:
+ - name: users
+ - name: roles
+ - name: tiles
+ - name: keys
+ - name: preferences
+ - name: actions
+paths:
+ /users:
+ get:
+ summary: List users
+ description: List users
+ operationId: listUsers
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/pageQueryParam'
+ - $ref: '#/components/parameters/pageSizeQueryParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ responses:
+ '200':
+ description: List of users
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UserListResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ post:
+ summary: Create user
+ description: Create user
+ operationId: createUser
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreateUserRequest'
+ responses:
+ '200':
+ description: Detail of user
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UserResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ '/users/{userId}':
+ get:
+ summary: Retrieve detail of user
+ description: Retrieve detail of user
+ operationId: getUser
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ responses:
+ '200':
+ description: Detail of user
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UserResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ put:
+ summary: Update user
+ description: Update user
+ operationId: updateUser
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UpdateUserRequest'
+ responses:
+ '200':
+ description: User updated successfully
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ delete:
+ summary: Delete user
+ description: Delete user
+ operationId: deleteUser
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ responses:
+ '204':
+ description: No Content
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ '/users/{userId}/roles':
+ get:
+ summary: List assigned roles
+ description: List assigned roles
+ operationId: listAssignedRoles
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ responses:
+ '200':
+ description: List of assigned roles
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RoleListResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ put:
+ summary: Update assigned roles
+ description: Update assigned roles
+ operationId: updateAssignedRoles
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ requestBody:
+ description: IDs of roles which should be assigned
+ required: false
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UpdateAssignedRolesRequest'
+ responses:
+ '200':
+ description: List of assigned roles
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RoleListResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ '/users/{userId}/roles/available':
+ get:
+ summary: List available roles
+ description: List available roles
+ operationId: listAvailableRoles
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ responses:
+ '200':
+ description: List of available roles
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RoleListResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ '/users/{userId}/password':
+ put:
+ summary: Update password
+ description: Update password
+ operationId: updatePassword
+ tags:
+ - users
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UpdateUserPasswordRequest'
+ responses:
+ '204':
+ description: Password was changed successfully
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ /roles:
+ get:
+ summary: List roles
+ description: List roles
+ operationId: listRoles
+ tags:
+ - roles
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ responses:
+ '200':
+ description: List of roles
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RoleListResponse'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ /preferences:
+ get:
+ description: Returns user preferences
+ summary: Get user preferences
+ operationId: getPreferences
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ tags:
+ - preferences
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PreferencesResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ put:
+ description: Updates user preferences
+ summary: Update user preferences
+ operationId: updatePreferences
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ tags:
+ - preferences
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreatePreferencesRequest'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PreferencesResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ post:
+ description: Save user preferences
+ summary: Save user preferences
+ operationId: savePreferences
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ tags:
+ - preferences
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreatePreferencesRequest'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PreferencesResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ '/actions/{userId}':
+ get:
+ summary: Retrieve all actions for a specific user
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActionsListResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ operationId: getActions
+ parameters:
+ - $ref: '#/components/parameters/pageQueryParam'
+ - $ref: '#/components/parameters/pageSizeQueryParam'
+ - schema:
+ type: integer
+ format: int32
+ in: query
+ name: showLastHours
+ description: Get all actions within the last X hours.
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ description: Get actions for the given userId
+ tags:
+ - actions
+ parameters:
+ - $ref: '#/components/parameters/userIdPathParam'
+ post:
+ summary: Create an action for a given user
+ operationId: createAction
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActionsResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreateActionRequest'
+ description: Only one action in each POST request
+ parameters:
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ description: Create a user action
+ tags:
+ - actions
+ /actions:
+ get:
+ summary: Retrieve all actions from the portal with an optional timeframe
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ActionsListResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ '502':
+ $ref: '#/components/responses/BadGateway'
+ operationId: listActions
+ parameters:
+ - $ref: '#/components/parameters/pageQueryParam'
+ - $ref: '#/components/parameters/pageSizeQueryParam'
+ - schema:
+ type: integer
+ format: int32
+ in: query
+ name: showLastHours
+ description: Get all actions within the last X hours.
+ - $ref: '#/components/parameters/xRequestIdHeader'
+ description: Get portal actions from all users
+ tags:
+ - actions
+ parameters: []
+components:
+ responses:
+ BadRequest:
+ description: '400: Bad Request'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Unauthorized:
+ description: '401: Unauthorized'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Forbidden:
+ description: '403: Forbidden'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ NotFound:
+ description: '404: Not Found'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ NotAllowed:
+ description: '405: Method Not Allowed'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ Conflict:
+ description: '409: Conflict'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ InternalServerError:
+ description: Internal Server Error
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ BadGateway:
+ description: Bad Gateway
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/Problem'
+ headers:
+ X-Request-Id:
+ schema:
+ type: string
+ description: A <uuid4> in each response
+ securitySchemes:
+ bearerAuth:
+ type: http
+ scheme: bearer
+ bearerFormat: JWT
+ headers:
+ X-Request-Id:
+ description: The unique identifier of the request
+ schema:
+ type: string
+ parameters:
+ xRequestIdHeader:
+ name: X-Request-Id
+ in: header
+ schema:
+ type: string
+ description: The unique identifier of the request
+ required: false
+ userIdPathParam:
+ name: userId
+ in: path
+ description: User ID
+ required: true
+ schema:
+ $ref: '#/components/schemas/ValidString'
+ tileIdPathParam:
+ name: tileId
+ in: path
+ description: Tile ID
+ required: true
+ schema:
+ type: integer
+ format: int64
+ pageQueryParam:
+ name: page
+ in: query
+ description: Page index (1..N)
+ required: false
+ schema:
+ type: integer
+ format: int32
+ minimum: 1
+ default: 1
+ pageSizeQueryParam:
+ name: pageSize
+ in: query
+ description: The size of the page to be returned
+ required: false
+ schema:
+ type: integer
+ format: int32
+ minimum: 1
+ maximum: 5000
+ default: 10
+ schemas:
+ CreatePreferencesRequest:
+ type: object
+ required:
+ - keys
+ properties:
+ properties:
+ type: object
+ title: CreatePreferencesRequest
+ x-internal: false
+ PreferencesResponse:
+ type: object
+ title: PreferencesResponse
+ properties:
+ properties:
+ type: object
+ required:
+ - properties
+ ValidString:
+ type: string
+ pattern: '[\w,/!=§#@€:µ.*+?'' \-\u00C0-\u017F]*'
+ Problem:
+ type: object
+ required:
+ - status
+ - title
+ properties:
+ type:
+ type: string
+ format: uri-reference
+ description: |
+ A URI reference that uniquely identifies the problem type only in the context of the provided API. Opposed to the specification in RFC-7807, it is neither recommended to be dereferencable and point to a human-readable documentation nor globally unique for the problem type.
+ default: 'about:blank'
+ example: /problem/connection-error
+ title:
+ type: string
+ description: |
+ A short summary of the problem type. Written in English and readable for engineers, usually not suited for non technical stakeholders and not localized.
+ example: Service Unavailable
+ status:
+ type: integer
+ format: int32
+ description: |
+ The HTTP status code generated by the origin server for this occurrence of the problem.
+ minimum: 100
+ maximum: 600
+ exclusiveMaximum: true
+ example: 503
+ detail:
+ type: string
+ description: |
+ A human readable explanation specific to this occurrence of the problem that is helpful to locate the problem and give advice on how to proceed. Written in English and readable for engineers, usually not suited for non technical stakeholders and not localized.
+ example: Connection to database timed out
+ downstreamSystem:
+ type: string
+ description: The downstream system that responded with error
+ enum:
+ - KEYCLOAK
+ - PORTAL_SERVICE
+ - PORTAL_PREFS
+ - PORTAL_HISTORY
+ downstreamStatus:
+ type: integer
+ format: int32
+ description: |
+ Response status from the downstream system.
+ example: 401
+ downstreamMessageId:
+ type: string
+ description: |
+ The identifier of the error message from the downstream system.
+ example: SVC3001
+ instance:
+ type: string
+ format: uri-reference
+ description: |
+ A URI reference that identifies the specific occurrence of the problem, e.g. by adding a fragment identifier or sub-path to the problem type. May be used to locate the root of this problem in the source code.
+ example: /problem/connection-error#token-info-read-timed-out
+ violations:
+ type: array
+ externalDocs:
+ url: https://opensource.zalando.com/problem/constraint-violation/
+ items:
+ $ref: '#/components/schemas/ConstraintViolation'
+ ConstraintViolation:
+ type: object
+ properties:
+ field:
+ type: string
+ message:
+ type: string
+ required:
+ - field
+ - message
+ UserResponse:
+ type: object
+ required:
+ - id
+ - username
+ - enabled
+ properties:
+ id:
+ type: string
+ username:
+ type: string
+ email:
+ type: string
+ firstName:
+ type: string
+ lastName:
+ type: string
+ enabled:
+ type: boolean
+ realmRoles:
+ type: array
+ items:
+ type: string
+ UserListResponse:
+ type: object
+ required:
+ - items
+ - totalCount
+ properties:
+ items:
+ type: array
+ items:
+ $ref: '#/components/schemas/UserResponse'
+ totalCount:
+ type: integer
+ format: int32
+ CreateUserRequest:
+ type: object
+ required:
+ - username
+ - enabled
+ - email
+ - roles
+ properties:
+ username:
+ $ref: '#/components/schemas/ValidString'
+ email:
+ $ref: '#/components/schemas/ValidString'
+ firstName:
+ $ref: '#/components/schemas/ValidString'
+ lastName:
+ $ref: '#/components/schemas/ValidString'
+ enabled:
+ type: boolean
+ roles:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ UpdateUserRequest:
+ type: object
+ required:
+ - enabled
+ properties:
+ email:
+ $ref: '#/components/schemas/ValidString'
+ firstName:
+ $ref: '#/components/schemas/ValidString'
+ lastName:
+ $ref: '#/components/schemas/ValidString'
+ enabled:
+ type: boolean
+ UpdateUserPasswordRequest:
+ type: object
+ required:
+ - value
+ - temporary
+ properties:
+ value:
+ $ref: '#/components/schemas/ValidString'
+ temporary:
+ type: boolean
+ Role:
+ type: object
+ required:
+ - id
+ - name
+ properties:
+ id:
+ $ref: '#/components/schemas/ValidString'
+ name:
+ $ref: '#/components/schemas/ValidString'
+ RoleListResponse:
+ type: object
+ required:
+ - items
+ - totalCount
+ properties:
+ items:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ totalCount:
+ type: integer
+ format: int32
+ UpdateAssignedRolesRequest:
+ type: array
+ items:
+ $ref: '#/components/schemas/Role'
+ TileListResponse:
+ type: object
+ required:
+ - items
+ properties:
+ items:
+ type: array
+ items:
+ $ref: '#/components/schemas/TileResponse'
+ TileResponse:
+ type: object
+ required:
+ - id
+ - title
+ - imageUrl
+ - redirectUrl
+ - groups
+ - roles
+ properties:
+ id:
+ type: integer
+ format: int64
+ title:
+ type: string
+ description:
+ type: string
+ imageUrl:
+ type: string
+ imageAltText:
+ type: string
+ redirectUrl:
+ type: string
+ headers:
+ type: string
+ groups:
+ type: array
+ items:
+ type: string
+ roles:
+ type: array
+ items:
+ type: string
+ ActionsResponse:
+ title: ActionsResponse
+ type: object
+ properties:
+ actionCreatedAt:
+ type: string
+ format: date-time
+ action:
+ type: object
+ saveInterval:
+ type: integer
+ format: int32
+ required:
+ - actionCreatedAt
+ - action
+ CreateActionRequest:
+ title: CreateActionRequest
+ type: object
+ properties:
+ userId:
+ type: string
+ actionCreatedAt:
+ type: string
+ format: date-time
+ action:
+ type: object
+ required:
+ - userId
+ - actionCreatedAt
+ - action
+ ActionsListResponse:
+ title: ActionsListResponse
+ type: object
+ properties:
+ items:
+ type: array
+ items:
+ $ref: '#/components/schemas/ActionsResponse'
+ totalCount:
+ type: integer
+ format: int32
+ required:
+ - items
+ - totalCount
+security:
+ - bearerAuth: []
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..18a70b9
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1,10 @@
+rootProject.name = 'portal-bff'
+
+include 'app'
+
+include 'openapi:server'
+include 'openapi:client-portal-prefs'
+include 'openapi:client-portal-history'
+include 'openapi:client-portal-keycloak'
+include 'lib'
+
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
new file mode 100644
index 0000000..490fb40
--- /dev/null
+++ b/spotbugs-exclude.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FindBugsFilter>
+ <Match>
+ <Bug pattern="SPRING_CSRF_PROTECTION_DISABLED"/>
+ </Match>
+</FindBugsFilter>
diff --git a/version b/version
new file mode 100644
index 0000000..6e8bf73
--- /dev/null
+++ b/version
@@ -0,0 +1 @@
+0.1.0