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