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