aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/org/onap/portalng
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/main/java/org/onap/portalng')
-rw-r--r--app/src/main/java/org/onap/portalng/history/HistoryApplication.java40
-rw-r--r--app/src/main/java/org/onap/portalng/history/configuration/BeansConfig.java50
-rw-r--r--app/src/main/java/org/onap/portalng/history/configuration/Errorhandler.java95
-rw-r--r--app/src/main/java/org/onap/portalng/history/configuration/HistoryConfig.java35
-rw-r--r--app/src/main/java/org/onap/portalng/history/configuration/RequestIdInterceptor.java56
-rw-r--r--app/src/main/java/org/onap/portalng/history/configuration/SchedulerConfig.java53
-rw-r--r--app/src/main/java/org/onap/portalng/history/configuration/SecurityConfig.java53
-rw-r--r--app/src/main/java/org/onap/portalng/history/controller/ActionsController.java84
-rw-r--r--app/src/main/java/org/onap/portalng/history/entities/ActionsDao.java44
-rw-r--r--app/src/main/java/org/onap/portalng/history/exception/ProblemException.java55
-rw-r--r--app/src/main/java/org/onap/portalng/history/logging/LogContextVariable.java40
-rw-r--r--app/src/main/java/org/onap/portalng/history/logging/LoggerProperties.java11
-rw-r--r--app/src/main/java/org/onap/portalng/history/logging/LoggingHelper.java68
-rw-r--r--app/src/main/java/org/onap/portalng/history/logging/ReactiveRequestLoggingFilter.java89
-rw-r--r--app/src/main/java/org/onap/portalng/history/logging/StatusCode.java28
-rw-r--r--app/src/main/java/org/onap/portalng/history/logging/WebExchangeUtils.java92
-rw-r--r--app/src/main/java/org/onap/portalng/history/repository/ActionsRepository.java42
-rw-r--r--app/src/main/java/org/onap/portalng/history/services/ActionsService.java218
-rw-r--r--app/src/main/java/org/onap/portalng/history/util/IdTokenExchange.java126
-rw-r--r--app/src/main/java/org/onap/portalng/history/util/Logger.java65
20 files changed, 1344 insertions, 0 deletions
diff --git a/app/src/main/java/org/onap/portalng/history/HistoryApplication.java b/app/src/main/java/org/onap/portalng/history/HistoryApplication.java
new file mode 100644
index 0000000..1a9cd8e
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/HistoryApplication.java
@@ -0,0 +1,40 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+/*
+ * This Java source file was generated by the Gradle 'init' task.
+ */
+package org.onap.portalng.history;
+
+
+import org.onap.portalng.history.configuration.HistoryConfig;
+import org.onap.portalng.history.logging.LoggerProperties;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+
+@SpringBootApplication
+@EnableConfigurationProperties({HistoryConfig.class, LoggerProperties.class})
+public class HistoryApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(HistoryApplication.class, args);
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/configuration/BeansConfig.java b/app/src/main/java/org/onap/portalng/history/configuration/BeansConfig.java
new file mode 100644
index 0000000..a1fb5f2
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.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/portalng/history/configuration/Errorhandler.java b/app/src/main/java/org/onap/portalng/history/configuration/Errorhandler.java
new file mode 100644
index 0000000..515935b
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/configuration/Errorhandler.java
@@ -0,0 +1,95 @@
+/*
+ *
+ * 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.portalng.history.configuration;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.onap.portalng.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/portalng/history/configuration/HistoryConfig.java b/app/src/main/java/org/onap/portalng/history/configuration/HistoryConfig.java
new file mode 100644
index 0000000..c790288
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/configuration/HistoryConfig.java
@@ -0,0 +1,35 @@
+/*
+ *
+ * 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.portalng.history.configuration;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import jakarta.validation.constraints.NotBlank;
+
+@Data
+@ConfigurationProperties("history")
+public class HistoryConfig {
+
+ @NotBlank
+ private final Integer saveInterval;
+}
diff --git a/app/src/main/java/org/onap/portalng/history/configuration/RequestIdInterceptor.java b/app/src/main/java/org/onap/portalng/history/configuration/RequestIdInterceptor.java
new file mode 100644
index 0000000..291e5e6
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/configuration/RequestIdInterceptor.java
@@ -0,0 +1,56 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portalng.history.configuration;
+
+import org.onap.portalng.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 RequestIdInterceptor 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);
+ exchange.getResponse().getHeaders().add(X_REQUEST_ID, xRequestId);
+ }
+ return chain
+ .filter(exchange)
+ .contextWrite(cxt -> cxt.put(EXCHANGE_CONTEXT_ATTRIBUTE, exchange));
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/configuration/SchedulerConfig.java b/app/src/main/java/org/onap/portalng/history/configuration/SchedulerConfig.java
new file mode 100644
index 0000000..81299b1
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/configuration/SchedulerConfig.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.portalng.history.configuration;
+
+import lombok.extern.slf4j.Slf4j;
+
+import org.onap.portalng.history.services.ActionsService;
+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 HistoryConfig historyConfig;
+
+ public SchedulerConfig(ActionsService actionsService, HistoryConfig historyConfig){
+ this.actionsService = actionsService;
+ this.historyConfig = historyConfig;
+ }
+
+ /**
+ * 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="${history.delete-interval}")
+ public void runDeleteActions(){
+ actionsService.deleteActions(historyConfig.getSaveInterval());
+ log.info("Delete actions in scheduled job");
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/configuration/SecurityConfig.java b/app/src/main/java/org/onap/portalng/history/configuration/SecurityConfig.java
new file mode 100644
index 0000000..9d17bba
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.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/portalng/history/controller/ActionsController.java b/app/src/main/java/org/onap/portalng/history/controller/ActionsController.java
new file mode 100644
index 0000000..dbab575
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/controller/ActionsController.java
@@ -0,0 +1,84 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portalng.history.controller;
+
+import java.util.Optional;
+
+import org.onap.portalng.history.openapi.api.ActionsApi;
+import org.onap.portalng.history.openapi.model.ActionResponse;
+import org.onap.portalng.history.openapi.model.ActionsListResponse;
+import org.onap.portalng.history.openapi.model.CreateActionRequest;
+import org.onap.portalng.history.configuration.HistoryConfig;
+import org.onap.portalng.history.services.ActionsService;
+import org.onap.portalng.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 HistoryConfig historyConfig;
+
+ public ActionsController(ActionsService actionsService, HistoryConfig historyConfig){
+ this.actionsService = actionsService;
+ this.historyConfig = historyConfig;
+ }
+
+ @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, historyConfig.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(historyConfig.getSaveInterval()), historyConfig.getSaveInterval(), xRequestId))
+ .map(ResponseEntity::ok);
+ }
+
+ @Override
+ public Mono<ResponseEntity<ActionsListResponse>> listActions(String xRequestId, Optional<Integer> page, Optional<Integer> pageSize, Optional<Integer> showLastHours, ServerWebExchange exchange) {
+
+ return actionsService
+ .listActions(page.orElse(1), pageSize.orElse(10), showLastHours.orElse(historyConfig.getSaveInterval()), historyConfig.getSaveInterval(), xRequestId)
+ .map(ResponseEntity::ok);
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/entities/ActionsDao.java b/app/src/main/java/org/onap/portalng/history/entities/ActionsDao.java
new file mode 100644
index 0000000..127e093
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.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/portalng/history/exception/ProblemException.java b/app/src/main/java/org/onap/portalng/history/exception/ProblemException.java
new file mode 100644
index 0000000..8c71ce4
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.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/portalng/history/logging/LogContextVariable.java b/app/src/main/java/org/onap/portalng/history/logging/LogContextVariable.java
new file mode 100644
index 0000000..1b1c505
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/logging/LogContextVariable.java
@@ -0,0 +1,40 @@
+/*
+ *
+ * Copyright (c) 2023. 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.portalng.history.logging;
+
+import lombok.Getter;
+
+@Getter
+public enum LogContextVariable {
+ TRACE_ID("trace_id"),
+ STATUS("status"),
+ NORTHBOUND_METHOD("northbound.method"),
+ NORTHBOUND_URL("northbound.url"),
+ EXECUTION_TIME("execution.time_ms"),
+ HTTP_STATUS("httpStatus");
+
+ private final String variableName;
+
+ LogContextVariable(String variableName) {
+ this.variableName = variableName;
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/logging/LoggerProperties.java b/app/src/main/java/org/onap/portalng/history/logging/LoggerProperties.java
new file mode 100644
index 0000000..f785822
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/logging/LoggerProperties.java
@@ -0,0 +1,11 @@
+package org.onap.portalng.history.logging;
+
+import java.util.List;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@ConfigurationProperties("logger")
+public record LoggerProperties(
+ String traceIdHeaderName,
+ Boolean enabled, List<String> excludePaths) {
+} \ No newline at end of file
diff --git a/app/src/main/java/org/onap/portalng/history/logging/LoggingHelper.java b/app/src/main/java/org/onap/portalng/history/logging/LoggingHelper.java
new file mode 100644
index 0000000..90c61c4
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/logging/LoggingHelper.java
@@ -0,0 +1,68 @@
+/*
+ *
+ * Copyright (c) 2023. 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.portalng.history.logging;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.MDC;
+
+import java.util.Map;
+import java.util.function.BiConsumer;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class LoggingHelper {
+ public static void error(
+ Logger logger, Map<LogContextVariable, String> metadata, String message, Object... args) {
+ log(logger::error, metadata, message, args);
+ }
+
+ public static void debug(
+ Logger logger, Map<LogContextVariable, String> metadata, String message, Object... args) {
+ log(logger::debug, metadata, message, args);
+ }
+
+ public static void info(
+ Logger logger, Map<LogContextVariable, String> metadata, String message, Object... args) {
+ log(logger::info, metadata, message, args);
+ }
+
+ public static void warn(
+ Logger logger, Map<LogContextVariable, String> metadata, String message, Object... args) {
+ log(logger::warn, metadata, message, args);
+ }
+
+ public static void trace(
+ Logger logger, Map<LogContextVariable, String> metadata, String message, Object... args) {
+ log(logger::trace, metadata, message, args);
+ }
+
+ private static void log(
+ BiConsumer<String, Object[]> logMethod,
+ Map<LogContextVariable, String> metadata,
+ String message,
+ Object... args) {
+ metadata.forEach((variable, value) -> MDC.put(variable.getVariableName(), value));
+ logMethod.accept(message, args);
+ MDC.clear();
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/logging/ReactiveRequestLoggingFilter.java b/app/src/main/java/org/onap/portalng/history/logging/ReactiveRequestLoggingFilter.java
new file mode 100644
index 0000000..91df0c1
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/logging/ReactiveRequestLoggingFilter.java
@@ -0,0 +1,89 @@
+/*
+ *
+ * Copyright (c) 2023. 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.portalng.history.logging;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.stereotype.Component;
+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.time.Duration;
+import java.time.LocalDateTime;
+import java.util.List;
+
+@Slf4j
+@Component
+@RequiredArgsConstructor
+@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
+public class ReactiveRequestLoggingFilter implements WebFilter {
+
+ private final LoggerProperties loggerProperties;
+
+ @Override
+ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
+ if (loggingDisabled(exchange)) {
+ return chain.filter(exchange);
+ }
+
+ var logMessageMetadata =
+ WebExchangeUtils.getRequestMetadata(exchange, loggerProperties.traceIdHeaderName());
+
+ LoggingHelper.info(log, logMessageMetadata, "RECEIVED");
+
+ var invocationStart = LocalDateTime.now();
+ return chain
+ .filter(exchange)
+ .doOnTerminate(
+ () -> {
+ logMessageMetadata.put(
+ LogContextVariable.STATUS,
+ exchange.getResponse().getStatusCode().isError()
+ ? StatusCode.ERROR.name()
+ : StatusCode.COMPLETE.name());
+ logMessageMetadata.put(
+ LogContextVariable.HTTP_STATUS,
+ String.valueOf(exchange.getResponse().getStatusCode().value()));
+ logMessageMetadata.put(
+ LogContextVariable.EXECUTION_TIME,
+ String.valueOf(
+ Duration.between(invocationStart, LocalDateTime.now()).toMillis()));
+ })
+ .doOnSuccess(res -> LoggingHelper.info(log, logMessageMetadata, "FINISHED"))
+ .doOnError(
+ ex -> LoggingHelper.warn(log, logMessageMetadata, "FAILED: {}", ex.getMessage()));
+ }
+
+ private boolean loggingDisabled(ServerWebExchange exchange) {
+ boolean loggingDisabled = loggerProperties.enabled() == null || !loggerProperties.enabled();
+
+ boolean urlShouldBeSkipped =
+ WebExchangeUtils.matchUrlsPatternsToPath(loggerProperties.excludePaths(), exchange.getRequest().getPath().value());
+
+ return loggingDisabled || urlShouldBeSkipped;
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/logging/StatusCode.java b/app/src/main/java/org/onap/portalng/history/logging/StatusCode.java
new file mode 100644
index 0000000..9feae4d
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/logging/StatusCode.java
@@ -0,0 +1,28 @@
+/*
+ *
+ * Copyright (c) 2023. 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.portalng.history.logging;
+
+public enum StatusCode {
+ REQUEST,
+ COMPLETE,
+ ERROR
+}
diff --git a/app/src/main/java/org/onap/portalng/history/logging/WebExchangeUtils.java b/app/src/main/java/org/onap/portalng/history/logging/WebExchangeUtils.java
new file mode 100644
index 0000000..c92564e
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/logging/WebExchangeUtils.java
@@ -0,0 +1,92 @@
+/*
+ *
+ * Copyright (c) 2023. 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.portalng.history.logging;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.util.PathMatcher;
+import org.springframework.web.server.ServerWebExchange;
+
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class WebExchangeUtils {
+ private static final String DEFAULT_TRACE_ID = "REQUEST_ID_IS_NOT_SET";
+ private static final String DEFAULT_REQUEST_URL = "REQUEST_URL_IS_ABSENT";
+ private static final String DEFAULT_REQUEST_METHOD = "HTTP_METHOD_IS_ABSENT";
+
+ private static final PathMatcher pathMatcher = new AntPathMatcher();
+
+ public static String getRequestId(ServerWebExchange webExchange, String traceIdHeaderName) {
+ if (webExchange == null || traceIdHeaderName == null) {
+ return DEFAULT_TRACE_ID;
+ }
+
+ var requestIdHeaders = webExchange.getRequest().getHeaders().get(traceIdHeaderName);
+ if (requestIdHeaders != null) {
+ return requestIdHeaders.stream().findAny().orElse(DEFAULT_TRACE_ID);
+ } else {
+ return DEFAULT_TRACE_ID;
+ }
+ }
+
+ public static String getRequestUrl(ServerWebExchange webExchange) {
+ if (webExchange == null) {
+ return DEFAULT_REQUEST_URL;
+ }
+ return webExchange.getRequest().getURI().toString();
+ }
+
+ public static String getRequestHttpMethod(ServerWebExchange webExchange) {
+ if (webExchange == null) {
+ return DEFAULT_REQUEST_METHOD;
+ }
+ return webExchange.getRequest().getMethod().name();
+ }
+
+ public static boolean matchUrlPatternToPath(String pattern, String path) {
+ return pathMatcher.match(pattern, path);
+ }
+
+ public static boolean matchUrlsPatternsToPath(List<String> patterns, String path) {
+ return patterns != null
+ && patterns.stream().anyMatch(pathPattern -> matchUrlPatternToPath(pathPattern, path));
+ }
+
+ public static Map<LogContextVariable, String> getRequestMetadata(
+ ServerWebExchange exchange, String traceIdHeaderName) {
+ var traceId = WebExchangeUtils.getRequestId(exchange, traceIdHeaderName);
+ var requestMethod = WebExchangeUtils.getRequestHttpMethod(exchange);
+ var requestUrl = WebExchangeUtils.getRequestUrl(exchange);
+
+ var logMessageMetadata = new EnumMap<LogContextVariable, String>(LogContextVariable.class);
+ logMessageMetadata.put(LogContextVariable.TRACE_ID, traceId);
+ logMessageMetadata.put(LogContextVariable.STATUS, StatusCode.REQUEST.name());
+ logMessageMetadata.put(LogContextVariable.NORTHBOUND_METHOD, requestMethod);
+ logMessageMetadata.put(LogContextVariable.NORTHBOUND_URL, requestUrl);
+
+ return logMessageMetadata;
+ }
+}
diff --git a/app/src/main/java/org/onap/portalng/history/repository/ActionsRepository.java b/app/src/main/java/org/onap/portalng/history/repository/ActionsRepository.java
new file mode 100644
index 0000000..d0dcc44
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.history.repository;
+
+import java.util.Date;
+
+import org.onap.portalng.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/portalng/history/services/ActionsService.java b/app/src/main/java/org/onap/portalng/history/services/ActionsService.java
new file mode 100644
index 0000000..746b108
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.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.portalng.history.openapi.model.ActionResponse;
+import org.onap.portalng.history.openapi.model.ActionsListResponse;
+import org.onap.portalng.history.openapi.model.CreateActionRequest;
+import org.onap.portalng.history.entities.ActionsDao;
+import org.onap.portalng.history.exception.ProblemException;
+import org.onap.portalng.history.repository.ActionsRepository;
+import org.onap.portalng.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/portalng/history/util/IdTokenExchange.java b/app/src/main/java/org/onap/portalng/history/util/IdTokenExchange.java
new file mode 100644
index 0000000..91db5f9
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/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.portalng.history.util;
+
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.JWTParser;
+
+import java.text.ParseException;
+
+import org.onap.portalng.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/portalng/history/util/Logger.java b/app/src/main/java/org/onap/portalng/history/util/Logger.java
new file mode 100644
index 0000000..f1cb150
--- /dev/null
+++ b/app/src/main/java/org/onap/portalng/history/util/Logger.java
@@ -0,0 +1,65 @@
+/*
+ *
+ * Copyright (c) 2022. Deutsche Telekom AG
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ *
+ */
+
+package org.onap.portalng.history.util;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.HttpStatusCode;
+
+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("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, HttpStatusCode httpStatusCode) {
+ log.info("History - response - X-Request-Id {} {}", xRequestId, httpStatusCode);
+ }
+
+ /**
+ * 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(
+ "History - error - X-Request-Id {} {} {} not found", xRequestId, msg, id);
+ }
+}