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