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