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 * Modifications Copyright (C) 2022 TechMahindra Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl;
26 import com.google.common.collect.ImmutableSet;
27 import com.google.common.collect.ImmutableSet.Builder;
28 import java.io.Serializable;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
39 import java.util.stream.Collectors;
40 import javax.transaction.Transactional;
41 import lombok.RequiredArgsConstructor;
42 import lombok.extern.slf4j.Slf4j;
43 import org.hibernate.StaleStateException;
44 import org.onap.cps.cpspath.parser.CpsPathQuery;
45 import org.onap.cps.cpspath.parser.CpsPathUtil;
46 import org.onap.cps.cpspath.parser.PathParsingException;
47 import org.onap.cps.spi.CpsDataPersistenceService;
48 import org.onap.cps.spi.FetchDescendantsOption;
49 import org.onap.cps.spi.entities.AnchorEntity;
50 import org.onap.cps.spi.entities.DataspaceEntity;
51 import org.onap.cps.spi.entities.FragmentEntity;
52 import org.onap.cps.spi.entities.FragmentEntityArranger;
53 import org.onap.cps.spi.entities.FragmentExtract;
54 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
55 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
56 import org.onap.cps.spi.exceptions.ConcurrencyException;
57 import org.onap.cps.spi.exceptions.CpsAdminException;
58 import org.onap.cps.spi.exceptions.CpsPathException;
59 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
60 import org.onap.cps.spi.model.DataNode;
61 import org.onap.cps.spi.model.DataNodeBuilder;
62 import org.onap.cps.spi.repository.AnchorRepository;
63 import org.onap.cps.spi.repository.DataspaceRepository;
64 import org.onap.cps.spi.repository.FragmentRepository;
65 import org.onap.cps.spi.utils.SessionManager;
66 import org.onap.cps.utils.JsonObjectMapper;
67 import org.springframework.dao.DataIntegrityViolationException;
68 import org.springframework.stereotype.Service;
72 @RequiredArgsConstructor
73 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
75 private final DataspaceRepository dataspaceRepository;
76 private final AnchorRepository anchorRepository;
77 private final FragmentRepository fragmentRepository;
78 private final JsonObjectMapper jsonObjectMapper;
79 private final SessionManager sessionManager;
81 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
82 private static final Pattern REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE =
83 Pattern.compile("\\[(\\@([^\\/]{0,9999}))\\]$");
84 private static final String TOP_LEVEL_MODULE_PREFIX_PROPERTY_NAME = "topLevelModulePrefix";
87 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
88 final DataNode newChildDataNode) {
89 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
93 public void addChildDataNodes(final String dataspaceName, final String anchorName,
94 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
95 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
99 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
100 final Collection<DataNode> newListElements) {
101 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
105 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
106 final Collection<Collection<DataNode>> newLists) {
107 final Collection<String> failedXpaths = new HashSet<>();
108 newLists.forEach(newList -> {
110 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
111 } catch (final AlreadyDefinedExceptionBatch e) {
112 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
116 if (!failedXpaths.isEmpty()) {
117 throw new AlreadyDefinedExceptionBatch(failedXpaths);
122 private void addNewChildDataNode(final String dataspaceName, final String anchorName,
123 final String parentNodeXpath, final DataNode newChild) {
124 final FragmentEntity parentFragmentEntity =
125 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
126 final FragmentEntity newChildAsFragmentEntity =
127 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
128 parentFragmentEntity.getAnchor(), newChild);
129 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
131 fragmentRepository.save(newChildAsFragmentEntity);
132 } catch (final DataIntegrityViolationException e) {
133 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
138 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
139 final Collection<DataNode> newChildren) {
140 final FragmentEntity parentFragmentEntity =
141 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
142 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
144 newChildren.forEach(newChildAsDataNode -> {
145 final FragmentEntity newChildAsFragmentEntity =
146 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
147 parentFragmentEntity.getAnchor(), newChildAsDataNode);
148 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
149 fragmentEntities.add(newChildAsFragmentEntity);
151 fragmentRepository.saveAll(fragmentEntities);
152 } catch (final DataIntegrityViolationException e) {
153 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
154 e, fragmentEntities.size());
155 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
159 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
160 final String parentNodeXpath,
161 final Collection<DataNode> newChildren) {
162 final Collection<String> failedXpaths = new HashSet<>();
163 for (final DataNode newChild : newChildren) {
165 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
166 } catch (final AlreadyDefinedException e) {
167 failedXpaths.add(newChild.getXpath());
170 if (!failedXpaths.isEmpty()) {
171 throw new AlreadyDefinedExceptionBatch(failedXpaths);
176 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
177 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
181 public void storeDataNodes(final String dataspaceName, final String anchorName,
182 final Collection<DataNode> dataNodes) {
183 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
184 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
185 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
187 for (final DataNode dataNode: dataNodes) {
188 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
190 fragmentEntities.add(fragmentEntity);
192 fragmentRepository.saveAll(fragmentEntities);
193 } catch (final DataIntegrityViolationException exception) {
194 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
195 exception, dataNodes.size());
196 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
200 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
201 final Collection<DataNode> dataNodes) {
202 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
203 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
204 final Collection<String> failedXpaths = new HashSet<>();
205 for (final DataNode dataNode: dataNodes) {
207 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
209 fragmentRepository.save(fragmentEntity);
210 } catch (final DataIntegrityViolationException e) {
211 failedXpaths.add(dataNode.getXpath());
214 if (!failedXpaths.isEmpty()) {
215 throw new AlreadyDefinedExceptionBatch(failedXpaths);
220 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
221 * for all DataNode children recursively.
223 * @param dataspaceEntity dataspace
224 * @param anchorEntity anchorEntity
225 * @param dataNodeToBeConverted dataNode
226 * @return a Fragment built from current DataNode
228 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
229 final AnchorEntity anchorEntity,
230 final DataNode dataNodeToBeConverted) {
231 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
232 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
233 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
234 final FragmentEntity childFragment =
235 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
237 childFragmentsImmutableSetBuilder.add(childFragment);
239 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
240 return parentFragment;
243 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
244 final AnchorEntity anchorEntity, final DataNode dataNode) {
245 return FragmentEntity.builder()
246 .dataspace(dataspaceEntity)
247 .anchor(anchorEntity)
248 .xpath(dataNode.getXpath())
249 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
254 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
255 final FetchDescendantsOption fetchDescendantsOption) {
256 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
257 fetchDescendantsOption);
258 return toDataNode(fragmentEntity, fetchDescendantsOption);
261 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
262 final String anchorName,
263 final String xpath) {
264 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
267 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
268 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
269 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
270 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
271 if (isRootXpath(xpath)) {
272 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
274 return FragmentEntityArranger.toFragmentEntityTree(anchorEntity,
277 final String normalizedXpath = getNormalizedXpath(xpath);
278 final FragmentEntity fragmentEntity;
279 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
281 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
283 fragmentEntity = buildFragmentEntityFromFragmentExtracts(anchorEntity, normalizedXpath);
285 if (fragmentEntity == null) {
286 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
288 return fragmentEntity;
292 private FragmentEntity buildFragmentEntityFromFragmentExtracts(final AnchorEntity anchorEntity,
293 final String normalizedXpath) {
294 final FragmentEntity fragmentEntity;
295 final List<FragmentExtract> fragmentExtracts =
296 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
297 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
298 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
299 fragmentEntity = FragmentEntityArranger.toFragmentEntityTree(anchorEntity, fragmentExtracts);
300 return fragmentEntity;
304 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
305 final FetchDescendantsOption fetchDescendantsOption) {
306 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
307 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
308 final CpsPathQuery cpsPathQuery;
310 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
311 } catch (final PathParsingException e) {
312 throw new CpsPathException(e.getMessage());
314 List<FragmentEntity> fragmentEntities =
315 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
316 if (cpsPathQuery.hasAncestorAxis()) {
317 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
318 fragmentEntities = ancestorXpaths.isEmpty() ? Collections.emptyList()
319 : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
321 return createDataNodesFromFragmentEntities(fetchDescendantsOption, anchorEntity,
325 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
326 final AnchorEntity anchorEntity,
327 final List<FragmentEntity> fragmentEntities) {
328 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
329 for (final FragmentEntity proxiedFragmentEntity : fragmentEntities) {
330 final DataNode dataNode;
331 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
332 dataNode = toDataNode(proxiedFragmentEntity, fetchDescendantsOption);
334 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
335 final FragmentEntity unproxiedFragmentEntity = buildFragmentEntityFromFragmentExtracts(anchorEntity,
337 dataNode = toDataNode(unproxiedFragmentEntity, fetchDescendantsOption);
339 dataNodes.add(dataNode);
341 return Collections.unmodifiableList(dataNodes);
344 private static String getNormalizedXpath(final String xpathSource) {
345 final String normalizedXpath;
347 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
348 } catch (final PathParsingException e) {
349 throw new CpsPathException(e.getMessage());
351 return normalizedXpath;
355 public String startSession() {
356 return sessionManager.startSession();
360 public void closeSession(final String sessionId) {
361 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
365 public void lockAnchor(final String sessionId, final String dataspaceName,
366 final String anchorName, final Long timeoutInMilliseconds) {
367 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
370 private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
371 final CpsPathQuery cpsPathQuery) {
372 final Set<String> ancestorXpath = new HashSet<>();
373 final Pattern pattern =
374 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
375 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
376 for (final FragmentEntity fragmentEntity : fragmentEntities) {
377 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
378 if (matcher.matches()) {
379 ancestorXpath.add(matcher.group(1));
382 return ancestorXpath;
385 private DataNode toDataNode(final FragmentEntity fragmentEntity,
386 final FetchDescendantsOption fetchDescendantsOption) {
387 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
388 Map<String, Serializable> leaves = new HashMap<>();
389 if (fragmentEntity.getAttributes() != null) {
390 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
392 return new DataNodeBuilder()
393 .withXpath(fragmentEntity.getXpath())
395 .withChildDataNodes(childDataNodes).build();
398 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
399 final FetchDescendantsOption fetchDescendantsOption) {
400 if (fetchDescendantsOption.hasNext()) {
401 return fragmentEntity.getChildFragments().stream()
402 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
403 .collect(Collectors.toList());
405 return Collections.emptyList();
409 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
410 final Map<String, Serializable> leaves) {
411 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
412 fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
413 fragmentRepository.save(fragmentEntity);
417 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
418 final DataNode dataNode) {
419 final FragmentEntity fragmentEntity =
420 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
421 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
423 fragmentRepository.save(fragmentEntity);
424 } catch (final StaleStateException staleStateException) {
425 throw new ConcurrencyException("Concurrent Transactions",
426 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
427 dataspaceName, anchorName, dataNode.getXpath()));
432 public void updateDataNodesAndDescendants(final String dataspaceName,
433 final String anchorName,
434 final List<DataNode> dataNodes) {
436 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
437 .collect(Collectors.toMap(
438 dataNode -> dataNode,
440 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
441 dataNodeFragmentEntityMap.forEach(
442 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
444 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
445 } catch (final StaleStateException staleStateException) {
446 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
450 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
451 final Collection<FragmentEntity> fragmentEntities) {
452 final Collection<String> failedXpaths = new HashSet<>();
454 fragmentEntities.forEach(dataNodeFragment -> {
456 fragmentRepository.save(dataNodeFragment);
457 } catch (final StaleStateException e) {
458 failedXpaths.add(dataNodeFragment.getXpath());
462 if (!failedXpaths.isEmpty()) {
463 final String failedXpathsConcatenated = String.join(",", failedXpaths);
464 throw new ConcurrencyException("Concurrent Transactions", String.format(
465 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
466 failedXpathsConcatenated, dataspaceName, anchorName));
470 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
471 final DataNode newDataNode) {
473 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
475 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
476 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
478 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
480 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
481 final FragmentEntity childFragment;
482 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
483 childFragment = convertToFragmentWithAllDescendants(
484 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
486 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
487 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
489 updatedChildFragments.add(childFragment);
492 existingFragmentEntity.getChildFragments().clear();
493 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
498 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
499 final Collection<DataNode> newListElements) {
500 final FragmentEntity parentEntity =
501 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
502 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
503 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
504 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
505 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
506 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
507 for (final DataNode newListElement : newListElements) {
508 final FragmentEntity existingListElementEntity =
509 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
510 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
511 existingListElementEntity);
513 updatedChildFragmentEntities.add(entityToBeAdded);
515 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
516 fragmentRepository.save(parentEntity);
521 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
522 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
523 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
525 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
530 public void deleteListDataNode(final String dataspaceName, final String anchorName,
531 final String targetXpath) {
532 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
537 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
538 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
541 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
542 final boolean onlySupportListNodeDeletion) {
543 final String parentNodeXpath;
544 FragmentEntity parentFragmentEntity = null;
545 boolean targetDeleted;
546 if (isRootXpath(targetXpath)) {
547 deleteDataNodes(dataspaceName, anchorName);
548 targetDeleted = true;
550 if (isRootContainerNodeXpath(targetXpath)) {
551 parentNodeXpath = targetXpath;
553 parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
555 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
556 final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
557 final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE
558 .matcher(lastXpathElement).find();
560 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
562 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
563 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
564 if (tryToDeleteDataNode) {
565 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
569 if (!targetDeleted) {
570 final String additionalInformation = onlySupportListNodeDeletion
571 ? "The target is probably not a List." : "";
572 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
573 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
577 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
578 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
579 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
580 fragmentRepository.delete(parentFragmentEntity);
583 if (parentFragmentEntity.getChildFragments()
584 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
585 fragmentRepository.save(parentFragmentEntity);
591 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
592 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
593 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
594 if (parentFragmentEntity.getChildFragments()
595 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
596 fragmentRepository.save(parentFragmentEntity);
602 private static void deleteListElements(
603 final Collection<FragmentEntity> fragmentEntities,
604 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
605 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
608 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
609 if (newListElements.isEmpty()) {
610 throw new CpsAdminException("Invalid list replacement",
611 "Cannot replace list elements with empty collection");
613 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
614 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
617 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
618 final DataNode newListElement,
619 final FragmentEntity existingListElementEntity) {
620 if (existingListElementEntity == null) {
621 return convertToFragmentWithAllDescendants(
622 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
624 if (newListElement.getChildDataNodes().isEmpty()) {
625 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
626 existingListElementEntity.getChildFragments().clear();
628 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
630 return existingListElementEntity;
633 private static boolean isNewDataNode(final DataNode replacementDataNode,
634 final Map<String, FragmentEntity> existingListElementsByXpath) {
635 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
638 private static boolean isRootContainerNodeXpath(final String xpath) {
639 return 0 == xpath.lastIndexOf('/');
642 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
643 final DataNode newListElement) {
644 final FragmentEntity replacementFragmentEntity =
645 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
646 newListElement.getLeaves())).build();
647 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
650 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
651 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
652 return childEntities.stream()
653 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
654 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
657 private static boolean isRootXpath(final String xpath) {
658 return "/".equals(xpath) || "".equals(xpath);