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.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;
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;
75 @RequiredArgsConstructor
76 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
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;
84 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?])?)";
87 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
88 final DataNode newChildDataNode) {
89 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
90 addNewChildDataNode(anchorEntity, parentNodeXpath, newChildDataNode);
94 public void addChildDataNodes(final String dataspaceName, final String anchorName,
95 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
96 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
97 addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
101 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
102 final Collection<DataNode> newListElements) {
103 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
104 addChildrenDataNodes(anchorEntity, parentNodeXpath, newListElements);
108 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
109 final Collection<Collection<DataNode>> newLists) {
110 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
111 final Collection<String> failedXpaths = new HashSet<>();
112 for (final Collection<DataNode> newList : newLists) {
114 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
115 } catch (final AlreadyDefinedExceptionBatch e) {
116 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
119 if (!failedXpaths.isEmpty()) {
120 throw new AlreadyDefinedExceptionBatch(failedXpaths);
124 private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
125 final DataNode newChild) {
126 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
127 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
128 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
130 fragmentRepository.save(newChildAsFragmentEntity);
131 } catch (final DataIntegrityViolationException e) {
132 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorEntity.getName(), e);
136 private void addChildrenDataNodes(final AnchorEntity anchorEntity, final String parentNodeXpath,
137 final Collection<DataNode> newChildren) {
138 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
139 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
141 for (final DataNode newChildAsDataNode : newChildren) {
142 final FragmentEntity newChildAsFragmentEntity =
143 convertToFragmentWithAllDescendants(anchorEntity, newChildAsDataNode);
144 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
145 fragmentEntities.add(newChildAsFragmentEntity);
147 fragmentRepository.saveAll(fragmentEntities);
148 } catch (final DataIntegrityViolationException e) {
149 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
150 e, fragmentEntities.size());
151 retrySavingEachChildIndividually(anchorEntity, parentNodeXpath, newChildren);
155 private void retrySavingEachChildIndividually(final AnchorEntity anchorEntity, final String parentNodeXpath,
156 final Collection<DataNode> newChildren) {
157 final Collection<String> failedXpaths = new HashSet<>();
158 for (final DataNode newChild : newChildren) {
160 addNewChildDataNode(anchorEntity, parentNodeXpath, newChild);
161 } catch (final AlreadyDefinedException e) {
162 failedXpaths.add(newChild.getXpath());
165 if (!failedXpaths.isEmpty()) {
166 throw new AlreadyDefinedExceptionBatch(failedXpaths);
171 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
172 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
176 public void storeDataNodes(final String dataspaceName, final String anchorName,
177 final Collection<DataNode> dataNodes) {
178 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
179 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
181 for (final DataNode dataNode: dataNodes) {
182 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
183 fragmentEntities.add(fragmentEntity);
185 fragmentRepository.saveAll(fragmentEntities);
186 } catch (final DataIntegrityViolationException exception) {
187 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
188 exception, dataNodes.size());
189 storeDataNodesIndividually(anchorEntity, dataNodes);
193 private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
194 final Collection<String> failedXpaths = new HashSet<>();
195 for (final DataNode dataNode: dataNodes) {
197 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
198 fragmentRepository.save(fragmentEntity);
199 } catch (final DataIntegrityViolationException e) {
200 failedXpaths.add(dataNode.getXpath());
203 if (!failedXpaths.isEmpty()) {
204 throw new AlreadyDefinedExceptionBatch(failedXpaths);
209 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
210 * for all DataNode children recursively.
212 * @param anchorEntity anchorEntity
213 * @param dataNodeToBeConverted dataNode
214 * @return a Fragment built from current DataNode
216 private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
217 final DataNode dataNodeToBeConverted) {
218 final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
219 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
220 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
221 final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
222 childFragmentsImmutableSetBuilder.add(childFragment);
224 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
225 return parentFragment;
228 private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
229 return FragmentEntity.builder()
230 .dataspace(anchorEntity.getDataspace())
231 .anchor(anchorEntity)
232 .xpath(dataNode.getXpath())
233 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
238 @Timed(value = "cps.data.persistence.service.datanode.get",
239 description = "Time taken to get a data node")
240 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
242 final FetchDescendantsOption fetchDescendantsOption) {
243 final String targetXpath = getNormalizedXpath(xpath);
244 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
245 Collections.singletonList(targetXpath), fetchDescendantsOption);
246 if (dataNodes.isEmpty()) {
247 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
253 @Timed(value = "cps.data.persistence.service.datanode.batch.get",
254 description = "Time taken to get data nodes")
255 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
256 final Collection<String> xpaths,
257 final FetchDescendantsOption fetchDescendantsOption) {
258 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
259 final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpaths);
260 return toDataNodes(fragmentEntities, fetchDescendantsOption);
263 private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
264 final Collection<String> xpaths) {
265 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
266 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
268 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
269 for (final String xpath : nonRootXpaths) {
271 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
272 } catch (final PathParsingException e) {
273 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
276 final Collection<FragmentEntity> fragmentEntities =
277 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
280 final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
281 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
284 return fragmentEntities;
287 private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
288 final FragmentEntity fragmentEntity;
289 if (isRootXpath(xpath)) {
290 final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
291 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
292 .stream().findFirst().orElse(null);
294 fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
296 if (fragmentEntity == null) {
297 throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
299 return fragmentEntity;
302 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
303 final String normalizedXpath) {
304 final List<FragmentExtract> fragmentExtracts =
305 fragmentRepository.findByAnchorAndParentXpath(anchorEntity, normalizedXpath);
306 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
310 @Timed(value = "cps.data.persistence.service.datanode.query",
311 description = "Time taken to query data nodes")
312 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
313 final FetchDescendantsOption fetchDescendantsOption) {
314 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
315 final CpsPathQuery cpsPathQuery;
317 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
318 } catch (final PathParsingException e) {
319 throw new CpsPathException(e.getMessage());
322 Collection<FragmentEntity> fragmentEntities;
323 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
324 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
326 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
327 if (cpsPathQuery.hasAncestorAxis()) {
328 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
330 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
333 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
334 final CpsPathQuery cpsPathQuery) {
335 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
336 && !cpsPathQuery.hasLeafConditions()
337 && !cpsPathQuery.hasTextFunctionCondition();
340 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
341 final AnchorEntity anchorEntity,
342 final CpsPathQuery cpsPathQuery) {
343 Collection<FragmentEntity> fragmentEntities;
344 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
345 final List<FragmentExtract> fragmentExtracts =
346 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
347 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
348 if (cpsPathQuery.hasAncestorAxis()) {
349 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
351 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
354 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
355 final CpsPathQuery cpsPathQuery,
356 final Collection<FragmentEntity> fragmentEntities) {
357 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
358 return ancestorXpaths.isEmpty() ? Collections.emptyList()
359 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
362 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
363 final FetchDescendantsOption fetchDescendantsOption,
364 final AnchorEntity anchorEntity,
365 final Collection<FragmentEntity> proxiedFragmentEntities) {
366 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
367 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
368 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
369 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
371 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
372 final Collection<FragmentEntity> unproxiedFragmentEntities =
373 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
374 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
375 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
379 return Collections.unmodifiableList(dataNodes);
382 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
383 final Collection<FragmentEntity> fragmentEntities) {
384 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
385 for (final FragmentEntity fragmentEntity : fragmentEntities) {
386 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
388 return Collections.unmodifiableList(dataNodes);
391 private static String getNormalizedXpath(final String xpathSource) {
392 if (isRootXpath(xpathSource)) {
396 return CpsPathUtil.getNormalizedXpath(xpathSource);
397 } catch (final PathParsingException e) {
398 throw new CpsPathException(e.getMessage());
403 public String startSession() {
404 return sessionManager.startSession();
408 public void closeSession(final String sessionId) {
409 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
413 public void lockAnchor(final String sessionId, final String dataspaceName,
414 final String anchorName, final Long timeoutInMilliseconds) {
415 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
418 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
419 final CpsPathQuery cpsPathQuery) {
420 final Set<String> ancestorXpath = new HashSet<>();
421 final Pattern pattern =
422 Pattern.compile("([\\s\\S]*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
423 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/[\\s\\S]*");
424 for (final FragmentEntity fragmentEntity : fragmentEntities) {
425 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
426 if (matcher.matches()) {
427 ancestorXpath.add(matcher.group(1));
430 return ancestorXpath;
433 private DataNode toDataNode(final FragmentEntity fragmentEntity,
434 final FetchDescendantsOption fetchDescendantsOption) {
435 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
436 Map<String, Serializable> leaves = new HashMap<>();
437 if (fragmentEntity.getAttributes() != null) {
438 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
440 return new DataNodeBuilder()
441 .withXpath(fragmentEntity.getXpath())
443 .withChildDataNodes(childDataNodes).build();
446 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
447 final FetchDescendantsOption fetchDescendantsOption) {
448 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
449 for (final FragmentEntity fragmentEntity : fragmentEntities) {
450 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
455 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
456 final FetchDescendantsOption fetchDescendantsOption) {
457 if (fetchDescendantsOption.hasNext()) {
458 return fragmentEntity.getChildFragments().stream()
459 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
460 .collect(Collectors.toList());
462 return Collections.emptyList();
466 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
467 final Map<String, Serializable> updateLeaves) {
468 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
469 final FragmentEntity fragmentEntity = getFragmentEntity(anchorEntity, xpath);
470 final String currentLeavesAsString = fragmentEntity.getAttributes();
471 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
472 fragmentEntity.setAttributes(mergedLeaves);
473 fragmentRepository.save(fragmentEntity);
477 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
478 final DataNode dataNode) {
479 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
480 final FragmentEntity fragmentEntity = getFragmentEntity(anchorEntity, dataNode.getXpath());
481 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
483 fragmentRepository.save(fragmentEntity);
484 } catch (final StaleStateException staleStateException) {
485 throw new ConcurrencyException("Concurrent Transactions",
486 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
487 dataspaceName, anchorName, dataNode.getXpath()));
492 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
493 final List<DataNode> updatedDataNodes) {
494 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
496 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
497 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
499 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
500 final Collection<FragmentEntity> existingFragmentEntities = getFragmentEntities(anchorEntity, xpaths);
502 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
503 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
504 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
508 fragmentRepository.saveAll(existingFragmentEntities);
509 } catch (final StaleStateException staleStateException) {
510 retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
514 private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
515 final Collection<FragmentEntity> fragmentEntities) {
516 final Collection<String> failedXpaths = new HashSet<>();
517 for (final FragmentEntity dataNodeFragment : fragmentEntities) {
519 fragmentRepository.save(dataNodeFragment);
520 } catch (final StaleStateException e) {
521 failedXpaths.add(dataNodeFragment.getXpath());
524 if (!failedXpaths.isEmpty()) {
525 final String failedXpathsConcatenated = String.join(",", failedXpaths);
526 throw new ConcurrencyException("Concurrent Transactions", String.format(
527 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
528 failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
532 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
533 final DataNode newDataNode) {
534 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
536 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
537 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
539 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
540 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
541 final FragmentEntity childFragment;
542 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
543 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
546 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
547 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
549 updatedChildFragments.add(childFragment);
552 existingFragmentEntity.getChildFragments().clear();
553 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
558 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
559 final Collection<DataNode> newListElements) {
560 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
561 final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
562 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
563 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
564 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
565 parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
566 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
567 for (final DataNode newListElement : newListElements) {
568 final FragmentEntity existingListElementEntity =
569 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
570 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
571 existingListElementEntity);
572 updatedChildFragmentEntities.add(entityToBeAdded);
574 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
575 fragmentRepository.save(parentEntity);
580 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
581 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
582 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
583 .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
588 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
589 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
590 final Collection<AnchorEntity> anchorEntities =
591 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
592 fragmentRepository.deleteByAnchorIn(anchorEntities);
597 public void deleteDataNodes(final String dataspaceName, final String anchorName,
598 final Collection<String> xpathsToDelete) {
599 deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
602 private void deleteDataNodes(final String dataspaceName, final String anchorName,
603 final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
604 final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
606 deleteDataNodes(dataspaceName, anchorName);
610 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
612 final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
613 for (final String xpath : xpathsToDelete) {
615 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
616 } catch (final PathParsingException e) {
617 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
621 final Collection<String> xpathsToExistingContainers =
622 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
623 if (onlySupportListDeletion) {
624 final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
625 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
626 deleteChecklist.removeAll(xpathsToExistingListElements);
628 deleteChecklist.removeAll(xpathsToExistingContainers);
631 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
632 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
633 .collect(Collectors.toList());
634 deleteChecklist.removeAll(xpathsToExistingLists);
636 if (!deleteChecklist.isEmpty()) {
637 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
640 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
641 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
646 public void deleteListDataNode(final String dataspaceName, final String anchorName,
647 final String targetXpath) {
648 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
653 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
654 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
657 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
658 final boolean onlySupportListNodeDeletion) {
659 final String normalizedXpath = getNormalizedXpath(targetXpath);
661 deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
662 onlySupportListNodeDeletion);
663 } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
664 throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
668 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
669 if (newListElements.isEmpty()) {
670 throw new CpsAdminException("Invalid list replacement",
671 "Cannot replace list elements with empty collection");
673 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
674 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
677 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
678 final DataNode newListElement,
679 final FragmentEntity existingListElementEntity) {
680 if (existingListElementEntity == null) {
681 return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
683 if (newListElement.getChildDataNodes().isEmpty()) {
684 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
685 existingListElementEntity.getChildFragments().clear();
687 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
689 return existingListElementEntity;
692 private static boolean isNewDataNode(final DataNode replacementDataNode,
693 final Map<String, FragmentEntity> existingListElementsByXpath) {
694 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
697 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
698 final DataNode newListElement) {
699 final FragmentEntity replacementFragmentEntity =
700 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
701 newListElement.getLeaves())).build();
702 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
705 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
706 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
707 return childEntities.stream()
708 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
709 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
712 private static boolean isRootXpath(final String xpath) {
713 return "/".equals(xpath) || "".equals(xpath);
716 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
717 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
718 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
719 currentLeavesAsMap.putAll(updateLeaves);
720 if (currentLeavesAsMap.isEmpty()) {
723 return jsonObjectMapper.asJsonString(currentLeavesAsMap);
726 private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
727 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
728 return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);