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