47d03c679f13b0537d90d759c4e86279aa96dc31
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2025 OpenInfra Foundation Europe. All rights reserved.
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  Modifications Copyright (C) 2024 TechMahindra Ltd.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.ncmp.impl.inventory;
24
25 import static org.onap.cps.api.parameters.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
26 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
27 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_ALREADY_EXIST;
28 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
29 import static org.onap.cps.ncmp.impl.inventory.CmHandleRegistrationServicePropertyHandler.PropertyType.DMI_PROPERTY;
30 import static org.onap.cps.ncmp.impl.inventory.CmHandleRegistrationServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
31 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME;
32 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
33 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
34
35 import com.google.common.collect.ImmutableMap;
36 import com.hazelcast.map.IMap;
37 import java.time.OffsetDateTime;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.LinkedHashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47 import lombok.RequiredArgsConstructor;
48 import lombok.extern.slf4j.Slf4j;
49 import org.apache.commons.lang3.StringUtils;
50 import org.onap.cps.api.CpsDataService;
51 import org.onap.cps.api.exceptions.DataNodeNotFoundException;
52 import org.onap.cps.api.exceptions.DataValidationException;
53 import org.onap.cps.api.model.DataNode;
54 import org.onap.cps.impl.DataNodeBuilder;
55 import org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse;
56 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle;
57 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle;
58 import org.onap.cps.ncmp.impl.utils.YangDataConverter;
59 import org.onap.cps.utils.ContentType;
60 import org.onap.cps.utils.JsonObjectMapper;
61 import org.springframework.beans.factory.annotation.Qualifier;
62 import org.springframework.stereotype.Service;
63
64 @Slf4j
65 @Service
66 @RequiredArgsConstructor
67 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
68 @SuppressWarnings("squid:S5852")
69 public class CmHandleRegistrationServicePropertyHandler {
70
71     private final InventoryPersistence inventoryPersistence;
72     private final CpsDataService cpsDataService;
73     private final JsonObjectMapper jsonObjectMapper;
74     private final AlternateIdChecker alternateIdChecker;
75     @Qualifier("cmHandleIdPerAlternateId")
76     private final IMap<String, String> cmHandleIdPerAlternateId;
77
78     /**
79      * Iterates over incoming updatedNcmpServiceCmHandles and update the dataNodes based on the updated attributes.
80      * The attributes which are not passed will remain as is.
81      *
82      * @param updatedNcmpServiceCmHandles collection of CmHandles
83      */
84     public List<CmHandleRegistrationResponse> updateCmHandleProperties(
85             final Collection<NcmpServiceCmHandle> updatedNcmpServiceCmHandles) {
86         final Collection<String> rejectedCmHandleIds = alternateIdChecker
87             .getIdsOfCmHandlesWithRejectedAlternateId(updatedNcmpServiceCmHandles, AlternateIdChecker.Operation.UPDATE);
88         final List<CmHandleRegistrationResponse> failureResponses =
89             CmHandleRegistrationResponse.createFailureResponses(rejectedCmHandleIds, CM_HANDLE_ALREADY_EXIST);
90         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>(failureResponses);
91         for (final NcmpServiceCmHandle updatedNcmpServiceCmHandle : updatedNcmpServiceCmHandles) {
92             final String cmHandleId = updatedNcmpServiceCmHandle.getCmHandleId();
93             if (!rejectedCmHandleIds.contains(cmHandleId)) {
94                 try {
95                     final DataNode existingCmHandleDataNode = inventoryPersistence
96                             .getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS).iterator().next();
97                     processUpdates(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
98                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
99                 } catch (final DataNodeNotFoundException e) {
100                     log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId,
101                             e.getMessage());
102                     cmHandleRegistrationResponses.add(
103                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
104                 } catch (final DataValidationException e) {
105                     log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
106                     cmHandleRegistrationResponses.add(
107                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
108                 } catch (final Exception exception) {
109                     log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
110                     cmHandleRegistrationResponses.add(
111                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
112                 }
113             }
114         }
115         return cmHandleRegistrationResponses;
116     }
117
118     private void processUpdates(final DataNode existingCmHandleDataNode,
119                                 final NcmpServiceCmHandle updatedNcmpServiceCmHandle) {
120         updateAlternateId(updatedNcmpServiceCmHandle);
121         updateDataProducerIdentifier(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
122         if (!updatedNcmpServiceCmHandle.getPublicProperties().isEmpty()) {
123             updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY,
124                 updatedNcmpServiceCmHandle.getPublicProperties());
125         }
126         if (!updatedNcmpServiceCmHandle.getDmiProperties().isEmpty()) {
127             updateProperties(existingCmHandleDataNode, DMI_PROPERTY, updatedNcmpServiceCmHandle.getDmiProperties());
128         }
129     }
130
131     private void updateAlternateId(final NcmpServiceCmHandle ncmpServiceCmHandle) {
132         final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
133         final String newAlternateId = ncmpServiceCmHandle.getAlternateId();
134         if (StringUtils.isNotBlank(newAlternateId)) {
135             setAndUpdateCmHandleField(ncmpServiceCmHandle.getCmHandleId(), "alternate-id", newAlternateId);
136             cmHandleIdPerAlternateId.delete(cmHandleId);
137             cmHandleIdPerAlternateId.set(newAlternateId, cmHandleId);
138         }
139     }
140
141     private void updateDataProducerIdentifier(final DataNode cmHandleDataNode,
142                                               final NcmpServiceCmHandle ncmpServiceCmHandle) {
143         final String newDataProducerIdentifier = ncmpServiceCmHandle.getDataProducerIdentifier();
144         if (StringUtils.isNotBlank(newDataProducerIdentifier)) {
145             final YangModelCmHandle yangModelCmHandle = YangDataConverter.toYangModelCmHandle(cmHandleDataNode);
146             final String existingDataProducerIdentifier = yangModelCmHandle.getDataProducerIdentifier();
147             if (StringUtils.isNotBlank(existingDataProducerIdentifier)) {
148                 if (!existingDataProducerIdentifier.equals(newDataProducerIdentifier)) {
149                     log.warn("Unable to update dataProducerIdentifier for cmHandle {}. "
150                             + "Value for dataProducerIdentifier has been set previously.",
151                         ncmpServiceCmHandle.getCmHandleId());
152                 } else {
153                     log.debug("dataProducerIdentifier for cmHandle {} is already set to {}.",
154                         ncmpServiceCmHandle.getCmHandleId(), newDataProducerIdentifier);
155                 }
156             } else {
157                 setAndUpdateCmHandleField(
158                     yangModelCmHandle.getId(), "data-producer-identifier", newDataProducerIdentifier);
159             }
160         }
161     }
162
163     private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
164                                   final Map<String, String> updatedProperties) {
165         final Collection<DataNode> replacementPropertyDataNodes =
166                 getReplacementDataNodes(existingCmHandleDataNode, propertyType, updatedProperties);
167         replacementPropertyDataNodes.addAll(
168                 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, updatedProperties));
169         if (replacementPropertyDataNodes.isEmpty()) {
170             removeAllProperties(existingCmHandleDataNode, propertyType);
171         } else {
172             inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
173         }
174     }
175
176     private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
177         existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
178             final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
179             if (matcher.find()) {
180                 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
181                 inventoryPersistence.deleteDataNode(dataNode.getXpath());
182             }
183         });
184     }
185
186     private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
187                                                                final PropertyType propertyType,
188                                                                final Map<String, String> updatedProperties) {
189         final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
190         for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
191             final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
192             if (matcher.find()) {
193                 final String keyName = matcher.group(2);
194                 if (!updatedProperties.containsKey(keyName)) {
195                     unchangedPropertyDataNodes.add(existingPropertyDataNode);
196                 }
197             }
198         }
199         return unchangedPropertyDataNodes;
200     }
201
202     private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
203                                                          final PropertyType propertyType,
204                                                          final Map<String, String> updatedProperties) {
205         final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
206         updatedProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
207             final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
208             if (updatedAttributeValue != null) {
209                 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
210                         updatedAttributeKey, updatedAttributeValue);
211                 replacementPropertyDataNodes.add(
212                         buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
213             }
214         });
215         return replacementPropertyDataNodes;
216     }
217
218     private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
219                                      final String attributeKey) {
220         return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
221     }
222
223     private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
224         final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
225         updatedLeaves.put("name", attributeKey);
226         updatedLeaves.put("value", attributeValue);
227         log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
228                 attributeValue);
229         return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
230     }
231
232     private void setAndUpdateCmHandleField(final String cmHandleIdToUpdate, final String fieldName,
233                                            final String newFieldValue) {
234         final Map<String, Map<String, String>> dmiRegistryData = new HashMap<>(1);
235         final Map<String, String> cmHandleData = new HashMap<>(2);
236         cmHandleData.put("id", cmHandleIdToUpdate);
237         cmHandleData.put(fieldName, newFieldValue);
238         dmiRegistryData.put("cm-handles", cmHandleData);
239         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
240                 jsonObjectMapper.asJsonString(dmiRegistryData), OffsetDateTime.now(), ContentType.JSON);
241         log.debug("Updating {} for cmHandle {} with value : {})", fieldName, cmHandleIdToUpdate, newFieldValue);
242     }
243
244     enum PropertyType {
245         DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
246
247         private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
248
249         final String xpathPrefix;
250         final Pattern propertyXpathPattern;
251
252         PropertyType(final String xpathPrefix) {
253             this.xpathPrefix = xpathPrefix;
254             this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);
255         }
256     }
257 }