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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.ncmp.impl.inventory;
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.ADDITIONAL_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;
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;
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.inventory.sync.lcm.CmHandleTransitionPair;
59 import org.onap.cps.ncmp.impl.inventory.sync.lcm.LcmEventsHelper;
60 import org.onap.cps.ncmp.impl.utils.YangDataConverter;
61 import org.onap.cps.utils.ContentType;
62 import org.onap.cps.utils.JsonObjectMapper;
63 import org.springframework.beans.factory.annotation.Qualifier;
64 import org.springframework.stereotype.Service;
68 @RequiredArgsConstructor
69 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
70 @SuppressWarnings("squid:S5852")
71 public class CmHandleRegistrationServicePropertyHandler {
73 private final InventoryPersistence inventoryPersistence;
74 private final CpsDataService cpsDataService;
75 private final JsonObjectMapper jsonObjectMapper;
76 private final AlternateIdChecker alternateIdChecker;
77 @Qualifier("cmHandleIdPerAlternateId")
78 private final IMap<String, String> cmHandleIdPerAlternateId;
79 private final LcmEventsHelper lcmEventsHelper;
82 * Iterates over incoming updatedNcmpServiceCmHandles and update the dataNodes based on the updated attributes.
83 * The attributes which are not passed will remain as is.
85 * @param updatedNcmpServiceCmHandles collection of CmHandles
87 public List<CmHandleRegistrationResponse> updateCmHandleProperties(
88 final Collection<NcmpServiceCmHandle> updatedNcmpServiceCmHandles) {
89 final Collection<String> rejectedCmHandleIds = alternateIdChecker
90 .getIdsOfCmHandlesWithRejectedAlternateId(updatedNcmpServiceCmHandles, AlternateIdChecker.Operation.UPDATE);
91 final List<CmHandleRegistrationResponse> failureResponses =
92 CmHandleRegistrationResponse.createFailureResponses(rejectedCmHandleIds, CM_HANDLE_ALREADY_EXIST);
93 final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>(failureResponses);
94 for (final NcmpServiceCmHandle updatedNcmpServiceCmHandle : updatedNcmpServiceCmHandles) {
95 final String cmHandleId = updatedNcmpServiceCmHandle.getCmHandleId();
96 if (!rejectedCmHandleIds.contains(cmHandleId)) {
98 final DataNode existingCmHandleDataNode = inventoryPersistence
99 .getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS).iterator().next();
100 processUpdates(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
101 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
102 } catch (final DataNodeNotFoundException e) {
103 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId,
105 cmHandleRegistrationResponses.add(
106 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
107 } catch (final DataValidationException e) {
108 log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
109 cmHandleRegistrationResponses.add(
110 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
111 } catch (final Exception exception) {
112 log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
113 cmHandleRegistrationResponses.add(
114 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
118 return cmHandleRegistrationResponses;
121 private void processUpdates(final DataNode existingCmHandleDataNode,
122 final NcmpServiceCmHandle updatedNcmpServiceCmHandle) {
123 updateAlternateId(updatedNcmpServiceCmHandle);
124 updateDataProducerIdentifier(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
125 if (!updatedNcmpServiceCmHandle.getPublicProperties().isEmpty()) {
126 updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY,
127 updatedNcmpServiceCmHandle.getPublicProperties());
129 if (!updatedNcmpServiceCmHandle.getAdditionalProperties().isEmpty()) {
130 updateProperties(existingCmHandleDataNode, ADDITIONAL_PROPERTY,
131 updatedNcmpServiceCmHandle.getAdditionalProperties());
135 private void updateAlternateId(final NcmpServiceCmHandle ncmpServiceCmHandle) {
136 final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
137 final String newAlternateId = ncmpServiceCmHandle.getAlternateId();
138 if (StringUtils.isNotBlank(newAlternateId)) {
139 setAndUpdateCmHandleField(ncmpServiceCmHandle.getCmHandleId(), "alternate-id", newAlternateId);
140 cmHandleIdPerAlternateId.delete(cmHandleId);
141 cmHandleIdPerAlternateId.set(newAlternateId, cmHandleId);
145 private void updateDataProducerIdentifier(final DataNode cmHandleDataNode,
146 final NcmpServiceCmHandle ncmpServiceCmHandle) {
147 final String targetDataProducerIdentifier = ncmpServiceCmHandle.getDataProducerIdentifier();
148 final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
150 if (StringUtils.isBlank(targetDataProducerIdentifier)) {
151 log.warn("Ignoring update for cmHandle {}: target dataProducerIdentifier is null or blank.", cmHandleId);
155 final YangModelCmHandle currentYangModelCmHandle = YangDataConverter.toYangModelCmHandle(cmHandleDataNode);
156 final String currentDataProducerIdentifier = currentYangModelCmHandle.getDataProducerIdentifier();
158 if (currentDataProducerIdentifier.equals(targetDataProducerIdentifier)) {
159 log.debug("Ignoring update as dataProducerIdentifier for cmHandle {} is already set to {}.", cmHandleId,
160 targetDataProducerIdentifier);
163 setAndUpdateCmHandleField(cmHandleId, "data-producer-identifier", targetDataProducerIdentifier);
164 log.debug("dataProducerIdentifier for cmHandle {} updated from {} to {}", cmHandleId,
165 currentDataProducerIdentifier, targetDataProducerIdentifier);
166 sendLcmEventForDataProducerIdentifier(cmHandleId, currentYangModelCmHandle);
169 private void sendLcmEventForDataProducerIdentifier(final String cmHandleId,
170 final YangModelCmHandle currentYangModelCmHandle) {
171 final YangModelCmHandle updatedYangModelCmHandle = inventoryPersistence.getYangModelCmHandle(cmHandleId);
172 final CmHandleTransitionPair cmHandleTransitionPair =
173 new CmHandleTransitionPair(currentYangModelCmHandle, updatedYangModelCmHandle);
174 lcmEventsHelper.sendLcmEventBatchAsynchronously(List.of(cmHandleTransitionPair));
177 private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
178 final Map<String, String> updatedProperties) {
179 final Collection<DataNode> replacementPropertyDataNodes =
180 getReplacementDataNodes(existingCmHandleDataNode, propertyType, updatedProperties);
181 replacementPropertyDataNodes.addAll(
182 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, updatedProperties));
183 if (replacementPropertyDataNodes.isEmpty()) {
184 removeAllProperties(existingCmHandleDataNode, propertyType);
186 inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
190 private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
191 existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
192 final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
193 if (matcher.find()) {
194 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
195 inventoryPersistence.deleteDataNode(dataNode.getXpath());
200 private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
201 final PropertyType propertyType,
202 final Map<String, String> updatedProperties) {
203 final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
204 for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
205 final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
206 if (matcher.find()) {
207 final String keyName = matcher.group(2);
208 if (!updatedProperties.containsKey(keyName)) {
209 unchangedPropertyDataNodes.add(existingPropertyDataNode);
213 return unchangedPropertyDataNodes;
216 private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
217 final PropertyType propertyType,
218 final Map<String, String> updatedProperties) {
219 final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
220 updatedProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
221 final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
222 if (updatedAttributeValue != null) {
223 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
224 updatedAttributeKey, updatedAttributeValue);
225 replacementPropertyDataNodes.add(
226 buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
229 return replacementPropertyDataNodes;
232 private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
233 final String attributeKey) {
234 return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
237 private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
238 final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
239 updatedLeaves.put("name", attributeKey);
240 updatedLeaves.put("value", attributeValue);
241 log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
243 return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
246 private void setAndUpdateCmHandleField(final String cmHandleIdToUpdate, final String fieldName,
247 final String newFieldValue) {
248 final Map<String, Map<String, String>> dmiRegistryData = new HashMap<>(1);
249 final Map<String, String> cmHandleData = new HashMap<>(2);
250 cmHandleData.put("id", cmHandleIdToUpdate);
251 cmHandleData.put(fieldName, newFieldValue);
252 dmiRegistryData.put("cm-handles", cmHandleData);
253 cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
254 jsonObjectMapper.asJsonString(dmiRegistryData), OffsetDateTime.now(), ContentType.JSON);
255 log.debug("Updating {} for cmHandle {} with value : {})", fieldName, cmHandleIdToUpdate, newFieldValue);
259 ADDITIONAL_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
261 private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
263 final String xpathPrefix;
264 final Pattern propertyXpathPattern;
266 PropertyType(final String xpathPrefix) {
267 this.xpathPrefix = xpathPrefix;
268 this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);