Support for Patch across multiple data nodes
[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 = "(\\[@.+?])?)";
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 storeDataNodes(final String dataspaceName, final String anchorName,
175                                final Collection<DataNode> dataNodes) {
176         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
177         final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
178         try {
179             for (final DataNode dataNode: dataNodes) {
180                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
181                 fragmentEntities.add(fragmentEntity);
182             }
183             fragmentRepository.saveAll(fragmentEntities);
184         } catch (final DataIntegrityViolationException exception) {
185             log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
186                     exception, dataNodes.size());
187             storeDataNodesIndividually(anchorEntity, dataNodes);
188         }
189     }
190
191     private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
192         final Collection<String> failedXpaths = new HashSet<>();
193         for (final DataNode dataNode: dataNodes) {
194             try {
195                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
196                 fragmentRepository.save(fragmentEntity);
197             } catch (final DataIntegrityViolationException e) {
198                 failedXpaths.add(dataNode.getXpath());
199             }
200         }
201         if (!failedXpaths.isEmpty()) {
202             throw new AlreadyDefinedExceptionBatch(failedXpaths);
203         }
204     }
205
206     /**
207      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
208      * for all DataNode children recursively.
209      *
210      * @param anchorEntity          anchorEntity
211      * @param dataNodeToBeConverted dataNode
212      * @return a Fragment built from current DataNode
213      */
214     private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
215                                                                final DataNode dataNodeToBeConverted) {
216         final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
217         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
218         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
219             final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
220             childFragmentsImmutableSetBuilder.add(childFragment);
221         }
222         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
223         return parentFragment;
224     }
225
226     private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
227         return FragmentEntity.builder()
228                 .dataspace(anchorEntity.getDataspace())
229                 .anchor(anchorEntity)
230                 .xpath(dataNode.getXpath())
231                 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
232                 .build();
233     }
234
235     @Override
236     @Timed(value = "cps.data.persistence.service.datanode.get",
237             description = "Time taken to get a data node")
238     public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
239                                              final String xpath,
240                                              final FetchDescendantsOption fetchDescendantsOption) {
241         final String targetXpath = getNormalizedXpath(xpath);
242         final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
243                 Collections.singletonList(targetXpath), fetchDescendantsOption);
244         if (dataNodes.isEmpty()) {
245             throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
246         }
247         return dataNodes;
248     }
249
250     @Override
251     @Timed(value = "cps.data.persistence.service.datanode.batch.get",
252             description = "Time taken to get data nodes")
253     public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
254                                                               final Collection<String> xpaths,
255                                                               final FetchDescendantsOption fetchDescendantsOption) {
256         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
257         final Collection<FragmentEntity> fragmentEntities =
258             getFragmentEntities(anchorEntity, xpaths, fetchDescendantsOption);
259         return toDataNodes(fragmentEntities, fetchDescendantsOption);
260     }
261
262     private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
263                                                            final Collection<String> xpaths,
264                                                            final FetchDescendantsOption fetchDescendantsOption) {
265         final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
266         final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
267
268         final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
269         for (final String xpath : nonRootXpaths) {
270             try {
271                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
272             } catch (final PathParsingException e) {
273                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
274             }
275         }
276         if (haveRootXpath) {
277             normalizedXpaths.addAll(fragmentRepository.findAllXpathByAnchorAndParentIdIsNull(anchorEntity));
278         }
279
280         final List<FragmentExtract> fragmentExtracts =
281             fragmentRepository.findExtractsWithDescendants(anchorEntity.getId(), normalizedXpaths,
282                 fetchDescendantsOption.getDepth());
283
284         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
285     }
286
287     private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
288         final FragmentEntity fragmentEntity;
289         if (isRootXpath(xpath)) {
290             final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
291             fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
292                 .stream().findFirst().orElse(null);
293         } else {
294             fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
295         }
296         if (fragmentEntity == null) {
297             throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
298         }
299         return fragmentEntity;
300     }
301
302     @Override
303     @Timed(value = "cps.data.persistence.service.datanode.query",
304             description = "Time taken to query data nodes")
305     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
306                                          final FetchDescendantsOption fetchDescendantsOption) {
307         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
308         final AnchorEntity anchorEntity = Strings.isNullOrEmpty(anchorName) ? ALL_ANCHORS
309             : anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
310         final CpsPathQuery cpsPathQuery;
311         try {
312             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
313         } catch (final PathParsingException e) {
314             throw new CpsPathException(e.getMessage());
315         }
316
317         Collection<FragmentEntity> fragmentEntities;
318         if (anchorEntity == ALL_ANCHORS) {
319             fragmentEntities = fragmentRepository.findByDataspaceAndCpsPath(dataspaceEntity, cpsPathQuery);
320         } else {
321             fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity, cpsPathQuery);
322         }
323         if (cpsPathQuery.hasAncestorAxis()) {
324             final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
325             if (anchorEntity == ALL_ANCHORS) {
326                 fragmentEntities = fragmentRepository.findByDataspaceAndXpathIn(dataspaceEntity, ancestorXpaths);
327             } else {
328                 fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
329             }
330         }
331         fragmentEntities = prefetchDescendantsForFragmentEntities(fetchDescendantsOption, anchorEntity,
332             fragmentEntities);
333         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
334     }
335
336     @Override
337     public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
338                                                       final FetchDescendantsOption fetchDescendantsOption) {
339         return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
340     }
341
342     private Collection<FragmentEntity> prefetchDescendantsForFragmentEntities(
343                                             final FetchDescendantsOption fetchDescendantsOption,
344                                             final AnchorEntity anchorEntity,
345                                             final Collection<FragmentEntity> proxiedFragmentEntities) {
346         if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
347             return proxiedFragmentEntities;
348         }
349
350         final List<Long> fragmentEntityIds = proxiedFragmentEntities.stream()
351             .map(FragmentEntity::getId).collect(Collectors.toList());
352
353         final List<FragmentExtract> fragmentExtracts =
354             fragmentRepository.findExtractsWithDescendantsByIds(fragmentEntityIds, fetchDescendantsOption.getDepth());
355
356         if (anchorEntity == ALL_ANCHORS) {
357             final Collection<Integer> anchorIds = fragmentExtracts.stream()
358                 .map(FragmentExtract::getAnchorId).collect(Collectors.toSet());
359             final List<AnchorEntity> anchorEntities = anchorRepository.findAllById(anchorIds);
360             final Map<Integer, AnchorEntity> anchorEntityPerId = anchorEntities.stream()
361                 .collect(Collectors.toMap(AnchorEntity::getId, Function.identity()));
362             return FragmentEntityArranger.toFragmentEntityTreesAcrossAnchors(anchorEntityPerId, fragmentExtracts);
363         }
364         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
365     }
366
367     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
368                                                                final Collection<FragmentEntity> fragmentEntities) {
369         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
370         for (final FragmentEntity fragmentEntity : fragmentEntities) {
371             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
372         }
373         return Collections.unmodifiableList(dataNodes);
374     }
375
376     private static String getNormalizedXpath(final String xpathSource) {
377         if (isRootXpath(xpathSource)) {
378             return xpathSource;
379         }
380         try {
381             return CpsPathUtil.getNormalizedXpath(xpathSource);
382         } catch (final PathParsingException e) {
383             throw new CpsPathException(e.getMessage());
384         }
385     }
386
387     @Override
388     public String startSession() {
389         return sessionManager.startSession();
390     }
391
392     @Override
393     public void closeSession(final String sessionId) {
394         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
395     }
396
397     @Override
398     public void lockAnchor(final String sessionId, final String dataspaceName,
399                            final String anchorName, final Long timeoutInMilliseconds) {
400         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
401     }
402
403     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
404                                                     final CpsPathQuery cpsPathQuery) {
405         final Set<String> ancestorXpath = new HashSet<>();
406         final Pattern pattern =
407                 Pattern.compile("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
408                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
409         for (final FragmentEntity fragmentEntity : fragmentEntities) {
410             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
411             if (matcher.matches()) {
412                 ancestorXpath.add(matcher.group(1));
413             }
414         }
415         return ancestorXpath;
416     }
417
418     private DataNode toDataNode(final FragmentEntity fragmentEntity,
419                                 final FetchDescendantsOption fetchDescendantsOption) {
420         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
421         Map<String, Serializable> leaves = new HashMap<>();
422         if (fragmentEntity.getAttributes() != null) {
423             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
424         }
425         return new DataNodeBuilder()
426                 .withXpath(fragmentEntity.getXpath())
427                 .withLeaves(leaves)
428                 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
429                 .withAnchor(fragmentEntity.getAnchor().getName())
430                 .withChildDataNodes(childDataNodes).build();
431     }
432
433     private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
434                                              final FetchDescendantsOption fetchDescendantsOption) {
435         final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
436         for (final FragmentEntity fragmentEntity : fragmentEntities) {
437             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
438         }
439         return dataNodes;
440     }
441
442     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
443                                              final FetchDescendantsOption fetchDescendantsOption) {
444         if (fetchDescendantsOption.hasNext()) {
445             return fragmentEntity.getChildFragments().stream()
446                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
447                     .collect(Collectors.toList());
448         }
449         return Collections.emptyList();
450     }
451
452     @Override
453     public void batchUpdateDataLeaves(final String dataspaceName, final String anchorName,
454                                         final Map<String, Map<String, Serializable>> updatedLeavesPerXPath) {
455         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
456
457         final Collection<String> xpathsOfUpdatedLeaves = updatedLeavesPerXPath.keySet();
458         final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpathsOfUpdatedLeaves,
459                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
460
461         for (final FragmentEntity fragmentEntity : fragmentEntities) {
462             final Map<String, Serializable> updatedLeaves = updatedLeavesPerXPath.get(fragmentEntity.getXpath());
463             final String mergedLeaves = mergeLeaves(updatedLeaves, fragmentEntity.getAttributes());
464             fragmentEntity.setAttributes(mergedLeaves);
465         }
466
467         try {
468             fragmentRepository.saveAll(fragmentEntities);
469         } catch (final StaleStateException staleStateException) {
470             retryUpdateDataNodesIndividually(anchorEntity, fragmentEntities);
471         }
472     }
473
474     @Override
475     public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
476                                               final Collection<DataNode> updatedDataNodes) {
477         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
478
479         final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
480             .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
481
482         final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
483         final Collection<FragmentEntity> existingFragmentEntities =
484             getFragmentEntities(anchorEntity, xpaths, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
485
486         for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
487             final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
488             updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
489         }
490
491         try {
492             fragmentRepository.saveAll(existingFragmentEntities);
493         } catch (final StaleStateException staleStateException) {
494             retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
495         }
496     }
497
498     private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
499                                                   final Collection<FragmentEntity> fragmentEntities) {
500         final Collection<String> failedXpaths = new HashSet<>();
501         for (final FragmentEntity dataNodeFragment : fragmentEntities) {
502             try {
503                 fragmentRepository.save(dataNodeFragment);
504             } catch (final StaleStateException e) {
505                 failedXpaths.add(dataNodeFragment.getXpath());
506             }
507         }
508         if (!failedXpaths.isEmpty()) {
509             final String failedXpathsConcatenated = String.join(",", failedXpaths);
510             throw new ConcurrencyException("Concurrent Transactions", String.format(
511                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
512                     failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
513         }
514     }
515
516     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
517                                                                 final DataNode newDataNode) {
518         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
519
520         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
521                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
522
523         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
524         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
525             final FragmentEntity childFragment;
526             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
527                 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
528                     newDataNodeChild);
529             } else {
530                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
531                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
532             }
533             updatedChildFragments.add(childFragment);
534         }
535
536         existingFragmentEntity.getChildFragments().clear();
537         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
538     }
539
540     @Override
541     @Transactional
542     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
543                                    final Collection<DataNode> newListElements) {
544         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
545         final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
546         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
547         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
548                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
549         parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
550         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
551         for (final DataNode newListElement : newListElements) {
552             final FragmentEntity existingListElementEntity =
553                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
554             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
555                     existingListElementEntity);
556             updatedChildFragmentEntities.add(entityToBeAdded);
557         }
558         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
559         fragmentRepository.save(parentEntity);
560     }
561
562     @Override
563     @Transactional
564     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
565         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
566         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
567             .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
568     }
569
570     @Override
571     @Transactional
572     public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
573         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
574         final Collection<AnchorEntity> anchorEntities =
575             anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
576         fragmentRepository.deleteByAnchorIn(anchorEntities);
577     }
578
579     @Override
580     @Transactional
581     public void deleteDataNodes(final String dataspaceName, final String anchorName,
582                                 final Collection<String> xpathsToDelete) {
583         deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
584     }
585
586     private void deleteDataNodes(final String dataspaceName, final String anchorName,
587                                  final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
588         final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
589         if (haveRootXpath) {
590             deleteDataNodes(dataspaceName, anchorName);
591             return;
592         }
593
594         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
595
596         final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
597         for (final String xpath : xpathsToDelete) {
598             try {
599                 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
600             } catch (final PathParsingException e) {
601                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
602             }
603         }
604
605         final Collection<String> xpathsToExistingContainers =
606             fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
607         if (onlySupportListDeletion) {
608             final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
609                 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
610             deleteChecklist.removeAll(xpathsToExistingListElements);
611         } else {
612             deleteChecklist.removeAll(xpathsToExistingContainers);
613         }
614
615         final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
616             .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
617             .collect(Collectors.toList());
618         deleteChecklist.removeAll(xpathsToExistingLists);
619
620         if (!deleteChecklist.isEmpty()) {
621             throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
622         }
623
624         fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
625         fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
626     }
627
628     @Override
629     @Transactional
630     public void deleteListDataNode(final String dataspaceName, final String anchorName,
631                                    final String targetXpath) {
632         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
633     }
634
635     @Override
636     @Transactional
637     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
638         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
639     }
640
641     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
642                                 final boolean onlySupportListNodeDeletion) {
643         final String normalizedXpath = getNormalizedXpath(targetXpath);
644         try {
645             deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
646                 onlySupportListNodeDeletion);
647         } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
648             throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
649         }
650     }
651
652     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
653         if (newListElements.isEmpty()) {
654             throw new CpsAdminException("Invalid list replacement",
655                     "Cannot replace list elements with empty collection");
656         }
657         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
658         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
659     }
660
661     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
662                                                      final DataNode newListElement,
663                                                      final FragmentEntity existingListElementEntity) {
664         if (existingListElementEntity == null) {
665             return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
666         }
667         if (newListElement.getChildDataNodes().isEmpty()) {
668             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
669             existingListElementEntity.getChildFragments().clear();
670         } else {
671             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
672         }
673         return existingListElementEntity;
674     }
675
676     private static boolean isNewDataNode(final DataNode replacementDataNode,
677                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
678         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
679     }
680
681     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
682                                                   final DataNode newListElement) {
683         final FragmentEntity replacementFragmentEntity =
684                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
685                         newListElement.getLeaves())).build();
686         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
687     }
688
689     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
690             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
691         return childEntities.stream()
692                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
693                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
694     }
695
696     private static boolean isRootXpath(final String xpath) {
697         return "/".equals(xpath) || "".equals(xpath);
698     }
699
700     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
701         Map<String, Serializable> currentLeavesAsMap = new HashMap<>();
702         if (currentLeavesAsString != null) {
703             currentLeavesAsMap = currentLeavesAsString.isEmpty()
704                     ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
705             currentLeavesAsMap.putAll(updateLeaves);
706         }
707
708         if (currentLeavesAsMap.isEmpty()) {
709             return "";
710         }
711         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
712     }
713
714     private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
715         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
716         return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
717     }
718 }