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})";
84 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
85 final DataNode newChildDataNode) {
86 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
90 public void addChildDataNodes(final String dataspaceName, final String anchorName,
91 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
92 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
96 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
97 final Collection<DataNode> newListElements) {
98 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
102 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
103 final Collection<Collection<DataNode>> newLists) {
104 final Collection<String> failedXpaths = new HashSet<>();
105 newLists.forEach(newList -> {
107 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
108 } catch (final AlreadyDefinedExceptionBatch e) {
109 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
113 if (!failedXpaths.isEmpty()) {
114 throw new AlreadyDefinedExceptionBatch(failedXpaths);
119 private void addNewChildDataNode(final String dataspaceName, final String anchorName,
120 final String parentNodeXpath, final DataNode newChild) {
121 final FragmentEntity parentFragmentEntity =
122 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
123 final FragmentEntity newChildAsFragmentEntity =
124 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
125 parentFragmentEntity.getAnchor(), newChild);
126 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
128 fragmentRepository.save(newChildAsFragmentEntity);
129 } catch (final DataIntegrityViolationException e) {
130 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
135 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
136 final Collection<DataNode> newChildren) {
137 final FragmentEntity parentFragmentEntity =
138 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
139 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
141 newChildren.forEach(newChildAsDataNode -> {
142 final FragmentEntity newChildAsFragmentEntity =
143 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
144 parentFragmentEntity.getAnchor(), newChildAsDataNode);
145 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
146 fragmentEntities.add(newChildAsFragmentEntity);
148 fragmentRepository.saveAll(fragmentEntities);
149 } catch (final DataIntegrityViolationException e) {
150 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
151 e, fragmentEntities.size());
152 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
156 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
157 final String parentNodeXpath,
158 final Collection<DataNode> newChildren) {
159 final Collection<String> failedXpaths = new HashSet<>();
160 for (final DataNode newChild : newChildren) {
162 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
163 } catch (final AlreadyDefinedException e) {
164 failedXpaths.add(newChild.getXpath());
167 if (!failedXpaths.isEmpty()) {
168 throw new AlreadyDefinedExceptionBatch(failedXpaths);
173 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
174 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
178 public void storeDataNodes(final String dataspaceName, final String anchorName,
179 final Collection<DataNode> dataNodes) {
180 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
181 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
182 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
184 for (final DataNode dataNode: dataNodes) {
185 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
187 fragmentEntities.add(fragmentEntity);
189 fragmentRepository.saveAll(fragmentEntities);
190 } catch (final DataIntegrityViolationException exception) {
191 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
192 exception, dataNodes.size());
193 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
197 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
198 final Collection<DataNode> dataNodes) {
199 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
200 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
201 final Collection<String> failedXpaths = new HashSet<>();
202 for (final DataNode dataNode: dataNodes) {
204 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
206 fragmentRepository.save(fragmentEntity);
207 } catch (final DataIntegrityViolationException e) {
208 failedXpaths.add(dataNode.getXpath());
211 if (!failedXpaths.isEmpty()) {
212 throw new AlreadyDefinedExceptionBatch(failedXpaths);
217 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
218 * for all DataNode children recursively.
220 * @param dataspaceEntity dataspace
221 * @param anchorEntity anchorEntity
222 * @param dataNodeToBeConverted dataNode
223 * @return a Fragment built from current DataNode
225 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
226 final AnchorEntity anchorEntity,
227 final DataNode dataNodeToBeConverted) {
228 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
229 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
230 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
231 final FragmentEntity childFragment =
232 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
234 childFragmentsImmutableSetBuilder.add(childFragment);
236 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
237 return parentFragment;
240 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
241 final AnchorEntity anchorEntity, final DataNode dataNode) {
242 return FragmentEntity.builder()
243 .dataspace(dataspaceEntity)
244 .anchor(anchorEntity)
245 .xpath(dataNode.getXpath())
246 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
251 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
252 final FetchDescendantsOption fetchDescendantsOption) {
253 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
254 fetchDescendantsOption);
255 return toDataNode(fragmentEntity, fetchDescendantsOption);
258 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
259 final String anchorName,
260 final String xpath) {
261 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
264 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
265 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
266 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
267 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
268 if (isRootXpath(xpath)) {
269 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
271 return FragmentEntityArranger.toFragmentEntityTree(anchorEntity,
274 final String normalizedXpath = getNormalizedXpath(xpath);
275 final FragmentEntity fragmentEntity;
276 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
278 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
280 fragmentEntity = buildFragmentEntityFromFragmentExtracts(anchorEntity, normalizedXpath);
282 if (fragmentEntity == null) {
283 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
285 return fragmentEntity;
289 private FragmentEntity buildFragmentEntityFromFragmentExtracts(final AnchorEntity anchorEntity,
290 final String normalizedXpath) {
291 final FragmentEntity fragmentEntity;
292 final List<FragmentExtract> fragmentExtracts =
293 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
294 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
295 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
296 fragmentEntity = FragmentEntityArranger.toFragmentEntityTree(anchorEntity, fragmentExtracts);
297 return fragmentEntity;
301 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
302 final FetchDescendantsOption fetchDescendantsOption) {
303 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
304 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
305 final CpsPathQuery cpsPathQuery;
307 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
308 } catch (final PathParsingException e) {
309 throw new CpsPathException(e.getMessage());
311 List<FragmentEntity> fragmentEntities =
312 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
313 if (cpsPathQuery.hasAncestorAxis()) {
314 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
315 fragmentEntities = ancestorXpaths.isEmpty() ? Collections.emptyList()
316 : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
318 return createDataNodesFromFragmentEntities(fetchDescendantsOption, anchorEntity,
322 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
323 final AnchorEntity anchorEntity,
324 final List<FragmentEntity> fragmentEntities) {
325 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
326 for (final FragmentEntity proxiedFragmentEntity : fragmentEntities) {
327 final DataNode dataNode;
328 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
329 dataNode = toDataNode(proxiedFragmentEntity, fetchDescendantsOption);
331 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
332 final FragmentEntity unproxiedFragmentEntity = buildFragmentEntityFromFragmentExtracts(anchorEntity,
334 dataNode = toDataNode(unproxiedFragmentEntity, fetchDescendantsOption);
336 dataNodes.add(dataNode);
338 return Collections.unmodifiableList(dataNodes);
341 private static String getNormalizedXpath(final String xpathSource) {
342 final String normalizedXpath;
344 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
345 } catch (final PathParsingException e) {
346 throw new CpsPathException(e.getMessage());
348 return normalizedXpath;
352 public String startSession() {
353 return sessionManager.startSession();
357 public void closeSession(final String sessionId) {
358 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
362 public void lockAnchor(final String sessionId, final String dataspaceName,
363 final String anchorName, final Long timeoutInMilliseconds) {
364 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
367 private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
368 final CpsPathQuery cpsPathQuery) {
369 final Set<String> ancestorXpath = new HashSet<>();
370 final Pattern pattern =
371 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
372 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
373 for (final FragmentEntity fragmentEntity : fragmentEntities) {
374 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
375 if (matcher.matches()) {
376 ancestorXpath.add(matcher.group(1));
379 return ancestorXpath;
382 private DataNode toDataNode(final FragmentEntity fragmentEntity,
383 final FetchDescendantsOption fetchDescendantsOption) {
384 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
385 Map<String, Serializable> leaves = new HashMap<>();
386 if (fragmentEntity.getAttributes() != null) {
387 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
389 return new DataNodeBuilder()
390 .withXpath(fragmentEntity.getXpath())
392 .withChildDataNodes(childDataNodes).build();
395 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
396 final FetchDescendantsOption fetchDescendantsOption) {
397 if (fetchDescendantsOption.hasNext()) {
398 return fragmentEntity.getChildFragments().stream()
399 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
400 .collect(Collectors.toList());
402 return Collections.emptyList();
406 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
407 final Map<String, Serializable> leaves) {
408 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
409 fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
410 fragmentRepository.save(fragmentEntity);
414 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
415 final DataNode dataNode) {
416 final FragmentEntity fragmentEntity =
417 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
418 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
420 fragmentRepository.save(fragmentEntity);
421 } catch (final StaleStateException staleStateException) {
422 throw new ConcurrencyException("Concurrent Transactions",
423 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
424 dataspaceName, anchorName, dataNode.getXpath()));
429 public void updateDataNodesAndDescendants(final String dataspaceName,
430 final String anchorName,
431 final List<DataNode> dataNodes) {
433 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
434 .collect(Collectors.toMap(
435 dataNode -> dataNode,
437 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
438 dataNodeFragmentEntityMap.forEach(
439 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
441 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
442 } catch (final StaleStateException staleStateException) {
443 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
447 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
448 final Collection<FragmentEntity> fragmentEntities) {
449 final Collection<String> failedXpaths = new HashSet<>();
451 fragmentEntities.forEach(dataNodeFragment -> {
453 fragmentRepository.save(dataNodeFragment);
454 } catch (final StaleStateException e) {
455 failedXpaths.add(dataNodeFragment.getXpath());
459 if (!failedXpaths.isEmpty()) {
460 final String failedXpathsConcatenated = String.join(",", failedXpaths);
461 throw new ConcurrencyException("Concurrent Transactions", String.format(
462 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
463 failedXpathsConcatenated, dataspaceName, anchorName));
467 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
468 final DataNode newDataNode) {
470 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
472 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
473 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
475 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
477 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
478 final FragmentEntity childFragment;
479 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
480 childFragment = convertToFragmentWithAllDescendants(
481 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
483 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
484 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
486 updatedChildFragments.add(childFragment);
489 existingFragmentEntity.getChildFragments().clear();
490 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
495 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
496 final Collection<DataNode> newListElements) {
497 final FragmentEntity parentEntity =
498 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
499 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
500 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
501 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
502 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
503 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
504 for (final DataNode newListElement : newListElements) {
505 final FragmentEntity existingListElementEntity =
506 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
507 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
508 existingListElementEntity);
510 updatedChildFragmentEntities.add(entityToBeAdded);
512 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
513 fragmentRepository.save(parentEntity);
518 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
519 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
520 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
522 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
527 public void deleteListDataNode(final String dataspaceName, final String anchorName,
528 final String targetXpath) {
529 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
534 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
535 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
538 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
539 final boolean onlySupportListNodeDeletion) {
540 final String parentNodeXpath;
541 FragmentEntity parentFragmentEntity = null;
542 boolean targetDeleted;
543 if (isRootXpath(targetXpath)) {
544 deleteDataNodes(dataspaceName, anchorName);
545 targetDeleted = true;
547 if (isRootContainerNodeXpath(targetXpath)) {
548 parentNodeXpath = targetXpath;
550 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
552 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
553 if (CpsPathUtil.isPathToListElement(targetXpath)) {
554 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
556 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
557 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
558 if (tryToDeleteDataNode) {
559 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
563 if (!targetDeleted) {
564 final String additionalInformation = onlySupportListNodeDeletion
565 ? "The target is probably not a List." : "";
566 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
567 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
571 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
572 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
573 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
574 fragmentRepository.delete(parentFragmentEntity);
577 if (parentFragmentEntity.getChildFragments()
578 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
579 fragmentRepository.save(parentFragmentEntity);
585 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
586 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
587 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
588 if (parentFragmentEntity.getChildFragments()
589 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
590 fragmentRepository.save(parentFragmentEntity);
596 private static void deleteListElements(
597 final Collection<FragmentEntity> fragmentEntities,
598 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
599 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
602 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
603 if (newListElements.isEmpty()) {
604 throw new CpsAdminException("Invalid list replacement",
605 "Cannot replace list elements with empty collection");
607 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
608 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
611 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
612 final DataNode newListElement,
613 final FragmentEntity existingListElementEntity) {
614 if (existingListElementEntity == null) {
615 return convertToFragmentWithAllDescendants(
616 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
618 if (newListElement.getChildDataNodes().isEmpty()) {
619 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
620 existingListElementEntity.getChildFragments().clear();
622 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
624 return existingListElementEntity;
627 private static boolean isNewDataNode(final DataNode replacementDataNode,
628 final Map<String, FragmentEntity> existingListElementsByXpath) {
629 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
632 private static boolean isRootContainerNodeXpath(final String xpath) {
633 return 0 == xpath.lastIndexOf('/');
636 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
637 final DataNode newListElement) {
638 final FragmentEntity replacementFragmentEntity =
639 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
640 newListElement.getLeaves())).build();
641 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
644 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
645 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
646 return childEntities.stream()
647 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
648 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
651 private static boolean isRootXpath(final String xpath) {
652 return "/".equals(xpath) || "".equals(xpath);