2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2022-2024 Nordix Foundation
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.ncmp.api.NcmpResponseStatus.ALTERNATE_ID_ALREADY_ASSOCIATED;
26 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
27 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
28 import static org.onap.cps.ncmp.impl.inventory.CmHandleRegistrationServicePropertyHandler.PropertyType.DMI_PROPERTY;
29 import static org.onap.cps.ncmp.impl.inventory.CmHandleRegistrationServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
30 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME;
31 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
32 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
34 import com.google.common.collect.ImmutableMap;
35 import java.time.OffsetDateTime;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.LinkedHashMap;
41 import java.util.List;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import lombok.RequiredArgsConstructor;
46 import lombok.extern.slf4j.Slf4j;
47 import org.apache.commons.lang3.StringUtils;
48 import org.onap.cps.api.CpsDataService;
49 import org.onap.cps.api.exceptions.DataNodeNotFoundException;
50 import org.onap.cps.api.exceptions.DataValidationException;
51 import org.onap.cps.api.model.DataNode;
52 import org.onap.cps.api.model.DataNodeBuilder;
53 import org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse;
54 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle;
55 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle;
56 import org.onap.cps.ncmp.impl.utils.YangDataConverter;
57 import org.onap.cps.utils.ContentType;
58 import org.onap.cps.utils.JsonObjectMapper;
59 import org.springframework.stereotype.Service;
63 @RequiredArgsConstructor
64 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
65 @SuppressWarnings("squid:S5852")
66 public class CmHandleRegistrationServicePropertyHandler {
68 private final InventoryPersistence inventoryPersistence;
69 private final CpsDataService cpsDataService;
70 private final JsonObjectMapper jsonObjectMapper;
71 private final AlternateIdChecker alternateIdChecker;
74 * Iterates over incoming updatedNcmpServiceCmHandles and update the dataNodes based on the updated attributes.
75 * The attributes which are not passed will remain as is.
77 * @param updatedNcmpServiceCmHandles collection of CmHandles
79 public List<CmHandleRegistrationResponse> updateCmHandleProperties(
80 final Collection<NcmpServiceCmHandle> updatedNcmpServiceCmHandles) {
81 final Collection<String> rejectedCmHandleIds = alternateIdChecker
82 .getIdsOfCmHandlesWithRejectedAlternateId(updatedNcmpServiceCmHandles, AlternateIdChecker.Operation.UPDATE);
83 final List<CmHandleRegistrationResponse> failureResponses =
84 CmHandleRegistrationResponse.createFailureResponses(rejectedCmHandleIds, ALTERNATE_ID_ALREADY_ASSOCIATED);
85 final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>(failureResponses);
86 for (final NcmpServiceCmHandle updatedNcmpServiceCmHandle : updatedNcmpServiceCmHandles) {
87 final String cmHandleId = updatedNcmpServiceCmHandle.getCmHandleId();
88 if (!rejectedCmHandleIds.contains(cmHandleId)) {
90 final DataNode existingCmHandleDataNode = inventoryPersistence
91 .getCmHandleDataNodeByCmHandleId(cmHandleId).iterator().next();
92 processUpdates(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
93 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
94 } catch (final DataNodeNotFoundException e) {
95 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId,
97 cmHandleRegistrationResponses.add(
98 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
99 } catch (final DataValidationException e) {
100 log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
101 cmHandleRegistrationResponses.add(
102 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
103 } catch (final Exception exception) {
104 log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
105 cmHandleRegistrationResponses.add(
106 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
110 return cmHandleRegistrationResponses;
113 private void processUpdates(final DataNode existingCmHandleDataNode,
114 final NcmpServiceCmHandle updatedNcmpServiceCmHandle) {
115 updateAlternateId(updatedNcmpServiceCmHandle);
116 updateDataProducerIdentifier(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
117 if (!updatedNcmpServiceCmHandle.getPublicProperties().isEmpty()) {
118 updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY,
119 updatedNcmpServiceCmHandle.getPublicProperties());
121 if (!updatedNcmpServiceCmHandle.getDmiProperties().isEmpty()) {
122 updateProperties(existingCmHandleDataNode, DMI_PROPERTY, updatedNcmpServiceCmHandle.getDmiProperties());
126 private void updateAlternateId(final NcmpServiceCmHandle ncmpServiceCmHandle) {
127 final String newAlternateId = ncmpServiceCmHandle.getAlternateId();
128 if (StringUtils.isNotBlank(newAlternateId)) {
129 setAndUpdateCmHandleField(ncmpServiceCmHandle.getCmHandleId(), "alternate-id", newAlternateId);
133 private void updateDataProducerIdentifier(final DataNode cmHandleDataNode,
134 final NcmpServiceCmHandle ncmpServiceCmHandle) {
135 final String newDataProducerIdentifier = ncmpServiceCmHandle.getDataProducerIdentifier();
136 if (StringUtils.isNotBlank(newDataProducerIdentifier)) {
137 final YangModelCmHandle yangModelCmHandle = YangDataConverter.toYangModelCmHandle(cmHandleDataNode);
138 final String existingDataProducerIdentifier = yangModelCmHandle.getDataProducerIdentifier();
139 if (StringUtils.isNotBlank(existingDataProducerIdentifier)) {
140 if (!existingDataProducerIdentifier.equals(newDataProducerIdentifier)) {
141 log.warn("Unable to update dataProducerIdentifier for cmHandle {}. "
142 + "Value for dataProducerIdentifier has been set previously.",
143 ncmpServiceCmHandle.getCmHandleId());
145 log.debug("dataProducerIdentifier for cmHandle {} is already set to {}.",
146 ncmpServiceCmHandle.getCmHandleId(), newDataProducerIdentifier);
149 setAndUpdateCmHandleField(
150 yangModelCmHandle.getId(), "data-producer-identifier", newDataProducerIdentifier);
155 private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
156 final Map<String, String> updatedProperties) {
157 final Collection<DataNode> replacementPropertyDataNodes =
158 getReplacementDataNodes(existingCmHandleDataNode, propertyType, updatedProperties);
159 replacementPropertyDataNodes.addAll(
160 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, updatedProperties));
161 if (replacementPropertyDataNodes.isEmpty()) {
162 removeAllProperties(existingCmHandleDataNode, propertyType);
164 inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
168 private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
169 existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
170 final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
171 if (matcher.find()) {
172 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
173 inventoryPersistence.deleteDataNode(dataNode.getXpath());
178 private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
179 final PropertyType propertyType,
180 final Map<String, String> updatedProperties) {
181 final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
182 for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
183 final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
184 if (matcher.find()) {
185 final String keyName = matcher.group(2);
186 if (!updatedProperties.containsKey(keyName)) {
187 unchangedPropertyDataNodes.add(existingPropertyDataNode);
191 return unchangedPropertyDataNodes;
194 private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
195 final PropertyType propertyType,
196 final Map<String, String> updatedProperties) {
197 final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
198 updatedProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
199 final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
200 if (updatedAttributeValue != null) {
201 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
202 updatedAttributeKey, updatedAttributeValue);
203 replacementPropertyDataNodes.add(
204 buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
207 return replacementPropertyDataNodes;
210 private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
211 final String attributeKey) {
212 return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
215 private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
216 final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
217 updatedLeaves.put("name", attributeKey);
218 updatedLeaves.put("value", attributeValue);
219 log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
221 return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
224 private void setAndUpdateCmHandleField(final String cmHandleIdToUpdate, final String fieldName,
225 final String newFieldValue) {
226 final Map<String, Map<String, String>> dmiRegistryData = new HashMap<>(1);
227 final Map<String, String> cmHandleData = new HashMap<>(2);
228 cmHandleData.put("id", cmHandleIdToUpdate);
229 cmHandleData.put(fieldName, newFieldValue);
230 dmiRegistryData.put("cm-handles", cmHandleData);
231 cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
232 jsonObjectMapper.asJsonString(dmiRegistryData), OffsetDateTime.now(), ContentType.JSON);
233 log.debug("Updating {} for cmHandle {} with value : {})", fieldName, cmHandleIdToUpdate, newFieldValue);
237 DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
239 private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
241 final String xpathPrefix;
242 final Pattern propertyXpathPattern;
244 PropertyType(final String xpathPrefix) {
245 this.xpathPrefix = xpathPrefix;
246 this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);