Merge "DMI Data AVC to use kafka headers"
[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                 .dataspace(anchorEntity.getDataspace())
222                 .anchor(anchorEntity)
223                 .xpath(dataNode.getXpath())
224                 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
225                 .build();
226     }
227
228     @Override
229     @Timed(value = "cps.data.persistence.service.datanode.get",
230             description = "Time taken to get a data node")
231     public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
232                                              final String xpath,
233                                              final FetchDescendantsOption fetchDescendantsOption) {
234         final String targetXpath = getNormalizedXpath(xpath);
235         final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
236                 Collections.singletonList(targetXpath), fetchDescendantsOption);
237         if (dataNodes.isEmpty()) {
238             throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
239         }
240         return dataNodes;
241     }
242
243     @Override
244     @Timed(value = "cps.data.persistence.service.datanode.batch.get",
245             description = "Time taken to get data nodes")
246     public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
247                                                               final Collection<String> xpaths,
248                                                               final FetchDescendantsOption fetchDescendantsOption) {
249         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
250         final Collection<FragmentEntity> fragmentEntities =
251             getFragmentEntities(anchorEntity, xpaths, fetchDescendantsOption);
252         return toDataNodes(fragmentEntities, fetchDescendantsOption);
253     }
254
255     private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
256                                                            final Collection<String> xpaths,
257                                                            final FetchDescendantsOption fetchDescendantsOption) {
258         final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
259         final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
260
261         final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
262         for (final String xpath : nonRootXpaths) {
263             try {
264                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
265             } catch (final PathParsingException e) {
266                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
267             }
268         }
269         if (haveRootXpath) {
270             normalizedXpaths.addAll(fragmentRepository.findAllXpathByAnchorAndParentIdIsNull(anchorEntity));
271         }
272
273         final List<FragmentExtract> fragmentExtracts =
274             fragmentRepository.findExtractsWithDescendants(anchorEntity.getId(), normalizedXpaths,
275                 fetchDescendantsOption.getDepth());
276
277         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
278     }
279
280     private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
281         final FragmentEntity fragmentEntity;
282         if (isRootXpath(xpath)) {
283             final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
284             fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
285                 .stream().findFirst().orElse(null);
286         } else {
287             fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
288         }
289         if (fragmentEntity == null) {
290             throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
291         }
292         return fragmentEntity;
293     }
294
295     @Override
296     @Timed(value = "cps.data.persistence.service.datanode.query",
297             description = "Time taken to query data nodes")
298     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
299                                          final FetchDescendantsOption fetchDescendantsOption) {
300         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
301         final AnchorEntity anchorEntity = Strings.isNullOrEmpty(anchorName) ? ALL_ANCHORS
302             : anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
303         final CpsPathQuery cpsPathQuery;
304         try {
305             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
306         } catch (final PathParsingException e) {
307             throw new CpsPathException(e.getMessage());
308         }
309
310         Collection<FragmentEntity> fragmentEntities;
311         if (anchorEntity == ALL_ANCHORS) {
312             fragmentEntities = fragmentRepository.findByDataspaceAndCpsPath(dataspaceEntity, cpsPathQuery);
313         } else {
314             fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity, cpsPathQuery);
315         }
316         if (cpsPathQuery.hasAncestorAxis()) {
317             final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
318             if (anchorEntity == ALL_ANCHORS) {
319                 fragmentEntities = fragmentRepository.findByDataspaceAndXpathIn(dataspaceEntity, ancestorXpaths);
320             } else {
321                 fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
322             }
323         }
324         fragmentEntities = prefetchDescendantsForFragmentEntities(fetchDescendantsOption, anchorEntity,
325             fragmentEntities);
326         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
327     }
328
329     @Override
330     public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
331                                                       final FetchDescendantsOption fetchDescendantsOption) {
332         return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
333     }
334
335     private Collection<FragmentEntity> prefetchDescendantsForFragmentEntities(
336                                             final FetchDescendantsOption fetchDescendantsOption,
337                                             final AnchorEntity anchorEntity,
338                                             final Collection<FragmentEntity> proxiedFragmentEntities) {
339         if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
340             return proxiedFragmentEntities;
341         }
342
343         final List<Long> fragmentEntityIds = proxiedFragmentEntities.stream()
344             .map(FragmentEntity::getId).collect(Collectors.toList());
345
346         final List<FragmentExtract> fragmentExtracts =
347             fragmentRepository.findExtractsWithDescendantsByIds(fragmentEntityIds, fetchDescendantsOption.getDepth());
348
349         if (anchorEntity == ALL_ANCHORS) {
350             final Collection<Integer> anchorIds = fragmentExtracts.stream()
351                 .map(FragmentExtract::getAnchorId).collect(Collectors.toSet());
352             final List<AnchorEntity> anchorEntities = anchorRepository.findAllById(anchorIds);
353             final Map<Integer, AnchorEntity> anchorEntityPerId = anchorEntities.stream()
354                 .collect(Collectors.toMap(AnchorEntity::getId, Function.identity()));
355             return FragmentEntityArranger.toFragmentEntityTreesAcrossAnchors(anchorEntityPerId, fragmentExtracts);
356         }
357         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
358     }
359
360     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
361                                                                final Collection<FragmentEntity> fragmentEntities) {
362         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
363         for (final FragmentEntity fragmentEntity : fragmentEntities) {
364             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
365         }
366         return Collections.unmodifiableList(dataNodes);
367     }
368
369     private static String getNormalizedXpath(final String xpathSource) {
370         if (isRootXpath(xpathSource)) {
371             return xpathSource;
372         }
373         try {
374             return CpsPathUtil.getNormalizedXpath(xpathSource);
375         } catch (final PathParsingException e) {
376             throw new CpsPathException(e.getMessage());
377         }
378     }
379
380     @Override
381     public String startSession() {
382         return sessionManager.startSession();
383     }
384
385     @Override
386     public void closeSession(final String sessionId) {
387         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
388     }
389
390     @Override
391     public void lockAnchor(final String sessionId, final String dataspaceName,
392                            final String anchorName, final Long timeoutInMilliseconds) {
393         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
394     }
395
396     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
397                                                     final CpsPathQuery cpsPathQuery) {
398         final Set<String> ancestorXpath = new HashSet<>();
399         final Pattern pattern =
400                 Pattern.compile("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
401                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
402         for (final FragmentEntity fragmentEntity : fragmentEntities) {
403             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
404             if (matcher.matches()) {
405                 ancestorXpath.add(matcher.group(1));
406             }
407         }
408         return ancestorXpath;
409     }
410
411     private DataNode toDataNode(final FragmentEntity fragmentEntity,
412                                 final FetchDescendantsOption fetchDescendantsOption) {
413         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
414         Map<String, Serializable> leaves = new HashMap<>();
415         if (fragmentEntity.getAttributes() != null) {
416             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
417         }
418         return new DataNodeBuilder()
419                 .withXpath(fragmentEntity.getXpath())
420                 .withLeaves(leaves)
421                 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
422                 .withAnchor(fragmentEntity.getAnchor().getName())
423                 .withChildDataNodes(childDataNodes).build();
424     }
425
426     private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
427                                              final FetchDescendantsOption fetchDescendantsOption) {
428         final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
429         for (final FragmentEntity fragmentEntity : fragmentEntities) {
430             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
431         }
432         return dataNodes;
433     }
434
435     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
436                                              final FetchDescendantsOption fetchDescendantsOption) {
437         if (fetchDescendantsOption.hasNext()) {
438             return fragmentEntity.getChildFragments().stream()
439                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
440                     .collect(Collectors.toList());
441         }
442         return Collections.emptyList();
443     }
444
445     @Override
446     public void batchUpdateDataLeaves(final String dataspaceName, final String anchorName,
447                                         final Map<String, Map<String, Serializable>> updatedLeavesPerXPath) {
448         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
449
450         final Collection<String> xpathsOfUpdatedLeaves = updatedLeavesPerXPath.keySet();
451         final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpathsOfUpdatedLeaves,
452                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
453
454         for (final FragmentEntity fragmentEntity : fragmentEntities) {
455             final Map<String, Serializable> updatedLeaves = updatedLeavesPerXPath.get(fragmentEntity.getXpath());
456             final String mergedLeaves = mergeLeaves(updatedLeaves, fragmentEntity.getAttributes());
457             fragmentEntity.setAttributes(mergedLeaves);
458         }
459
460         try {
461             fragmentRepository.saveAll(fragmentEntities);
462         } catch (final StaleStateException staleStateException) {
463             retryUpdateDataNodesIndividually(anchorEntity, fragmentEntities);
464         }
465     }
466
467     @Override
468     public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
469                                               final Collection<DataNode> updatedDataNodes) {
470         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
471
472         final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
473             .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
474
475         final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
476         final Collection<FragmentEntity> existingFragmentEntities =
477             getFragmentEntities(anchorEntity, xpaths, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
478
479         for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
480             final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
481             updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
482         }
483
484         try {
485             fragmentRepository.saveAll(existingFragmentEntities);
486         } catch (final StaleStateException staleStateException) {
487             retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
488         }
489     }
490
491     private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
492                                                   final Collection<FragmentEntity> fragmentEntities) {
493         final Collection<String> failedXpaths = new HashSet<>();
494         for (final FragmentEntity dataNodeFragment : fragmentEntities) {
495             try {
496                 fragmentRepository.save(dataNodeFragment);
497             } catch (final StaleStateException e) {
498                 failedXpaths.add(dataNodeFragment.getXpath());
499             }
500         }
501         if (!failedXpaths.isEmpty()) {
502             final String failedXpathsConcatenated = String.join(",", failedXpaths);
503             throw new ConcurrencyException("Concurrent Transactions", String.format(
504                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
505                     failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
506         }
507     }
508
509     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
510                                                                 final DataNode newDataNode) {
511         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
512
513         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
514                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
515
516         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
517         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
518             final FragmentEntity childFragment;
519             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
520                 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
521                     newDataNodeChild);
522             } else {
523                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
524                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
525             }
526             updatedChildFragments.add(childFragment);
527         }
528
529         existingFragmentEntity.getChildFragments().clear();
530         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
531     }
532
533     @Override
534     @Transactional
535     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
536                                    final Collection<DataNode> newListElements) {
537         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
538         final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
539         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
540         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
541                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
542         parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
543         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
544         for (final DataNode newListElement : newListElements) {
545             final FragmentEntity existingListElementEntity =
546                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
547             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
548                     existingListElementEntity);
549             updatedChildFragmentEntities.add(entityToBeAdded);
550         }
551         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
552         fragmentRepository.save(parentEntity);
553     }
554
555     @Override
556     @Transactional
557     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
558         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
559         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
560             .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
561     }
562
563     @Override
564     @Transactional
565     public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
566         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
567         final Collection<AnchorEntity> anchorEntities =
568             anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
569         fragmentRepository.deleteByAnchorIn(anchorEntities);
570     }
571
572     @Override
573     @Transactional
574     public void deleteDataNodes(final String dataspaceName, final String anchorName,
575                                 final Collection<String> xpathsToDelete) {
576         deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
577     }
578
579     private void deleteDataNodes(final String dataspaceName, final String anchorName,
580                                  final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
581         final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
582         if (haveRootXpath) {
583             deleteDataNodes(dataspaceName, anchorName);
584             return;
585         }
586
587         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
588
589         final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
590         for (final String xpath : xpathsToDelete) {
591             try {
592                 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
593             } catch (final PathParsingException e) {
594                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
595             }
596         }
597
598         final Collection<String> xpathsToExistingContainers =
599             fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
600         if (onlySupportListDeletion) {
601             final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
602                 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
603             deleteChecklist.removeAll(xpathsToExistingListElements);
604         } else {
605             deleteChecklist.removeAll(xpathsToExistingContainers);
606         }
607
608         final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
609             .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
610             .collect(Collectors.toList());
611         deleteChecklist.removeAll(xpathsToExistingLists);
612
613         if (!deleteChecklist.isEmpty()) {
614             throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
615         }
616
617         fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
618         fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
619     }
620
621     @Override
622     @Transactional
623     public void deleteListDataNode(final String dataspaceName, final String anchorName,
624                                    final String targetXpath) {
625         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
626     }
627
628     @Override
629     @Transactional
630     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
631         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
632     }
633
634     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
635                                 final boolean onlySupportListNodeDeletion) {
636         final String normalizedXpath = getNormalizedXpath(targetXpath);
637         try {
638             deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
639                 onlySupportListNodeDeletion);
640         } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
641             throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
642         }
643     }
644
645     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
646         if (newListElements.isEmpty()) {
647             throw new CpsAdminException("Invalid list replacement",
648                     "Cannot replace list elements with empty collection");
649         }
650         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
651         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
652     }
653
654     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
655                                                      final DataNode newListElement,
656                                                      final FragmentEntity existingListElementEntity) {
657         if (existingListElementEntity == null) {
658             return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
659         }
660         if (newListElement.getChildDataNodes().isEmpty()) {
661             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
662             existingListElementEntity.getChildFragments().clear();
663         } else {
664             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
665         }
666         return existingListElementEntity;
667     }
668
669     private static boolean isNewDataNode(final DataNode replacementDataNode,
670                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
671         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
672     }
673
674     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
675                                                   final DataNode newListElement) {
676         final FragmentEntity replacementFragmentEntity =
677                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
678                         newListElement.getLeaves())).build();
679         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
680     }
681
682     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
683             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
684         return childEntities.stream()
685                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
686                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
687     }
688
689     private static boolean isRootXpath(final String xpath) {
690         return "/".equals(xpath) || "".equals(xpath);
691     }
692
693     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
694         Map<String, Serializable> currentLeavesAsMap = new HashMap<>();
695         if (currentLeavesAsString != null) {
696             currentLeavesAsMap = currentLeavesAsString.isEmpty()
697                     ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
698             currentLeavesAsMap.putAll(updateLeaves);
699         }
700
701         if (currentLeavesAsMap.isEmpty()) {
702             return "";
703         }
704         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
705     }
706
707     private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
708         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
709         return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
710     }
711 }