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 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
93 public void addChildDataNodes(final String dataspaceName, final String anchorName,
94 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
95 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
99 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
100 final Collection<DataNode> newListElements) {
101 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
105 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
106 final Collection<Collection<DataNode>> newLists) {
107 final Collection<String> failedXpaths = new HashSet<>();
108 newLists.forEach(newList -> {
110 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
111 } catch (final AlreadyDefinedExceptionBatch e) {
112 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
116 if (!failedXpaths.isEmpty()) {
117 throw new AlreadyDefinedExceptionBatch(failedXpaths);
122 private void addNewChildDataNode(final String dataspaceName, final String anchorName,
123 final String parentNodeXpath, final DataNode newChild) {
124 final FragmentEntity parentFragmentEntity =
125 getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
126 final FragmentEntity newChildAsFragmentEntity =
127 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
128 parentFragmentEntity.getAnchor(), newChild);
129 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
131 fragmentRepository.save(newChildAsFragmentEntity);
132 } catch (final DataIntegrityViolationException e) {
133 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
138 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
139 final Collection<DataNode> newChildren) {
140 final FragmentEntity parentFragmentEntity =
141 getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
142 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
144 newChildren.forEach(newChildAsDataNode -> {
145 final FragmentEntity newChildAsFragmentEntity =
146 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
147 parentFragmentEntity.getAnchor(), newChildAsDataNode);
148 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
149 fragmentEntities.add(newChildAsFragmentEntity);
151 fragmentRepository.saveAll(fragmentEntities);
152 } catch (final DataIntegrityViolationException e) {
153 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
154 e, fragmentEntities.size());
155 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
159 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
160 final String parentNodeXpath,
161 final Collection<DataNode> newChildren) {
162 final Collection<String> failedXpaths = new HashSet<>();
163 for (final DataNode newChild : newChildren) {
165 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
166 } catch (final AlreadyDefinedException e) {
167 failedXpaths.add(newChild.getXpath());
170 if (!failedXpaths.isEmpty()) {
171 throw new AlreadyDefinedExceptionBatch(failedXpaths);
176 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
177 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
181 public void storeDataNodes(final String dataspaceName, final String anchorName,
182 final Collection<DataNode> dataNodes) {
183 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
184 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
185 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
187 for (final DataNode dataNode: dataNodes) {
188 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
190 fragmentEntities.add(fragmentEntity);
192 fragmentRepository.saveAll(fragmentEntities);
193 } catch (final DataIntegrityViolationException exception) {
194 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
195 exception, dataNodes.size());
196 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
200 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
201 final Collection<DataNode> dataNodes) {
202 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
203 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
204 final Collection<String> failedXpaths = new HashSet<>();
205 for (final DataNode dataNode: dataNodes) {
207 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
209 fragmentRepository.save(fragmentEntity);
210 } catch (final DataIntegrityViolationException e) {
211 failedXpaths.add(dataNode.getXpath());
214 if (!failedXpaths.isEmpty()) {
215 throw new AlreadyDefinedExceptionBatch(failedXpaths);
220 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
221 * for all DataNode children recursively.
223 * @param dataspaceEntity dataspace
224 * @param anchorEntity anchorEntity
225 * @param dataNodeToBeConverted dataNode
226 * @return a Fragment built from current DataNode
228 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
229 final AnchorEntity anchorEntity,
230 final DataNode dataNodeToBeConverted) {
231 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
232 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
233 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
234 final FragmentEntity childFragment =
235 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
237 childFragmentsImmutableSetBuilder.add(childFragment);
239 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
240 return parentFragment;
243 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
244 final AnchorEntity anchorEntity, final DataNode dataNode) {
245 return FragmentEntity.builder()
246 .dataspace(dataspaceEntity)
247 .anchor(anchorEntity)
248 .xpath(dataNode.getXpath())
249 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
254 @Timed(value = "cps.data.persistence.service.datanode.get",
255 description = "Time taken to get a data node")
256 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
258 final FetchDescendantsOption fetchDescendantsOption) {
259 final String targetXpath = getNormalizedXpath(xpath);
260 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
261 Collections.singletonList(targetXpath), fetchDescendantsOption);
262 if (dataNodes.isEmpty()) {
263 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
269 @Timed(value = "cps.data.persistence.service.datanode.batch.get",
270 description = "Time taken to get data nodes")
271 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
272 final Collection<String> xpaths,
273 final FetchDescendantsOption fetchDescendantsOption) {
274 final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(dataspaceName, anchorName, xpaths);
275 return toDataNodes(fragmentEntities, fetchDescendantsOption);
278 private Collection<FragmentEntity> getFragmentEntities(final String dataspaceName, final String anchorName,
279 final Collection<String> xpaths) {
280 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
281 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
283 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
284 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
286 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
287 for (final String xpath : nonRootXpaths) {
289 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
290 } catch (final PathParsingException e) {
291 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
294 final Collection<FragmentEntity> fragmentEntities =
295 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
298 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
300 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
303 return fragmentEntities;
306 private FragmentEntity getFragmentEntity(final String dataspaceName, final String anchorName, final String xpath) {
307 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
308 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
309 final FragmentEntity fragmentEntity;
310 if (isRootXpath(xpath)) {
311 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
313 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
314 .stream().findFirst().orElse(null);
316 final String normalizedXpath = getNormalizedXpath(xpath);
318 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
320 if (fragmentEntity == null) {
321 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
323 return fragmentEntity;
327 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
328 final String normalizedXpath) {
329 final List<FragmentExtract> fragmentExtracts =
330 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
331 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
332 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
333 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
338 @Timed(value = "cps.data.persistence.service.datanode.query",
339 description = "Time taken to query data nodes")
340 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
341 final FetchDescendantsOption fetchDescendantsOption) {
342 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
343 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
344 final CpsPathQuery cpsPathQuery;
346 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
347 } catch (final PathParsingException e) {
348 throw new CpsPathException(e.getMessage());
351 Collection<FragmentEntity> fragmentEntities;
352 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
353 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
355 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
356 if (cpsPathQuery.hasAncestorAxis()) {
357 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
359 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
362 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
363 final CpsPathQuery cpsPathQuery) {
364 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
365 && !cpsPathQuery.hasLeafConditions()
366 && !cpsPathQuery.hasTextFunctionCondition();
369 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
370 final AnchorEntity anchorEntity,
371 final CpsPathQuery cpsPathQuery) {
372 Collection<FragmentEntity> fragmentEntities;
373 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
374 final List<FragmentExtract> fragmentExtracts =
375 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
376 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
377 if (cpsPathQuery.hasAncestorAxis()) {
378 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
380 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
383 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
384 final CpsPathQuery cpsPathQuery,
385 final Collection<FragmentEntity> fragmentEntities) {
386 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
387 return ancestorXpaths.isEmpty() ? Collections.emptyList()
388 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
391 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
392 final FetchDescendantsOption fetchDescendantsOption,
393 final AnchorEntity anchorEntity,
394 final Collection<FragmentEntity> proxiedFragmentEntities) {
395 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
396 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
397 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
398 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
400 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
401 final Collection<FragmentEntity> unproxiedFragmentEntities =
402 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
403 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
404 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
408 return Collections.unmodifiableList(dataNodes);
411 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
412 final Collection<FragmentEntity> fragmentEntities) {
413 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
414 for (final FragmentEntity fragmentEntity : fragmentEntities) {
415 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
417 return Collections.unmodifiableList(dataNodes);
420 private static String getNormalizedXpath(final String xpathSource) {
421 if (isRootXpath(xpathSource)) {
425 return CpsPathUtil.getNormalizedXpath(xpathSource);
426 } catch (final PathParsingException e) {
427 throw new CpsPathException(e.getMessage());
432 public String startSession() {
433 return sessionManager.startSession();
437 public void closeSession(final String sessionId) {
438 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
442 public void lockAnchor(final String sessionId, final String dataspaceName,
443 final String anchorName, final Long timeoutInMilliseconds) {
444 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
447 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
448 final CpsPathQuery cpsPathQuery) {
449 final Set<String> ancestorXpath = new HashSet<>();
450 final Pattern pattern =
451 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
452 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
453 for (final FragmentEntity fragmentEntity : fragmentEntities) {
454 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
455 if (matcher.matches()) {
456 ancestorXpath.add(matcher.group(1));
459 return ancestorXpath;
462 private DataNode toDataNode(final FragmentEntity fragmentEntity,
463 final FetchDescendantsOption fetchDescendantsOption) {
464 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
465 Map<String, Serializable> leaves = new HashMap<>();
466 if (fragmentEntity.getAttributes() != null) {
467 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
469 return new DataNodeBuilder()
470 .withXpath(fragmentEntity.getXpath())
472 .withChildDataNodes(childDataNodes).build();
475 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
476 final FetchDescendantsOption fetchDescendantsOption) {
477 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
478 for (final FragmentEntity fragmentEntity : fragmentEntities) {
479 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
484 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
485 final FetchDescendantsOption fetchDescendantsOption) {
486 if (fetchDescendantsOption.hasNext()) {
487 return fragmentEntity.getChildFragments().stream()
488 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
489 .collect(Collectors.toList());
491 return Collections.emptyList();
495 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
496 final Map<String, Serializable> updateLeaves) {
497 final FragmentEntity fragmentEntity = getFragmentEntity(dataspaceName, anchorName, xpath);
498 final String currentLeavesAsString = fragmentEntity.getAttributes();
499 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
500 fragmentEntity.setAttributes(mergedLeaves);
501 fragmentRepository.save(fragmentEntity);
505 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
506 final DataNode dataNode) {
507 final FragmentEntity fragmentEntity = getFragmentEntity(dataspaceName, anchorName, dataNode.getXpath());
508 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
510 fragmentRepository.save(fragmentEntity);
511 } catch (final StaleStateException staleStateException) {
512 throw new ConcurrencyException("Concurrent Transactions",
513 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
514 dataspaceName, anchorName, dataNode.getXpath()));
519 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
520 final List<DataNode> updatedDataNodes) {
521 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
522 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
524 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
525 final Collection<FragmentEntity> existingFragmentEntities =
526 getFragmentEntities(dataspaceName, anchorName, xpaths);
528 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
529 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
530 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
534 fragmentRepository.saveAll(existingFragmentEntities);
535 } catch (final StaleStateException staleStateException) {
536 retryUpdateDataNodesIndividually(dataspaceName, anchorName, existingFragmentEntities);
540 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
541 final Collection<FragmentEntity> fragmentEntities) {
542 final Collection<String> failedXpaths = new HashSet<>();
544 fragmentEntities.forEach(dataNodeFragment -> {
546 fragmentRepository.save(dataNodeFragment);
547 } catch (final StaleStateException e) {
548 failedXpaths.add(dataNodeFragment.getXpath());
552 if (!failedXpaths.isEmpty()) {
553 final String failedXpathsConcatenated = String.join(",", failedXpaths);
554 throw new ConcurrencyException("Concurrent Transactions", String.format(
555 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
556 failedXpathsConcatenated, dataspaceName, anchorName));
560 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
561 final DataNode newDataNode) {
563 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
565 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
566 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
568 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
570 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
571 final FragmentEntity childFragment;
572 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
573 childFragment = convertToFragmentWithAllDescendants(
574 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
576 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
577 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
579 updatedChildFragments.add(childFragment);
582 existingFragmentEntity.getChildFragments().clear();
583 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
588 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
589 final Collection<DataNode> newListElements) {
590 final FragmentEntity parentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
591 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
592 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
593 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
594 parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
595 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
596 for (final DataNode newListElement : newListElements) {
597 final FragmentEntity existingListElementEntity =
598 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
599 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
600 existingListElementEntity);
602 updatedChildFragmentEntities.add(entityToBeAdded);
604 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
605 fragmentRepository.save(parentEntity);
610 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
611 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
612 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
613 .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
618 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
619 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
620 final Collection<AnchorEntity> anchorEntities =
621 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
622 fragmentRepository.deleteByAnchorIn(anchorEntities);
627 public void deleteDataNodes(final String dataspaceName, final String anchorName,
628 final Collection<String> xpathsToDelete) {
629 deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
632 private void deleteDataNodes(final String dataspaceName, final String anchorName,
633 final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
634 final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
636 deleteDataNodes(dataspaceName, anchorName);
640 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
641 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
643 final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
644 for (final String xpath : xpathsToDelete) {
646 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
647 } catch (final PathParsingException e) {
648 log.debug("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
652 final Collection<String> xpathsToExistingContainers =
653 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
654 if (onlySupportListDeletion) {
655 final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
656 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
657 deleteChecklist.removeAll(xpathsToExistingListElements);
659 deleteChecklist.removeAll(xpathsToExistingContainers);
662 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
663 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
664 .collect(Collectors.toList());
665 deleteChecklist.removeAll(xpathsToExistingLists);
667 if (!deleteChecklist.isEmpty()) {
668 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
671 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
672 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
677 public void deleteListDataNode(final String dataspaceName, final String anchorName,
678 final String targetXpath) {
679 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
684 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
685 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
688 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
689 final boolean onlySupportListNodeDeletion) {
690 final String normalizedXpath = getNormalizedXpath(targetXpath);
692 deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
693 onlySupportListNodeDeletion);
694 } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
695 throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
699 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
700 if (newListElements.isEmpty()) {
701 throw new CpsAdminException("Invalid list replacement",
702 "Cannot replace list elements with empty collection");
704 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
705 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
708 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
709 final DataNode newListElement,
710 final FragmentEntity existingListElementEntity) {
711 if (existingListElementEntity == null) {
712 return convertToFragmentWithAllDescendants(
713 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
715 if (newListElement.getChildDataNodes().isEmpty()) {
716 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
717 existingListElementEntity.getChildFragments().clear();
719 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
721 return existingListElementEntity;
724 private static boolean isNewDataNode(final DataNode replacementDataNode,
725 final Map<String, FragmentEntity> existingListElementsByXpath) {
726 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
729 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
730 final DataNode newListElement) {
731 final FragmentEntity replacementFragmentEntity =
732 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
733 newListElement.getLeaves())).build();
734 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
737 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
738 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
739 return childEntities.stream()
740 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
741 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
744 private static boolean isRootXpath(final String xpath) {
745 return "/".equals(xpath) || "".equals(xpath);
748 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
749 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
750 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
751 currentLeavesAsMap.putAll(updateLeaves);
752 if (currentLeavesAsMap.isEmpty()) {
755 return jsonObjectMapper.asJsonString(currentLeavesAsMap);