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