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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl;
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;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.stream.Collectors;
42 import javax.transaction.Transactional;
43 import lombok.RequiredArgsConstructor;
44 import lombok.extern.slf4j.Slf4j;
45 import org.hibernate.StaleStateException;
46 import org.onap.cps.cpspath.parser.CpsPathQuery;
47 import org.onap.cps.cpspath.parser.CpsPathUtil;
48 import org.onap.cps.cpspath.parser.PathParsingException;
49 import org.onap.cps.spi.CpsDataPersistenceService;
50 import org.onap.cps.spi.FetchDescendantsOption;
51 import org.onap.cps.spi.entities.AnchorEntity;
52 import org.onap.cps.spi.entities.DataspaceEntity;
53 import org.onap.cps.spi.entities.FragmentEntity;
54 import org.onap.cps.spi.entities.FragmentEntityArranger;
55 import org.onap.cps.spi.entities.FragmentExtract;
56 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
57 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
58 import org.onap.cps.spi.exceptions.ConcurrencyException;
59 import org.onap.cps.spi.exceptions.CpsAdminException;
60 import org.onap.cps.spi.exceptions.CpsPathException;
61 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
62 import org.onap.cps.spi.exceptions.DataNodeNotFoundExceptionBatch;
63 import org.onap.cps.spi.model.DataNode;
64 import org.onap.cps.spi.model.DataNodeBuilder;
65 import org.onap.cps.spi.repository.AnchorRepository;
66 import org.onap.cps.spi.repository.DataspaceRepository;
67 import org.onap.cps.spi.repository.FragmentQueryBuilder;
68 import org.onap.cps.spi.repository.FragmentRepository;
69 import org.onap.cps.spi.utils.SessionManager;
70 import org.onap.cps.utils.JsonObjectMapper;
71 import org.springframework.dao.DataIntegrityViolationException;
72 import org.springframework.stereotype.Service;
76 @RequiredArgsConstructor
77 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
79 private final DataspaceRepository dataspaceRepository;
80 private final AnchorRepository anchorRepository;
81 private final FragmentRepository fragmentRepository;
82 private final JsonObjectMapper jsonObjectMapper;
83 private final SessionManager sessionManager;
85 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?])?)";
86 private static final String QUERY_ACROSS_ANCHORS = null;
87 private static final AnchorEntity ALL_ANCHORS = null;
90 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
91 final DataNode newChildDataNode) {
92 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
93 addNewChildDataNode(anchorEntity, parentNodeXpath, newChildDataNode);
97 public void addChildDataNodes(final String dataspaceName, final String anchorName,
98 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
99 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
100 addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
104 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
105 final Collection<DataNode> newListElements) {
106 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
107 addChildrenDataNodes(anchorEntity, parentNodeXpath, newListElements);
111 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
112 final Collection<Collection<DataNode>> newLists) {
113 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
114 final Collection<String> failedXpaths = new HashSet<>();
115 for (final Collection<DataNode> newList : newLists) {
117 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
118 } catch (final AlreadyDefinedExceptionBatch e) {
119 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
122 if (!failedXpaths.isEmpty()) {
123 throw new AlreadyDefinedExceptionBatch(failedXpaths);
127 private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
128 final DataNode newChild) {
129 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
130 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
131 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
133 fragmentRepository.save(newChildAsFragmentEntity);
134 } catch (final DataIntegrityViolationException e) {
135 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorEntity.getName(), e);
139 private void addChildrenDataNodes(final AnchorEntity anchorEntity, final String parentNodeXpath,
140 final Collection<DataNode> newChildren) {
141 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
142 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
144 for (final DataNode newChildAsDataNode : newChildren) {
145 final FragmentEntity newChildAsFragmentEntity =
146 convertToFragmentWithAllDescendants(anchorEntity, newChildAsDataNode);
147 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
148 fragmentEntities.add(newChildAsFragmentEntity);
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(anchorEntity, parentNodeXpath, newChildren);
158 private void retrySavingEachChildIndividually(final AnchorEntity anchorEntity, final String parentNodeXpath,
159 final Collection<DataNode> newChildren) {
160 final Collection<String> failedXpaths = new HashSet<>();
161 for (final DataNode newChild : newChildren) {
163 addNewChildDataNode(anchorEntity, parentNodeXpath, newChild);
164 } catch (final AlreadyDefinedException e) {
165 failedXpaths.add(newChild.getXpath());
168 if (!failedXpaths.isEmpty()) {
169 throw new AlreadyDefinedExceptionBatch(failedXpaths);
174 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
175 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
179 public void storeDataNodes(final String dataspaceName, final String anchorName,
180 final Collection<DataNode> dataNodes) {
181 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
182 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
184 for (final DataNode dataNode: dataNodes) {
185 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
186 fragmentEntities.add(fragmentEntity);
188 fragmentRepository.saveAll(fragmentEntities);
189 } catch (final DataIntegrityViolationException exception) {
190 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
191 exception, dataNodes.size());
192 storeDataNodesIndividually(anchorEntity, dataNodes);
196 private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
197 final Collection<String> failedXpaths = new HashSet<>();
198 for (final DataNode dataNode: dataNodes) {
200 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
201 fragmentRepository.save(fragmentEntity);
202 } catch (final DataIntegrityViolationException e) {
203 failedXpaths.add(dataNode.getXpath());
206 if (!failedXpaths.isEmpty()) {
207 throw new AlreadyDefinedExceptionBatch(failedXpaths);
212 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
213 * for all DataNode children recursively.
215 * @param anchorEntity anchorEntity
216 * @param dataNodeToBeConverted dataNode
217 * @return a Fragment built from current DataNode
219 private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
220 final DataNode dataNodeToBeConverted) {
221 final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
222 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
223 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
224 final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
225 childFragmentsImmutableSetBuilder.add(childFragment);
227 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
228 return parentFragment;
231 private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
232 return FragmentEntity.builder()
233 .dataspace(anchorEntity.getDataspace())
234 .anchor(anchorEntity)
235 .xpath(dataNode.getXpath())
236 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
241 @Timed(value = "cps.data.persistence.service.datanode.get",
242 description = "Time taken to get a data node")
243 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
245 final FetchDescendantsOption fetchDescendantsOption) {
246 final String targetXpath = getNormalizedXpath(xpath);
247 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
248 Collections.singletonList(targetXpath), fetchDescendantsOption);
249 if (dataNodes.isEmpty()) {
250 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
256 @Timed(value = "cps.data.persistence.service.datanode.batch.get",
257 description = "Time taken to get data nodes")
258 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
259 final Collection<String> xpaths,
260 final FetchDescendantsOption fetchDescendantsOption) {
261 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
262 final Collection<FragmentEntity> fragmentEntities =
263 getFragmentEntities(anchorEntity, xpaths, fetchDescendantsOption);
264 return toDataNodes(fragmentEntities, fetchDescendantsOption);
267 private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
268 final Collection<String> xpaths,
269 final FetchDescendantsOption fetchDescendantsOption) {
270 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
271 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
273 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
274 for (final String xpath : nonRootXpaths) {
276 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
277 } catch (final PathParsingException e) {
278 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
282 normalizedXpaths.addAll(fragmentRepository.findAllXpathByAnchorAndParentIdIsNull(anchorEntity));
285 final List<FragmentExtract> fragmentExtracts =
286 fragmentRepository.findExtractsWithDescendants(anchorEntity.getId(), normalizedXpaths,
287 fetchDescendantsOption.getDepth());
289 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
292 private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
293 final FragmentEntity fragmentEntity;
294 if (isRootXpath(xpath)) {
295 final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
296 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
297 .stream().findFirst().orElse(null);
299 fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
301 if (fragmentEntity == null) {
302 throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
304 return fragmentEntity;
307 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
308 final String normalizedXpath) {
309 final List<FragmentExtract> fragmentExtracts =
310 fragmentRepository.findByAnchorAndParentXpath(anchorEntity, normalizedXpath);
311 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
315 @Timed(value = "cps.data.persistence.service.datanode.query",
316 description = "Time taken to query data nodes")
317 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
318 final FetchDescendantsOption fetchDescendantsOption) {
319 final AnchorEntity anchorEntity = (Strings.isNullOrEmpty(anchorName)) ? ALL_ANCHORS
320 : getAnchorEntity(dataspaceName, anchorName);
321 final CpsPathQuery cpsPathQuery;
323 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
324 } catch (final PathParsingException e) {
325 throw new CpsPathException(e.getMessage());
328 Collection<FragmentEntity> fragmentEntities;
329 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
330 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
332 fragmentEntities = (anchorEntity == ALL_ANCHORS) ? fragmentRepository.findByCpsPath(cpsPathQuery)
333 : fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
334 if (cpsPathQuery.hasAncestorAxis()) {
335 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
336 fragmentEntities = (anchorEntity == ALL_ANCHORS) ? getAncestorFragmentEntitiesAcrossAnchors(cpsPathQuery,
337 fragmentEntities) : getFragmentEntities(anchorEntity, ancestorXpaths, fetchDescendantsOption);
339 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
343 public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
344 final FetchDescendantsOption fetchDescendantsOption) {
345 return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
348 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
349 final CpsPathQuery cpsPathQuery) {
350 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
351 && !cpsPathQuery.hasAncestorAxis()
352 && !cpsPathQuery.hasLeafConditions()
353 && !cpsPathQuery.hasTextFunctionCondition()
354 && !cpsPathQuery.hasContainsFunctionCondition();
357 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
358 final AnchorEntity anchorEntity,
359 final CpsPathQuery cpsPathQuery) {
360 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegexForQuickFindWithDescendants(cpsPathQuery);
361 final List<FragmentExtract> fragmentExtracts = (anchorEntity == ALL_ANCHORS)
362 ? fragmentRepository.quickFindWithDescendantsAcrossAnchors(xpathRegex)
363 : fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
364 final Collection<FragmentEntity> fragmentEntities =
365 FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
366 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
369 private Collection<FragmentEntity> getAncestorFragmentEntitiesAcrossAnchors(final CpsPathQuery cpsPathQuery,
370 final Collection<FragmentEntity> fragmentEntities) {
371 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
372 return ancestorXpaths.isEmpty() ? Collections.emptyList() : fragmentRepository.findAllByXpathIn(ancestorXpaths);
375 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
376 final FetchDescendantsOption fetchDescendantsOption,
377 final AnchorEntity anchorEntity,
378 final Collection<FragmentEntity> proxiedFragmentEntities) {
379 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
380 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
381 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
382 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
384 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
385 final AnchorEntity anchorEntityForFragmentExtract = (anchorEntity == ALL_ANCHORS)
386 ? proxiedFragmentEntity.getAnchor() : anchorEntity;
387 final Collection<FragmentEntity> unproxiedFragmentEntities =
388 buildFragmentEntitiesFromFragmentExtracts(anchorEntityForFragmentExtract, normalizedXpath);
389 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
390 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
394 return Collections.unmodifiableList(dataNodes);
397 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
398 final Collection<FragmentEntity> fragmentEntities) {
399 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
400 for (final FragmentEntity fragmentEntity : fragmentEntities) {
401 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
403 return Collections.unmodifiableList(dataNodes);
406 private static String getNormalizedXpath(final String xpathSource) {
407 if (isRootXpath(xpathSource)) {
411 return CpsPathUtil.getNormalizedXpath(xpathSource);
412 } catch (final PathParsingException e) {
413 throw new CpsPathException(e.getMessage());
418 public String startSession() {
419 return sessionManager.startSession();
423 public void closeSession(final String sessionId) {
424 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
428 public void lockAnchor(final String sessionId, final String dataspaceName,
429 final String anchorName, final Long timeoutInMilliseconds) {
430 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
433 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
434 final CpsPathQuery cpsPathQuery) {
435 final Set<String> ancestorXpath = new HashSet<>();
436 final Pattern pattern =
437 Pattern.compile("([\\s\\S]*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
438 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/[\\s\\S]*");
439 for (final FragmentEntity fragmentEntity : fragmentEntities) {
440 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
441 if (matcher.matches()) {
442 ancestorXpath.add(matcher.group(1));
445 return ancestorXpath;
448 private DataNode toDataNode(final FragmentEntity fragmentEntity,
449 final FetchDescendantsOption fetchDescendantsOption) {
450 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
451 Map<String, Serializable> leaves = new HashMap<>();
452 if (fragmentEntity.getAttributes() != null) {
453 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
455 return new DataNodeBuilder()
456 .withXpath(fragmentEntity.getXpath())
458 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
459 .withAnchor(fragmentEntity.getAnchor().getName())
460 .withChildDataNodes(childDataNodes).build();
463 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
464 final FetchDescendantsOption fetchDescendantsOption) {
465 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
466 for (final FragmentEntity fragmentEntity : fragmentEntities) {
467 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
472 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
473 final FetchDescendantsOption fetchDescendantsOption) {
474 if (fetchDescendantsOption.hasNext()) {
475 return fragmentEntity.getChildFragments().stream()
476 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
477 .collect(Collectors.toList());
479 return Collections.emptyList();
483 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
484 final Map<String, Serializable> updateLeaves) {
485 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
486 final FragmentEntity fragmentEntity = getFragmentEntity(anchorEntity, xpath);
487 final String currentLeavesAsString = fragmentEntity.getAttributes();
488 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
489 fragmentEntity.setAttributes(mergedLeaves);
490 fragmentRepository.save(fragmentEntity);
494 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
495 final Collection<DataNode> updatedDataNodes) {
496 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
498 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
499 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
501 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
502 final Collection<FragmentEntity> existingFragmentEntities =
503 getFragmentEntities(anchorEntity, xpaths, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
505 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
506 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
507 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
511 fragmentRepository.saveAll(existingFragmentEntities);
512 } catch (final StaleStateException staleStateException) {
513 retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
517 private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
518 final Collection<FragmentEntity> fragmentEntities) {
519 final Collection<String> failedXpaths = new HashSet<>();
520 for (final FragmentEntity dataNodeFragment : fragmentEntities) {
522 fragmentRepository.save(dataNodeFragment);
523 } catch (final StaleStateException e) {
524 failedXpaths.add(dataNodeFragment.getXpath());
527 if (!failedXpaths.isEmpty()) {
528 final String failedXpathsConcatenated = String.join(",", failedXpaths);
529 throw new ConcurrencyException("Concurrent Transactions", String.format(
530 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
531 failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
535 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
536 final DataNode newDataNode) {
537 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
539 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
540 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
542 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
543 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
544 final FragmentEntity childFragment;
545 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
546 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
549 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
550 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
552 updatedChildFragments.add(childFragment);
555 existingFragmentEntity.getChildFragments().clear();
556 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
561 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
562 final Collection<DataNode> newListElements) {
563 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
564 final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
565 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
566 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
567 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
568 parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
569 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
570 for (final DataNode newListElement : newListElements) {
571 final FragmentEntity existingListElementEntity =
572 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
573 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
574 existingListElementEntity);
575 updatedChildFragmentEntities.add(entityToBeAdded);
577 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
578 fragmentRepository.save(parentEntity);
583 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
584 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
585 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
586 .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
591 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
592 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
593 final Collection<AnchorEntity> anchorEntities =
594 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
595 fragmentRepository.deleteByAnchorIn(anchorEntities);
600 public void deleteDataNodes(final String dataspaceName, final String anchorName,
601 final Collection<String> xpathsToDelete) {
602 deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
605 private void deleteDataNodes(final String dataspaceName, final String anchorName,
606 final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
607 final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
609 deleteDataNodes(dataspaceName, anchorName);
613 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
615 final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
616 for (final String xpath : xpathsToDelete) {
618 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
619 } catch (final PathParsingException e) {
620 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
624 final Collection<String> xpathsToExistingContainers =
625 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
626 if (onlySupportListDeletion) {
627 final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
628 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
629 deleteChecklist.removeAll(xpathsToExistingListElements);
631 deleteChecklist.removeAll(xpathsToExistingContainers);
634 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
635 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
636 .collect(Collectors.toList());
637 deleteChecklist.removeAll(xpathsToExistingLists);
639 if (!deleteChecklist.isEmpty()) {
640 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
643 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
644 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
649 public void deleteListDataNode(final String dataspaceName, final String anchorName,
650 final String targetXpath) {
651 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
656 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
657 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
660 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
661 final boolean onlySupportListNodeDeletion) {
662 final String normalizedXpath = getNormalizedXpath(targetXpath);
664 deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
665 onlySupportListNodeDeletion);
666 } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
667 throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
671 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
672 if (newListElements.isEmpty()) {
673 throw new CpsAdminException("Invalid list replacement",
674 "Cannot replace list elements with empty collection");
676 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
677 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
680 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
681 final DataNode newListElement,
682 final FragmentEntity existingListElementEntity) {
683 if (existingListElementEntity == null) {
684 return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
686 if (newListElement.getChildDataNodes().isEmpty()) {
687 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
688 existingListElementEntity.getChildFragments().clear();
690 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
692 return existingListElementEntity;
695 private static boolean isNewDataNode(final DataNode replacementDataNode,
696 final Map<String, FragmentEntity> existingListElementsByXpath) {
697 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
700 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
701 final DataNode newListElement) {
702 final FragmentEntity replacementFragmentEntity =
703 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
704 newListElement.getLeaves())).build();
705 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
708 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
709 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
710 return childEntities.stream()
711 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
712 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
715 private static boolean isRootXpath(final String xpath) {
716 return "/".equals(xpath) || "".equals(xpath);
719 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
720 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
721 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
722 currentLeavesAsMap.putAll(updateLeaves);
723 if (currentLeavesAsMap.isEmpty()) {
726 return jsonObjectMapper.asJsonString(currentLeavesAsMap);
729 private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
730 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
731 return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);