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.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;
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 {
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;
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.
82 * @param updatedNcmpServiceCmHandles collection of CmHandles
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)) {
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,
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));
115 return cmHandleRegistrationResponses;
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());
126 if (!updatedNcmpServiceCmHandle.getAdditionalProperties().isEmpty()) {
127 updateProperties(existingCmHandleDataNode, ADDITIONAL_PROPERTY,
128 updatedNcmpServiceCmHandle.getAdditionalProperties());
132 private void updateAlternateId(final NcmpServiceCmHandle ncmpServiceCmHandle) {
133 final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
134 final String newAlternateId = ncmpServiceCmHandle.getAlternateId();
135 if (StringUtils.isNotBlank(newAlternateId)) {
136 setAndUpdateCmHandleField(ncmpServiceCmHandle.getCmHandleId(), "alternate-id", newAlternateId);
137 cmHandleIdPerAlternateId.delete(cmHandleId);
138 cmHandleIdPerAlternateId.set(newAlternateId, cmHandleId);
142 private void updateDataProducerIdentifier(final DataNode cmHandleDataNode,
143 final NcmpServiceCmHandle ncmpServiceCmHandle) {
144 final String newDataProducerIdentifier = ncmpServiceCmHandle.getDataProducerIdentifier();
145 if (StringUtils.isNotBlank(newDataProducerIdentifier)) {
146 final YangModelCmHandle yangModelCmHandle = YangDataConverter.toYangModelCmHandle(cmHandleDataNode);
147 final String existingDataProducerIdentifier = yangModelCmHandle.getDataProducerIdentifier();
148 if (StringUtils.isNotBlank(existingDataProducerIdentifier)) {
149 if (!existingDataProducerIdentifier.equals(newDataProducerIdentifier)) {
150 log.warn("Unable to update dataProducerIdentifier for cmHandle {}. "
151 + "Value for dataProducerIdentifier has been set previously.",
152 ncmpServiceCmHandle.getCmHandleId());
154 log.debug("dataProducerIdentifier for cmHandle {} is already set to {}.",
155 ncmpServiceCmHandle.getCmHandleId(), newDataProducerIdentifier);
158 setAndUpdateCmHandleField(
159 yangModelCmHandle.getId(), "data-producer-identifier", newDataProducerIdentifier);
164 private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
165 final Map<String, String> updatedProperties) {
166 final Collection<DataNode> replacementPropertyDataNodes =
167 getReplacementDataNodes(existingCmHandleDataNode, propertyType, updatedProperties);
168 replacementPropertyDataNodes.addAll(
169 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, updatedProperties));
170 if (replacementPropertyDataNodes.isEmpty()) {
171 removeAllProperties(existingCmHandleDataNode, propertyType);
173 inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
177 private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
178 existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
179 final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
180 if (matcher.find()) {
181 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
182 inventoryPersistence.deleteDataNode(dataNode.getXpath());
187 private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
188 final PropertyType propertyType,
189 final Map<String, String> updatedProperties) {
190 final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
191 for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
192 final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
193 if (matcher.find()) {
194 final String keyName = matcher.group(2);
195 if (!updatedProperties.containsKey(keyName)) {
196 unchangedPropertyDataNodes.add(existingPropertyDataNode);
200 return unchangedPropertyDataNodes;
203 private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
204 final PropertyType propertyType,
205 final Map<String, String> updatedProperties) {
206 final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
207 updatedProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
208 final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
209 if (updatedAttributeValue != null) {
210 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
211 updatedAttributeKey, updatedAttributeValue);
212 replacementPropertyDataNodes.add(
213 buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
216 return replacementPropertyDataNodes;
219 private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
220 final String attributeKey) {
221 return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
224 private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
225 final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
226 updatedLeaves.put("name", attributeKey);
227 updatedLeaves.put("value", attributeValue);
228 log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
230 return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
233 private void setAndUpdateCmHandleField(final String cmHandleIdToUpdate, final String fieldName,
234 final String newFieldValue) {
235 final Map<String, Map<String, String>> dmiRegistryData = new HashMap<>(1);
236 final Map<String, String> cmHandleData = new HashMap<>(2);
237 cmHandleData.put("id", cmHandleIdToUpdate);
238 cmHandleData.put(fieldName, newFieldValue);
239 dmiRegistryData.put("cm-handles", cmHandleData);
240 cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
241 jsonObjectMapper.asJsonString(dmiRegistryData), OffsetDateTime.now(), ContentType.JSON);
242 log.debug("Updating {} for cmHandle {} with value : {})", fieldName, cmHandleIdToUpdate, newFieldValue);
246 ADDITIONAL_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
248 private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
250 final String xpathPrefix;
251 final Pattern propertyXpathPattern;
253 PropertyType(final String xpathPrefix) {
254 this.xpathPrefix = xpathPrefix;
255 this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);