Additional validation for names/identifiers
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServicePropertyHandler.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
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.api.impl;
23
24 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.DMI_PROPERTY;
25 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
26 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DATASPACE_NAME;
27 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_ANCHOR;
28 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_PARENT;
29 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NO_TIMESTAMP;
30
31 import com.google.common.collect.ImmutableMap;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.HashSet;
35 import java.util.LinkedHashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40 import lombok.RequiredArgsConstructor;
41 import lombok.extern.slf4j.Slf4j;
42 import org.onap.cps.api.CpsDataService;
43 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
44 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError;
45 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
46 import org.onap.cps.spi.FetchDescendantsOption;
47 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
48 import org.onap.cps.spi.exceptions.DataValidationException;
49 import org.onap.cps.spi.model.DataNode;
50 import org.onap.cps.spi.model.DataNodeBuilder;
51 import org.onap.cps.utils.CpsValidator;
52 import org.springframework.stereotype.Service;
53
54 @Slf4j
55 @Service
56 @RequiredArgsConstructor
57 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
58 @SuppressWarnings("squid:S5852")
59 public class NetworkCmProxyDataServicePropertyHandler {
60
61     private static final String CM_HANDLE_XPATH_TEMPLATE = NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='%s']";
62
63     private final CpsDataService cpsDataService;
64
65     /**
66      * Iterates over incoming ncmpServiceCmHandles and update the dataNodes based on the updated attributes.
67      * The attributes which are not passed will remain as is.
68      *
69      * @param ncmpServiceCmHandles collection of ncmpServiceCmHandles
70      */
71     public List<CmHandleRegistrationResponse> updateCmHandleProperties(
72         final Collection<NcmpServiceCmHandle> ncmpServiceCmHandles) {
73         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>();
74         for (final NcmpServiceCmHandle ncmpServiceCmHandle : ncmpServiceCmHandles) {
75             final String cmHandle = ncmpServiceCmHandle.getCmHandleID();
76             try {
77                 CpsValidator.validateNameCharacters(cmHandle);
78                 final String cmHandleXpath = String.format(CM_HANDLE_XPATH_TEMPLATE, cmHandle);
79                 final DataNode existingCmHandleDataNode =
80                         cpsDataService.getDataNode(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, cmHandleXpath,
81                                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
82                 processUpdates(existingCmHandleDataNode, ncmpServiceCmHandle);
83                 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandle));
84             } catch (final DataNodeNotFoundException e) {
85                 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
86                     cmHandle, e.getMessage());
87                 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse
88                     .createFailureResponse(cmHandle, RegistrationError.CM_HANDLE_DOES_NOT_EXIST));
89             } catch (final DataValidationException e) {
90                 log.error("Unable to update cm handle : {}, caused by : {}",
91                     cmHandle, e.getMessage());
92                 cmHandleRegistrationResponses.add(
93                     CmHandleRegistrationResponse.createFailureResponse(cmHandle,
94                         RegistrationError.CM_HANDLE_INVALID_ID));
95             } catch (final Exception exception) {
96                 log.error("Unable to update cmHandle : {} , caused by : {}",
97                     cmHandle, exception.getMessage());
98                 cmHandleRegistrationResponses.add(
99                     CmHandleRegistrationResponse.createFailureResponse(cmHandle, exception));
100             }
101         }
102         return cmHandleRegistrationResponses;
103     }
104
105     private void processUpdates(final DataNode existingCmHandleDataNode, final NcmpServiceCmHandle incomingCmHandle) {
106         if (!incomingCmHandle.getPublicProperties().isEmpty()) {
107             updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY, incomingCmHandle.getPublicProperties());
108         }
109         if (!incomingCmHandle.getDmiProperties().isEmpty()) {
110             updateProperties(existingCmHandleDataNode, DMI_PROPERTY, incomingCmHandle.getDmiProperties());
111         }
112     }
113
114     private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
115             final Map<String, String> incomingProperties) {
116         final Collection<DataNode> replacementPropertyDataNodes =
117                 getReplacementDataNodes(existingCmHandleDataNode, propertyType, incomingProperties);
118         replacementPropertyDataNodes.addAll(
119                 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, incomingProperties));
120         if (replacementPropertyDataNodes.isEmpty()) {
121             removeAllProperties(existingCmHandleDataNode, propertyType);
122         } else {
123             cpsDataService.replaceListContent(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
124                     existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes, NO_TIMESTAMP);
125         }
126     }
127
128     private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
129         existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
130             final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
131             if (matcher.find()) {
132                 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
133                 cpsDataService.deleteDataNode(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, dataNode.getXpath(),
134                         NO_TIMESTAMP);
135             }
136         });
137     }
138
139     private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
140             final PropertyType propertyType, final Map<String, String> incomingProperties) {
141         final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
142         for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
143             final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
144             if (matcher.find()) {
145                 final String keyName = matcher.group(2);
146                 if (!incomingProperties.containsKey(keyName)) {
147                     unchangedPropertyDataNodes.add(existingPropertyDataNode);
148                 }
149             }
150         }
151         return unchangedPropertyDataNodes;
152     }
153
154     private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
155             final PropertyType propertyType, final Map<String, String> incomingProperties) {
156         final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
157         incomingProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
158             final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
159             if (updatedAttributeValue != null) {
160                 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
161                         updatedAttributeKey, updatedAttributeValue);
162                 replacementPropertyDataNodes.add(
163                         buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
164             }
165         });
166         return replacementPropertyDataNodes;
167     }
168
169     private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
170             final String attributeKey) {
171         return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
172     }
173
174     private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
175         final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
176         updatedLeaves.put("name", attributeKey);
177         updatedLeaves.put("value", attributeValue);
178         log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
179                 attributeValue);
180         return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
181     }
182
183     enum PropertyType {
184         DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
185
186         private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
187
188         final String xpathPrefix;
189         final Pattern propertyXpathPattern;
190
191         PropertyType(final String xpathPrefix) {
192             this.xpathPrefix = xpathPrefix;
193             this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);
194         }
195     }
196 }