Merge "Update INFO.yaml Committers"
[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 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.FragmentNativeRepository;
65 import org.onap.cps.spi.repository.FragmentQueryBuilder;
66 import org.onap.cps.spi.repository.FragmentRepository;
67 import org.onap.cps.spi.utils.SessionManager;
68 import org.onap.cps.utils.JsonObjectMapper;
69 import org.springframework.dao.DataIntegrityViolationException;
70 import org.springframework.stereotype.Service;
71
72 @Service
73 @Slf4j
74 @RequiredArgsConstructor
75 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
76
77     private final DataspaceRepository dataspaceRepository;
78     private final AnchorRepository anchorRepository;
79     private final FragmentRepository fragmentRepository;
80     private final JsonObjectMapper jsonObjectMapper;
81     private final SessionManager sessionManager;
82     private final FragmentNativeRepository fragmentNativeRepositoryImpl;
83
84     private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
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             getFragmentWithoutDescendantsByXpath(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             getFragmentWithoutDescendantsByXpath(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     public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
255                                 final FetchDescendantsOption fetchDescendantsOption) {
256         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
257             fetchDescendantsOption);
258         return toDataNode(fragmentEntity, fetchDescendantsOption);
259     }
260
261     @Override
262     public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
263                                              final Collection<String> xpaths,
264                                              final FetchDescendantsOption fetchDescendantsOption) {
265         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
266         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
267
268         final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
269         final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
270
271         final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
272         for (final String xpath : nonRootXpaths) {
273             try {
274                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
275             } catch (final PathParsingException e) {
276                 log.warn("Error parsing xpath \"{}\" in getDataNodes: {}", xpath, e.getMessage());
277             }
278         }
279         final Collection<FragmentEntity> fragmentEntities =
280             new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
281
282         if (haveRootXpath) {
283             final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
284                 anchorEntity);
285             fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
286         }
287
288         return toDataNodes(fragmentEntities, fetchDescendantsOption);
289     }
290
291     private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
292                                                                 final String anchorName,
293                                                                 final String xpath) {
294         return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
295     }
296
297     private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
298                                               final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
299         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
300         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
301         final FragmentEntity fragmentEntity;
302         if (isRootXpath(xpath)) {
303             final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
304                     anchorEntity);
305             fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
306                 .stream().findFirst().orElse(null);
307         } else {
308             final String normalizedXpath = getNormalizedXpath(xpath);
309             if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
310                 fragmentEntity =
311                     fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
312             } else {
313                 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
314                     .stream().findFirst().orElse(null);
315             }
316         }
317         if (fragmentEntity == null) {
318             throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
319         }
320         return fragmentEntity;
321
322     }
323
324     private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
325                                                                                  final String normalizedXpath) {
326         final List<FragmentExtract> fragmentExtracts =
327                 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
328         log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
329                 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
330         return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
331
332     }
333
334     @Override
335     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
336                                          final FetchDescendantsOption fetchDescendantsOption) {
337         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
338         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
339         final CpsPathQuery cpsPathQuery;
340         try {
341             cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
342         } catch (final PathParsingException e) {
343             throw new CpsPathException(e.getMessage());
344         }
345
346         Collection<FragmentEntity> fragmentEntities;
347         if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
348             return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
349         }
350         fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
351         if (cpsPathQuery.hasAncestorAxis()) {
352             fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
353         }
354         return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
355     }
356
357     private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
358                                                 final CpsPathQuery cpsPathQuery) {
359         return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
360             && !cpsPathQuery.hasLeafConditions()
361             && !cpsPathQuery.hasTextFunctionCondition();
362     }
363
364     private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
365                                                            final AnchorEntity anchorEntity,
366                                                            final CpsPathQuery cpsPathQuery) {
367         Collection<FragmentEntity> fragmentEntities;
368         final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
369         final List<FragmentExtract> fragmentExtracts =
370             fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
371         fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
372         if (cpsPathQuery.hasAncestorAxis()) {
373             fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
374         }
375         return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
376     }
377
378     private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
379                                                                    final CpsPathQuery cpsPathQuery,
380                                                                    final Collection<FragmentEntity> fragmentEntities) {
381         final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
382         return ancestorXpaths.isEmpty() ? Collections.emptyList()
383             : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
384     }
385
386     private List<DataNode> createDataNodesFromProxiedFragmentEntities(
387                                             final FetchDescendantsOption fetchDescendantsOption,
388                                             final AnchorEntity anchorEntity,
389                                             final Collection<FragmentEntity> proxiedFragmentEntities) {
390         final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
391         for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
392             if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
393                 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
394             } else {
395                 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
396                 final Collection<FragmentEntity> unproxiedFragmentEntities =
397                     buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
398                 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
399                     dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
400                 }
401             }
402         }
403         return Collections.unmodifiableList(dataNodes);
404     }
405
406     private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
407                                                                final Collection<FragmentEntity> fragmentEntities) {
408         final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
409         for (final FragmentEntity fragmentEntity : fragmentEntities) {
410             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
411         }
412         return Collections.unmodifiableList(dataNodes);
413     }
414
415     private static String getNormalizedXpath(final String xpathSource) {
416         final String normalizedXpath;
417         try {
418             normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
419         } catch (final PathParsingException e) {
420             throw new CpsPathException(e.getMessage());
421         }
422         return normalizedXpath;
423     }
424
425     @Override
426     public String startSession() {
427         return sessionManager.startSession();
428     }
429
430     @Override
431     public void closeSession(final String sessionId) {
432         sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
433     }
434
435     @Override
436     public void lockAnchor(final String sessionId, final String dataspaceName,
437                            final String anchorName, final Long timeoutInMilliseconds) {
438         sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
439     }
440
441     private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
442                                                     final CpsPathQuery cpsPathQuery) {
443         final Set<String> ancestorXpath = new HashSet<>();
444         final Pattern pattern =
445                 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
446                         + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
447         for (final FragmentEntity fragmentEntity : fragmentEntities) {
448             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
449             if (matcher.matches()) {
450                 ancestorXpath.add(matcher.group(1));
451             }
452         }
453         return ancestorXpath;
454     }
455
456     private DataNode toDataNode(final FragmentEntity fragmentEntity,
457                                 final FetchDescendantsOption fetchDescendantsOption) {
458         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
459         Map<String, Serializable> leaves = new HashMap<>();
460         if (fragmentEntity.getAttributes() != null) {
461             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
462         }
463         return new DataNodeBuilder()
464                 .withXpath(fragmentEntity.getXpath())
465                 .withLeaves(leaves)
466                 .withChildDataNodes(childDataNodes).build();
467     }
468
469     private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
470                                              final FetchDescendantsOption fetchDescendantsOption) {
471         final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
472         for (final FragmentEntity fragmentEntity : fragmentEntities) {
473             dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
474         }
475         return dataNodes;
476     }
477
478     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
479                                              final FetchDescendantsOption fetchDescendantsOption) {
480         if (fetchDescendantsOption.hasNext()) {
481             return fragmentEntity.getChildFragments().stream()
482                     .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
483                     .collect(Collectors.toList());
484         }
485         return Collections.emptyList();
486     }
487
488     @Override
489     public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
490                                  final Map<String, Serializable> updateLeaves) {
491         final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
492         final String currentLeavesAsString = fragmentEntity.getAttributes();
493         final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
494         fragmentEntity.setAttributes(mergedLeaves);
495         fragmentRepository.save(fragmentEntity);
496     }
497
498     @Override
499     public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
500                                              final DataNode dataNode) {
501         final FragmentEntity fragmentEntity =
502             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
503         updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
504         try {
505             fragmentRepository.save(fragmentEntity);
506         } catch (final StaleStateException staleStateException) {
507             throw new ConcurrencyException("Concurrent Transactions",
508                     String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
509                             dataspaceName, anchorName, dataNode.getXpath()));
510         }
511     }
512
513     @Override
514     public void updateDataNodesAndDescendants(final String dataspaceName,
515                                               final String anchorName,
516                                               final List<DataNode> dataNodes) {
517
518         final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
519                 .collect(Collectors.toMap(
520                         dataNode -> dataNode,
521                         dataNode ->
522                             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
523         dataNodeFragmentEntityMap.forEach(
524                 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
525         try {
526             fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
527         } catch (final StaleStateException staleStateException) {
528             retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
529         }
530     }
531
532     private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
533                                                   final Collection<FragmentEntity> fragmentEntities) {
534         final Collection<String> failedXpaths = new HashSet<>();
535
536         fragmentEntities.forEach(dataNodeFragment -> {
537             try {
538                 fragmentRepository.save(dataNodeFragment);
539             } catch (final StaleStateException e) {
540                 failedXpaths.add(dataNodeFragment.getXpath());
541             }
542         });
543
544         if (!failedXpaths.isEmpty()) {
545             final String failedXpathsConcatenated = String.join(",", failedXpaths);
546             throw new ConcurrencyException("Concurrent Transactions", String.format(
547                     "DataNodes : %s in Dataspace :'%s' with Anchor : '%s'  are updated by another transaction.",
548                     failedXpathsConcatenated, dataspaceName, anchorName));
549         }
550     }
551
552     private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
553                                                                 final DataNode newDataNode) {
554
555         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
556
557         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
558                 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
559
560         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
561
562         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
563             final FragmentEntity childFragment;
564             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
565                 childFragment = convertToFragmentWithAllDescendants(
566                         existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
567             } else {
568                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
569                 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
570             }
571             updatedChildFragments.add(childFragment);
572         }
573
574         existingFragmentEntity.getChildFragments().clear();
575         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
576     }
577
578     @Override
579     @Transactional
580     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
581                                    final Collection<DataNode> newListElements) {
582         final FragmentEntity parentEntity =
583             getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
584         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
585         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
586                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
587         deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
588         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
589         for (final DataNode newListElement : newListElements) {
590             final FragmentEntity existingListElementEntity =
591                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
592             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
593                     existingListElementEntity);
594
595             updatedChildFragmentEntities.add(entityToBeAdded);
596         }
597         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
598         fragmentRepository.save(parentEntity);
599     }
600
601     @Override
602     @Transactional
603     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
604         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
605         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
606                 .ifPresent(
607                         anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
608     }
609
610     @Override
611     @Transactional
612     public void deleteListDataNode(final String dataspaceName, final String anchorName,
613                                    final String targetXpath) {
614         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
615     }
616
617     @Override
618     @Transactional
619     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
620         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
621     }
622
623     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
624                                 final boolean onlySupportListNodeDeletion) {
625         final String parentNodeXpath;
626         FragmentEntity parentFragmentEntity = null;
627         boolean targetDeleted;
628         if (isRootXpath(targetXpath)) {
629             deleteDataNodes(dataspaceName, anchorName);
630             targetDeleted = true;
631         } else {
632             if (isRootContainerNodeXpath(targetXpath)) {
633                 parentNodeXpath = targetXpath;
634             } else {
635                 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
636             }
637             parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
638             if (CpsPathUtil.isPathToListElement(targetXpath)) {
639                 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
640             } else {
641                 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
642                 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
643                 if (tryToDeleteDataNode) {
644                     targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
645                 }
646             }
647         }
648         if (!targetDeleted) {
649             final String additionalInformation = onlySupportListNodeDeletion
650                     ? "The target is probably not a List." : "";
651             throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
652                     parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
653         }
654     }
655
656     private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
657         final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
658         if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
659             fragmentNativeRepositoryImpl.deleteFragmentEntity(parentFragmentEntity.getId());
660             return true;
661         }
662         if (parentFragmentEntity.getChildFragments()
663                 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
664             fragmentRepository.save(parentFragmentEntity);
665             return true;
666         }
667         return false;
668     }
669
670     private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
671         final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
672         final String deleteTargetXpathPrefix = normalizedListXpath + "[";
673         if (parentFragmentEntity.getChildFragments()
674                 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
675             fragmentRepository.save(parentFragmentEntity);
676             return true;
677         }
678         return false;
679     }
680
681     private static void deleteListElements(
682             final Collection<FragmentEntity> fragmentEntities,
683             final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
684         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
685     }
686
687     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
688         if (newListElements.isEmpty()) {
689             throw new CpsAdminException("Invalid list replacement",
690                     "Cannot replace list elements with empty collection");
691         }
692         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
693         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
694     }
695
696     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
697                                                      final DataNode newListElement,
698                                                      final FragmentEntity existingListElementEntity) {
699         if (existingListElementEntity == null) {
700             return convertToFragmentWithAllDescendants(
701                     parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
702         }
703         if (newListElement.getChildDataNodes().isEmpty()) {
704             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
705             existingListElementEntity.getChildFragments().clear();
706         } else {
707             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
708         }
709         return existingListElementEntity;
710     }
711
712     private static boolean isNewDataNode(final DataNode replacementDataNode,
713                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
714         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
715     }
716
717     private static boolean isRootContainerNodeXpath(final String xpath) {
718         return 0 == xpath.lastIndexOf('/');
719     }
720
721     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
722                                                   final DataNode newListElement) {
723         final FragmentEntity replacementFragmentEntity =
724                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
725                         newListElement.getLeaves())).build();
726         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
727     }
728
729     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
730             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
731         return childEntities.stream()
732                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
733                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
734     }
735
736     private static boolean isRootXpath(final String xpath) {
737         return "/".equals(xpath) || "".equals(xpath);
738     }
739
740     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
741         final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
742             ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
743         currentLeavesAsMap.putAll(updateLeaves);
744         if (currentLeavesAsMap.isEmpty()) {
745             return "";
746         }
747         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
748     }
749 }