Merge "Allow getDataNodes to read whole lists(ep 1)"
[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.ConcurrencyException;
56 import org.onap.cps.spi.exceptions.CpsAdminException;
57 import org.onap.cps.spi.exceptions.CpsPathException;
58 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
59 import org.onap.cps.spi.exceptions.DataNodeNotFoundExceptionBatch;
60 import org.onap.cps.spi.model.DataNode;
61 import org.onap.cps.spi.model.DataNodeBuilder;
62 import org.onap.cps.spi.repository.AnchorRepository;
63 import org.onap.cps.spi.repository.DataspaceRepository;
64 import org.onap.cps.spi.repository.FragmentRepository;
65 import org.onap.cps.spi.utils.SessionManager;
66 import org.onap.cps.utils.JsonObjectMapper;
67 import org.springframework.dao.DataIntegrityViolationException;
68 import org.springframework.stereotype.Service;
69
70 @Service
71 @Slf4j
72 @RequiredArgsConstructor
73 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
74
75     private final DataspaceRepository dataspaceRepository;
76     private final AnchorRepository anchorRepository;
77     private final FragmentRepository fragmentRepository;
78     private final JsonObjectMapper jsonObjectMapper;
79     private final SessionManager sessionManager;
80
81     private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@.+?])?)";
82     private static final String QUERY_ACROSS_ANCHORS = null;
83     private static final AnchorEntity ALL_ANCHORS = null;
84
85     @Override
86     public void addChildDataNodes(final String dataspaceName, final String anchorName,
87                                   final String parentNodeXpath, final Collection<DataNode> dataNodes) {
88         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
89         addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
90     }
91
92     @Override
93     public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
94                                 final Collection<DataNode> newListElements) {
95         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
96         addChildrenDataNodes(anchorEntity, parentNodeXpath, newListElements);
97     }
98
99     @Override
100     public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
101                                  final Collection<Collection<DataNode>> newLists) {
102         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
103         final Collection<String> failedXpaths = new HashSet<>();
104         for (final Collection<DataNode> newList : newLists) {
105             try {
106                 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
107             } catch (final AlreadyDefinedException alreadyDefinedException) {
108                 failedXpaths.addAll(alreadyDefinedException.getAlreadyDefinedObjectNames());
109             }
110         }
111         if (!failedXpaths.isEmpty()) {
112             throw AlreadyDefinedException.forDataNodes(failedXpaths, anchorEntity.getName());
113         }
114     }
115
116     private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
117                                      final DataNode newChild) {
118         final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
119         final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
120         newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
121         try {
122             fragmentRepository.save(newChildAsFragmentEntity);
123         } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
124             throw AlreadyDefinedException.forDataNodes(Collections.singletonList(newChild.getXpath()),
125                     anchorEntity.getName());
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 dataIntegrityViolationException) {
142             log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
143                     dataIntegrityViolationException, 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 alreadyDefinedException) {
155                 failedXpaths.add(newChild.getXpath());
156             }
157         }
158         if (!failedXpaths.isEmpty()) {
159             throw AlreadyDefinedException.forDataNodes(failedXpaths, anchorEntity.getName());
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 dataIntegrityViolationException) {
188                 failedXpaths.add(dataNode.getXpath());
189             }
190         }
191         if (!failedXpaths.isEmpty()) {
192             throw AlreadyDefinedException.forDataNodes(failedXpaths, anchorEntity.getName());
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         Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpaths);
247         fragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption,
248                 fragmentEntities);
249         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
250     }
251
252     private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
253                                                            final Collection<String> xpaths) {
254         final Collection<String> normalizedXpaths = getNormalizedXpaths(xpaths);
255
256         final boolean haveRootXpath = normalizedXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
257
258         final List<FragmentEntity> fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity,
259                 normalizedXpaths);
260
261         for (final FragmentEntity fragmentEntity : fragmentEntities) {
262             normalizedXpaths.remove(fragmentEntity.getXpath());
263         }
264
265         for (final String xpath : normalizedXpaths) {
266             if (!CpsPathUtil.isPathToListElement(xpath)) {
267                 fragmentEntities.addAll(fragmentRepository.findListByAnchorAndXpath(anchorEntity, xpath));
268             }
269         }
270
271         if (haveRootXpath) {
272             fragmentEntities.addAll(fragmentRepository.findRootsByAnchorId(anchorEntity.getId()));
273         }
274
275         return fragmentEntities;
276     }
277
278     private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
279         final FragmentEntity fragmentEntity;
280         if (isRootXpath(xpath)) {
281             fragmentEntity = fragmentRepository.findOneByAnchorId(anchorEntity.getId()).orElse(null);
282         } else {
283             fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
284         }
285         if (fragmentEntity == null) {
286             throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
287         }
288         return fragmentEntity;
289     }
290
291     @Override
292     @Timed(value = "cps.data.persistence.service.datanode.query",
293             description = "Time taken to query data nodes")
294     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
295                                          final FetchDescendantsOption fetchDescendantsOption) {
296         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
297         final AnchorEntity anchorEntity = Strings.isNullOrEmpty(anchorName) ? ALL_ANCHORS
298             : anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
299         final CpsPathQuery cpsPathQuery;
300         try {
301             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
302         } catch (final PathParsingException pathParsingException) {
303             throw new CpsPathException(pathParsingException.getMessage());
304         }
305
306         Collection<FragmentEntity> fragmentEntities;
307         if (anchorEntity == ALL_ANCHORS) {
308             fragmentEntities = fragmentRepository.findByDataspaceAndCpsPath(dataspaceEntity, cpsPathQuery);
309         } else {
310             fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity, cpsPathQuery);
311         }
312         if (cpsPathQuery.hasAncestorAxis()) {
313             final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
314             if (anchorEntity == ALL_ANCHORS) {
315                 fragmentEntities = fragmentRepository.findByDataspaceAndXpathIn(dataspaceEntity, ancestorXpaths);
316             } else {
317                 fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
318             }
319         }
320         fragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption,
321                 fragmentEntities);
322         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
323     }
324
325     @Override
326     public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
327                                                       final FetchDescendantsOption fetchDescendantsOption) {
328         return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
329     }
330
331     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
332                                                                final Collection<FragmentEntity> fragmentEntities) {
333         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
334         for (final FragmentEntity fragmentEntity : fragmentEntities) {
335             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
336         }
337         return Collections.unmodifiableList(dataNodes);
338     }
339
340     private static String getNormalizedXpath(final String xpathSource) {
341         if (isRootXpath(xpathSource)) {
342             return xpathSource;
343         }
344         try {
345             return CpsPathUtil.getNormalizedXpath(xpathSource);
346         } catch (final PathParsingException pathParsingException) {
347             throw new CpsPathException(pathParsingException.getMessage());
348         }
349     }
350
351     private static Collection<String> getNormalizedXpaths(final Collection<String> xpaths) {
352         final Collection<String> normalizedXpaths = new HashSet<>(xpaths.size());
353         for (final String xpath : xpaths) {
354             try {
355                 normalizedXpaths.add(getNormalizedXpath(xpath));
356             } catch (final CpsPathException cpsPathException) {
357                 log.warn("Error parsing xpath \"{}\": {}", xpath, cpsPathException.getMessage());
358             }
359         }
360         return normalizedXpaths;
361     }
362
363     @Override
364     public String startSession() {
365         return sessionManager.startSession();
366     }
367
368     @Override
369     public void closeSession(final String sessionId) {
370         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
371     }
372
373     @Override
374     public void lockAnchor(final String sessionId, final String dataspaceName,
375                            final String anchorName, final Long timeoutInMilliseconds) {
376         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
377     }
378
379     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
380                                                     final CpsPathQuery cpsPathQuery) {
381         final Set<String> ancestorXpath = new HashSet<>();
382         final Pattern pattern =
383                 Pattern.compile("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
384                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
385         for (final FragmentEntity fragmentEntity : fragmentEntities) {
386             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
387             if (matcher.matches()) {
388                 ancestorXpath.add(matcher.group(1));
389             }
390         }
391         return ancestorXpath;
392     }
393
394     private DataNode toDataNode(final FragmentEntity fragmentEntity,
395                                 final FetchDescendantsOption fetchDescendantsOption) {
396         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
397         Map<String, Serializable> leaves = new HashMap<>();
398         if (fragmentEntity.getAttributes() != null) {
399             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
400         }
401         return new DataNodeBuilder()
402                 .withXpath(fragmentEntity.getXpath())
403                 .withLeaves(leaves)
404                 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
405                 .withAnchor(fragmentEntity.getAnchor().getName())
406                 .withChildDataNodes(childDataNodes).build();
407     }
408
409     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
410                                              final FetchDescendantsOption fetchDescendantsOption) {
411         if (fetchDescendantsOption.hasNext()) {
412             return fragmentEntity.getChildFragments().stream()
413                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
414                     .collect(Collectors.toList());
415         }
416         return Collections.emptyList();
417     }
418
419     @Override
420     public void batchUpdateDataLeaves(final String dataspaceName, final String anchorName,
421                                         final Map<String, Map<String, Serializable>> updatedLeavesPerXPath) {
422         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
423
424         final Collection<String> xpathsOfUpdatedLeaves = updatedLeavesPerXPath.keySet();
425         final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpathsOfUpdatedLeaves);
426
427         for (final FragmentEntity fragmentEntity : fragmentEntities) {
428             final Map<String, Serializable> updatedLeaves = updatedLeavesPerXPath.get(fragmentEntity.getXpath());
429             final String mergedLeaves = mergeLeaves(updatedLeaves, fragmentEntity.getAttributes());
430             fragmentEntity.setAttributes(mergedLeaves);
431         }
432
433         try {
434             fragmentRepository.saveAll(fragmentEntities);
435         } catch (final StaleStateException staleStateException) {
436             retryUpdateDataNodesIndividually(anchorEntity, fragmentEntities);
437         }
438     }
439
440     @Override
441     public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
442                                               final Collection<DataNode> updatedDataNodes) {
443         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
444
445         final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
446             .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
447
448         final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
449         Collection<FragmentEntity> existingFragmentEntities = getFragmentEntities(anchorEntity, xpaths);
450         existingFragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(
451                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS, existingFragmentEntities);
452
453         for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
454             final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
455             updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
456         }
457
458         try {
459             fragmentRepository.saveAll(existingFragmentEntities);
460         } catch (final StaleStateException staleStateException) {
461             retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
462         }
463     }
464
465     private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
466                                                   final Collection<FragmentEntity> fragmentEntities) {
467         final Collection<String> failedXpaths = new HashSet<>();
468         for (final FragmentEntity dataNodeFragment : fragmentEntities) {
469             try {
470                 fragmentRepository.save(dataNodeFragment);
471             } catch (final StaleStateException staleStateException) {
472                 failedXpaths.add(dataNodeFragment.getXpath());
473             }
474         }
475         if (!failedXpaths.isEmpty()) {
476             final String failedXpathsConcatenated = String.join(",", failedXpaths);
477             throw new ConcurrencyException("Concurrent Transactions", String.format(
478                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
479                     failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
480         }
481     }
482
483     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
484                                                                 final DataNode newDataNode) {
485         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
486
487         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
488                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
489
490         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
491         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
492             final FragmentEntity childFragment;
493             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
494                 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
495                     newDataNodeChild);
496             } else {
497                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
498                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
499             }
500             updatedChildFragments.add(childFragment);
501         }
502
503         existingFragmentEntity.getChildFragments().clear();
504         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
505     }
506
507     @Override
508     @Transactional
509     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
510                                    final Collection<DataNode> newListElements) {
511         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
512         final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
513         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
514         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
515                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
516         parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
517         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
518         for (final DataNode newListElement : newListElements) {
519             final FragmentEntity existingListElementEntity =
520                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
521             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
522                     existingListElementEntity);
523             updatedChildFragmentEntities.add(entityToBeAdded);
524         }
525         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
526         fragmentRepository.save(parentEntity);
527     }
528
529     @Override
530     @Transactional
531     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
532         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
533         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
534             .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
535     }
536
537     @Override
538     @Transactional
539     public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
540         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
541         final Collection<AnchorEntity> anchorEntities =
542             anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
543         fragmentRepository.deleteByAnchorIn(anchorEntities);
544     }
545
546     @Override
547     @Transactional
548     public void deleteDataNodes(final String dataspaceName, final String anchorName,
549                                 final Collection<String> xpathsToDelete) {
550         deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
551     }
552
553     private void deleteDataNodes(final String dataspaceName, final String anchorName,
554                                  final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
555         final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
556         if (haveRootXpath) {
557             deleteDataNodes(dataspaceName, anchorName);
558             return;
559         }
560
561         final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
562
563         final Collection<String> deleteChecklist = getNormalizedXpaths(xpathsToDelete);
564         final Collection<String> xpathsToExistingContainers =
565             fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
566         if (onlySupportListDeletion) {
567             final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
568                 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
569             deleteChecklist.removeAll(xpathsToExistingListElements);
570         } else {
571             deleteChecklist.removeAll(xpathsToExistingContainers);
572         }
573
574         final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
575             .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
576             .collect(Collectors.toList());
577         deleteChecklist.removeAll(xpathsToExistingLists);
578
579         if (!deleteChecklist.isEmpty()) {
580             throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
581         }
582
583         fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
584         fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
585     }
586
587     @Override
588     @Transactional
589     public void deleteListDataNode(final String dataspaceName, final String anchorName,
590                                    final String targetXpath) {
591         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
592     }
593
594     @Override
595     @Transactional
596     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
597         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
598     }
599
600     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
601                                 final boolean onlySupportListNodeDeletion) {
602         final String normalizedXpath = getNormalizedXpath(targetXpath);
603         try {
604             deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
605                 onlySupportListNodeDeletion);
606         } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
607             throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
608         }
609     }
610
611     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
612         if (newListElements.isEmpty()) {
613             throw new CpsAdminException("Invalid list replacement",
614                     "Cannot replace list elements with empty collection");
615         }
616         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
617         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
618     }
619
620     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
621                                                      final DataNode newListElement,
622                                                      final FragmentEntity existingListElementEntity) {
623         if (existingListElementEntity == null) {
624             return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
625         }
626         if (newListElement.getChildDataNodes().isEmpty()) {
627             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
628             existingListElementEntity.getChildFragments().clear();
629         } else {
630             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
631         }
632         return existingListElementEntity;
633     }
634
635     private static boolean isNewDataNode(final DataNode replacementDataNode,
636                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
637         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
638     }
639
640     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
641                                                   final DataNode newListElement) {
642         final FragmentEntity replacementFragmentEntity =
643                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
644                         newListElement.getLeaves())).build();
645         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
646     }
647
648     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
649             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
650         return childEntities.stream()
651                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
652                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
653     }
654
655     private static boolean isRootXpath(final String xpath) {
656         return "/".equals(xpath) || "".equals(xpath);
657     }
658
659     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
660         Map<String, Serializable> currentLeavesAsMap = new HashMap<>();
661         if (currentLeavesAsString != null) {
662             currentLeavesAsMap = jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
663             currentLeavesAsMap.putAll(updateLeaves);
664         }
665
666         if (currentLeavesAsMap.isEmpty()) {
667             return "";
668         }
669         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
670     }
671
672     private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
673         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
674         return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
675     }
676 }