fdb01485ad6ee3b86fffa0be31ff0ae8abbe84ad
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsDataPersistenceServiceImpl.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2023 Nordix Foundation
4  *  Modifications Copyright (C) 2021 Pantheon.tech
5  *  Modifications Copyright (C) 2020-2022 Bell Canada.
6  *  Modifications Copyright (C) 2022-2023 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.base.Strings;
27 import com.google.common.collect.ImmutableSet;
28 import com.google.common.collect.ImmutableSet.Builder;
29 import io.micrometer.core.annotation.Timed;
30 import java.io.Serializable;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.function.Function;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
43 import javax.transaction.Transactional;
44 import lombok.RequiredArgsConstructor;
45 import lombok.extern.slf4j.Slf4j;
46 import org.hibernate.StaleStateException;
47 import org.onap.cps.cpspath.parser.CpsPathQuery;
48 import org.onap.cps.cpspath.parser.CpsPathUtil;
49 import org.onap.cps.cpspath.parser.PathParsingException;
50 import org.onap.cps.spi.CpsDataPersistenceService;
51 import org.onap.cps.spi.FetchDescendantsOption;
52 import org.onap.cps.spi.entities.AnchorEntity;
53 import org.onap.cps.spi.entities.DataspaceEntity;
54 import org.onap.cps.spi.entities.FragmentEntity;
55 import org.onap.cps.spi.entities.FragmentEntityArranger;
56 import org.onap.cps.spi.entities.FragmentExtract;
57 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
58 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
59 import org.onap.cps.spi.exceptions.ConcurrencyException;
60 import org.onap.cps.spi.exceptions.CpsAdminException;
61 import org.onap.cps.spi.exceptions.CpsPathException;
62 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
63 import org.onap.cps.spi.exceptions.DataNodeNotFoundExceptionBatch;
64 import org.onap.cps.spi.model.DataNode;
65 import org.onap.cps.spi.model.DataNodeBuilder;
66 import org.onap.cps.spi.repository.AnchorRepository;
67 import org.onap.cps.spi.repository.DataspaceRepository;
68 import org.onap.cps.spi.repository.FragmentRepository;
69 import org.onap.cps.spi.utils.SessionManager;
70 import org.onap.cps.utils.JsonObjectMapper;
71 import org.springframework.dao.DataIntegrityViolationException;
72 import org.springframework.stereotype.Service;
73
74 @Service
75 @Slf4j
76 @RequiredArgsConstructor
77 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
78
79     private final DataspaceRepository dataspaceRepository;
80     private final AnchorRepository anchorRepository;
81     private final FragmentRepository fragmentRepository;
82     private final JsonObjectMapper jsonObjectMapper;
83     private final SessionManager sessionManager;
84
85     private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@.+?])?)";
86     private static final String QUERY_ACROSS_ANCHORS = null;
87     private static final AnchorEntity ALL_ANCHORS = null;
88
89     @Override
90     public void addChildDataNodes(final String dataspaceName, final String anchorName,
91                                   final String parentNodeXpath, final Collection<DataNode> dataNodes) {
92         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
93         addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
94     }
95
96     @Override
97     public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
98                                 final Collection<DataNode> newListElements) {
99         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
100         addChildrenDataNodes(anchorEntity, 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 AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
107         final Collection<String> failedXpaths = new HashSet<>();
108         for (final Collection<DataNode> newList : newLists) {
109             try {
110                 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
111             } catch (final AlreadyDefinedExceptionBatch e) {
112                 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
113             }
114         }
115         if (!failedXpaths.isEmpty()) {
116             throw new AlreadyDefinedExceptionBatch(failedXpaths);
117         }
118     }
119
120     private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
121                                      final DataNode newChild) {
122         final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
123         final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
124         newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
125         try {
126             fragmentRepository.save(newChildAsFragmentEntity);
127         } catch (final DataIntegrityViolationException e) {
128             throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorEntity.getName(), e);
129         }
130     }
131
132     private void addChildrenDataNodes(final AnchorEntity anchorEntity, final String parentNodeXpath,
133                                       final Collection<DataNode> newChildren) {
134         final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
135         final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
136         try {
137             for (final DataNode newChildAsDataNode : newChildren) {
138                 final FragmentEntity newChildAsFragmentEntity =
139                     convertToFragmentWithAllDescendants(anchorEntity, 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(anchorEntity, parentNodeXpath, newChildren);
148         }
149     }
150
151     private void retrySavingEachChildIndividually(final AnchorEntity anchorEntity, final String parentNodeXpath,
152                                                   final Collection<DataNode> newChildren) {
153         final Collection<String> failedXpaths = new HashSet<>();
154         for (final DataNode newChild : newChildren) {
155             try {
156                 addNewChildDataNode(anchorEntity, parentNodeXpath, newChild);
157             } catch (final AlreadyDefinedException e) {
158                 failedXpaths.add(newChild.getXpath());
159             }
160         }
161         if (!failedXpaths.isEmpty()) {
162             throw new AlreadyDefinedExceptionBatch(failedXpaths);
163         }
164     }
165
166     @Override
167     public void storeDataNodes(final String dataspaceName, final String anchorName,
168                                final Collection<DataNode> dataNodes) {
169         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
170         final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
171         try {
172             for (final DataNode dataNode: dataNodes) {
173                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
174                 fragmentEntities.add(fragmentEntity);
175             }
176             fragmentRepository.saveAll(fragmentEntities);
177         } catch (final DataIntegrityViolationException exception) {
178             log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
179                     exception, dataNodes.size());
180             storeDataNodesIndividually(anchorEntity, dataNodes);
181         }
182     }
183
184     private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
185         final Collection<String> failedXpaths = new HashSet<>();
186         for (final DataNode dataNode: dataNodes) {
187             try {
188                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
189                 fragmentRepository.save(fragmentEntity);
190             } catch (final DataIntegrityViolationException e) {
191                 failedXpaths.add(dataNode.getXpath());
192             }
193         }
194         if (!failedXpaths.isEmpty()) {
195             throw new AlreadyDefinedExceptionBatch(failedXpaths);
196         }
197     }
198
199     /**
200      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
201      * for all DataNode children recursively.
202      *
203      * @param anchorEntity          anchorEntity
204      * @param dataNodeToBeConverted dataNode
205      * @return a Fragment built from current DataNode
206      */
207     private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
208                                                                final DataNode dataNodeToBeConverted) {
209         final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
210         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
211         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
212             final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
213             childFragmentsImmutableSetBuilder.add(childFragment);
214         }
215         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
216         return parentFragment;
217     }
218
219     private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
220         return FragmentEntity.builder()
221                 .anchor(anchorEntity)
222                 .xpath(dataNode.getXpath())
223                 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
224                 .build();
225     }
226
227     @Override
228     @Timed(value = "cps.data.persistence.service.datanode.get",
229             description = "Time taken to get a data node")
230     public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
231                                              final String xpath,
232                                              final FetchDescendantsOption fetchDescendantsOption) {
233         final String targetXpath = getNormalizedXpath(xpath);
234         final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
235                 Collections.singletonList(targetXpath), fetchDescendantsOption);
236         if (dataNodes.isEmpty()) {
237             throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
238         }
239         return dataNodes;
240     }
241
242     @Override
243     @Timed(value = "cps.data.persistence.service.datanode.batch.get",
244             description = "Time taken to get data nodes")
245     public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
246                                                               final Collection<String> xpaths,
247                                                               final FetchDescendantsOption fetchDescendantsOption) {
248         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
249         final Collection<FragmentEntity> fragmentEntities =
250             getFragmentEntities(anchorEntity, xpaths, fetchDescendantsOption);
251         return toDataNodes(fragmentEntities, fetchDescendantsOption);
252     }
253
254     private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
255                                                            final Collection<String> xpaths,
256                                                            final FetchDescendantsOption fetchDescendantsOption) {
257         final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
258         final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
259
260         final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
261         for (final String xpath : nonRootXpaths) {
262             try {
263                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
264             } catch (final PathParsingException e) {
265                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
266             }
267         }
268         if (haveRootXpath) {
269             normalizedXpaths.addAll(fragmentRepository.findAllXpathByAnchorAndParentIdIsNull(anchorEntity));
270         }
271
272         final List<FragmentExtract> fragmentExtracts =
273             fragmentRepository.findExtractsWithDescendants(anchorEntity.getId(), normalizedXpaths,
274                 fetchDescendantsOption.getDepth());
275
276         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
277     }
278
279     private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
280         final FragmentEntity fragmentEntity;
281         if (isRootXpath(xpath)) {
282             final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
283             fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
284                 .stream().findFirst().orElse(null);
285         } else {
286             fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
287         }
288         if (fragmentEntity == null) {
289             throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
290         }
291         return fragmentEntity;
292     }
293
294     @Override
295     @Timed(value = "cps.data.persistence.service.datanode.query",
296             description = "Time taken to query data nodes")
297     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
298                                          final FetchDescendantsOption fetchDescendantsOption) {
299         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
300         final AnchorEntity anchorEntity = Strings.isNullOrEmpty(anchorName) ? ALL_ANCHORS
301             : anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
302         final CpsPathQuery cpsPathQuery;
303         try {
304             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
305         } catch (final PathParsingException e) {
306             throw new CpsPathException(e.getMessage());
307         }
308
309         Collection<FragmentEntity> fragmentEntities;
310         if (anchorEntity == ALL_ANCHORS) {
311             fragmentEntities = fragmentRepository.findByDataspaceAndCpsPath(dataspaceEntity, cpsPathQuery);
312         } else {
313             fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity, cpsPathQuery);
314         }
315         if (cpsPathQuery.hasAncestorAxis()) {
316             final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
317             if (anchorEntity == ALL_ANCHORS) {
318                 fragmentEntities = fragmentRepository.findByDataspaceAndXpathIn(dataspaceEntity, ancestorXpaths);
319             } else {
320                 fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
321             }
322         }
323         fragmentEntities = prefetchDescendantsForFragmentEntities(fetchDescendantsOption, anchorEntity,
324             fragmentEntities);
325         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
326     }
327
328     @Override
329     public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
330                                                       final FetchDescendantsOption fetchDescendantsOption) {
331         return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
332     }
333
334     private Collection<FragmentEntity> prefetchDescendantsForFragmentEntities(
335                                             final FetchDescendantsOption fetchDescendantsOption,
336                                             final AnchorEntity anchorEntity,
337                                             final Collection<FragmentEntity> proxiedFragmentEntities) {
338         if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
339             return proxiedFragmentEntities;
340         }
341
342         final List<Long> fragmentEntityIds = proxiedFragmentEntities.stream()
343             .map(FragmentEntity::getId).collect(Collectors.toList());
344
345         final List<FragmentExtract> fragmentExtracts =
346             fragmentRepository.findExtractsWithDescendantsByIds(fragmentEntityIds, fetchDescendantsOption.getDepth());
347
348         if (anchorEntity == ALL_ANCHORS) {
349             final Collection<Long> anchorIds = fragmentExtracts.stream()
350                 .map(FragmentExtract::getAnchorId).collect(Collectors.toSet());
351             final List<AnchorEntity> anchorEntities = anchorRepository.findAllById(anchorIds);
352             final Map<Long, AnchorEntity> anchorEntityPerId = anchorEntities.stream()
353                 .collect(Collectors.toMap(AnchorEntity::getId, Function.identity()));
354             return FragmentEntityArranger.toFragmentEntityTreesAcrossAnchors(anchorEntityPerId, fragmentExtracts);
355         }
356         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
357     }
358
359     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
360                                                                final Collection<FragmentEntity> fragmentEntities) {
361         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
362         for (final FragmentEntity fragmentEntity : fragmentEntities) {
363             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
364         }
365         return Collections.unmodifiableList(dataNodes);
366     }
367
368     private static String getNormalizedXpath(final String xpathSource) {
369         if (isRootXpath(xpathSource)) {
370             return xpathSource;
371         }
372         try {
373             return CpsPathUtil.getNormalizedXpath(xpathSource);
374         } catch (final PathParsingException e) {
375             throw new CpsPathException(e.getMessage());
376         }
377     }
378
379     @Override
380     public String startSession() {
381         return sessionManager.startSession();
382     }
383
384     @Override
385     public void closeSession(final String sessionId) {
386         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
387     }
388
389     @Override
390     public void lockAnchor(final String sessionId, final String dataspaceName,
391                            final String anchorName, final Long timeoutInMilliseconds) {
392         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
393     }
394
395     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
396                                                     final CpsPathQuery cpsPathQuery) {
397         final Set<String> ancestorXpath = new HashSet<>();
398         final Pattern pattern =
399                 Pattern.compile("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
400                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
401         for (final FragmentEntity fragmentEntity : fragmentEntities) {
402             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
403             if (matcher.matches()) {
404                 ancestorXpath.add(matcher.group(1));
405             }
406         }
407         return ancestorXpath;
408     }
409
410     private DataNode toDataNode(final FragmentEntity fragmentEntity,
411                                 final FetchDescendantsOption fetchDescendantsOption) {
412         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
413         Map<String, Serializable> leaves = new HashMap<>();
414         if (fragmentEntity.getAttributes() != null) {
415             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
416         }
417         return new DataNodeBuilder()
418                 .withXpath(fragmentEntity.getXpath())
419                 .withLeaves(leaves)
420                 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
421                 .withAnchor(fragmentEntity.getAnchor().getName())
422                 .withChildDataNodes(childDataNodes).build();
423     }
424
425     private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
426                                              final FetchDescendantsOption fetchDescendantsOption) {
427         final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
428         for (final FragmentEntity fragmentEntity : fragmentEntities) {
429             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
430         }
431         return dataNodes;
432     }
433
434     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
435                                              final FetchDescendantsOption fetchDescendantsOption) {
436         if (fetchDescendantsOption.hasNext()) {
437             return fragmentEntity.getChildFragments().stream()
438                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
439                     .collect(Collectors.toList());
440         }
441         return Collections.emptyList();
442     }
443
444     @Override
445     public void batchUpdateDataLeaves(final String dataspaceName, final String anchorName,
446                                         final Map<String, Map<String, Serializable>> updatedLeavesPerXPath) {
447         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
448
449         final Collection<String> xpathsOfUpdatedLeaves = updatedLeavesPerXPath.keySet();
450         final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpathsOfUpdatedLeaves,
451                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
452
453         for (final FragmentEntity fragmentEntity : fragmentEntities) {
454             final Map<String, Serializable> updatedLeaves = updatedLeavesPerXPath.get(fragmentEntity.getXpath());
455             final String mergedLeaves = mergeLeaves(updatedLeaves, fragmentEntity.getAttributes());
456             fragmentEntity.setAttributes(mergedLeaves);
457         }
458
459         try {
460             fragmentRepository.saveAll(fragmentEntities);
461         } catch (final StaleStateException staleStateException) {
462             retryUpdateDataNodesIndividually(anchorEntity, fragmentEntities);
463         }
464     }
465
466     @Override
467     public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
468                                               final Collection<DataNode> updatedDataNodes) {
469         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
470
471         final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
472             .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
473
474         final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
475         final Collection<FragmentEntity> existingFragmentEntities =
476             getFragmentEntities(anchorEntity, xpaths, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
477
478         for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
479             final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
480             updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
481         }
482
483         try {
484             fragmentRepository.saveAll(existingFragmentEntities);
485         } catch (final StaleStateException staleStateException) {
486             retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
487         }
488     }
489
490     private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
491                                                   final Collection<FragmentEntity> fragmentEntities) {
492         final Collection<String> failedXpaths = new HashSet<>();
493         for (final FragmentEntity dataNodeFragment : fragmentEntities) {
494             try {
495                 fragmentRepository.save(dataNodeFragment);
496             } catch (final StaleStateException e) {
497                 failedXpaths.add(dataNodeFragment.getXpath());
498             }
499         }
500         if (!failedXpaths.isEmpty()) {
501             final String failedXpathsConcatenated = String.join(",", failedXpaths);
502             throw new ConcurrencyException("Concurrent Transactions", String.format(
503                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
504                     failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
505         }
506     }
507
508     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
509                                                                 final DataNode newDataNode) {
510         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
511
512         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
513                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
514
515         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
516         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
517             final FragmentEntity childFragment;
518             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
519                 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
520                     newDataNodeChild);
521             } else {
522                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
523                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
524             }
525             updatedChildFragments.add(childFragment);
526         }
527
528         existingFragmentEntity.getChildFragments().clear();
529         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
530     }
531
532     @Override
533     @Transactional
534     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
535                                    final Collection<DataNode> newListElements) {
536         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
537         final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
538         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
539         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
540                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
541         parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
542         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
543         for (final DataNode newListElement : newListElements) {
544             final FragmentEntity existingListElementEntity =
545                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
546             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
547                     existingListElementEntity);
548             updatedChildFragmentEntities.add(entityToBeAdded);
549         }
550         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
551         fragmentRepository.save(parentEntity);
552     }
553
554     @Override
555     @Transactional
556     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
557         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
558         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
559             .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
560     }
561
562     @Override
563     @Transactional
564     public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
565         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
566         final Collection<AnchorEntity> anchorEntities =
567             anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
568         fragmentRepository.deleteByAnchorIn(anchorEntities);
569     }
570
571     @Override
572     @Transactional
573     public void deleteDataNodes(final String dataspaceName, final String anchorName,
574                                 final Collection<String> xpathsToDelete) {
575         deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
576     }
577
578     private void deleteDataNodes(final String dataspaceName, final String anchorName,
579                                  final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
580         final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
581         if (haveRootXpath) {
582             deleteDataNodes(dataspaceName, anchorName);
583             return;
584         }
585
586         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
587
588         final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
589         for (final String xpath : xpathsToDelete) {
590             try {
591                 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
592             } catch (final PathParsingException e) {
593                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
594             }
595         }
596
597         final Collection<String> xpathsToExistingContainers =
598             fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
599         if (onlySupportListDeletion) {
600             final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
601                 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
602             deleteChecklist.removeAll(xpathsToExistingListElements);
603         } else {
604             deleteChecklist.removeAll(xpathsToExistingContainers);
605         }
606
607         final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
608             .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
609             .collect(Collectors.toList());
610         deleteChecklist.removeAll(xpathsToExistingLists);
611
612         if (!deleteChecklist.isEmpty()) {
613             throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
614         }
615
616         fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
617         fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
618     }
619
620     @Override
621     @Transactional
622     public void deleteListDataNode(final String dataspaceName, final String anchorName,
623                                    final String targetXpath) {
624         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
625     }
626
627     @Override
628     @Transactional
629     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
630         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
631     }
632
633     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
634                                 final boolean onlySupportListNodeDeletion) {
635         final String normalizedXpath = getNormalizedXpath(targetXpath);
636         try {
637             deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
638                 onlySupportListNodeDeletion);
639         } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
640             throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
641         }
642     }
643
644     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
645         if (newListElements.isEmpty()) {
646             throw new CpsAdminException("Invalid list replacement",
647                     "Cannot replace list elements with empty collection");
648         }
649         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
650         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
651     }
652
653     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
654                                                      final DataNode newListElement,
655                                                      final FragmentEntity existingListElementEntity) {
656         if (existingListElementEntity == null) {
657             return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
658         }
659         if (newListElement.getChildDataNodes().isEmpty()) {
660             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
661             existingListElementEntity.getChildFragments().clear();
662         } else {
663             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
664         }
665         return existingListElementEntity;
666     }
667
668     private static boolean isNewDataNode(final DataNode replacementDataNode,
669                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
670         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
671     }
672
673     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
674                                                   final DataNode newListElement) {
675         final FragmentEntity replacementFragmentEntity =
676                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
677                         newListElement.getLeaves())).build();
678         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
679     }
680
681     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
682             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
683         return childEntities.stream()
684                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
685                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
686     }
687
688     private static boolean isRootXpath(final String xpath) {
689         return "/".equals(xpath) || "".equals(xpath);
690     }
691
692     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
693         Map<String, Serializable> currentLeavesAsMap = new HashMap<>();
694         if (currentLeavesAsString != null) {
695             currentLeavesAsMap = currentLeavesAsString.isEmpty()
696                     ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
697             currentLeavesAsMap.putAll(updateLeaves);
698         }
699
700         if (currentLeavesAsMap.isEmpty()) {
701             return "";
702         }
703         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
704     }
705
706     private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
707         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
708         return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
709     }
710 }