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