5c53f3d53b63c90c642ec8aa7465fb2d1aed98c5
[cps.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2024-2025 OpenInfra Foundation Europe. All rights reserved.
4  *  Modifications Copyright (C) 2024 TechMahindra Ltd.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.impl.cmnotificationsubscription.utils;
23
24 import static org.onap.cps.api.parameters.FetchDescendantsOption.OMIT_DESCENDANTS;
25
26 import java.io.Serializable;
27 import java.time.OffsetDateTime;
28 import java.util.Collection;
29 import java.util.Collections;
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.api.model.DataNode;
37 import org.onap.cps.utils.ContentType;
38 import org.onap.cps.utils.JsonObjectMapper;
39 import org.springframework.stereotype.Service;
40
41 @Slf4j
42 @Service
43 @RequiredArgsConstructor
44 public class CmDataJobSubscriptionPersistenceService {
45
46     private static final String NCMP_DATASPACE_NAME = "NCMP-Admin";
47     private static final String CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME = "cm-data-job-subscriptions";
48     private static final String CM_DATA_JOB_SUBSCRIPTIONS_PARENT_NODE_XPATH = "/dataJob";
49     private static final String CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_ALTERNATE_ID_AND_DATATYPE =
50             "/dataJob/subscription[@alternateId='%s' and @dataTypeId='%s']";
51     private static final String CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_DATA_JOB_ID =
52             "//subscription/dataJobId[text()='%s']";
53
54     private final JsonObjectMapper jsonObjectMapper;
55     private final CpsQueryService cpsQueryService;
56     private final CpsDataService cpsDataService;
57
58     /**
59      * Check if we have a cm data job subscription for the given data type and target (FDN).
60      *
61      * @param dataType      the data type of the data job subscription
62      * @param alternateId   the alternate id target of the data job subscription
63      * @return              true if the subscription details has at least one subscriber , otherwise false
64      */
65     public boolean hasAtLeastOneSubscription(final String dataType, final String alternateId) {
66         return !getSubscriptionIds(dataType, alternateId).isEmpty();
67     }
68
69     /**
70      * Check if the input is a new subscription ID against ongoing subscriptions.
71      *
72      * @param subscriptionId subscription ID
73      * @return true if subscriptionId is not used in active subscriptions, otherwise false
74      */
75     public boolean isNewSubscriptionId(final String subscriptionId) {
76         final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_DATA_JOB_ID.formatted(subscriptionId);
77         return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME,
78                 query, OMIT_DESCENDANTS).isEmpty();
79     }
80
81     /**
82      * Get the ids for the subscriptions for the given data type and targets.
83      *
84      * @param dataType      the data type of the data job subscription
85      * @param alternateId   the alternate id target of the data job subscription
86      * @return              collection of subscription ids of ongoing cm notification subscription
87      */
88     public Collection<String> getSubscriptionIds(final String dataType, final String alternateId) {
89         final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_ALTERNATE_ID_AND_DATATYPE.formatted(
90                 alternateId, dataType);
91         final Collection<DataNode> existingNodes =
92                 cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME,
93                         query, OMIT_DESCENDANTS);
94         if (existingNodes.isEmpty()) {
95             return Collections.emptyList();
96         }
97         return (List<String>) existingNodes.iterator().next().getLeaves().get("dataJobId");
98     }
99
100     /**
101      * Add cm notification data job subscription.
102      *
103      * @param dataType          the data type of the data job subscription
104      * @param alternateId       the alternate id target of the data job subscription
105      * @param subscriptionId data job subscription id to be added
106      */
107     public void addSubscription(final String dataType, final String alternateId, final String subscriptionId) {
108         final Collection<String> subscriptionIds =
109                 getSubscriptionIds(dataType, alternateId);
110         if (subscriptionIds.isEmpty()) {
111             addNewSubscriptionDetails(dataType, alternateId, subscriptionId);
112         } else {
113             subscriptionIds.add(subscriptionId);
114             updateSubscriptionDetails(subscriptionIds, dataType, alternateId);
115         }
116     }
117
118     /**
119      * Remove cm notification data job Subscription.
120      *
121      * @param dataType          the data type of the data job subscription
122      * @param alternateId       the alternate id target of the data job subscription
123      * @param subscriptionId    data subscription id to remove
124      */
125     public void removeSubscription(final String dataType, final String alternateId, final String subscriptionId) {
126         final Collection<String> subscriptionIds = getSubscriptionIds(dataType, alternateId);
127         if (subscriptionIds.remove(subscriptionId)) {
128             updateSubscriptionDetails(subscriptionIds, dataType, alternateId);
129             log.info("There is at least one subscriber left for dataType {} on {}", dataType, alternateId);
130             if (subscriptionIds.isEmpty()) {
131                 log.info("There are no subscribers left for dataType {} on {}", dataType, alternateId);
132                 deleteUnusedSubscriptionDetails(dataType, alternateId);
133             }
134         }
135     }
136
137     /**
138      * Retrieve all existing data nodes for given data job subscription id.
139      *
140      * @param subscriptionId  data job subscription id
141      * @return                collection of DataNodes
142      */
143     public Collection<DataNode> getAffectedDataNodes(final String subscriptionId) {
144         final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_DATA_JOB_ID.formatted(subscriptionId);
145         return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME,
146                 query, OMIT_DESCENDANTS);
147     }
148
149     private void deleteUnusedSubscriptionDetails(final String dataType, final String alternateId) {
150         final String deleteListOfSubscriptionCpsPathQuery =
151                 CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_ALTERNATE_ID_AND_DATATYPE.formatted(alternateId,
152                         dataType);
153         cpsDataService.deleteDataNode(NCMP_DATASPACE_NAME, CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME,
154                 deleteListOfSubscriptionCpsPathQuery, OffsetDateTime.now());
155     }
156
157     private void addNewSubscriptionDetails(final String dataType,
158                                            final String alternateId,
159                                            final String subscriptionId) {
160         final Collection<String> newSubscriptionList = Collections.singletonList(subscriptionId);
161         final String subscriptionDetailsAsJson = getSubscriptionDetailsAsJson(newSubscriptionList, dataType,
162                 alternateId);
163         cpsDataService.saveData(NCMP_DATASPACE_NAME, CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME, subscriptionDetailsAsJson,
164                 OffsetDateTime.now(), ContentType.JSON);
165     }
166
167     private void updateSubscriptionDetails(final Collection<String> subscriptionIds, final String dataType,
168                                            final String alternateId) {
169         final String subscriptionDetailsAsJson = getSubscriptionDetailsAsJson(subscriptionIds, dataType, alternateId);
170         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, CM_DATA_JOB_SUBSCRIPTIONS_ANCHOR_NAME,
171                 CM_DATA_JOB_SUBSCRIPTIONS_PARENT_NODE_XPATH, subscriptionDetailsAsJson, OffsetDateTime.now(),
172                 ContentType.JSON);
173     }
174
175     private String getSubscriptionDetailsAsJson(final Collection<String> subscriptionIds,
176                                                 final String dataTypeId,
177                                                 final String alternateId) {
178         final Map<String, Serializable> subscriptionDetailsAsMap =
179                 Map.of("dataTypeId", dataTypeId,
180                         "alternateId", alternateId,
181                         "dataJobId", (Serializable) subscriptionIds);
182         return "{\"subscription\":[" + jsonObjectMapper.asJsonString(subscriptionDetailsAsMap) + "]}";
183     }
184
185 }
186