Add timeout to async test-cases
[cps.git] / cps-service / src / main / java / org / onap / cps / notification / NotificationService.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (c) 2021 Bell Canada.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *         http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.notification;
22
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.Future;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import lombok.extern.slf4j.Slf4j;
31 import org.springframework.scheduling.annotation.Async;
32 import org.springframework.stereotype.Service;
33
34 @Service
35 @Slf4j
36 public class NotificationService {
37
38     private NotificationProperties notificationProperties;
39     private NotificationPublisher notificationPublisher;
40     private CpsDataUpdatedEventFactory cpsDataUpdatedEventFactory;
41     private NotificationErrorHandler notificationErrorHandler;
42     private List<Pattern> dataspacePatterns;
43
44     /**
45      * Create an instance of Notification Subscriber.
46      *
47      * @param notificationProperties     properties for notification
48      * @param notificationPublisher      notification Publisher
49      * @param cpsDataUpdatedEventFactory to create CPSDataUpdatedEvent
50      * @param notificationErrorHandler   error handler
51      */
52     public NotificationService(
53         final NotificationProperties notificationProperties,
54         final NotificationPublisher notificationPublisher,
55         final CpsDataUpdatedEventFactory cpsDataUpdatedEventFactory,
56         final NotificationErrorHandler notificationErrorHandler) {
57         log.info("Notification Properties {}", notificationProperties);
58         this.notificationProperties = notificationProperties;
59         this.notificationPublisher = notificationPublisher;
60         this.cpsDataUpdatedEventFactory = cpsDataUpdatedEventFactory;
61         this.notificationErrorHandler = notificationErrorHandler;
62         this.dataspacePatterns = getDataspaceFilterPatterns(notificationProperties);
63     }
64
65     private List<Pattern> getDataspaceFilterPatterns(final NotificationProperties notificationProperties) {
66         if (notificationProperties.isEnabled()) {
67             return Arrays.stream(notificationProperties.getFilters()
68                 .getOrDefault("enabled-dataspaces", "")
69                 .split(","))
70                 .map(filterPattern -> Pattern.compile(filterPattern, Pattern.CASE_INSENSITIVE))
71                 .collect(Collectors.toList());
72         } else {
73             return Collections.emptyList();
74         }
75     }
76
77     /**
78      * Process Data Updated Event and publishes the notification.
79      *
80      * @param dataspaceName dataspace name
81      * @param anchorName    anchor name
82      * @return future
83      */
84     @Async("notificationExecutor")
85     public Future<Void> processDataUpdatedEvent(final String dataspaceName, final String anchorName) {
86         log.debug("process data updated event for dataspace '{}' & anchor '{}'", dataspaceName, anchorName);
87         try {
88             if (shouldSendNotification(dataspaceName)) {
89                 final var cpsDataUpdatedEvent =
90                     cpsDataUpdatedEventFactory.createCpsDataUpdatedEvent(dataspaceName, anchorName);
91                 log.debug("data updated event to be published {}", cpsDataUpdatedEvent);
92                 notificationPublisher.sendNotification(cpsDataUpdatedEvent);
93             }
94         } catch (final Exception exception) {
95             /* All the exceptions are handled to not to propagate it to caller.
96                CPS operation should not fail if sending event fails for any reason.
97              */
98             notificationErrorHandler.onException("Failed to process cps-data-updated-event.",
99                 exception, dataspaceName, anchorName);
100         }
101         return CompletableFuture.completedFuture(null);
102     }
103
104     /*
105         Add more complex rules based on dataspace and anchor later
106      */
107     private boolean shouldSendNotification(final String dataspaceName) {
108
109         return notificationProperties.isEnabled()
110             && dataspacePatterns.stream()
111             .anyMatch(pattern -> pattern.matcher(dataspaceName).find());
112     }
113
114 }