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