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