Cm Subscription: Remove subscription method
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / events / cmsubscription / service / CmNotificationSubscriptionPersistenceServiceImpl.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2024 Nordix Foundation
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.ncmp.api.impl.events.cmsubscription.service;
22
23 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS;
24
25 import java.io.Serializable;
26 import java.time.OffsetDateTime;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import lombok.RequiredArgsConstructor;
33 import lombok.extern.slf4j.Slf4j;
34 import org.onap.cps.api.CpsDataService;
35 import org.onap.cps.api.CpsQueryService;
36 import org.onap.cps.cpspath.parser.CpsPathUtil;
37 import org.onap.cps.ncmp.api.impl.operations.DatastoreType;
38 import org.onap.cps.spi.model.DataNode;
39 import org.onap.cps.utils.ContentType;
40 import org.onap.cps.utils.JsonObjectMapper;
41 import org.springframework.stereotype.Service;
42
43 @Slf4j
44 @Service
45 @RequiredArgsConstructor
46 public class CmNotificationSubscriptionPersistenceServiceImpl implements CmNotificationSubscriptionPersistenceService {
47
48     private static final String SUBSCRIPTION_ANCHOR_NAME = "cm-data-subscriptions";
49     private static final String CM_SUBSCRIPTION_CPS_PATH_QUERY = """
50             /datastores/datastore[@name='%s']/cm-handles/cm-handle[@id='%s']/filters/filter[@xpath='%s']
51             """.trim();
52     private static final String SUBSCRIPTION_IDS_CPS_PATH_QUERY = """
53             //filter/subscriptionIds[text()='%s']
54             """.trim();
55
56     private final JsonObjectMapper jsonObjectMapper;
57     private final CpsQueryService cpsQueryService;
58     private final CpsDataService cpsDataService;
59
60     @Override
61     public boolean isOngoingCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
62                                                        final String xpath) {
63         return !getOngoingCmNotificationSubscriptionIds(datastoreType, cmHandleId, xpath).isEmpty();
64     }
65
66     @Override
67     public boolean isUniqueSubscriptionId(final String subscriptionId) {
68         return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
69                 SUBSCRIPTION_IDS_CPS_PATH_QUERY.formatted(subscriptionId),
70                 OMIT_DESCENDANTS).isEmpty();
71     }
72
73     @Override
74     public Collection<String> getOngoingCmNotificationSubscriptionIds(final DatastoreType datastoreType,
75                                                                       final String cmHandleId, final String xpath) {
76
77         final String isOngoingCmSubscriptionCpsPathQuery =
78                 CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
79                         escapeQuotesByDoublingThem(xpath));
80         final Collection<DataNode> existingNodes =
81                 cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, CM_SUBSCRIPTIONS_ANCHOR_NAME,
82                         isOngoingCmSubscriptionCpsPathQuery, OMIT_DESCENDANTS);
83         if (existingNodes.isEmpty()) {
84             return Collections.emptyList();
85         }
86         return (List<String>) existingNodes.iterator().next().getLeaves().get("subscriptionIds");
87     }
88
89     @Override
90     public void addCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
91                                               final String xpath, final String subscriptionId) {
92         if (isOngoingCmNotificationSubscription(datastoreType, cmHandleId, xpath)
93                 && (!getOngoingCmNotificationSubscriptionIds(datastoreType, cmHandleId, xpath)
94                 .contains(subscriptionId))) {
95             final DataNode subscriptionAsDataNode = getSubscriptionAsDataNode(datastoreType, cmHandleId, xpath);
96             final Collection<String> subscriptionIds = getOngoingCmNotificationSubscriptionIds(datastoreType,
97                     cmHandleId, xpath);
98             subscriptionIds.add(subscriptionId);
99             saveSubscriptionDetails(subscriptionAsDataNode, subscriptionIds);
100         } else {
101             addNewSubscriptionViaDatastore(datastoreType, cmHandleId, xpath, subscriptionId);
102         }
103     }
104
105     @Override
106     public void removeCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
107                                                  final String xpath, final String subscriptionId) {
108         final DataNode subscriptionAsDataNode = getSubscriptionAsDataNode(datastoreType, cmHandleId, xpath);
109         final Collection<String> subscriptionIds = getOngoingCmNotificationSubscriptionIds(datastoreType,
110                 cmHandleId, xpath);
111         subscriptionIds.remove(subscriptionId);
112         saveSubscriptionDetails(subscriptionAsDataNode, subscriptionIds);
113         if (isOngoingCmNotificationSubscription(datastoreType, cmHandleId, xpath)) {
114             log.info("There are subscribers left for the following cps path {} :",
115                     CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
116                             escapeQuotesByDoublingThem(xpath)));
117         } else {
118             log.info("No subscribers left for the following cps path {} :",
119                     CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
120                             escapeQuotesByDoublingThem(xpath)));
121             deleteListOfSubscriptionsFor(datastoreType, cmHandleId, xpath);
122         }
123     }
124
125     private void deleteListOfSubscriptionsFor(final DatastoreType datastoreType, final String cmHandleId,
126                                               final String xpath) {
127         cpsDataService.deleteDataNode(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
128                 CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
129                         escapeQuotesByDoublingThem(xpath)),
130                 OffsetDateTime.now());
131     }
132
133     private DataNode getSubscriptionAsDataNode(final DatastoreType datastoreType, final String cmHandleId,
134                                                final String xpath) {
135         return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
136                 CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
137                         escapeQuotesByDoublingThem(xpath)),
138                 OMIT_DESCENDANTS).iterator().next();
139     }
140
141     private void addNewSubscriptionViaDatastore(final DatastoreType datastoreType, final String cmHandleId,
142                                                 final String xpath, final String newSubscriptionId) {
143         final String parentXpath = "/datastores/datastore[@name='%s']/cm-handles"
144                 .formatted(datastoreType.getDatastoreName());
145         final String subscriptionAsJson = String.format("{\"cm-handle\":[{\"id\":\"%s\",\"filters\":{\"filter\":"
146                 + "[{\"xpath\":\"%s\",\"subscriptionIds\":[\"%s\"]}]}}]}", cmHandleId, xpath, newSubscriptionId);
147         cpsDataService.saveData(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME, parentXpath, subscriptionAsJson,
148                 OffsetDateTime.now(), ContentType.JSON);
149     }
150
151     private void saveSubscriptionDetails(final DataNode subscriptionDetailsAsDataNode,
152                                          final  Collection<String> subscriptionIds) {
153         final Map<String, Serializable> subscriptionDetailsAsMap = new HashMap<>();
154         subscriptionDetailsAsMap.put("xpath", subscriptionDetailsAsDataNode.getLeaves().get("xpath"));
155         subscriptionDetailsAsMap.put("subscriptionIds", (Serializable) subscriptionIds);
156         final String parentXpath = CpsPathUtil.getNormalizedParentXpath(subscriptionDetailsAsDataNode.getXpath());
157         final String subscriptionDetailsAsJson = "{\"filter\":["
158                 + jsonObjectMapper.asJsonString(subscriptionDetailsAsMap).replace("'", "\"") + "]}";
159         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME, parentXpath,
160                 subscriptionDetailsAsJson, OffsetDateTime.now());
161     }
162
163     private static String escapeQuotesByDoublingThem(final String inputXpath) {
164         return inputXpath.replace("'", "''");
165     }
166 }