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