Add DataNodeNotFoundException to deleteDataNodes
[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.exceptions.DataNodeNotFoundExceptionBatch;
61 import org.onap.cps.spi.model.DataNode;
62 import org.onap.cps.spi.model.DataNodeBuilder;
63 import org.onap.cps.spi.repository.AnchorRepository;
64 import org.onap.cps.spi.repository.DataspaceRepository;
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
83     private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
84
85     @Override
86     public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
87                                  final DataNode newChildDataNode) {
88         addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
89     }
90
91     @Override
92     public void addChildDataNodes(final String dataspaceName, final String anchorName,
93                                   final String parentNodeXpath, final Collection<DataNode> dataNodes) {
94         addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
95     }
96
97     @Override
98     public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
99                                 final Collection<DataNode> newListElements) {
100         addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
101     }
102
103     @Override
104     public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
105                                  final Collection<Collection<DataNode>> newLists) {
106         final Collection<String> failedXpaths = new HashSet<>();
107         newLists.forEach(newList -> {
108             try {
109                 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
110             } catch (final AlreadyDefinedExceptionBatch e) {
111                 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
112             }
113         });
114
115         if (!failedXpaths.isEmpty()) {
116             throw new AlreadyDefinedExceptionBatch(failedXpaths);
117         }
118
119     }
120
121     private void addNewChildDataNode(final String dataspaceName, final String anchorName,
122                                      final String parentNodeXpath, final DataNode newChild) {
123         final FragmentEntity parentFragmentEntity =
124             getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
125         final FragmentEntity newChildAsFragmentEntity =
126                 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
127                         parentFragmentEntity.getAnchor(), newChild);
128         newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
129         try {
130             fragmentRepository.save(newChildAsFragmentEntity);
131         } catch (final DataIntegrityViolationException e) {
132             throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
133         }
134
135     }
136
137     private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
138                                       final Collection<DataNode> newChildren) {
139         final FragmentEntity parentFragmentEntity =
140             getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
141         final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
142         try {
143             newChildren.forEach(newChildAsDataNode -> {
144                 final FragmentEntity newChildAsFragmentEntity =
145                         convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
146                                 parentFragmentEntity.getAnchor(), newChildAsDataNode);
147                 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
148                 fragmentEntities.add(newChildAsFragmentEntity);
149             });
150             fragmentRepository.saveAll(fragmentEntities);
151         } catch (final DataIntegrityViolationException e) {
152             log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
153                     e, fragmentEntities.size());
154             retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
155         }
156     }
157
158     private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
159                                                   final String parentNodeXpath,
160                                                   final Collection<DataNode> newChildren) {
161         final Collection<String> failedXpaths = new HashSet<>();
162         for (final DataNode newChild : newChildren) {
163             try {
164                 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
165             } catch (final AlreadyDefinedException e) {
166                 failedXpaths.add(newChild.getXpath());
167             }
168         }
169         if (!failedXpaths.isEmpty()) {
170             throw new AlreadyDefinedExceptionBatch(failedXpaths);
171         }
172     }
173
174     @Override
175     public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
176         storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
177     }
178
179     @Override
180     public void storeDataNodes(final String dataspaceName, final String anchorName,
181                                final Collection<DataNode> dataNodes) {
182         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
183         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
184         final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
185         try {
186             for (final DataNode dataNode: dataNodes) {
187                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
188                         dataNode);
189                 fragmentEntities.add(fragmentEntity);
190             }
191             fragmentRepository.saveAll(fragmentEntities);
192         } catch (final DataIntegrityViolationException exception) {
193             log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
194                     exception, dataNodes.size());
195             storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
196         }
197     }
198
199     private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
200                                            final Collection<DataNode> dataNodes) {
201         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
202         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
203         final Collection<String> failedXpaths = new HashSet<>();
204         for (final DataNode dataNode: dataNodes) {
205             try {
206                 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
207                         dataNode);
208                 fragmentRepository.save(fragmentEntity);
209             } catch (final DataIntegrityViolationException e) {
210                 failedXpaths.add(dataNode.getXpath());
211             }
212         }
213         if (!failedXpaths.isEmpty()) {
214             throw new AlreadyDefinedExceptionBatch(failedXpaths);
215         }
216     }
217
218     /**
219      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
220      * for all DataNode children recursively.
221      *
222      * @param dataspaceEntity       dataspace
223      * @param anchorEntity          anchorEntity
224      * @param dataNodeToBeConverted dataNode
225      * @return a Fragment built from current DataNode
226      */
227     private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
228                                                                final AnchorEntity anchorEntity,
229                                                                final DataNode dataNodeToBeConverted) {
230         final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
231         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
232         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
233             final FragmentEntity childFragment =
234                     convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
235                             childDataNode);
236             childFragmentsImmutableSetBuilder.add(childFragment);
237         }
238         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
239         return parentFragment;
240     }
241
242     private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
243                                             final AnchorEntity anchorEntity, final DataNode dataNode) {
244         return FragmentEntity.builder()
245                 .dataspace(dataspaceEntity)
246                 .anchor(anchorEntity)
247                 .xpath(dataNode.getXpath())
248                 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
249                 .build();
250     }
251
252     @Override
253     public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
254                                              final String xpath,
255                                              final FetchDescendantsOption fetchDescendantsOption) {
256         final String targetXpath = isRootXpath(xpath) ? xpath : CpsPathUtil.getNormalizedXpath(xpath);
257         final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
258                 Collections.singletonList(targetXpath), fetchDescendantsOption);
259         if (dataNodes.isEmpty()) {
260             throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
261         }
262         return dataNodes;
263     }
264
265     @Override
266     public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
267                                                               final Collection<String> xpaths,
268                                                               final FetchDescendantsOption fetchDescendantsOption) {
269         final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(dataspaceName, anchorName, xpaths);
270         return toDataNodes(fragmentEntities, fetchDescendantsOption);
271     }
272
273     private Collection<FragmentEntity> getFragmentEntities(final String dataspaceName, final String anchorName,
274                                                            final Collection<String> xpaths) {
275         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
276         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
277
278         final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
279         final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
280
281         final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
282         for (final String xpath : nonRootXpaths) {
283             try {
284                 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
285             } catch (final PathParsingException e) {
286                 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
287             }
288         }
289         final Collection<FragmentEntity> fragmentEntities =
290             new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
291
292         if (haveRootXpath) {
293             final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
294                 anchorEntity);
295             fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
296         }
297
298         return fragmentEntities;
299     }
300
301     private FragmentEntity getFragmentEntity(final String dataspaceName, final String anchorName, final String xpath) {
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             fragmentEntity =
313                 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
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 = getFragmentEntity(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 = getFragmentEntity(dataspaceName, anchorName, dataNode.getXpath());
500         updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
501         try {
502             fragmentRepository.save(fragmentEntity);
503         } catch (final StaleStateException staleStateException) {
504             throw new ConcurrencyException("Concurrent Transactions",
505                     String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
506                             dataspaceName, anchorName, dataNode.getXpath()));
507         }
508     }
509
510     @Override
511     public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
512                                               final List<DataNode> updatedDataNodes) {
513         final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
514             .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
515
516         final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
517         final Collection<FragmentEntity> existingFragmentEntities =
518             getFragmentEntities(dataspaceName, anchorName, xpaths);
519
520         for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
521             final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
522             updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
523         }
524
525         try {
526             fragmentRepository.saveAll(existingFragmentEntities);
527         } catch (final StaleStateException staleStateException) {
528             retryUpdateDataNodesIndividually(dataspaceName, anchorName, existingFragmentEntities);
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 = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
583         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
584         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
585                 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
586         deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
587         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
588         for (final DataNode newListElement : newListElements) {
589             final FragmentEntity existingListElementEntity =
590                     existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
591             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
592                     existingListElementEntity);
593
594             updatedChildFragmentEntities.add(entityToBeAdded);
595         }
596         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
597         fragmentRepository.save(parentEntity);
598     }
599
600     @Override
601     @Transactional
602     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
603         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
604         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
605                 .ifPresent(
606                         anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
607     }
608
609     @Override
610     @Transactional
611     public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
612         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
613         final Collection<AnchorEntity> anchorEntities =
614             anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
615         fragmentRepository.deleteByAnchorIn(anchorEntities);
616     }
617
618     @Override
619     @Transactional
620     public void deleteDataNodes(final String dataspaceName, final String anchorName,
621                                 final Collection<String> xpathsToDelete) {
622         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
623         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
624
625         final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
626         for (final String xpath : xpathsToDelete) {
627             try {
628                 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
629             } catch (final PathParsingException e) {
630                 log.debug("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
631             }
632         }
633
634         final Collection<String> xpathsToExistingContainers =
635             fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
636         deleteChecklist.removeAll(xpathsToExistingContainers);
637
638         final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
639             .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
640             .collect(Collectors.toList());
641         deleteChecklist.removeAll(xpathsToExistingLists);
642
643         if (!deleteChecklist.isEmpty()) {
644             throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
645         }
646
647         fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
648         fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
649     }
650
651     @Override
652     @Transactional
653     public void deleteListDataNode(final String dataspaceName, final String anchorName,
654                                    final String targetXpath) {
655         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
656     }
657
658     @Override
659     @Transactional
660     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
661         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
662     }
663
664     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
665                                 final boolean onlySupportListNodeDeletion) {
666         final String parentNodeXpath;
667         FragmentEntity parentFragmentEntity = null;
668         boolean targetDeleted;
669         if (isRootXpath(targetXpath)) {
670             deleteDataNodes(dataspaceName, anchorName);
671             targetDeleted = true;
672         } else {
673             if (isRootContainerNodeXpath(targetXpath)) {
674                 parentNodeXpath = targetXpath;
675             } else {
676                 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
677             }
678             parentFragmentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
679             if (CpsPathUtil.isPathToListElement(targetXpath)) {
680                 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
681             } else {
682                 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
683                 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
684                 if (tryToDeleteDataNode) {
685                     targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
686                 }
687             }
688         }
689         if (!targetDeleted) {
690             final String additionalInformation = onlySupportListNodeDeletion
691                     ? "The target is probably not a List." : "";
692             throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
693                     parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
694         }
695     }
696
697     private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
698         final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
699         if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
700             fragmentRepository.deleteFragmentEntity(parentFragmentEntity.getId());
701             return true;
702         }
703         if (parentFragmentEntity.getChildFragments()
704                 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
705             fragmentRepository.save(parentFragmentEntity);
706             return true;
707         }
708         return false;
709     }
710
711     private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
712         final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
713         final String deleteTargetXpathPrefix = normalizedListXpath + "[";
714         if (parentFragmentEntity.getChildFragments()
715                 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
716             fragmentRepository.save(parentFragmentEntity);
717             return true;
718         }
719         return false;
720     }
721
722     private static void deleteListElements(
723             final Collection<FragmentEntity> fragmentEntities,
724             final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
725         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
726     }
727
728     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
729         if (newListElements.isEmpty()) {
730             throw new CpsAdminException("Invalid list replacement",
731                     "Cannot replace list elements with empty collection");
732         }
733         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
734         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
735     }
736
737     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
738                                                      final DataNode newListElement,
739                                                      final FragmentEntity existingListElementEntity) {
740         if (existingListElementEntity == null) {
741             return convertToFragmentWithAllDescendants(
742                     parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
743         }
744         if (newListElement.getChildDataNodes().isEmpty()) {
745             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
746             existingListElementEntity.getChildFragments().clear();
747         } else {
748             updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
749         }
750         return existingListElementEntity;
751     }
752
753     private static boolean isNewDataNode(final DataNode replacementDataNode,
754                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
755         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
756     }
757
758     private static boolean isRootContainerNodeXpath(final String xpath) {
759         return 0 == xpath.lastIndexOf('/');
760     }
761
762     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
763                                                   final DataNode newListElement) {
764         final FragmentEntity replacementFragmentEntity =
765                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
766                         newListElement.getLeaves())).build();
767         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
768     }
769
770     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
771             final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
772         return childEntities.stream()
773                 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
774                 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
775     }
776
777     private static boolean isRootXpath(final String xpath) {
778         return "/".equals(xpath) || "".equals(xpath);
779     }
780
781     private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
782         final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
783             ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
784         currentLeavesAsMap.putAll(updateLeaves);
785         if (currentLeavesAsMap.isEmpty()) {
786             return "";
787         }
788         return jsonObjectMapper.asJsonString(currentLeavesAsMap);
789     }
790 }