Handle partial failure (improvements)
[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             return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
238                     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                     staleStateException);
350         }
351     }
352
353     @Override
354     public void updateDataNodesAndDescendants(final String dataspaceName,
355                                               final String anchorName,
356                                               final List<DataNode> dataNodes) {
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             throw new ConcurrencyException("Concurrent Transactions",
366                 String.format("A data node in dataspace :'%s' with Anchor : '%s' is updated by another transaction.",
367                     dataspaceName, anchorName),
368                 staleStateException);
369         }
370     }
371
372     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
373                                                                 final DataNode newDataNode) {
374
375         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
376
377         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
378                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
379
380         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
381
382         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
383             final FragmentEntity childFragment;
384             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
385                 childFragment = convertToFragmentWithAllDescendants(
386                         existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
387             } else {
388                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
389                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
390             }
391             updatedChildFragments.add(childFragment);
392         }
393
394         existingFragmentEntity.getChildFragments().clear();
395         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
396     }
397
398     @Override
399     @Transactional
400     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
401                                    final Collection<DataNode> newListElements) {
402         final FragmentEntity parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
403         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
404         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
405                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
406         deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
407         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
408         for (final DataNode newListElement : newListElements) {
409             final FragmentEntity existingListElementEntity =
410                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
411             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
412                     existingListElementEntity);
413
414             updatedChildFragmentEntities.add(entityToBeAdded);
415         }
416         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
417         fragmentRepository.save(parentEntity);
418     }
419
420     @Override
421     @Transactional
422     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
423         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
424         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
425                 .ifPresent(
426                         anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
427     }
428
429     @Override
430     @Transactional
431     public void deleteListDataNode(final String dataspaceName, final String anchorName,
432                                    final String targetXpath) {
433         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
434     }
435
436     @Override
437     @Transactional
438     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
439         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
440     }
441
442     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
443                                 final boolean onlySupportListNodeDeletion) {
444         final String parentNodeXpath;
445         FragmentEntity parentFragmentEntity = null;
446         boolean targetDeleted = false;
447         if (isRootXpath(targetXpath)) {
448             deleteDataNodes(dataspaceName, anchorName);
449             targetDeleted = true;
450         } else {
451             if (isRootContainerNodeXpath(targetXpath)) {
452                 parentNodeXpath = targetXpath;
453             } else {
454                 parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
455             }
456             parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
457             final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
458             final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE
459                     .matcher(lastXpathElement).find();
460             if (isListElement) {
461                 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
462             } else {
463                 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
464                 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
465                 if (tryToDeleteDataNode) {
466                     targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
467                 }
468             }
469         }
470         if (!targetDeleted) {
471             final String additionalInformation = onlySupportListNodeDeletion
472                     ? "The target is probably not a List." : "";
473             throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
474                     parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
475         }
476     }
477
478     private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
479         final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
480         if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
481             fragmentRepository.delete(parentFragmentEntity);
482             return true;
483         }
484         if (parentFragmentEntity.getChildFragments()
485                 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
486             fragmentRepository.save(parentFragmentEntity);
487             return true;
488         }
489         return false;
490     }
491
492     private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
493         final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
494         final String deleteTargetXpathPrefix = normalizedListXpath + "[";
495         if (parentFragmentEntity.getChildFragments()
496                 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
497             fragmentRepository.save(parentFragmentEntity);
498             return true;
499         }
500         return false;
501     }
502
503     private static void deleteListElements(
504             final Collection<FragmentEntity> fragmentEntities,
505             final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
506         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
507     }
508
509     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
510         if (newListElements.isEmpty()) {
511             throw new CpsAdminException("Invalid list replacement",
512                     "Cannot replace list elements with empty collection");
513         }
514         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
515         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
516     }
517
518     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
519                                                      final DataNode newListElement,
520                                                      final FragmentEntity existingListElementEntity) {
521         if (existingListElementEntity == null) {
522             return convertToFragmentWithAllDescendants(
523                     parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
524         }
525         if (newListElement.getChildDataNodes().isEmpty()) {
526             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
527             existingListElementEntity.getChildFragments().clear();
528         } else {
529             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
530         }
531         return existingListElementEntity;
532     }
533
534     private static boolean isNewDataNode(final DataNode replacementDataNode,
535                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
536         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
537     }
538
539     private static boolean isRootContainerNodeXpath(final String xpath) {
540         return 0 == xpath.lastIndexOf('/');
541     }
542
543     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
544                                                   final DataNode newListElement) {
545         final FragmentEntity replacementFragmentEntity =
546                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
547                         newListElement.getLeaves())).build();
548         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
549     }
550
551     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
552             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
553         return childEntities.stream()
554                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
555                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
556     }
557
558     private static boolean isRootXpath(final String xpath) {
559         return "/".equals(xpath) || "".equals(xpath);
560     }
561 }