Add RTD link to CPS in Release notes
[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.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.stream.Collectors;
42 import javax.transaction.Transactional;
43 import lombok.RequiredArgsConstructor;
44 import lombok.extern.slf4j.Slf4j;
45 import org.hibernate.StaleStateException;
46 import org.onap.cps.cpspath.parser.CpsPathQuery;
47 import org.onap.cps.cpspath.parser.CpsPathUtil;
48 import org.onap.cps.cpspath.parser.PathParsingException;
49 import org.onap.cps.spi.CpsDataPersistenceService;
50 import org.onap.cps.spi.FetchDescendantsOption;
51 import org.onap.cps.spi.entities.AnchorEntity;
52 import org.onap.cps.spi.entities.DataspaceEntity;
53 import org.onap.cps.spi.entities.FragmentEntity;
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.exceptions.DataNodeNotFoundExceptionBatch;
61 import org.onap.cps.spi.model.DataNode;
62 import org.onap.cps.spi.model.DataNodeBuilder;
63 import org.onap.cps.spi.repository.AnchorRepository;
64 import org.onap.cps.spi.repository.DataspaceRepository;
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 = "(\\[@.+?])?)";
83     private static final String QUERY_ACROSS_ANCHORS = null;
84     private static final AnchorEntity ALL_ANCHORS = null;
85
86     @Override
87     public void addChildDataNodes(final String dataspaceName, final String anchorName,
88                                   final String parentNodeXpath, final Collection<DataNode> dataNodes) {
89         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
90         addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
91     }
92
93     @Override
94     public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
95                                 final Collection<DataNode> newListElements) {
96         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
97         addChildrenDataNodes(anchorEntity, parentNodeXpath, newListElements);
98     }
99
100     @Override
101     public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
102                                  final Collection<Collection<DataNode>> newLists) {
103         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
104         final Collection<String> failedXpaths = new HashSet<>();
105         for (final Collection<DataNode> newList : newLists) {
106             try {
107                 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
108             } catch (final AlreadyDefinedExceptionBatch e) {
109                 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
110             }
111         }
112         if (!failedXpaths.isEmpty()) {
113             throw new AlreadyDefinedExceptionBatch(failedXpaths);
114         }
115     }
116
117     private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
118                                      final DataNode newChild) {
119         final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
120         final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
121         newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
122         try {
123             fragmentRepository.save(newChildAsFragmentEntity);
124         } catch (final DataIntegrityViolationException e) {
125             throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorEntity.getName(), e);
126         }
127     }
128
129     private void addChildrenDataNodes(final AnchorEntity anchorEntity, final String parentNodeXpath,
130                                       final Collection<DataNode> newChildren) {
131         final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
132         final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
133         try {
134             for (final DataNode newChildAsDataNode : newChildren) {
135                 final FragmentEntity newChildAsFragmentEntity =
136                     convertToFragmentWithAllDescendants(anchorEntity, newChildAsDataNode);
137                 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
138                 fragmentEntities.add(newChildAsFragmentEntity);
139             }
140             fragmentRepository.saveAll(fragmentEntities);
141         } catch (final DataIntegrityViolationException e) {
142             log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
143                     e, fragmentEntities.size());
144             retrySavingEachChildIndividually(anchorEntity, parentNodeXpath, newChildren);
145         }
146     }
147
148     private void retrySavingEachChildIndividually(final AnchorEntity anchorEntity, final String parentNodeXpath,
149                                                   final Collection<DataNode> newChildren) {
150         final Collection<String> failedXpaths = new HashSet<>();
151         for (final DataNode newChild : newChildren) {
152             try {
153                 addNewChildDataNode(anchorEntity, parentNodeXpath, newChild);
154             } catch (final AlreadyDefinedException e) {
155                 failedXpaths.add(newChild.getXpath());
156             }
157         }
158         if (!failedXpaths.isEmpty()) {
159             throw new AlreadyDefinedExceptionBatch(failedXpaths);
160         }
161     }
162
163     @Override
164     public void storeDataNodes(final String dataspaceName, final String anchorName,
165                                final Collection<DataNode> dataNodes) {
166         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
167         final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
168         try {
169             for (final DataNode dataNode: dataNodes) {
170                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
171                 fragmentEntities.add(fragmentEntity);
172             }
173             fragmentRepository.saveAll(fragmentEntities);
174         } catch (final DataIntegrityViolationException exception) {
175             log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
176                     exception, dataNodes.size());
177             storeDataNodesIndividually(anchorEntity, dataNodes);
178         }
179     }
180
181     private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
182         final Collection<String> failedXpaths = new HashSet<>();
183         for (final DataNode dataNode: dataNodes) {
184             try {
185                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
186                 fragmentRepository.save(fragmentEntity);
187             } catch (final DataIntegrityViolationException e) {
188                 failedXpaths.add(dataNode.getXpath());
189             }
190         }
191         if (!failedXpaths.isEmpty()) {
192             throw new AlreadyDefinedExceptionBatch(failedXpaths);
193         }
194     }
195
196     /**
197      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
198      * for all DataNode children recursively.
199      *
200      * @param anchorEntity          anchorEntity
201      * @param dataNodeToBeConverted dataNode
202      * @return a Fragment built from current DataNode
203      */
204     private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
205                                                                final DataNode dataNodeToBeConverted) {
206         final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
207         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
208         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
209             final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
210             childFragmentsImmutableSetBuilder.add(childFragment);
211         }
212         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
213         return parentFragment;
214     }
215
216     private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
217         return FragmentEntity.builder()
218                 .anchor(anchorEntity)
219                 .xpath(dataNode.getXpath())
220                 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
221                 .build();
222     }
223
224     @Override
225     @Timed(value = "cps.data.persistence.service.datanode.get",
226             description = "Time taken to get a data node")
227     public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
228                                              final String xpath,
229                                              final FetchDescendantsOption fetchDescendantsOption) {
230         final String targetXpath = getNormalizedXpath(xpath);
231         final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
232                 Collections.singletonList(targetXpath), fetchDescendantsOption);
233         if (dataNodes.isEmpty()) {
234             throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
235         }
236         return dataNodes;
237     }
238
239     @Override
240     @Timed(value = "cps.data.persistence.service.datanode.batch.get",
241             description = "Time taken to get data nodes")
242     public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
243                                                               final Collection<String> xpaths,
244                                                               final FetchDescendantsOption fetchDescendantsOption) {
245         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
246         final Collection<FragmentEntity> fragmentEntities =
247             getFragmentEntities(anchorEntity, xpaths, fetchDescendantsOption);
248         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
249     }
250
251     private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
252                                                            final Collection<String> xpaths,
253                                                            final FetchDescendantsOption fetchDescendantsOption) {
254         final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
255         final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
256
257         final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
258         for (final String xpath : nonRootXpaths) {
259             try {
260                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
261             } catch (final PathParsingException e) {
262                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
263             }
264         }
265         if (haveRootXpath) {
266             normalizedXpaths.addAll(fragmentRepository.findAllXpathByAnchorAndParentIdIsNull(anchorEntity));
267         }
268
269         final List<FragmentEntity> fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity,
270                 normalizedXpaths);
271
272         return fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption, fragmentEntities);
273     }
274
275     private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
276         final FragmentEntity fragmentEntity;
277         if (isRootXpath(xpath)) {
278             fragmentEntity = fragmentRepository.findOneByAnchorId(anchorEntity.getId()).orElse(null);
279         } else {
280             fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
281         }
282         if (fragmentEntity == null) {
283             throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
284         }
285         return fragmentEntity;
286     }
287
288     @Override
289     @Timed(value = "cps.data.persistence.service.datanode.query",
290             description = "Time taken to query data nodes")
291     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
292                                          final FetchDescendantsOption fetchDescendantsOption) {
293         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
294         final AnchorEntity anchorEntity = Strings.isNullOrEmpty(anchorName) ? ALL_ANCHORS
295             : anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
296         final CpsPathQuery cpsPathQuery;
297         try {
298             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
299         } catch (final PathParsingException e) {
300             throw new CpsPathException(e.getMessage());
301         }
302
303         Collection<FragmentEntity> fragmentEntities;
304         if (anchorEntity == ALL_ANCHORS) {
305             fragmentEntities = fragmentRepository.findByDataspaceAndCpsPath(dataspaceEntity, cpsPathQuery);
306         } else {
307             fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity, cpsPathQuery);
308         }
309         if (cpsPathQuery.hasAncestorAxis()) {
310             final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
311             if (anchorEntity == ALL_ANCHORS) {
312                 fragmentEntities = fragmentRepository.findByDataspaceAndXpathIn(dataspaceEntity, ancestorXpaths);
313             } else {
314                 fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
315             }
316         }
317         fragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption,
318                 fragmentEntities);
319         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
320     }
321
322     @Override
323     public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
324                                                       final FetchDescendantsOption fetchDescendantsOption) {
325         return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
326     }
327
328     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
329                                                                final Collection<FragmentEntity> fragmentEntities) {
330         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
331         for (final FragmentEntity fragmentEntity : fragmentEntities) {
332             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
333         }
334         return Collections.unmodifiableList(dataNodes);
335     }
336
337     private static String getNormalizedXpath(final String xpathSource) {
338         if (isRootXpath(xpathSource)) {
339             return xpathSource;
340         }
341         try {
342             return CpsPathUtil.getNormalizedXpath(xpathSource);
343         } catch (final PathParsingException e) {
344             throw new CpsPathException(e.getMessage());
345         }
346     }
347
348     @Override
349     public String startSession() {
350         return sessionManager.startSession();
351     }
352
353     @Override
354     public void closeSession(final String sessionId) {
355         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
356     }
357
358     @Override
359     public void lockAnchor(final String sessionId, final String dataspaceName,
360                            final String anchorName, final Long timeoutInMilliseconds) {
361         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
362     }
363
364     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
365                                                     final CpsPathQuery cpsPathQuery) {
366         final Set<String> ancestorXpath = new HashSet<>();
367         final Pattern pattern =
368                 Pattern.compile("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
369                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
370         for (final FragmentEntity fragmentEntity : fragmentEntities) {
371             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
372             if (matcher.matches()) {
373                 ancestorXpath.add(matcher.group(1));
374             }
375         }
376         return ancestorXpath;
377     }
378
379     private DataNode toDataNode(final FragmentEntity fragmentEntity,
380                                 final FetchDescendantsOption fetchDescendantsOption) {
381         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
382         Map<String, Serializable> leaves = new HashMap<>();
383         if (fragmentEntity.getAttributes() != null) {
384             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
385         }
386         return new DataNodeBuilder()
387                 .withXpath(fragmentEntity.getXpath())
388                 .withLeaves(leaves)
389                 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
390                 .withAnchor(fragmentEntity.getAnchor().getName())
391                 .withChildDataNodes(childDataNodes).build();
392     }
393
394     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
395                                              final FetchDescendantsOption fetchDescendantsOption) {
396         if (fetchDescendantsOption.hasNext()) {
397             return fragmentEntity.getChildFragments().stream()
398                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
399                     .collect(Collectors.toList());
400         }
401         return Collections.emptyList();
402     }
403
404     @Override
405     public void batchUpdateDataLeaves(final String dataspaceName, final String anchorName,
406                                         final Map<String, Map<String, Serializable>> updatedLeavesPerXPath) {
407         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
408
409         final Collection<String> xpathsOfUpdatedLeaves = updatedLeavesPerXPath.keySet();
410         final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpathsOfUpdatedLeaves,
411                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
412
413         for (final FragmentEntity fragmentEntity : fragmentEntities) {
414             final Map<String, Serializable> updatedLeaves = updatedLeavesPerXPath.get(fragmentEntity.getXpath());
415             final String mergedLeaves = mergeLeaves(updatedLeaves, fragmentEntity.getAttributes());
416             fragmentEntity.setAttributes(mergedLeaves);
417         }
418
419         try {
420             fragmentRepository.saveAll(fragmentEntities);
421         } catch (final StaleStateException staleStateException) {
422             retryUpdateDataNodesIndividually(anchorEntity, fragmentEntities);
423         }
424     }
425
426     @Override
427     public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
428                                               final Collection<DataNode> updatedDataNodes) {
429         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
430
431         final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
432             .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
433
434         final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
435         final Collection<FragmentEntity> existingFragmentEntities =
436             getFragmentEntities(anchorEntity, xpaths, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
437
438         for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
439             final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
440             updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
441         }
442
443         try {
444             fragmentRepository.saveAll(existingFragmentEntities);
445         } catch (final StaleStateException staleStateException) {
446             retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
447         }
448     }
449
450     private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
451                                                   final Collection<FragmentEntity> fragmentEntities) {
452         final Collection<String> failedXpaths = new HashSet<>();
453         for (final FragmentEntity dataNodeFragment : fragmentEntities) {
454             try {
455                 fragmentRepository.save(dataNodeFragment);
456             } catch (final StaleStateException e) {
457                 failedXpaths.add(dataNodeFragment.getXpath());
458             }
459         }
460         if (!failedXpaths.isEmpty()) {
461             final String failedXpathsConcatenated = String.join(",", failedXpaths);
462             throw new ConcurrencyException("Concurrent Transactions", String.format(
463                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
464                     failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
465         }
466     }
467
468     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
469                                                                 final DataNode newDataNode) {
470         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
471
472         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
473                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
474
475         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
476         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
477             final FragmentEntity childFragment;
478             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
479                 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
480                     newDataNodeChild);
481             } else {
482                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
483                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
484             }
485             updatedChildFragments.add(childFragment);
486         }
487
488         existingFragmentEntity.getChildFragments().clear();
489         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
490     }
491
492     @Override
493     @Transactional
494     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
495                                    final Collection<DataNode> newListElements) {
496         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
497         final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
498         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
499         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
500                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
501         parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
502         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
503         for (final DataNode newListElement : newListElements) {
504             final FragmentEntity existingListElementEntity =
505                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
506             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
507                     existingListElementEntity);
508             updatedChildFragmentEntities.add(entityToBeAdded);
509         }
510         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
511         fragmentRepository.save(parentEntity);
512     }
513
514     @Override
515     @Transactional
516     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
517         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
518         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
519             .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
520     }
521
522     @Override
523     @Transactional
524     public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
525         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
526         final Collection<AnchorEntity> anchorEntities =
527             anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
528         fragmentRepository.deleteByAnchorIn(anchorEntities);
529     }
530
531     @Override
532     @Transactional
533     public void deleteDataNodes(final String dataspaceName, final String anchorName,
534                                 final Collection<String> xpathsToDelete) {
535         deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
536     }
537
538     private void deleteDataNodes(final String dataspaceName, final String anchorName,
539                                  final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
540         final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
541         if (haveRootXpath) {
542             deleteDataNodes(dataspaceName, anchorName);
543             return;
544         }
545
546         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
547
548         final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
549         for (final String xpath : xpathsToDelete) {
550             try {
551                 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
552             } catch (final PathParsingException e) {
553                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
554             }
555         }
556
557         final Collection<String> xpathsToExistingContainers =
558             fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
559         if (onlySupportListDeletion) {
560             final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
561                 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
562             deleteChecklist.removeAll(xpathsToExistingListElements);
563         } else {
564             deleteChecklist.removeAll(xpathsToExistingContainers);
565         }
566
567         final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
568             .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
569             .collect(Collectors.toList());
570         deleteChecklist.removeAll(xpathsToExistingLists);
571
572         if (!deleteChecklist.isEmpty()) {
573             throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
574         }
575
576         fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
577         fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
578     }
579
580     @Override
581     @Transactional
582     public void deleteListDataNode(final String dataspaceName, final String anchorName,
583                                    final String targetXpath) {
584         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
585     }
586
587     @Override
588     @Transactional
589     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
590         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
591     }
592
593     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
594                                 final boolean onlySupportListNodeDeletion) {
595         final String normalizedXpath = getNormalizedXpath(targetXpath);
596         try {
597             deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
598                 onlySupportListNodeDeletion);
599         } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
600             throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
601         }
602     }
603
604     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
605         if (newListElements.isEmpty()) {
606             throw new CpsAdminException("Invalid list replacement",
607                     "Cannot replace list elements with empty collection");
608         }
609         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
610         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
611     }
612
613     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
614                                                      final DataNode newListElement,
615                                                      final FragmentEntity existingListElementEntity) {
616         if (existingListElementEntity == null) {
617             return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
618         }
619         if (newListElement.getChildDataNodes().isEmpty()) {
620             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
621             existingListElementEntity.getChildFragments().clear();
622         } else {
623             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
624         }
625         return existingListElementEntity;
626     }
627
628     private static boolean isNewDataNode(final DataNode replacementDataNode,
629                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
630         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
631     }
632
633     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
634                                                   final DataNode newListElement) {
635         final FragmentEntity replacementFragmentEntity =
636                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
637                         newListElement.getLeaves())).build();
638         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
639     }
640
641     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
642             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
643         return childEntities.stream()
644                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
645                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
646     }
647
648     private static boolean isRootXpath(final String xpath) {
649         return "/".equals(xpath) || "".equals(xpath);
650     }
651
652     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
653         Map<String, Serializable> currentLeavesAsMap = new HashMap<>();
654         if (currentLeavesAsString != null) {
655             currentLeavesAsMap = jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
656             currentLeavesAsMap.putAll(updateLeaves);
657         }
658
659         if (currentLeavesAsMap.isEmpty()) {
660             return "";
661         }
662         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
663     }
664
665     private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
666         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
667         return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
668     }
669 }