Merge "Added depth parameter in query nodes API."
[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 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
266         final Set<String> normalizedXpaths = new HashSet<>(xpaths.size());
267         for (final String xpath : xpaths) {
268             try {
269                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
270             } catch (final PathParsingException e) {
271                 log.warn("Error parsing xpath \"{}\" in getDataNodes: {}", xpath, e.getMessage());
272             }
273         }
274
275         final List<FragmentEntity> fragmentEntities =
276                 fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths);
277         return toDataNodes(fragmentEntities, fetchDescendantsOption);
278     }
279
280     private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
281                                                                 final String anchorName,
282                                                                 final String xpath) {
283         return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
284     }
285
286     private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
287                                               final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
288         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
289         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
290         final FragmentEntity fragmentEntity;
291         if (isRootXpath(xpath)) {
292             final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
293                     anchorEntity);
294             fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
295                 .stream().findFirst().orElse(null);
296         } else {
297             final String normalizedXpath = getNormalizedXpath(xpath);
298             if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
299                 fragmentEntity =
300                     fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
301             } else {
302                 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
303                     .stream().findFirst().orElse(null);
304             }
305         }
306         if (fragmentEntity == null) {
307             throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
308         }
309         return fragmentEntity;
310
311     }
312
313     private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
314                                                                                  final String normalizedXpath) {
315         final List<FragmentExtract> fragmentExtracts =
316                 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
317         log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
318                 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
319         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
320
321     }
322
323     @Override
324     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
325                                          final FetchDescendantsOption fetchDescendantsOption) {
326         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
327         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
328         final CpsPathQuery cpsPathQuery;
329         try {
330             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
331         } catch (final PathParsingException e) {
332             throw new CpsPathException(e.getMessage());
333         }
334
335         Collection<FragmentEntity> fragmentEntities;
336         if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
337             return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
338         }
339         fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
340         if (cpsPathQuery.hasAncestorAxis()) {
341             fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
342         }
343         return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
344     }
345
346     private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
347                                                 final CpsPathQuery cpsPathQuery) {
348         return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
349             && !cpsPathQuery.hasLeafConditions()
350             && !cpsPathQuery.hasTextFunctionCondition();
351     }
352
353     private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
354                                                            final AnchorEntity anchorEntity,
355                                                            final CpsPathQuery cpsPathQuery) {
356         Collection<FragmentEntity> fragmentEntities;
357         final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
358         final List<FragmentExtract> fragmentExtracts =
359             fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
360         fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
361         if (cpsPathQuery.hasAncestorAxis()) {
362             fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
363         }
364         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
365     }
366
367     private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
368                                                                    final CpsPathQuery cpsPathQuery,
369                                                                    final Collection<FragmentEntity> fragmentEntities) {
370         final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
371         return ancestorXpaths.isEmpty() ? Collections.emptyList()
372             : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
373     }
374
375     private List<DataNode> createDataNodesFromProxiedFragmentEntities(
376                                             final FetchDescendantsOption fetchDescendantsOption,
377                                             final AnchorEntity anchorEntity,
378                                             final Collection<FragmentEntity> proxiedFragmentEntities) {
379         final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
380         for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
381             if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
382                 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
383             } else {
384                 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
385                 final Collection<FragmentEntity> unproxiedFragmentEntities =
386                     buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
387                 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
388                     dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
389                 }
390             }
391         }
392         return Collections.unmodifiableList(dataNodes);
393     }
394
395     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
396                                                                final Collection<FragmentEntity> fragmentEntities) {
397         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
398         for (final FragmentEntity fragmentEntity : fragmentEntities) {
399             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
400         }
401         return Collections.unmodifiableList(dataNodes);
402     }
403
404     private static String getNormalizedXpath(final String xpathSource) {
405         final String normalizedXpath;
406         try {
407             normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
408         } catch (final PathParsingException e) {
409             throw new CpsPathException(e.getMessage());
410         }
411         return normalizedXpath;
412     }
413
414     @Override
415     public String startSession() {
416         return sessionManager.startSession();
417     }
418
419     @Override
420     public void closeSession(final String sessionId) {
421         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
422     }
423
424     @Override
425     public void lockAnchor(final String sessionId, final String dataspaceName,
426                            final String anchorName, final Long timeoutInMilliseconds) {
427         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
428     }
429
430     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
431                                                     final CpsPathQuery cpsPathQuery) {
432         final Set<String> ancestorXpath = new HashSet<>();
433         final Pattern pattern =
434                 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
435                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
436         for (final FragmentEntity fragmentEntity : fragmentEntities) {
437             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
438             if (matcher.matches()) {
439                 ancestorXpath.add(matcher.group(1));
440             }
441         }
442         return ancestorXpath;
443     }
444
445     private DataNode toDataNode(final FragmentEntity fragmentEntity,
446                                 final FetchDescendantsOption fetchDescendantsOption) {
447         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
448         Map<String, Serializable> leaves = new HashMap<>();
449         if (fragmentEntity.getAttributes() != null) {
450             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
451         }
452         return new DataNodeBuilder()
453                 .withXpath(fragmentEntity.getXpath())
454                 .withLeaves(leaves)
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 FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
481         final String currentLeavesAsString = fragmentEntity.getAttributes();
482         final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
483         fragmentEntity.setAttributes(mergedLeaves);
484         fragmentRepository.save(fragmentEntity);
485     }
486
487     @Override
488     public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
489                                              final DataNode dataNode) {
490         final FragmentEntity fragmentEntity =
491             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
492         updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
493         try {
494             fragmentRepository.save(fragmentEntity);
495         } catch (final StaleStateException staleStateException) {
496             throw new ConcurrencyException("Concurrent Transactions",
497                     String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
498                             dataspaceName, anchorName, dataNode.getXpath()));
499         }
500     }
501
502     @Override
503     public void updateDataNodesAndDescendants(final String dataspaceName,
504                                               final String anchorName,
505                                               final List<DataNode> dataNodes) {
506
507         final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
508                 .collect(Collectors.toMap(
509                         dataNode -> dataNode,
510                         dataNode ->
511                             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
512         dataNodeFragmentEntityMap.forEach(
513                 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
514         try {
515             fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
516         } catch (final StaleStateException staleStateException) {
517             retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
518         }
519     }
520
521     private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
522                                                   final Collection<FragmentEntity> fragmentEntities) {
523         final Collection<String> failedXpaths = new HashSet<>();
524
525         fragmentEntities.forEach(dataNodeFragment -> {
526             try {
527                 fragmentRepository.save(dataNodeFragment);
528             } catch (final StaleStateException e) {
529                 failedXpaths.add(dataNodeFragment.getXpath());
530             }
531         });
532
533         if (!failedXpaths.isEmpty()) {
534             final String failedXpathsConcatenated = String.join(",", failedXpaths);
535             throw new ConcurrencyException("Concurrent Transactions", String.format(
536                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
537                     failedXpathsConcatenated, dataspaceName, anchorName));
538         }
539     }
540
541     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
542                                                                 final DataNode newDataNode) {
543
544         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
545
546         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
547                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
548
549         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
550
551         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
552             final FragmentEntity childFragment;
553             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
554                 childFragment = convertToFragmentWithAllDescendants(
555                         existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
556             } else {
557                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
558                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
559             }
560             updatedChildFragments.add(childFragment);
561         }
562
563         existingFragmentEntity.getChildFragments().clear();
564         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
565     }
566
567     @Override
568     @Transactional
569     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
570                                    final Collection<DataNode> newListElements) {
571         final FragmentEntity parentEntity =
572             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
573         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
574         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
575                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
576         deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
577         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
578         for (final DataNode newListElement : newListElements) {
579             final FragmentEntity existingListElementEntity =
580                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
581             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
582                     existingListElementEntity);
583
584             updatedChildFragmentEntities.add(entityToBeAdded);
585         }
586         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
587         fragmentRepository.save(parentEntity);
588     }
589
590     @Override
591     @Transactional
592     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
593         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
594         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
595                 .ifPresent(
596                         anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
597     }
598
599     @Override
600     @Transactional
601     public void deleteListDataNode(final String dataspaceName, final String anchorName,
602                                    final String targetXpath) {
603         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
604     }
605
606     @Override
607     @Transactional
608     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
609         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
610     }
611
612     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
613                                 final boolean onlySupportListNodeDeletion) {
614         final String parentNodeXpath;
615         FragmentEntity parentFragmentEntity = null;
616         boolean targetDeleted;
617         if (isRootXpath(targetXpath)) {
618             deleteDataNodes(dataspaceName, anchorName);
619             targetDeleted = true;
620         } else {
621             if (isRootContainerNodeXpath(targetXpath)) {
622                 parentNodeXpath = targetXpath;
623             } else {
624                 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
625             }
626             parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
627             if (CpsPathUtil.isPathToListElement(targetXpath)) {
628                 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
629             } else {
630                 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
631                 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
632                 if (tryToDeleteDataNode) {
633                     targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
634                 }
635             }
636         }
637         if (!targetDeleted) {
638             final String additionalInformation = onlySupportListNodeDeletion
639                     ? "The target is probably not a List." : "";
640             throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
641                     parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
642         }
643     }
644
645     private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
646         final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
647         if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
648             fragmentRepository.delete(parentFragmentEntity);
649             return true;
650         }
651         if (parentFragmentEntity.getChildFragments()
652                 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
653             fragmentRepository.save(parentFragmentEntity);
654             return true;
655         }
656         return false;
657     }
658
659     private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
660         final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
661         final String deleteTargetXpathPrefix = normalizedListXpath + "[";
662         if (parentFragmentEntity.getChildFragments()
663                 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
664             fragmentRepository.save(parentFragmentEntity);
665             return true;
666         }
667         return false;
668     }
669
670     private static void deleteListElements(
671             final Collection<FragmentEntity> fragmentEntities,
672             final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
673         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
674     }
675
676     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
677         if (newListElements.isEmpty()) {
678             throw new CpsAdminException("Invalid list replacement",
679                     "Cannot replace list elements with empty collection");
680         }
681         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
682         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
683     }
684
685     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
686                                                      final DataNode newListElement,
687                                                      final FragmentEntity existingListElementEntity) {
688         if (existingListElementEntity == null) {
689             return convertToFragmentWithAllDescendants(
690                     parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
691         }
692         if (newListElement.getChildDataNodes().isEmpty()) {
693             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
694             existingListElementEntity.getChildFragments().clear();
695         } else {
696             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
697         }
698         return existingListElementEntity;
699     }
700
701     private static boolean isNewDataNode(final DataNode replacementDataNode,
702                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
703         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
704     }
705
706     private static boolean isRootContainerNodeXpath(final String xpath) {
707         return 0 == xpath.lastIndexOf('/');
708     }
709
710     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
711                                                   final DataNode newListElement) {
712         final FragmentEntity replacementFragmentEntity =
713                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
714                         newListElement.getLeaves())).build();
715         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
716     }
717
718     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
719             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
720         return childEntities.stream()
721                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
722                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
723     }
724
725     private static boolean isRootXpath(final String xpath) {
726         return "/".equals(xpath) || "".equals(xpath);
727     }
728
729     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
730         final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
731             ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
732         currentLeavesAsMap.putAll(updateLeaves);
733         if (currentLeavesAsMap.isEmpty()) {
734             return "";
735         }
736         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
737     }
738 }