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