2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2022 Nordix Foundation
4 * Modifications Copyright (C) 2021 Pantheon.tech
5 * Modifications Copyright (C) 2020-2022 Bell Canada.
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.spi.impl;
25 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
27 import com.google.common.collect.ImmutableSet;
28 import com.google.common.collect.ImmutableSet.Builder;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import javax.transaction.Transactional;
40 import lombok.RequiredArgsConstructor;
41 import lombok.extern.slf4j.Slf4j;
42 import org.hibernate.StaleStateException;
43 import org.onap.cps.cpspath.parser.CpsPathQuery;
44 import org.onap.cps.spi.CpsDataPersistenceService;
45 import org.onap.cps.spi.FetchDescendantsOption;
46 import org.onap.cps.spi.entities.AnchorEntity;
47 import org.onap.cps.spi.entities.DataspaceEntity;
48 import org.onap.cps.spi.entities.FragmentEntity;
49 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
50 import org.onap.cps.spi.exceptions.ConcurrencyException;
51 import org.onap.cps.spi.exceptions.CpsAdminException;
52 import org.onap.cps.spi.exceptions.CpsPathException;
53 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
54 import org.onap.cps.spi.model.DataNode;
55 import org.onap.cps.spi.model.DataNodeBuilder;
56 import org.onap.cps.spi.repository.AnchorRepository;
57 import org.onap.cps.spi.repository.DataspaceRepository;
58 import org.onap.cps.spi.repository.FragmentRepository;
59 import org.onap.cps.utils.JsonObjectMapper;
60 import org.springframework.dao.DataIntegrityViolationException;
61 import org.springframework.stereotype.Service;
65 @RequiredArgsConstructor
66 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
68 private final DataspaceRepository dataspaceRepository;
70 private final AnchorRepository anchorRepository;
72 private final FragmentRepository fragmentRepository;
74 private final JsonObjectMapper jsonObjectMapper;
76 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
77 private static final Pattern REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE =
78 Pattern.compile("\\[(\\@([^\\/]{0,9999}))\\]$");
82 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
83 final DataNode newChildDataNode) {
84 addChildDataNodes(dataspaceName, anchorName, parentNodeXpath, Collections.singleton(newChildDataNode));
89 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
90 final Collection<DataNode> newListElements) {
91 addChildDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
94 private void addChildDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
95 final Collection<DataNode> newChildren) {
96 final FragmentEntity parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
98 for (final DataNode newChildAsDataNode : newChildren) {
99 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(
100 parentFragmentEntity.getDataspace(),
101 parentFragmentEntity.getAnchor(),
103 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
104 fragmentRepository.save(newChildAsFragmentEntity);
106 } catch (final DataIntegrityViolationException exception) {
107 final List<String> conflictXpaths = newChildren.stream()
108 .map(DataNode::getXpath)
109 .collect(Collectors.toList());
110 throw AlreadyDefinedException.forDataNodes(conflictXpaths, anchorName, exception);
115 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
116 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
117 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
118 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
121 fragmentRepository.save(fragmentEntity);
122 } catch (final DataIntegrityViolationException exception) {
123 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
128 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
129 * for all DataNode children recursively.
131 * @param dataspaceEntity dataspace
132 * @param anchorEntity anchorEntity
133 * @param dataNodeToBeConverted dataNode
134 * @return a Fragment built from current DataNode
136 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
137 final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
138 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
139 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
140 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
141 final FragmentEntity childFragment =
142 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
144 childFragmentsImmutableSetBuilder.add(childFragment);
146 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
147 return parentFragment;
150 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
151 final AnchorEntity anchorEntity, final DataNode dataNode) {
152 return FragmentEntity.builder()
153 .dataspace(dataspaceEntity)
154 .anchor(anchorEntity)
155 .xpath(dataNode.getXpath())
156 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
161 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
162 final FetchDescendantsOption fetchDescendantsOption) {
163 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
164 return toDataNode(fragmentEntity, fetchDescendantsOption);
167 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
168 final String xpath) {
169 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
170 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
171 if (isRootXpath(xpath)) {
172 return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
174 return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
180 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
181 final FetchDescendantsOption fetchDescendantsOption) {
182 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
183 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
184 final CpsPathQuery cpsPathQuery;
186 cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
187 } catch (final IllegalStateException e) {
188 throw new CpsPathException(e.getMessage());
190 List<FragmentEntity> fragmentEntities =
191 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
192 if (cpsPathQuery.hasAncestorAxis()) {
193 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
194 fragmentEntities = ancestorXpaths.isEmpty()
195 ? Collections.emptyList() : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
197 return fragmentEntities.stream()
198 .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
199 .collect(Collectors.toUnmodifiableList());
202 private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
203 final CpsPathQuery cpsPathQuery) {
204 final Set<String> ancestorXpath = new HashSet<>();
205 final Pattern pattern =
206 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
207 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
208 for (final FragmentEntity fragmentEntity : fragmentEntities) {
209 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
210 if (matcher.matches()) {
211 ancestorXpath.add(matcher.group(1));
214 return ancestorXpath;
217 private DataNode toDataNode(final FragmentEntity fragmentEntity,
218 final FetchDescendantsOption fetchDescendantsOption) {
219 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
220 Map<String, Object> leaves = new HashMap<>();
221 if (fragmentEntity.getAttributes() != null) {
222 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
224 return new DataNodeBuilder()
225 .withXpath(fragmentEntity.getXpath())
227 .withChildDataNodes(childDataNodes).build();
230 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
231 final FetchDescendantsOption fetchDescendantsOption) {
232 if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
233 return fragmentEntity.getChildFragments().stream()
234 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
235 .collect(Collectors.toUnmodifiableList());
237 return Collections.emptyList();
241 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
242 final Map<String, Object> leaves) {
243 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
244 fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
245 fragmentRepository.save(fragmentEntity);
249 public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
250 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
251 replaceDataNodeTree(fragmentEntity, dataNode);
253 fragmentRepository.save(fragmentEntity);
254 } catch (final StaleStateException staleStateException) {
255 throw new ConcurrencyException("Concurrent Transactions",
256 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
257 dataspaceName, anchorName, dataNode.getXpath()),
258 staleStateException);
262 private void replaceDataNodeTree(final FragmentEntity existingFragmentEntity,
263 final DataNode newDataNode) {
265 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
267 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
268 .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
270 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
272 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
273 final FragmentEntity childFragment;
274 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
275 childFragment = convertToFragmentWithAllDescendants(
276 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
278 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
279 replaceDataNodeTree(childFragment, newDataNodeChild);
281 updatedChildFragments.add(childFragment);
283 existingFragmentEntity.getChildFragments().clear();
284 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
289 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
290 final Collection<DataNode> newListElements) {
291 final FragmentEntity parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
292 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
293 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
294 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
295 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
296 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
297 for (final DataNode newListElement : newListElements) {
298 final FragmentEntity existingListElementEntity =
299 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
300 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
301 existingListElementEntity);
303 updatedChildFragmentEntities.add(entityToBeAdded);
305 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
306 fragmentRepository.save(parentEntity);
311 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
312 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
313 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
315 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
320 public void deleteListDataNode(final String dataspaceName, final String anchorName,
321 final String targetXpath) {
322 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
327 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
328 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
331 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
332 final boolean onlySupportListNodeDeletion) {
333 final String parentNodeXpath;
334 FragmentEntity parentFragmentEntity = null;
335 boolean targetDeleted = false;
336 if (isRootXpath(targetXpath)) {
337 deleteDataNodes(dataspaceName, anchorName);
338 targetDeleted = true;
340 if (isContainerNodeXpath(targetXpath)) {
341 parentNodeXpath = targetXpath;
343 parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
345 parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
346 final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
347 final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE
348 .matcher(lastXpathElement).find();
350 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
352 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
353 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
354 if (tryToDeleteDataNode) {
355 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
359 if (!targetDeleted) {
360 final String additionalInformation = onlySupportListNodeDeletion
361 ? "The target is probably not a List." : "";
362 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
363 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
367 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
368 if (parentFragmentEntity.getXpath().equals(targetXpath)) {
369 fragmentRepository.delete(parentFragmentEntity);
372 if (parentFragmentEntity.getChildFragments()
373 .removeIf(fragment -> fragment.getXpath().equals(targetXpath))) {
374 fragmentRepository.save(parentFragmentEntity);
380 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
381 final String deleteTargetXpathPrefix = listXpath + "[";
382 if (parentFragmentEntity.getChildFragments()
383 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
384 fragmentRepository.save(parentFragmentEntity);
390 private static void deleteListElements(
391 final Collection<FragmentEntity> fragmentEntities,
392 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
393 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
396 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
397 if (newListElements.isEmpty()) {
398 throw new CpsAdminException("Invalid list replacement",
399 "Cannot replace list elements with empty collection");
401 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
402 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
405 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
406 final DataNode newListElement,
407 final FragmentEntity existingListElementEntity) {
408 if (existingListElementEntity == null) {
409 return convertToFragmentWithAllDescendants(
410 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
412 if (newListElement.getChildDataNodes().isEmpty()) {
413 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
414 existingListElementEntity.getChildFragments().clear();
416 replaceDataNodeTree(existingListElementEntity, newListElement);
418 return existingListElementEntity;
421 private static boolean isNewDataNode(final DataNode replacementDataNode,
422 final Map<String, FragmentEntity> existingListElementsByXpath) {
423 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
426 private static boolean isContainerNodeXpath(final String xpath) {
427 return 0 == xpath.lastIndexOf('/');
430 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
431 final DataNode newListElement) {
432 final FragmentEntity replacementFragmentEntity =
433 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
434 newListElement.getLeaves())).build();
435 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
438 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
439 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
440 return childEntities.stream()
441 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
442 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
445 private static boolean isRootXpath(final String xpath) {
446 return "/".equals(xpath) || "".equals(xpath);