diff options
author | Fiete Ostkamp <Fiete.Ostkamp@telekom.de> | 2023-07-11 08:44:51 +0000 |
---|---|---|
committer | Fiete Ostkamp <Fiete.Ostkamp@telekom.de> | 2023-07-11 08:44:51 +0000 |
commit | b146259516cc90cc9084bdf2f69c358b896cfdf7 (patch) | |
tree | cfbe215be6415cd2ffb0f03d23eaae26b3886bf1 | |
parent | 24a8c0fc70f6493bd7f07f12c723b7e2acf3f558 (diff) |
history repo code is missing
Issue-ID: PORTALNG-8
Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de>
Change-Id: I01f1789eb840661115bfd806a0622d02666100c0
53 files changed, 3745 insertions, 0 deletions
diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f7f5eb5 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +# Ignore everything +* +# but the build jar +!/app/build/libs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..00a51af --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2d8e73e --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +gradle.properties + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ +.attach_pid* diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a563a99 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM eclipse-temurin:17 as builder +COPY . ./history +WORKDIR /history + +RUN ./gradlew build + +FROM eclipse-temurin:17-jre-alpine +ARG JAR_FILE=/history/app/build/libs/app.jar +COPY --from=builder ${JAR_FILE} app.jar +EXPOSE 9080 +ENTRYPOINT [ "java","-jar","app.jar" ] diff --git a/README.md b/README.md new file mode 100644 index 0000000..769f5d0 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# Portal-history +This microservice manages the user actions for the `ui` frontend application. It is a Spring Boot application that is build upon MongoDB and Webflux. + +## Build +```sh +./gradlew build +``` + +## Run +```sh +./gradlew bootRun +``` + +## Test +```sh +./gradlew test # run all tests +./gradlew test --tests ActionsControllerIntegrationTest # run all tests in file +./gradlew test --tests ActionsControllerIntegrationTest.thatActionCanBeSaved # run individual test in file +./gradlew test --tests ActionsControllerIntegrationTest.thatActionCanBeSaved --debug # run individual test in file with debug enabled +``` + +## 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, a Postgres and a Mongo db in the background. + +**Prerequisites:** Running local docker daemon and a docker cli + +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..160f0c4 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,106 @@ +/* + * This file was generated by the Gradle 'init' task. + */ +plugins { + id 'org.onap.portal.history.java-application-conventions' + id 'io.spring.dependency-management' + id 'org.springframework.boot' + id 'jacoco' + id 'org.sonarqube' + id 'com.github.hierynomus.license' + id 'com.gorylenko.gradle-git-properties' +} +apply from: "${rootDir}/gradle/verify-licenses.gradle" + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +ext { + vavrVersion = '0.10.4' + problemVersion = '0.27.1' + problemSpringVersion = '0.27.0' + logbackVersion = '1.2.11' + logstashLogbackVersion = '7.2' + embedMongoVersion = '3.2.8' + embedMongoIntegrationVersion = '1.1.0-spring27x' + springCloudWiremockVersion = '3.1.0' +} + +dependencies { + implementation project(':openapi') + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive' + implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-webflux' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation "io.vavr:vavr:$vavrVersion" + implementation "org.zalando:problem:$problemVersion" + implementation "org.zalando:jackson-datatype-problem:$problemVersion" + implementation "org.zalando:problem-spring-webflux:$problemSpringVersion" + implementation "ch.qos.logback:logback-classic:$logbackVersion" + implementation "ch.qos.logback:logback-core:$logbackVersion" + implementation "net.logstash.logback:logstash-logback-encoder:$logstashLogbackVersion" + + compileOnly 'org.projectlombok:lombok' + + developmentOnly 'org.springframework.boot:spring-boot-devtools' + + annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' + annotationProcessor 'org.projectlombok:lombok' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'io.projectreactor:reactor-test' + testImplementation 'io.rest-assured:rest-assured' + testImplementation "org.springframework.cloud:spring-cloud-contract-wiremock:$springCloudWiremockVersion" + testImplementation "de.flapdoodle.embed:de.flapdoodle.embed.mongo:$embedMongoVersion" + testImplementation "de.flapdoodle.embed:de.flapdoodle.embed.mongo.spring:$embedMongoIntegrationVersion" + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' +} + +test { + useJUnitPlatform() + finalizedBy(jacocoTestReport) +} + +jacocoTestReport { + reports { + xml.enabled true + } +} + +application { + // Define the main class for the application. + mainClass = 'org.onap.portal.history.PortalHistoryApplication' +} + +sourceCompatibility = '17' +targetCompatibility = '17' + +downloadLicenses { + dependencyConfiguration = 'implementation' + includeProjectDependencies = false +} + +license { + ignoreFailures = true + header = project.file('LICENSE_HEADER') + includes(["**/*.java"]) + ext.year = Calendar.getInstance().get(Calendar.YEAR) +} +configurations.implementation.setCanBeResolved(true) + +springBoot { + buildInfo { + properties { + artifact = "org-onap-portal-history" + version = rootProject.file('version').text.trim() + group = rootProject.group + name = "History service that saves user actions" + } + } +}
\ No newline at end of file diff --git a/app/src/main/java/org/onap/portal/history/PortalHistoryApplication.java b/app/src/main/java/org/onap/portal/history/PortalHistoryApplication.java new file mode 100644 index 0000000..0e712f2 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/PortalHistoryApplication.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 + * + * + */ + +/* + * This Java source file was generated by the Gradle 'init' task. + */ +package org.onap.portal.history; + + +import org.onap.portal.history.configuration.PortalHistoryConfig; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +@EnableConfigurationProperties(PortalHistoryConfig.class) +@SpringBootApplication +public class PortalHistoryApplication { + public static void main(String[] args) { + SpringApplication.run(PortalHistoryApplication.class, args); + } +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/BeansConfig.java b/app/src/main/java/org/onap/portal/history/configuration/BeansConfig.java new file mode 100644 index 0000000..9a60681 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/BeansConfig.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.history.configuration; + + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.zalando.problem.jackson.ProblemModule; + +import java.time.Clock; + +@Configuration +public class BeansConfig { + @Bean + Clock clock() { + return Clock.systemUTC(); + } + + @Bean + public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { + return builder + .modules(new ProblemModule(), new JavaTimeModule()) + .build() + .setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/Errorhandler.java b/app/src/main/java/org/onap/portal/history/configuration/Errorhandler.java new file mode 100644 index 0000000..583420b --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/Errorhandler.java @@ -0,0 +1,94 @@ +/* + * + * 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.history.configuration; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.portal.history.exception.ProblemException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; +import org.springframework.core.io.buffer.DataBufferFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.zalando.problem.Problem; +import org.zalando.problem.Status; +import reactor.core.publisher.Mono; + +@Component +public class Errorhandler implements ErrorWebExceptionHandler { + + @Autowired + ObjectMapper objectMapper; + + /** + * Override the handle methode to implement custom error handling + * Set response status code to BAD REQUEST, set header content-type and fill the body with the Problem object along the API model + */ + @Override + public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) { + ServerHttpResponse httpResponse = exchange.getResponse(); + setResponseStatus(httpResponse, ex); + httpResponse.getHeaders().add("Content-Type", "application/problem+json"); + return httpResponse.writeWith(Mono.fromSupplier(() -> { + DataBufferFactory bufferFactory = httpResponse.bufferFactory(); + try { + return + (httpResponse.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) + ? httpResponse.bufferFactory().wrap(objectMapper.writeValueAsBytes(setProblemException(httpResponse, ex.getMessage()))) + : httpResponse.bufferFactory().wrap(objectMapper.writeValueAsBytes(ex)); + } catch (JsonProcessingException e) { + return bufferFactory.wrap(new byte[0]); + } + })); + } + + /** + * Set the response status + * @param httpResponse response which status code should be set + * @param ex throwable exception to identify the Problem class + */ + private void setResponseStatus(ServerHttpResponse httpResponse, Throwable ex) { + if (ex instanceof Problem) { + httpResponse.setStatusCode(HttpStatus.BAD_REQUEST); + } else { + httpResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * Build a problem exception and set the response status code to BAD REQUEST for every response + * @param httpResponse response which status code should be set + * @param message for the detail of the problem exception + * @return problem exception instance + */ + private ProblemException setProblemException(ServerHttpResponse httpResponse, String message){ + httpResponse.setStatusCode(HttpStatus.BAD_REQUEST); + return ProblemException.builder() + .status(Status.INTERNAL_SERVER_ERROR) + .title(Status.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .detail(message) + .build(); + + } +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/LogInterceptor.java b/app/src/main/java/org/onap/portal/history/configuration/LogInterceptor.java new file mode 100644 index 0000000..113aad8 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/LogInterceptor.java @@ -0,0 +1,62 @@ +/* + * + * 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.history.configuration; + +import org.onap.portal.history.util.Logger; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.reactive.ServerWebExchangeContextFilter; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; +import reactor.core.publisher.Mono; + +import java.util.List; + +@Component +public class LogInterceptor implements WebFilter { + public static final String EXCHANGE_CONTEXT_ATTRIBUTE = + ServerWebExchangeContextFilter.class.getName() + ".EXCHANGE_CONTEXT"; + + public static final String X_REQUEST_ID = "X-Request-Id"; + + /** + * Override a web filter to write log entries for every request and response and add header in response with 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); + exchange.getResponse().beforeCommit(() -> { + Logger.responseLog(xRequestId,exchange.getResponse().getStatusCode()); + return Mono.empty(); + }); + } + + return chain + .filter(exchange) + .contextWrite(cxt -> cxt.put(EXCHANGE_CONTEXT_ATTRIBUTE, exchange)); + } +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/PortalHistoryConfig.java b/app/src/main/java/org/onap/portal/history/configuration/PortalHistoryConfig.java new file mode 100644 index 0000000..85304b9 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/PortalHistoryConfig.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.history.configuration; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.ConstructorBinding; + +import javax.validation.constraints.NotBlank; + +@Data +@ConstructorBinding +@ConfigurationProperties("portal-history") +public class PortalHistoryConfig { + + @NotBlank + private final Integer saveInterval; +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/SchedulerConfig.java b/app/src/main/java/org/onap/portal/history/configuration/SchedulerConfig.java new file mode 100644 index 0000000..529cbc3 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/SchedulerConfig.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.history.configuration; + +import org.onap.portal.history.services.ActionsService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@EnableScheduling +public class SchedulerConfig { + + private final ActionsService actionsService; + private final PortalHistoryConfig portalHistoryConfig; + + @Autowired + public SchedulerConfig(ActionsService actionsService, PortalHistoryConfig portalHistoryConfig){ + this.actionsService = actionsService; + this.portalHistoryConfig = portalHistoryConfig; + } + + /** + * This method will be trigger by Spring Boot scheduler. + * The cron execution time is configured in the application properties as well as the save interval. + */ + @Scheduled(cron="${portal-history.delete-interval}") + public void runDeleteActions(){ + actionsService.deleteActions(portalHistoryConfig.getSaveInterval()); + log.info("Delete actions in scheduled job"); + } +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/SecurityConfig.java b/app/src/main/java/org/onap/portal/history/configuration/SecurityConfig.java new file mode 100644 index 0000000..e825295 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/SecurityConfig.java @@ -0,0 +1,53 @@ +/* + * + * 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.history.configuration; + +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.web.server.SecurityWebFilterChain; + +/** + * Configures the access control of the API endpoints. + */ +// https://hantsy.github.io/spring-reactive-sample/security/config.html +@EnableWebFluxSecurity +@Configuration +public class SecurityConfig { + + @Bean + public SecurityWebFilterChain springSecurityWebFilterChain(ServerHttpSecurity http) { + return http.httpBasic().disable() + .formLogin().disable() + .csrf().disable() + .cors() + .and() + .authorizeExchange() + .pathMatchers(HttpMethod.GET, "/actuator/**").permitAll() + .anyExchange().authenticated() + .and() + .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt) + .build(); + } +} diff --git a/app/src/main/java/org/onap/portal/history/configuration/package-info.java b/app/src/main/java/org/onap/portal/history/configuration/package-info.java new file mode 100644 index 0000000..ccaa303 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/configuration/package-info.java @@ -0,0 +1,25 @@ +/* + * + * 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 + * + * + */ + +@ParametersAreNonnullByDefault +package org.onap.portal.history.configuration; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/app/src/main/java/org/onap/portal/history/controller/ActionsController.java b/app/src/main/java/org/onap/portal/history/controller/ActionsController.java new file mode 100644 index 0000000..9fd9f79 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/controller/ActionsController.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.history.controller; + +import java.util.Optional; + +import javax.validation.Valid; +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; + +import org.onap.portal.history.configuration.PortalHistoryConfig; +import org.onap.portal.history.openapi.api.ActionsApi; +import org.onap.portal.history.openapi.model.ActionResponse; +import org.onap.portal.history.openapi.model.ActionsListResponse; +import org.onap.portal.history.openapi.model.CreateActionRequest; +import org.onap.portal.history.services.ActionsService; +import org.onap.portal.history.util.IdTokenExchange; +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 implements ActionsApi { + + private final ActionsService actionsService; + private final PortalHistoryConfig portalHistoryConfig; + + public ActionsController(ActionsService actionsService, PortalHistoryConfig portalHistoryConfig){ + this.actionsService = actionsService; + this.portalHistoryConfig = portalHistoryConfig; + } + + @Override + public Mono<ResponseEntity<ActionResponse>> createAction(String userId, String xRequestId, Mono<CreateActionRequest> createActionRequest, ServerWebExchange exchange) { + + return IdTokenExchange + .validateUserId(userId, exchange, xRequestId) + .then(createActionRequest.flatMap(action -> actionsService.createActions(userId, action, portalHistoryConfig.getSaveInterval(), xRequestId))) + .map(ResponseEntity::ok); + } + + @Override + public Mono<ResponseEntity<Object>> deleteActions(String userId, String xRequestId, Integer deleteAfterHours, ServerWebExchange exchange) { + + return IdTokenExchange + .validateUserId(userId, exchange, xRequestId) + .then(actionsService.deleteUserActions(userId, deleteAfterHours, xRequestId)) + .map(ResponseEntity::ok); + } + + @Override + public Mono<ResponseEntity<ActionsListResponse>> getActions(String userId, String xRequestId, Optional<Integer> page, Optional<Integer> pageSize, Optional<Integer> showLastHours, ServerWebExchange exchange) { + + return IdTokenExchange + .validateUserId(userId, exchange, xRequestId) + .then(actionsService.getActions(userId, page.orElse(1), pageSize.orElse(10), showLastHours.orElse(portalHistoryConfig.getSaveInterval()), portalHistoryConfig.getSaveInterval(), xRequestId)) + .map(ResponseEntity::ok); + } + + @Override + public Mono<ResponseEntity<ActionsListResponse>> listActions(String xRequestId, @Valid Optional<@Min(1) Integer> page, @Valid Optional<@Min(1) @Max(5000) Integer> pageSize, @Valid Optional<Integer> showLastHours, ServerWebExchange exchange) { + + return actionsService + .listActions(page.orElse(1), pageSize.orElse(10), showLastHours.orElse(portalHistoryConfig.getSaveInterval()), portalHistoryConfig.getSaveInterval(), xRequestId) + .map(ResponseEntity::ok); + } +} diff --git a/app/src/main/java/org/onap/portal/history/entities/ActionsDao.java b/app/src/main/java/org/onap/portal/history/entities/ActionsDao.java new file mode 100644 index 0000000..5457e87 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/entities/ActionsDao.java @@ -0,0 +1,44 @@ +/* + * + * 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.history.entities; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.data.mongodb.core.mapping.Document; +import java.util.Date; + +/** + * Data access object for the actions in the MongoDB repository. + * No database id is set in this class because MongoDB use internal _id as primary key / uniq object identifier + */ +@Document(collection = "actions") +@Getter +@Setter +public class ActionsDao { + + private String userId; + + private Date actionCreatedAt; + + private Object action; + +} diff --git a/app/src/main/java/org/onap/portal/history/exception/ProblemException.java b/app/src/main/java/org/onap/portal/history/exception/ProblemException.java new file mode 100644 index 0000000..f51d246 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/exception/ProblemException.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.history.exception; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.zalando.problem.AbstractThrowableProblem; +import org.zalando.problem.Problem; +import org.zalando.problem.Status; +import org.zalando.problem.StatusType; + +import java.net.URI; + +/** + * Default problem exception. This class has the same structure as the problem response model from the api. + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +@EqualsAndHashCode(callSuper = true) +public class ProblemException extends AbstractThrowableProblem { + @Builder.Default private final URI type = Problem.DEFAULT_TYPE; + + @Builder.Default private final String title = "Bad history error"; + + @Builder.Default private final StatusType status = Status.BAD_REQUEST; + + @Builder.Default private final String detail = "Please add more details here"; + + @Builder.Default private final URI instance = null; + +} diff --git a/app/src/main/java/org/onap/portal/history/repository/ActionsRepository.java b/app/src/main/java/org/onap/portal/history/repository/ActionsRepository.java new file mode 100644 index 0000000..79fc378 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/repository/ActionsRepository.java @@ -0,0 +1,42 @@ +/* + * + * 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.history.repository; + +import java.util.Date; + +import org.onap.portal.history.entities.ActionsDao; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface ActionsRepository extends ReactiveMongoRepository<ActionsDao, String> { + + Flux<ActionsDao> findAllByActionCreatedAtAfter(Pageable pageable, Date actionCreatedAt); + + Flux<ActionsDao> findAllByUserIdAndActionCreatedAtAfter(Pageable pageable, String userId, Date actionCreatedAt); + + Mono<Long> deleteAllByUserIdAndActionCreatedAtIsBefore(String userId, Date actionCreatedAt); + + Mono<Long> deleteAllByActionCreatedAtIsBefore(Date actionCreatedAt); +} diff --git a/app/src/main/java/org/onap/portal/history/services/ActionsService.java b/app/src/main/java/org/onap/portal/history/services/ActionsService.java new file mode 100644 index 0000000..a14fef2 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/services/ActionsService.java @@ -0,0 +1,218 @@ +/* + * + * 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.history.services; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Date; + +import org.onap.portal.history.entities.ActionsDao; +import org.onap.portal.history.exception.ProblemException; +import org.onap.portal.history.openapi.model.ActionResponse; +import org.onap.portal.history.openapi.model.ActionsListResponse; +import org.onap.portal.history.openapi.model.CreateActionRequest; +import org.onap.portal.history.repository.ActionsRepository; +import org.onap.portal.history.util.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.zalando.problem.Problem; +import org.zalando.problem.Status; + +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Mono; + + +@Slf4j +@Service +public class ActionsService { + + @Autowired + private ActionsRepository repository; + + /** + * Retrieve actions for a given userId from the database and provide a list with actions + * @param userId only actions for this <code>userId</code> should be retrieved + * @param page which page should be retrieved from the list of actions. From a user perspective the first page has the page number 1. + * In the response list the first page starts with 0. Therefore, a subtraction is needed. + * @param pageSize length of the response list + * @param showLastHours for which hours from the current time the actions should be retrieved. + * @param saveInterval value will be part of the response action object. This value is set in the application properties. + * In the future this value can be provided from the client. + * @param xRequestId from the request header. Will be used in an error log + * @return If successful object with an item list of action objects and an item with the list count, otherwise Mono error + */ + public Mono<ActionsListResponse> getActions(String userId, Integer page, Integer pageSize, Integer showLastHours, Integer saveInterval, String xRequestId){ + Pageable paging = PageRequest.of(page - 1 , pageSize, Sort.by(Sort.Direction.DESC, "actionCreatedAt")); + var dateAfter = Date.from(ZonedDateTime.now().minusHours(showLastHours).toInstant()); + return repository + .findAllByUserIdAndActionCreatedAtAfter(paging,userId, dateAfter) + .map(actionDao -> toActionResponse(actionDao, saveInterval)) + .collectList() + .map(this::toActionsListResponse) + .switchIfEmpty(Mono.just(new ActionsListResponse().totalCount(0))) + .onErrorResume(ex -> { + Logger.errorLog(xRequestId,"Get actions cannot be executed for user with id ", userId); + return getError("Get actions can not be executed for user with id " + userId); + }); + } + + /** + * Create an action data record in the database + * @param userId the id of the user for which the action should be stored + * @param createActionRequest the action object which should be stored + * @param saveInterval value will be part of the response action object. This value is set in the application properties. + * In the future this value can be provided from the client. + * @param xRequestId from the request header. Will be used in an error log + * @return If successful object with the stored action, otherwise Mono error + */ + public Mono<ActionResponse> createActions(String userId, CreateActionRequest createActionRequest, Integer saveInterval, String xRequestId) { + return repository + .save(toActionsDao(userId, createActionRequest)) + .map(action -> toActionResponse(action, saveInterval)) + .onErrorResume(ex -> { + Logger.errorLog(xRequestId,"Action for user can not be executed for user with id ", userId ); + return Mono.error(ProblemException.builder() + .type(Problem.DEFAULT_TYPE) + .status(Status.BAD_REQUEST) + .title(HttpStatus.BAD_REQUEST.toString()) + .detail("Action for user can not be executed for user with id " + userId) + .build()); + }); + } + + /** + * List all actions without a userId filter. + * @param page which page should be retrieved from the list of actions. From a user perspective the first page has the page number 1. + * In the response list the first page starts with 0. Therefore, a subtraction is needed. + * @param pageSize length of the response list + * @param showLastHours for which hours from the current time the actions should be retrieved. + * @param saveInterval value will be part of the response action object. This value is set in the application properties. + * * In the future this value can be provided from the client. + * @param xRequestId from the request header. Will be used in an error log + * @return If successful list with action response object, otherwise Mono error + */ + public Mono<ActionsListResponse> listActions(Integer page, Integer pageSize, Integer showLastHours, Integer saveInterval, String xRequestId){ + + var paging = PageRequest.of(page - 1 , pageSize, Sort.by(Sort.Direction.DESC, "actionCreatedAt")); + var dateAfter = Date.from(ZonedDateTime.now().minusHours(showLastHours).toInstant()); + + return repository + .findAllByActionCreatedAtAfter(paging,dateAfter) + .map(actionDto -> toActionResponse(actionDto, saveInterval)) + .collectList() + .map(this::toActionsListResponse) + .onErrorResume(ProblemException.class, + ex -> { + Logger.errorLog(xRequestId,"List actions cannot be created", null ); + return getError("List actions cannot be created"); + }); + } + + /** + * Delete actions for a given userId and action is create after hours + * @param userId the id of the user for which the action should be deleted + * @param deleteAfterHours hours after the actions should be deleted + * @param xRequestId from the request header. Will be used in an error log + * @return If successful empty Mono object, otherwise Mono error + */ + public Mono<Object> deleteUserActions(String userId, Integer deleteAfterHours, String xRequestId ){ + var dateAfter = Date.from(ZonedDateTime.now().minusHours(deleteAfterHours).toInstant()); + return repository + .deleteAllByUserIdAndActionCreatedAtIsBefore(userId, dateAfter) + .map(resp -> new Object()) + .onErrorResume(ProblemException.class,ex -> { + Logger.errorLog(xRequestId,"Deletion of actions cannot be executed for user", userId ); + return Mono.error(ex); + }); + } + + /** + * Delete actions after hours. This service will be used in the cron job. The job will be implemented with a separate user story. + * @param deleteAfterHours hours after the actions should be deleted + * @return If successful empty Mono object, otherwise Mono error + */ + public Mono<Object> deleteActions(Integer deleteAfterHours ){ + var dateAfter = Date.from(LocalDateTime.now().minusHours(deleteAfterHours).atZone(ZoneId.of("CET")).toInstant()); + return repository + .deleteAllByActionCreatedAtIsBefore(dateAfter) + .map(resp -> new Object()) + .onErrorResume(ProblemException.class,ex -> { + Logger.errorLog(null,"Delete all actions in cron job cannot be executed ", null); + return getError("Delete all actions after hours cannot be executed"); + }); + } + + /** + * + * @param resp List of ActionResponses + * @param saveInterval value will be part of the response action object. This value is set in the application properties. + * @return ActionsListResponse + */ + private ActionsListResponse toActionsListResponse(java.util.List<ActionResponse> actionResponses) { + var actionsListResponse = new ActionsListResponse(); + actionsListResponse.setActionsList(actionResponses); + actionsListResponse.setTotalCount(actionResponses.size()); + return actionsListResponse; + } + + /** + * + * @param actionsDao ActionsDao, return from the MongoDB repository query + * @param saveInterval value will be part of the response action object. This value is set in the application properties. + * @return action response object + */ + public ActionResponse toActionResponse(ActionsDao actionsDao, Integer saveInterval){ + return new ActionResponse() + .actionCreatedAt(actionsDao.getActionCreatedAt().toInstant().atOffset(ZoneOffset.ofHours(0))) + .saveInterval(saveInterval) + .action(actionsDao.getAction()); + } + + private ActionsDao toActionsDao(String userId, CreateActionRequest createActionRequest) { + var actionsDao = new ActionsDao(); + actionsDao.setUserId(userId); + actionsDao.setActionCreatedAt(new Date(createActionRequest.getActionCreatedAt().toEpochSecond()*1000)); + actionsDao.setAction(createActionRequest.getAction()); + return actionsDao; + } + + /** + * Build a problem exception with given message + * @param message will be detail part of the problem object + * @return Mono error with problem exception + */ + private Mono<ActionsListResponse> getError(String message) { + return Mono.error(ProblemException.builder() + .type(Problem.DEFAULT_TYPE) + .status(Status.BAD_REQUEST) + .title(HttpStatus.BAD_REQUEST.toString()) + .detail(message) + .build()); + } + +} diff --git a/app/src/main/java/org/onap/portal/history/util/IdTokenExchange.java b/app/src/main/java/org/onap/portal/history/util/IdTokenExchange.java new file mode 100644 index 0000000..82cc67a --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/util/IdTokenExchange.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.history.util; + +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.JWTParser; + +import java.text.ParseException; + +import org.onap.portal.history.exception.ProblemException; +import org.springframework.web.server.ServerWebExchange; +import org.zalando.problem.Problem; +import org.zalando.problem.Status; +import reactor.core.publisher.Mono; + +/** + * Represents a function that handles the <a href="https://jwt.io/introduction">JWT</a> identity token. + * Use this to check if the incoming requests are authorized to call the given endpoint + */ + +public final class IdTokenExchange { + + public static final String X_AUTH_IDENTITY_HEADER = "X-Auth-Identity"; + public static final String JWT_CLAIM_USERID = "sub"; + + private IdTokenExchange(){ + + } + + /** + * Extract the identity header from the given {@link ServerWebExchange}. + * @param exchange the ServerWebExchange that contains information about the incoming request + * @param xRequestId the id of the request to use in error log + * @return the identity header in the form of <code>Bearer {@literal <Token>}<c/ode> + */ + private static Mono<String> extractIdentityHeader(ServerWebExchange exchange, String xRequestId) { + return Mono.just(exchange.getRequest().getHeaders().getOrEmpty(X_AUTH_IDENTITY_HEADER)) + .map(headers -> headers.get(0)) + .onErrorResume(Exception.class, ex -> Mono.error(ProblemException.builder() + .type(Problem.DEFAULT_TYPE) + .status(Status.FORBIDDEN) + .title("Forbidden access") + .detail(X_AUTH_IDENTITY_HEADER + " is not set") + .build())); + } + + /** + * Extract the identity token from the given {@link ServerWebExchange}. + * @see <a href="https://openid.net/specs/openid-connect-core-1_0.html#IDToken">OpenId Connect ID Token</a> + * @param exchange the ServerWebExchange that contains information about the incoming request + * @param xRequestId the id of the request to use in error log + * @return the identity token that contains user roles + */ + private static Mono<String> extractIdToken(ServerWebExchange exchange, String xRequestId) { + return extractIdentityHeader(exchange, xRequestId) + .map(identityHeader -> identityHeader.replace("Bearer ", "")); + } + + /** + * Extract the <code>userId</code> from the given {@link ServerWebExchange} + * @param exchange the ServerWebExchange that contains information about the incoming request + * @param xRequestId the id of the request to use in error log + * @return the id of the user + */ + public static Mono<String> extractUserId(ServerWebExchange exchange,String xRequestId) { + return extractIdToken(exchange, xRequestId) + .flatMap(idToken -> extractUserClaim(idToken)); + } + + private static Mono<String> extractUserClaim(String idToken) { + JWTClaimsSet jwtClaimSet; + try { + jwtClaimSet = JWTParser.parse(idToken).getJWTClaimsSet(); + } catch (ParseException e) { + return Mono.error(e); + } + return Mono.just(String.class.cast(jwtClaimSet.getClaim(JWT_CLAIM_USERID))); + } + + + /** + * Validate if given <code>userId</code> is same as extracted from the given {@link ServerWebExchange} + * @param userId from the path parameter of the REST call + * @param exchange the ServerWebExchange that contains information about the incoming request + * @param xRequestId the id of the request to use in error log + * @return <code>empty Mono</code> userId is the same as extracted from {@link ServerWebExchange} + * <code>Forbidden</code> userId is <bold>not</bold> the same as extracted from {@link ServerWebExchange} + */ + public static Mono<Void> validateUserId(String userId, ServerWebExchange exchange, String xRequestId){ + + return extractUserId(exchange, xRequestId) + .map(userSub -> userSub.equals(userId)) + .flatMap( match -> { + if (Boolean.TRUE.equals(match)) { + return Mono.empty(); + } else{ + Logger.errorLog(xRequestId,"Requested "+ userId + " did not match the JWT in the X-Auth-Identity header" , userId ); + return Mono.error(ProblemException.builder() + .type(Problem.DEFAULT_TYPE) + .status(Status.FORBIDDEN) + .title("Forbidden access") + .detail("UserId did not match with JWT in " + X_AUTH_IDENTITY_HEADER) + .build()); + } + }); + } +} diff --git a/app/src/main/java/org/onap/portal/history/util/Logger.java b/app/src/main/java/org/onap/portal/history/util/Logger.java new file mode 100644 index 0000000..4cb3420 --- /dev/null +++ b/app/src/main/java/org/onap/portal/history/util/Logger.java @@ -0,0 +1,64 @@ +/* + * + * 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.history.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; + +import java.net.URI; + +@Slf4j +public class Logger { + + private Logger(){} + + /** + * Write log to stdout for incoming request + * @param xRequestId from the request header + * @param methode http methode which is invoke + * @param path which is called be the request + */ + public static void requestLog(String xRequestId, HttpMethod methode, URI path) { + log.info("Portal-history - request - X-Request-Id {} {} {}", xRequestId, methode, path); + } + + /** + * Write log to stdout for the outgoing response + * @param xRequestId from the request header + * @param code http status of the response + */ + public static void responseLog(String xRequestId, HttpStatus code) { + log.info("Portal-history - response - X-Request-Id {} {}", xRequestId, code); + } + + /** + * Write error log to stdout + * @param xRequestId from the request header + * @param msg message which should be written + * @param id of the related object of the message + */ + public static void errorLog(String xRequestId, String msg, String id) { + log.info( + "Portal-history - error - X-Request-Id {} {} {} not found", xRequestId, msg, id); + } +} diff --git a/app/src/main/resources/application-local.yml b/app/src/main/resources/application-local.yml new file mode 100644 index 0000000..a908c1b --- /dev/null +++ b/app/src/main/resources/application-local.yml @@ -0,0 +1,42 @@ +server: + port: 9002 + address: 0.0.0.0 + +spring: + jackson: + serialization: + # needed for serializing objects of type object + FAIL_ON_EMPTY_BEANS: false + security: + oauth2: + resourceserver: + jwt: + jwk-set-uri: http://localhost:8080/auth/realms/ONAP/protocol/openid-connect/certs #Keycloak Endpoint + data: + mongodb: + database: portal_history + host: localhost + port: 27017 + username: root + password: password + +portal-history: + save-interval: 72 + delete-interval: 0 * * * * * + +management: + endpoints: + web: + exposure: + include: "*" + info: + build: + enabled: true + env: + enabled: true + git: + enabled: true + java: + enabled: true + + diff --git a/app/src/main/resources/application.yml b/app/src/main/resources/application.yml new file mode 100644 index 0000000..3bfd624 --- /dev/null +++ b/app/src/main/resources/application.yml @@ -0,0 +1,40 @@ +server: + port: 9002 + address: 0.0.0.0 + +spring: + jackson: + serialization: + # needed for serializing objects of type object + FAIL_ON_EMPTY_BEANS: false + security: + oauth2: + resourceserver: + jwt: + jwk-set-uri: ${KEYCLOAK_URL}/auth/realms/${KEYCLOAK_REALM}/protocol/openid-connect/certs #Keycloak Endpoint + data: + mongodb: + database: ${PORTALHISTORY_DATABASE} + host: ${PORTALHISTORY_HOST} + port: ${PORTALHISTORY_PORT} + username: ${PORTALHISTORY_USERNAME} + password: ${PORTALHISTORY_PASSWORD} + +portal-history: + save-interval: 72 + delete-interval: 0 0 * * * * + +management: + endpoints: + web: + exposure: + include: "*" + info: + build: + enabled: true + env: + enabled: true + git: + enabled: true + java: + enabled: true diff --git a/app/src/main/resources/logback-spring.xml b/app/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..f4ef0bf --- /dev/null +++ b/app/src/main/resources/logback-spring.xml @@ -0,0 +1,15 @@ +<?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 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/history/BaseIntegrationTest.java b/app/src/test/java/org/onap/portal/history/BaseIntegrationTest.java new file mode 100644 index 0000000..e00b770 --- /dev/null +++ b/app/src/test/java/org/onap/portal/history/BaseIntegrationTest.java @@ -0,0 +1,180 @@ +/* + * + * 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.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.nimbusds.jose.jwk.JWKSet; +import org.onap.portal.history.util.IdTokenExchange; +import io.restassured.RestAssured; +import io.restassured.filter.log.RequestLoggingFilter; +import io.restassured.filter.log.ResponseLoggingFilter; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +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.web.server.LocalServerPort; +import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.http.MediaType; + +import java.util.List; +import java.util.UUID; + +/** 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-history.realm}") + protected String realm; + + @Value("${portal-history.delete-interval}") + protected String deleteInterval; + + @Autowired protected ObjectMapper objectMapper; + @Autowired private TokenGenerator tokenGenerator; + + @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).sub("test-user").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()))); + } + + /** + * Builds an OAuth2 configuration including the roles, port and realm. This config can be used to + * generate OAuth2 access tokens. + * + * @param sub the userId + * @param roles the roles used for RBAC + * @return the OAuth2 configuration + */ + protected TokenGenerator.TokenGeneratorConfig getTokenGeneratorConfig(String sub, List<String> roles) { + return TokenGenerator.TokenGeneratorConfig.builder() + .port(port) + .sub(sub) + .realm(realm) + .roles(roles) + .build(); + } + + /** Get a RequestSpecification that does not have an Identity header. */ + protected RequestSpecification unauthenticatedRequestSpecification() { + return RestAssured.given().port(port); + } + + /** + * 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. + * @return the definition of the incoming request (northbound) + */ + protected RequestSpecification requestSpecification() { + final String idToken = tokenGenerator.generateToken(getTokenGeneratorConfig("test-user", List.of("foo"))); + + return unauthenticatedRequestSpecification() + .auth() + .preemptive() + .oauth2(idToken) + .header(IdTokenExchange.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 <code>onap_admin</code> role to the request. + * @param userId the userId that should be contained in the incoming request + * @return the definition of the incoming request (northbound) + */ + protected RequestSpecification requestSpecification(String userId) { + final String idToken = tokenGenerator.generateToken(getTokenGeneratorConfig(userId, List.of("foo"))); + + return unauthenticatedRequestSpecification() + .auth() + .preemptive() + .oauth2(idToken) + .header(IdTokenExchange.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 <code>onap_admin</code> role to the request. + * @param userId the userId that should be contained in the incoming request + * @return the definition of the incoming request (northbound) + */ + protected RequestSpecification wrongHeaderRequestSpecification(String userId) { + final String idToken = tokenGenerator.generateToken(getTokenGeneratorConfig(userId, List.of("foo"))); + + return unauthenticatedRequestSpecification() + .auth() + .preemptive() + .oauth2(idToken) + .header("X-WRONG-HEADER", "Bearer " + idToken); + } +} diff --git a/app/src/test/java/org/onap/portal/history/TokenGenerator.java b/app/src/test/java/org/onap/portal/history/TokenGenerator.java new file mode 100644 index 0000000..986507c --- /dev/null +++ b/app/src/test/java/org/onap/portal/history/TokenGenerator.java @@ -0,0 +1,129 @@ +/* + * + * 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.history; + +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 lombok.Builder; +import lombok.Getter; +import lombok.NonNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Component +public class TokenGenerator { + + private static final String ROLES_CLAIM = "roles"; + private static final String USERID_CLAIM = "sub"; + + 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()) + .claim(USERID_CLAIM, config.getSub()) + .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 sub; + + @NonNull private final String realm; + + @NonNull @Builder.Default private final Duration expireIn = Duration.ofMinutes(5); + + @Builder.Default private final List<String> roles = Collections.emptyList(); + + public String issuer() { + return String.format("http://localhost:%d/auth/realms/%s", port, realm); + } + } +} diff --git a/app/src/test/java/org/onap/portal/history/actions/ActionDto.java b/app/src/test/java/org/onap/portal/history/actions/ActionDto.java new file mode 100644 index 0000000..2deec8e --- /dev/null +++ b/app/src/test/java/org/onap/portal/history/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.history.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/history/actions/ActionFixtures.java b/app/src/test/java/org/onap/portal/history/actions/ActionFixtures.java new file mode 100644 index 0000000..efab59a --- /dev/null +++ b/app/src/test/java/org/onap/portal/history/actions/ActionFixtures.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.history.actions; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.onap.portal.history.entities.ActionsDao; +import org.onap.portal.history.openapi.model.CreateActionRequest; + +public class ActionFixtures { + + public static List<CreateActionRequest> createActionRequestList( + Integer numberOfActions, String userId, OffsetDateTime createdAt){ + List<CreateActionRequest> createActionRequestList = new ArrayList<>(); + for (Integer i = 1; i <= numberOfActions; i++) { + createActionRequestList.add( + generateActionRequest( + "Instantiation", "create", "action" + i, i.toString(), "SO", i, i, i, userId, createdAt)); + } + return createActionRequestList; + } + + public static List<CreateActionRequest> createActionRequestListHourOffsetOnly( + Integer numberOfActions, String userId, OffsetDateTime createdAt){ + List<CreateActionRequest> createActionRequestList = new ArrayList<>(); + for (Integer i = 1; i <= numberOfActions; i++) { + createActionRequestList.add( + generateActionRequest( + "Instantiation", "create", "action" + i, i.toString(), "SO", i, 0, 0, userId, createdAt)); + } + return createActionRequestList; + } + + public static CreateActionRequest generateActionRequest( + String type, + String action, + String message, + String id, + String downStreamSystem, + Integer deltaHours, + Integer deltaMinutes, + Integer deltaSeconds, + 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 CreateActionRequest() + .userId(userId) + .action(actionDto) + .actionCreatedAt(createdAt.minusHours(deltaHours).minusMinutes(deltaMinutes).minusSeconds(deltaSeconds)); + } + + public static List<ActionsDao> actionsDaoList( + Integer numberOfActions, String userId, OffsetDateTime createdAt){ + List<ActionsDao> actionsDaoList = new ArrayList<>(); + for (Integer i = 1; i <= numberOfActions; i++) { + actionsDaoList.add( + generateActionsDao( + "Instantiation", "create", "action" + i, i.toString(), "SO", i, i, i, userId, createdAt)); + } + return actionsDaoList; + } + + public static ActionsDao generateActionsDao( + String type, + String action, + String message, + String id, + String downStreamSystem, + Integer deltaHours, + Integer deltaMinutes, + Integer deltaSeconds, + String userId, + OffsetDateTime createdAt) { + ActionDto actionDto = new ActionDto(); + actionDto.setType(type); + actionDto.setAction(action); + actionDto.setMessage(message); + actionDto.setDownStreamSystem(downStreamSystem); + actionDto.setDownStreamId(id); + + ActionsDao actionsDao = new ActionsDao(); + actionsDao.setUserId(userId); + actionsDao.setAction(actionDto); + actionsDao.setActionCreatedAt(new Date(createdAt.minusHours(deltaHours).minusMinutes(deltaMinutes).minusSeconds(deltaSeconds).toEpochSecond()*1000)); + return actionsDao; + } + + public static List<ActionsDao> actionsDaoListHourOffsetOnly( + Integer numberOfActions, String userId, OffsetDateTime createdAt){ + List<ActionsDao> actionsDaoList = new ArrayList<>(); + for (Integer i = 1; i <= numberOfActions; i++) { + actionsDaoList.add( + generateActionsDao( + "Instantiation", "create", "action" + i, i.toString(), "SO", i, 0, 0, userId, createdAt)); + } + return actionsDaoList; + } +} diff --git a/app/src/test/java/org/onap/portal/history/actions/ActionsControllerIntegrationTest.java b/app/src/test/java/org/onap/portal/history/actions/ActionsControllerIntegrationTest.java new file mode 100644 index 0000000..c5fa17b --- /dev/null +++ b/app/src/test/java/org/onap/portal/history/actions/ActionsControllerIntegrationTest.java @@ -0,0 +1,571 @@ +/* + * + * 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.history.actions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.portal.history.BaseIntegrationTest; +import org.onap.portal.history.entities.ActionsDao; +import org.onap.portal.history.openapi.model.ActionResponse; +import org.onap.portal.history.openapi.model.ActionsListResponse; +import org.onap.portal.history.openapi.model.CreateActionRequest; +import org.onap.portal.history.openapi.model.Problem; +import org.onap.portal.history.repository.ActionsRepository; +import org.onap.portal.history.services.ActionsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import io.restassured.http.Header; + +class ActionsControllerIntegrationTest extends BaseIntegrationTest { + + protected static final String X_REQUEST_ID = "addf6005-3075-4c80-b7bc-2c70b7d42b57"; + protected static final String X_REQUEST_ID2 = "addf6005-3075-4c80-b7bc-2c70b7d42b22"; + + @Autowired + ActionsService actionsService; + + @Autowired + private ActionsRepository repository; + + // @Value("${portal-history.save-interval}") + protected Integer saveInterval = 72; + + @BeforeEach + void deleteMongoDataBase(){ + repository.deleteAll().block(); + } + + @Test + void thatUserCanHaveNoHistoryYet() throws JsonProcessingException { + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test-user") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertNotNull(response); + assertThat(response.getTotalCount()).isEqualTo(0); + } + + @Test + void thatActionCanBeSaved() throws Exception{ + ActionDto actionDto = new ActionDto(); + actionDto.setType("instantiation"); + actionDto.setAction("create"); + actionDto.setDownStreamId("1234"); + actionDto.setDownStreamSystem("SO"); + actionDto.setMessage("no details"); + + CreateActionRequest actionRequest = new CreateActionRequest() + .actionCreatedAt(OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)) + .userId("test-user") + .action(actionDto); + + ActionResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .body(actionRequest) + .when() + .post( "/v1/actions/test-user") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionResponse.class); + + assertThat(response.getActionCreatedAt()).isEqualTo(actionRequest.getActionCreatedAt().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_DATE_TIME)); + assertThat(response.getSaveInterval()).isEqualTo(saveInterval); + assertThat(objectMapper.writeValueAsString(response.getAction())).isEqualTo(objectMapper.writeValueAsString(actionRequest.getAction())); + } + + @Test + void thatActionsCanBeListedWithoutParameter() throws JsonProcessingException { + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoList(500, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + repository + .saveAll(actionsDaoList) + .blockLast(); + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(10); + assertThat(response.getActionsList().get(0).getSaveInterval()).isEqualTo(saveInterval); + assertThat(response.getActionsList().get(9).getSaveInterval()).isEqualTo(saveInterval); + assertThat(objectMapper.writeValueAsString(response.getActionsList().get(0).getAction())).isEqualTo(objectMapper.writeValueAsString(actionsDaoList.get(0).getAction())); + assertThat(objectMapper.writeValueAsString(response.getActionsList().get(9).getAction())).isEqualTo(objectMapper.writeValueAsString(actionsDaoList.get(9).getAction())); + } + + @Test + void thatActionsCanBeListedWithParameter() throws JsonProcessingException { + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoList(20, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + repository + .saveAll(actionsDaoList) + .blockLast(); + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions?page=1&pageSize=5") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(5); + assertThat(response.getActionsList().get(0).getSaveInterval()).isEqualTo(saveInterval); + assertThat(response.getActionsList().get(4).getSaveInterval()).isEqualTo(saveInterval); + assertThat(objectMapper.writeValueAsString(response.getActionsList().get(0).getAction())).isEqualTo(objectMapper.writeValueAsString(actionsDaoList.get(0).getAction())); + assertThat(objectMapper.writeValueAsString(response.getActionsList().get(4).getAction())).isEqualTo(objectMapper.writeValueAsString(actionsDaoList.get(4).getAction())); + } + + @Test + void thatActionsCanBeListedWithParameterInOrderByActionCreatedAt() { + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoList(5, "test-user", OffsetDateTime.of(LocalDateTime.now().minusDays(2), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + actionsDaoList.addAll(ActionFixtures.actionsDaoList(5, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS))); + actionsDaoList.addAll(ActionFixtures.actionsDaoList(5, "test-user", OffsetDateTime.of(LocalDateTime.now().minusHours(6), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS))); + actionsDaoList.addAll(ActionFixtures.actionsDaoList(5, "test-user", OffsetDateTime.of(LocalDateTime.now().minusHours(12), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS))); + repository + .saveAll(actionsDaoList) + .blockLast(); + + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions?page=1&pageSize=5") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(5); + assertThat(response.getActionsList().get(0).getSaveInterval()).isEqualTo(saveInterval); + assertThat(response.getActionsList().get(4).getSaveInterval()).isEqualTo(saveInterval); + assertThat(response.getActionsList().get(0).getActionCreatedAt()).isEqualTo(actionsDaoList.get(5).getActionCreatedAt().toInstant().atOffset(ZoneOffset.UTC)); + assertThat(response.getActionsList().get(4).getActionCreatedAt()).isEqualTo(actionsDaoList.get(9).getActionCreatedAt().toInstant().atOffset(ZoneOffset.UTC)); + } + + @Test + void thatActionsCanBeListedWithShowLastHours() throws JsonProcessingException { + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(20, "test-user", OffsetDateTime.now().plusMinutes(30).truncatedTo(ChronoUnit.SECONDS)); + repository + .saveAll(actionsDaoList) + .blockLast(); + + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions?page=1&pageSize=20&showLastHours=12") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(12); + assertThat(response.getActionsList().get(0).getSaveInterval()).isEqualTo(saveInterval); + assertThat(objectMapper.writeValueAsString(response.getActionsList().get(0).getAction())).isEqualTo(objectMapper.writeValueAsString(actionsDaoList.get(0).getAction())); + assertThat(objectMapper.writeValueAsString(response.getActionsList().get(11).getAction())).isEqualTo(objectMapper.writeValueAsString(actionsDaoList.get(11).getAction())); + } + + @Test + void thatActionsCanNotBeListedWithWrongPageParameter() { + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoList(5, "test-user", OffsetDateTime.of(LocalDateTime.now().minusDays(2), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + repository + .saveAll(actionsDaoList) + .blockLast(); + + Problem response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions?page=0&pageSize=5") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.BAD_REQUEST.value()) + .extract() + .body() + .as(Problem.class); + + assertThat(response.getStatus()).isEqualTo(500); + } + + @Test + void thatActionsCanBeGetForUserWithShowLastHours(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.now().plusMinutes(30).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList2 = ActionFixtures.actionsDaoList(10, "test2-user", OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList3 = ActionFixtures.actionsDaoList(10, "test3-user", OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)); + + actionsDaoList.addAll(actionsDaoList2); + actionsDaoList.addAll(actionsDaoList3); + + repository + .saveAll(actionsDaoList) + .blockLast(); + + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test-user?page=1&pageSize=20&showLastHours=2") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(2); + assertThat(response.getActionsList().get(0).getSaveInterval()).isEqualTo(saveInterval); + } + + @Test + void thatActionsCanBeGottenForUserWithShowLastHoursWithMinusValue(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList2 = ActionFixtures.actionsDaoList(10, "test2-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList3 = ActionFixtures.actionsDaoList(10, "test3-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList4 = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now().plusHours(48), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + actionsDaoList.addAll(actionsDaoList2); + actionsDaoList.addAll(actionsDaoList3); + actionsDaoList.addAll(actionsDaoList4); + + repository + .saveAll(actionsDaoList) + .blockLast(); + + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test-user?page=1&pageSize=20&showLastHours=-2") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(10); + } + + @Test + void thatActionsCanBeGottenForUserWithoutParameter(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList2 = ActionFixtures.actionsDaoList(10, "test2-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList3 = ActionFixtures.actionsDaoList(10, "test3-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList4 = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + actionsDaoList.addAll(actionsDaoList2); + actionsDaoList.addAll(actionsDaoList3); + actionsDaoList.addAll(actionsDaoList4); + repository + .saveAll(actionsDaoList) + .blockLast(); + + ActionsListResponse response = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test-user") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isEqualTo(10); + assertThat(response.getActionsList().get(0).getSaveInterval()).isEqualTo(saveInterval); + } + + @Test + void thatActionsCanBeGottenForUserWithShowLastHoursWithEmptyList() { + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList2 = ActionFixtures.actionsDaoList(10, "test2-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList3 = ActionFixtures.actionsDaoList(10, "test3-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList4 = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + actionsDaoList.addAll(actionsDaoList2); + actionsDaoList.addAll(actionsDaoList3); + actionsDaoList.addAll(actionsDaoList4); + repository + .saveAll(actionsDaoList) + .blockLast(); + + ActionsListResponse response = requestSpecification("test4-user") + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test4-user?page=1&pageSize=20&showLastHours=2") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(response.getTotalCount()).isZero(); + } + + @Test + void thatActionsCanBeDeleted(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.now().plusMinutes(30).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList2 = ActionFixtures.actionsDaoList(5, "test2-user", OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList3 = ActionFixtures.actionsDaoList(3, "test3-user", OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)); + actionsDaoList.addAll(actionsDaoList2); + actionsDaoList.addAll(actionsDaoList3); + repository + .saveAll(actionsDaoList) + .blockLast(); + + requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .delete( "/v1/actions/test-user?deleteAfterHours=2") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + ActionsListResponse responseGetUser = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID2 )) + .when() + .get( "/v1/actions/test-user?page=1&pageSize=20") + .then() + .header("X-Request-Id", X_REQUEST_ID2) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + ActionsListResponse responseGetUser2 = requestSpecification("test2-user") + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID2 )) + .when() + .get( "/v1/actions/test2-user") + .then() + .header("X-Request-Id", X_REQUEST_ID2) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + ActionsListResponse responseGetUser3 = requestSpecification("test3-user") + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID2 )) + .when() + .get( "/v1/actions/test3-user") + .then() + .header("X-Request-Id", X_REQUEST_ID2) + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(responseGetUser.getTotalCount()).isEqualTo(2); + assertThat(responseGetUser2.getTotalCount()).isEqualTo(5); + assertThat(responseGetUser3.getTotalCount()).isEqualTo(3); + } + + @Test + void thatActionsCanNotBeGetForUserBecauseOfWrongUserIdInToken(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + repository + .saveAll(actionsDaoList) + .blockLast(); + + Problem response = requestSpecification("wrong-userId") + .given() + .accept(MediaType.APPLICATION_PROBLEM_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test-user") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.BAD_REQUEST.value()) + .extract() + .body() + .as(Problem.class); + + assertThat(response).isNotNull(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.FORBIDDEN.value()); + } + + @Test + void thatActionsCanNotBeGetForUserBecauseOfWrongHeader(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + repository + .saveAll(actionsDaoList) + .blockLast(); + + Problem response = wrongHeaderRequestSpecification("test-user") + .given() + .accept(MediaType.APPLICATION_PROBLEM_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID )) + .when() + .get( "/v1/actions/test-user") + .then() + .header("X-Request-Id", X_REQUEST_ID) + .statusCode(HttpStatus.BAD_REQUEST.value()) + .extract() + .body() + .as(Problem.class); + + assertThat(response).isNotNull(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.FORBIDDEN.value()); + } + + @Test + void thatActionsCanBeDeletedForAllUsers(){ + // First mixed user actions for different users + List<ActionsDao> actionsDaoList = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now().minusHours(96), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList2 = ActionFixtures.actionsDaoList(8, "test2-user", OffsetDateTime.of(LocalDateTime.now().minusHours(24), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList3 = ActionFixtures.actionsDaoList(5, "test3-user", OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + List<ActionsDao> actionsDaoList4 = ActionFixtures.actionsDaoListHourOffsetOnly(10, "test-user", OffsetDateTime.of(LocalDateTime.now().minusHours(48), ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)); + + actionsDaoList.addAll(actionsDaoList2); + actionsDaoList.addAll(actionsDaoList3); + actionsDaoList.addAll(actionsDaoList4); + repository + .saveAll(actionsDaoList) + .blockLast(); + + actionsService.deleteActions(72).block(); + + ActionsListResponse responseGetUser = requestSpecification() + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID2 )) + .when() + .get( "/v1/actions/test-user?page=1&pageSize=20") + .then() + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + ActionsListResponse responseGetUser2 = requestSpecification("test2-user") + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID2 )) + .when() + .get( "/v1/actions/test2-user") + .then() + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + ActionsListResponse responseGetUser3 = requestSpecification("test3-user") + .given() + .accept(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .header(new Header("X-Request-Id", X_REQUEST_ID2 )) + .when() + .get( "/v1/actions/test3-user") + .then() + .statusCode(HttpStatus.OK.value()) + .extract() + .body() + .as(ActionsListResponse.class); + + assertThat(responseGetUser.getTotalCount()).isEqualTo(10); + assertThat(responseGetUser2.getTotalCount()).isEqualTo(8); + assertThat(responseGetUser3.getTotalCount()).isEqualTo(5); + } +} diff --git a/app/src/test/resources/application.yml b/app/src/test/resources/application.yml new file mode 100644 index 0000000..521befe --- /dev/null +++ b/app/src/test/resources/application.yml @@ -0,0 +1,38 @@ +server: + port: 9002 + address: 0.0.0.0 + +spring: + mongodb: + embedded: + version: 3.2.8 + jackson: + serialization: + # needed for serializing objects of type object + FAIL_ON_EMPTY_BEANS: false + security: + oauth2: + resourceserver: + jwt: + jwk-set-uri: http://localhost:${wiremock.server.port}/auth/realms/ONAP/protocol/openid-connect/certs #Keycloak Endpoint + +portal-history: + realm: ONAP + save-interval: 72 + delete-interval: '0 0 0 1 1 *' + +management: + endpoints: + web: + exposure: + include: "*" + info: + build: + enabled: true + env: + enabled: true + git: + enabled: true + java: + enabled: true + diff --git a/app/src/test/resources/logback-spring.xml b/app/src/test/resources/logback-spring.xml new file mode 100644 index 0000000..f4ef0bf --- /dev/null +++ b/app/src/test/resources/logback-spring.xml @@ -0,0 +1,15 @@ +<?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 class="net.logstash.logback.encoder.LogstashEncoder"/> + </appender> + + <root level="all"> + <appender-ref ref="stdout"/> + </root> +</configuration> diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 0000000..834af3a --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,9 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + // Support convention plugins written in Groovy. Convention plugins are build scripts in 'src/main' that automatically become available as plugins in the main build. + id 'groovy-gradle-plugin' +} + diff --git a/buildSrc/src/main/groovy/org.onap.portal.history.java-application-conventions.gradle b/buildSrc/src/main/groovy/org.onap.portal.history.java-application-conventions.gradle new file mode 100644 index 0000000..be78cf2 --- /dev/null +++ b/buildSrc/src/main/groovy/org.onap.portal.history.java-application-conventions.gradle @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + // Apply the common convention plugin for shared build configuration between library and application projects. + id 'org.onap.portal.history.java-common-conventions' + + // Apply the application plugin to add support for building a CLI application in Java. + id 'application' +} diff --git a/buildSrc/src/main/groovy/org.onap.portal.history.java-common-conventions.gradle b/buildSrc/src/main/groovy/org.onap.portal.history.java-common-conventions.gradle new file mode 100644 index 0000000..16cf302 --- /dev/null +++ b/buildSrc/src/main/groovy/org.onap.portal.history.java-common-conventions.gradle @@ -0,0 +1,28 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + // Apply the java Plugin to add support for Java. + id 'java' + id 'idea' +} + +repositories { +maven { + url "https://plugins.gradle.org/m2/" + } + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-webflux:2.5.5' + + // Use JUnit Jupiter for testing. + testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2' +} + +tasks.named('test') { + // Use JUnit Platform for unit tests. + useJUnitPlatform() +} diff --git a/buildSrc/src/main/groovy/org.onap.portal.history.java-library-conventions.gradle b/buildSrc/src/main/groovy/org.onap.portal.history.java-library-conventions.gradle new file mode 100644 index 0000000..24ddad6 --- /dev/null +++ b/buildSrc/src/main/groovy/org.onap.portal.history.java-library-conventions.gradle @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + // Apply the common convention plugin for shared build configuration between library and application projects. + id 'org.onap.portal.history.java-common-conventions' + + // Apply the java-library plugin for API and implementation separation. + id 'java-library' +} diff --git a/development/.env b/development/.env new file mode 100644 index 0000000..ff65652 --- /dev/null +++ b/development/.env @@ -0,0 +1,15 @@ +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 +POSTGRES_IMAGE=postgres +POSTGRES_VERSION=15rc1 +MONGO_IMAGE=mongo +MONGO_VERSION=latest +MONGO_USER=root +MONGO_PASSWORD=password + + diff --git a/development/config/onap-realm.json b/development/config/onap-realm.json new file mode 100644 index 0000000..75bdb6a --- /dev/null +++ b/development/config/onap-realm.json @@ -0,0 +1,70 @@ +{ + "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, + "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, + "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" + ], + "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..b08f7d5 --- /dev/null +++ b/development/docker-compose.yml @@ -0,0 +1,40 @@ +version: '3' + +volumes: + postgres_data: + driver: local + +services: + postgres: + image: "${POSTGRES_IMAGE}:${POSTGRES_VERSION}" + volumes: + - postgres_data:/var/lib/postgresql/data + environment: + POSTGRES_DB: ${KEYCLOAK_DB} + POSTGRES_USER: ${KEYCLOAK_DB_USER} + POSTGRES_PASSWORD: ${KEYCLOAK_DB_PASSWORD} + keycloak: + image: "${KEYCLOAK_IMAGE}:${KEYCLOAK_VERSION}" + environment: + DB_VENDOR: POSTGRES + DB_ADDR: postgres + DB_DATABASE: ${KEYCLOAK_DB} + DB_USER: ${KEYCLOAK_DB_USER} + 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: + image: "${MONGO_IMAGE}:${MONGO_VERSION}" + ports: + - 27017:27017 + environment: + MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER} + MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD} diff --git a/development/request.http b/development/request.http new file mode 100644 index 0000000..72bbb79 --- /dev/null +++ b/development/request.http @@ -0,0 +1,63 @@ + +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); + %} + +### + +POST http://localhost:9002/v1/actions/{{user_id}} +Accept: application/json +Authorization: Bearer {{access_token}} +X-Auth-Identity: Bearer {{id_token}} +X-Request-Id: {{$uuid}} +Content-Type: application/json + +{ + "userId": "{{user_id}}", + "actionCreatedAt": "{{$timestamp}}", + "action": { + "type": "DELETE", + "entity": "USERADMINISTRATION", + "entityParams": { + "userName": "uli", + "userId": "{{$randomInt}}" + } + } +} + +### + +GET http://localhost:9002/v1/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:9002/v1/actions?page=1&pageSize=10&showLastHours=1 +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..4f90ee5 --- /dev/null +++ b/development/run.sh @@ -0,0 +1,7 @@ +#!/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/verify-licenses.gradle b/gradle/verify-licenses.gradle new file mode 100644 index 0000000..a4cafd5 --- /dev/null +++ b/gradle/verify-licenses.gradle @@ -0,0 +1,39 @@ +// Source: https://github.com/abesto/zipkin/blob/8cbc69bfcd85e89c1be43f1038ecf7c200245933/gradle/verify-licenses.gradle +/** + * Gradle plugin used to verify that all dependencies of a project use allowed licenses. + * Usage: + * apply from: "${rootDir}/gradle/verify-licenses.gradle" + * + * The list of allowed licenses can be modified via `licenseBlackList` from project definitions. + */ + +ext.licenseBlackList = [ + 'No license found', + 'GNU GENERAL PUBLIC LICENSE, Version 3', + 'GNU GENERAL PUBLIC LICENSE, V3.0' +] + +// Verify that all dependency licenses are ones we like +task verifyLicenses { + description "Verify that none of the dependencies use black-listed licenses." + dependsOn 'downloadLicenses' + + doLast { + def xml = new XmlParser().parse('app/build/reports/license/license-dependency.xml') + def fail = false + xml.each { license -> + if (licenseBlackList*.toLowerCase().contains(license.@name.toLowerCase())) { + def depStrings = [] + license.dependency.each { depStrings << it.text() } + logger.error( + "License \"${license.@name}\" is not on the list of allowed licenses. " +\ + "The dependencies using it: ${depStrings}") + fail = true + } + } + if (fail) { + throw new GradleException("License verification failed.") + } + } +} +check.dependsOn verifyLicenses
\ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..249e583 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..98debb8 --- /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.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -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..f127cfd --- /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/lombok.config b/lombok.config new file mode 100644 index 0000000..df71bb6 --- /dev/null +++ b/lombok.config @@ -0,0 +1,2 @@ +config.stopBubbling = true +lombok.addLombokGeneratedAnnotation = true diff --git a/openapi/build.gradle b/openapi/build.gradle new file mode 100644 index 0000000..505ac7b --- /dev/null +++ b/openapi/build.gradle @@ -0,0 +1,53 @@ +plugins { + id 'org.onap.portal.history.java-application-conventions' + id 'org.openapi.generator' +} + +ext { + openapiVersion = '6.0.1' +} + +dependencies { + implementation "org.openapitools:openapi-generator:$openapiVersion" + // NOTE(KE) needed to add these dependencies, check in next version whether its removable... + // https://github.com/OpenAPITools/openapi-generator/issues/8360 + compileOnly "io.springfox:springfox-swagger2:3.0.0" +} + +// https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-gradle-plugin/README.adoc +openApiGenerate { + generatorName = "spring" + library = "spring-boot" + inputSpec = "$projectDir/src/main/resources/api/api.yml" + outputDir = "$buildDir/openapi" + configOptions = [ + openApiNullable: "false", + skipDefaultInterface: "true", + dateLibrary: "java8", + interfaceOnly: "true", + useTags: "true", + useOptional: "true", + reactive: "true" + ] + generateApiTests = false + generateApiDocumentation = false + generateModelTests = false + generateModelDocumentation = false + invokerPackage = "org.onap.portal.history.openapi" + apiPackage = "org.onap.portal.history.openapi.api" + modelPackage = "org.onap.portal.history.openapi.model" +} + +compileJava { + dependsOn tasks.openApiGenerate +} + +sourceSets { + main { + java { + srcDirs += file("$buildDir/openapi/src/main/java") + } + } +} + + diff --git a/openapi/src/main/resources/api/api.yml b/openapi/src/main/resources/api/api.yml new file mode 100644 index 0000000..1ab2d86 --- /dev/null +++ b/openapi/src/main/resources/api/api.yml @@ -0,0 +1,354 @@ +openapi: 3.0.2 +info: + title: History API + version: '1.0' + description: API to provide actions for portal-history +servers: + - url: 'http://localhost:9002/{base}' + variables: + base: + default: 'portal-history' + description: Basepath +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 +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 + 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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..9ac026b --- /dev/null +++ b/settings.gradle @@ -0,0 +1,22 @@ +// Centrally declare plugin versions here +// https://docs.gradle.org/current/userguide/plugins.html#sec:plugin_version_management +pluginManagement { + plugins { + id 'org.springframework.boot' version '2.7.3' + id 'io.spring.dependency-management' version '1.0.13.RELEASE' + id 'org.sonarqube' version '3.4.0.2513' + id 'com.github.hierynomus.license' version '0.16.1' + id 'org.openapi.generator' version '6.0.1' + id 'com.gorylenko.gradle-git-properties' version '2.4.1' + } + // https://docs.gradle.org/current/userguide/plugins.html#sec:custom_plugin_repositories + repositories { + maven { + url "https://plugins.gradle.org/m2/" + } + mavenCentral() + } +} + +rootProject.name = 'history' +include('app','openapi') @@ -0,0 +1 @@ +0.1.0 |