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