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