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