5fe646ff826ababe17050799e49c368592d3b00a
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsDataPersistenceServiceImpl.java
1 /*
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
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.spi.impl;
24
25 import com.google.common.collect.ImmutableSet;
26 import com.google.common.collect.ImmutableSet.Builder;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37 import java.util.stream.Collectors;
38 import javax.transaction.Transactional;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.hibernate.StaleStateException;
42 import org.onap.cps.cpspath.parser.CpsPathQuery;
43 import org.onap.cps.cpspath.parser.CpsPathUtil;
44 import org.onap.cps.cpspath.parser.PathParsingException;
45 import org.onap.cps.spi.CpsDataPersistenceService;
46 import org.onap.cps.spi.FetchDescendantsOption;
47 import org.onap.cps.spi.entities.AnchorEntity;
48 import org.onap.cps.spi.entities.DataspaceEntity;
49 import org.onap.cps.spi.entities.FragmentEntity;
50 import org.onap.cps.spi.entities.FragmentEntityArranger;
51 import org.onap.cps.spi.entities.FragmentExtract;
52 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
53 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
54 import org.onap.cps.spi.exceptions.ConcurrencyException;
55 import org.onap.cps.spi.exceptions.CpsAdminException;
56 import org.onap.cps.spi.exceptions.CpsPathException;
57 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
58 import org.onap.cps.spi.model.DataNode;
59 import org.onap.cps.spi.model.DataNodeBuilder;
60 import org.onap.cps.spi.repository.AnchorRepository;
61 import org.onap.cps.spi.repository.DataspaceRepository;
62 import org.onap.cps.spi.repository.FragmentRepository;
63 import org.onap.cps.spi.utils.SessionManager;
64 import org.onap.cps.utils.JsonObjectMapper;
65 import org.springframework.dao.DataIntegrityViolationException;
66 import org.springframework.stereotype.Service;
67
68 @Service
69 @Slf4j
70 @RequiredArgsConstructor
71 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
72
73     private final DataspaceRepository dataspaceRepository;
74     private final AnchorRepository anchorRepository;
75     private final FragmentRepository fragmentRepository;
76     private final JsonObjectMapper jsonObjectMapper;
77     private final SessionManager sessionManager;
78
79     private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
80     private static final Pattern REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE =
81             Pattern.compile("\\[(\\@([^\\/]{0,9999}))\\]$");
82     private static final String TOP_LEVEL_MODULE_PREFIX_PROPERTY_NAME = "topLevelModulePrefix";
83
84     @Override
85     public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
86                                  final DataNode newChildDataNode) {
87         addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
88     }
89
90     @Override
91     public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
92                                 final Collection<DataNode> newListElements) {
93         addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
94     }
95
96     @Override
97     public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
98                                  final Collection<Collection<DataNode>> newLists) {
99         final Collection<String> failedXpaths = new HashSet<>();
100         newLists.forEach(newList -> {
101             try {
102                 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
103             } catch (final AlreadyDefinedExceptionBatch e) {
104                 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
105             }
106         });
107
108         if (!failedXpaths.isEmpty()) {
109             throw new AlreadyDefinedExceptionBatch(failedXpaths);
110         }
111
112     }
113
114     private void addNewChildDataNode(final String dataspaceName, final String anchorName,
115                                      final String parentNodeXpath, final DataNode newChild) {
116         final FragmentEntity parentFragmentEntity =
117             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
118         final FragmentEntity newChildAsFragmentEntity =
119                 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
120                         parentFragmentEntity.getAnchor(), newChild);
121         newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
122         try {
123             fragmentRepository.save(newChildAsFragmentEntity);
124         } catch (final DataIntegrityViolationException e) {
125             throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
126         }
127
128     }
129
130     private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
131                                       final Collection<DataNode> newChildren) {
132         final FragmentEntity parentFragmentEntity =
133             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
134         final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
135         try {
136             newChildren.forEach(newChildAsDataNode -> {
137                 final FragmentEntity newChildAsFragmentEntity =
138                         convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
139                                 parentFragmentEntity.getAnchor(), newChildAsDataNode);
140                 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
141                 fragmentEntities.add(newChildAsFragmentEntity);
142             });
143             fragmentRepository.saveAll(fragmentEntities);
144         } catch (final DataIntegrityViolationException e) {
145             log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
146                     e, fragmentEntities.size());
147             retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
148         }
149     }
150
151     private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
152                                                   final String parentNodeXpath,
153                                                   final Collection<DataNode> newChildren) {
154         final Collection<String> failedXpaths = new HashSet<>();
155         for (final DataNode newChild : newChildren) {
156             try {
157                 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
158             } catch (final AlreadyDefinedException e) {
159                 failedXpaths.add(newChild.getXpath());
160             }
161         }
162         if (!failedXpaths.isEmpty()) {
163             throw new AlreadyDefinedExceptionBatch(failedXpaths);
164         }
165     }
166
167     @Override
168     public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
169         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
170         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
171         final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
172                 dataNode);
173         try {
174             fragmentRepository.save(fragmentEntity);
175         } catch (final DataIntegrityViolationException exception) {
176             throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
177         }
178     }
179
180     /**
181      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
182      * for all DataNode children recursively.
183      *
184      * @param dataspaceEntity       dataspace
185      * @param anchorEntity          anchorEntity
186      * @param dataNodeToBeConverted dataNode
187      * @return a Fragment built from current DataNode
188      */
189     private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
190                                                                final AnchorEntity anchorEntity,
191                                                                final DataNode dataNodeToBeConverted) {
192         final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
193         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
194         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
195             final FragmentEntity childFragment =
196                     convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
197                             childDataNode);
198             childFragmentsImmutableSetBuilder.add(childFragment);
199         }
200         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
201         return parentFragment;
202     }
203
204     private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
205                                             final AnchorEntity anchorEntity, final DataNode dataNode) {
206         return FragmentEntity.builder()
207                 .dataspace(dataspaceEntity)
208                 .anchor(anchorEntity)
209                 .xpath(dataNode.getXpath())
210                 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
211                 .build();
212     }
213
214     @Override
215     public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
216                                 final FetchDescendantsOption fetchDescendantsOption) {
217         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
218             fetchDescendantsOption);
219         return toDataNode(fragmentEntity, fetchDescendantsOption);
220     }
221
222     private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
223                                                                 final String anchorName,
224                                                                 final String xpath) {
225         return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
226     }
227
228     private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
229                                               final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
230         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
231         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
232         if (isRootXpath(xpath)) {
233             return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
234         } else {
235             final String normalizedXpath;
236             try {
237                 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpath);
238             } catch (final PathParsingException e) {
239                 throw new CpsPathException(e.getMessage());
240             }
241             final FragmentEntity fragmentEntity;
242             if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
243                 fragmentEntity =
244                     fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
245             } else {
246                 final List<FragmentExtract> fragmentExtracts =
247                     fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
248                 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
249                     fragmentExtracts.size(), anchorName, xpath);
250                 fragmentEntity = FragmentEntityArranger.toFragmentEntityTree(anchorEntity, fragmentExtracts);
251             }
252             if (fragmentEntity == null) {
253                 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
254             }
255             return fragmentEntity;
256         }
257     }
258
259     @Override
260     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
261                                          final FetchDescendantsOption fetchDescendantsOption) {
262         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
263         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
264         final CpsPathQuery cpsPathQuery;
265         try {
266             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
267         } catch (final PathParsingException e) {
268             throw new CpsPathException(e.getMessage());
269         }
270         List<FragmentEntity> fragmentEntities =
271                 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
272         if (cpsPathQuery.hasAncestorAxis()) {
273             final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
274             fragmentEntities = ancestorXpaths.isEmpty() ? Collections.emptyList()
275                     : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
276         }
277         return fragmentEntities.stream().map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
278                 .collect(Collectors.toUnmodifiableList());
279     }
280
281     @Override
282     public String startSession() {
283         return sessionManager.startSession();
284     }
285
286     @Override
287     public void closeSession(final String sessionId) {
288         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
289     }
290
291     @Override
292     public void lockAnchor(final String sessionId, final String dataspaceName,
293                            final String anchorName, final Long timeoutInMilliseconds) {
294         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
295     }
296
297     private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
298                                                     final CpsPathQuery cpsPathQuery) {
299         final Set<String> ancestorXpath = new HashSet<>();
300         final Pattern pattern =
301                 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
302                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
303         for (final FragmentEntity fragmentEntity : fragmentEntities) {
304             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
305             if (matcher.matches()) {
306                 ancestorXpath.add(matcher.group(1));
307             }
308         }
309         return ancestorXpath;
310     }
311
312     private DataNode toDataNode(final FragmentEntity fragmentEntity,
313                                 final FetchDescendantsOption fetchDescendantsOption) {
314         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
315         Map<String, Object> leaves = new HashMap<>();
316         if (fragmentEntity.getAttributes() != null) {
317             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
318         }
319         return new DataNodeBuilder()
320                 .withXpath(fragmentEntity.getXpath())
321                 .withLeaves(leaves)
322                 .withChildDataNodes(childDataNodes).build();
323     }
324
325     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
326                                              final FetchDescendantsOption fetchDescendantsOption) {
327         if (fetchDescendantsOption.hasNext()) {
328             return fragmentEntity.getChildFragments().stream()
329                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
330                     .collect(Collectors.toList());
331         }
332         return Collections.emptyList();
333     }
334
335     @Override
336     public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
337                                  final Map<String, Object> leaves) {
338         final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
339         fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
340         fragmentRepository.save(fragmentEntity);
341     }
342
343     @Override
344     public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
345                                              final DataNode dataNode) {
346         final FragmentEntity fragmentEntity =
347             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
348         updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
349         try {
350             fragmentRepository.save(fragmentEntity);
351         } catch (final StaleStateException staleStateException) {
352             throw new ConcurrencyException("Concurrent Transactions",
353                     String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
354                             dataspaceName, anchorName, dataNode.getXpath()));
355         }
356     }
357
358     @Override
359     public void updateDataNodesAndDescendants(final String dataspaceName,
360                                               final String anchorName,
361                                               final List<DataNode> dataNodes) {
362
363         final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
364                 .collect(Collectors.toMap(
365                         dataNode -> dataNode,
366                         dataNode ->
367                             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
368         dataNodeFragmentEntityMap.forEach(
369                 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
370         try {
371             fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
372         } catch (final StaleStateException staleStateException) {
373             retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
374         }
375     }
376
377     private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
378                                                   final Collection<FragmentEntity> fragmentEntities) {
379         final Collection<String> failedXpaths = new HashSet<>();
380
381         fragmentEntities.forEach(dataNodeFragment -> {
382             try {
383                 fragmentRepository.save(dataNodeFragment);
384             } catch (final StaleStateException e) {
385                 failedXpaths.add(dataNodeFragment.getXpath());
386             }
387         });
388
389         if (!failedXpaths.isEmpty()) {
390             final String failedXpathsConcatenated = String.join(",", failedXpaths);
391             throw new ConcurrencyException("Concurrent Transactions", String.format(
392                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
393                     failedXpathsConcatenated, dataspaceName, anchorName));
394         }
395     }
396
397     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
398                                                                 final DataNode newDataNode) {
399
400         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
401
402         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
403                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
404
405         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
406
407         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
408             final FragmentEntity childFragment;
409             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
410                 childFragment = convertToFragmentWithAllDescendants(
411                         existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
412             } else {
413                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
414                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
415             }
416             updatedChildFragments.add(childFragment);
417         }
418
419         existingFragmentEntity.getChildFragments().clear();
420         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
421     }
422
423     @Override
424     @Transactional
425     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
426                                    final Collection<DataNode> newListElements) {
427         final FragmentEntity parentEntity =
428             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
429         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
430         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
431                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
432         deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
433         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
434         for (final DataNode newListElement : newListElements) {
435             final FragmentEntity existingListElementEntity =
436                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
437             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
438                     existingListElementEntity);
439
440             updatedChildFragmentEntities.add(entityToBeAdded);
441         }
442         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
443         fragmentRepository.save(parentEntity);
444     }
445
446     @Override
447     @Transactional
448     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
449         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
450         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
451                 .ifPresent(
452                         anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
453     }
454
455     @Override
456     @Transactional
457     public void deleteListDataNode(final String dataspaceName, final String anchorName,
458                                    final String targetXpath) {
459         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
460     }
461
462     @Override
463     @Transactional
464     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
465         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
466     }
467
468     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
469                                 final boolean onlySupportListNodeDeletion) {
470         final String parentNodeXpath;
471         FragmentEntity parentFragmentEntity = null;
472         boolean targetDeleted = false;
473         if (isRootXpath(targetXpath)) {
474             deleteDataNodes(dataspaceName, anchorName);
475             targetDeleted = true;
476         } else {
477             if (isRootContainerNodeXpath(targetXpath)) {
478                 parentNodeXpath = targetXpath;
479             } else {
480                 parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
481             }
482             parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
483             final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
484             final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE
485                     .matcher(lastXpathElement).find();
486             if (isListElement) {
487                 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
488             } else {
489                 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
490                 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
491                 if (tryToDeleteDataNode) {
492                     targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
493                 }
494             }
495         }
496         if (!targetDeleted) {
497             final String additionalInformation = onlySupportListNodeDeletion
498                     ? "The target is probably not a List." : "";
499             throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
500                     parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
501         }
502     }
503
504     private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
505         final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
506         if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
507             fragmentRepository.delete(parentFragmentEntity);
508             return true;
509         }
510         if (parentFragmentEntity.getChildFragments()
511                 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
512             fragmentRepository.save(parentFragmentEntity);
513             return true;
514         }
515         return false;
516     }
517
518     private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
519         final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
520         final String deleteTargetXpathPrefix = normalizedListXpath + "[";
521         if (parentFragmentEntity.getChildFragments()
522                 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
523             fragmentRepository.save(parentFragmentEntity);
524             return true;
525         }
526         return false;
527     }
528
529     private static void deleteListElements(
530             final Collection<FragmentEntity> fragmentEntities,
531             final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
532         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
533     }
534
535     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
536         if (newListElements.isEmpty()) {
537             throw new CpsAdminException("Invalid list replacement",
538                     "Cannot replace list elements with empty collection");
539         }
540         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
541         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
542     }
543
544     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
545                                                      final DataNode newListElement,
546                                                      final FragmentEntity existingListElementEntity) {
547         if (existingListElementEntity == null) {
548             return convertToFragmentWithAllDescendants(
549                     parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
550         }
551         if (newListElement.getChildDataNodes().isEmpty()) {
552             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
553             existingListElementEntity.getChildFragments().clear();
554         } else {
555             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
556         }
557         return existingListElementEntity;
558     }
559
560     private static boolean isNewDataNode(final DataNode replacementDataNode,
561                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
562         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
563     }
564
565     private static boolean isRootContainerNodeXpath(final String xpath) {
566         return 0 == xpath.lastIndexOf('/');
567     }
568
569     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
570                                                   final DataNode newListElement) {
571         final FragmentEntity replacementFragmentEntity =
572                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
573                         newListElement.getLeaves())).build();
574         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
575     }
576
577     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
578             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
579         return childEntities.stream()
580                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
581                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
582     }
583
584     private static boolean isRootXpath(final String xpath) {
585         return "/".equals(xpath) || "".equals(xpath);
586     }
587 }