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 static org.onap.cps.spi.PaginationOption.NO_PAGINATION;
28 import com.google.common.collect.ImmutableSet;
29 import com.google.common.collect.ImmutableSet.Builder;
30 import io.micrometer.core.annotation.Timed;
31 import jakarta.transaction.Transactional;
32 import java.io.Serializable;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.List;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
43 import java.util.stream.Collectors;
44 import lombok.RequiredArgsConstructor;
45 import lombok.extern.slf4j.Slf4j;
46 import org.hibernate.StaleStateException;
47 import org.onap.cps.cpspath.parser.CpsPathQuery;
48 import org.onap.cps.cpspath.parser.CpsPathUtil;
49 import org.onap.cps.cpspath.parser.PathParsingException;
50 import org.onap.cps.spi.CpsDataPersistenceService;
51 import org.onap.cps.spi.FetchDescendantsOption;
52 import org.onap.cps.spi.PaginationOption;
53 import org.onap.cps.spi.entities.AnchorEntity;
54 import org.onap.cps.spi.entities.DataspaceEntity;
55 import org.onap.cps.spi.entities.FragmentEntity;
56 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
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.FragmentRepository;
67 import org.onap.cps.spi.utils.SessionManager;
68 import org.onap.cps.utils.JsonObjectMapper;
69 import org.springframework.dao.DataIntegrityViolationException;
70 import org.springframework.stereotype.Service;
74 @RequiredArgsConstructor
75 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
77 private final DataspaceRepository dataspaceRepository;
78 private final AnchorRepository anchorRepository;
79 private final FragmentRepository fragmentRepository;
80 private final JsonObjectMapper jsonObjectMapper;
81 private final SessionManager sessionManager;
83 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@.+?])?)";
86 public void addChildDataNodes(final String dataspaceName, final String anchorName,
87 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
88 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
89 addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
93 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
94 final Collection<DataNode> newListElements) {
95 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
96 addChildrenDataNodes(anchorEntity, parentNodeXpath, newListElements);
100 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
101 final Collection<Collection<DataNode>> newLists) {
102 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
103 final Collection<String> failedXpaths = new HashSet<>();
104 for (final Collection<DataNode> newList : newLists) {
106 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
107 } catch (final AlreadyDefinedException alreadyDefinedException) {
108 failedXpaths.addAll(alreadyDefinedException.getAlreadyDefinedObjectNames());
111 if (!failedXpaths.isEmpty()) {
112 throw AlreadyDefinedException.forDataNodes(failedXpaths, anchorEntity.getName());
116 private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
117 final DataNode newChild) {
118 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
119 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
120 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
122 fragmentRepository.save(newChildAsFragmentEntity);
123 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
124 throw AlreadyDefinedException.forDataNodes(Collections.singletonList(newChild.getXpath()),
125 anchorEntity.getName());
129 private void addChildrenDataNodes(final AnchorEntity anchorEntity, final String parentNodeXpath,
130 final Collection<DataNode> newChildren) {
131 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
132 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
134 for (final DataNode newChildAsDataNode : newChildren) {
135 final FragmentEntity newChildAsFragmentEntity =
136 convertToFragmentWithAllDescendants(anchorEntity, newChildAsDataNode);
137 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
138 fragmentEntities.add(newChildAsFragmentEntity);
140 fragmentRepository.saveAll(fragmentEntities);
141 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
142 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
143 dataIntegrityViolationException, fragmentEntities.size());
144 retrySavingEachChildIndividually(anchorEntity, parentNodeXpath, newChildren);
148 private void retrySavingEachChildIndividually(final AnchorEntity anchorEntity, final String parentNodeXpath,
149 final Collection<DataNode> newChildren) {
150 final Collection<String> failedXpaths = new HashSet<>();
151 for (final DataNode newChild : newChildren) {
153 addNewChildDataNode(anchorEntity, parentNodeXpath, newChild);
154 } catch (final AlreadyDefinedException alreadyDefinedException) {
155 failedXpaths.add(newChild.getXpath());
158 if (!failedXpaths.isEmpty()) {
159 throw AlreadyDefinedException.forDataNodes(failedXpaths, anchorEntity.getName());
164 public void storeDataNodes(final String dataspaceName, final String anchorName,
165 final Collection<DataNode> dataNodes) {
166 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
167 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
169 for (final DataNode dataNode: dataNodes) {
170 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
171 fragmentEntities.add(fragmentEntity);
173 fragmentRepository.saveAll(fragmentEntities);
174 } catch (final DataIntegrityViolationException exception) {
175 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
176 exception, dataNodes.size());
177 storeDataNodesIndividually(anchorEntity, dataNodes);
181 private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
182 final Collection<String> failedXpaths = new HashSet<>();
183 for (final DataNode dataNode: dataNodes) {
185 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
186 fragmentRepository.save(fragmentEntity);
187 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
188 failedXpaths.add(dataNode.getXpath());
191 if (!failedXpaths.isEmpty()) {
192 throw AlreadyDefinedException.forDataNodes(failedXpaths, anchorEntity.getName());
197 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
198 * for all DataNode children recursively.
200 * @param anchorEntity anchorEntity
201 * @param dataNodeToBeConverted dataNode
202 * @return a Fragment built from current DataNode
204 private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
205 final DataNode dataNodeToBeConverted) {
206 final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
207 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
208 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
209 final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
210 childFragmentsImmutableSetBuilder.add(childFragment);
212 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
213 return parentFragment;
216 private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
217 return FragmentEntity.builder()
218 .anchor(anchorEntity)
219 .xpath(dataNode.getXpath())
220 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
225 @Timed(value = "cps.data.persistence.service.datanode.get",
226 description = "Time taken to get a data node")
227 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
229 final FetchDescendantsOption fetchDescendantsOption) {
230 final String targetXpath = getNormalizedXpath(xpath);
231 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
232 Collections.singletonList(targetXpath), fetchDescendantsOption);
233 if (dataNodes.isEmpty()) {
234 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
240 @Timed(value = "cps.data.persistence.service.datanode.batch.get",
241 description = "Time taken to get data nodes")
242 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
243 final Collection<String> xpaths,
244 final FetchDescendantsOption fetchDescendantsOption) {
245 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
246 Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpaths);
247 fragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption,
249 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
252 private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
253 final Collection<String> xpaths) {
254 final Collection<String> normalizedXpaths = getNormalizedXpaths(xpaths);
256 final boolean haveRootXpath = normalizedXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
258 final List<FragmentEntity> fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity,
261 for (final FragmentEntity fragmentEntity : fragmentEntities) {
262 normalizedXpaths.remove(fragmentEntity.getXpath());
265 for (final String xpath : normalizedXpaths) {
266 if (!CpsPathUtil.isPathToListElement(xpath)) {
267 fragmentEntities.addAll(fragmentRepository.findListByAnchorAndXpath(anchorEntity, xpath));
272 fragmentEntities.addAll(fragmentRepository.findRootsByAnchorId(anchorEntity.getId()));
275 return fragmentEntities;
278 private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
279 final FragmentEntity fragmentEntity;
280 if (isRootXpath(xpath)) {
281 fragmentEntity = fragmentRepository.findOneByAnchorId(anchorEntity.getId()).orElse(null);
283 fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
285 if (fragmentEntity == null) {
286 throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
288 return fragmentEntity;
292 @Timed(value = "cps.data.persistence.service.datanode.query",
293 description = "Time taken to query data nodes")
294 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
295 final FetchDescendantsOption fetchDescendantsOption) {
296 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
297 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
298 final CpsPathQuery cpsPathQuery;
300 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
301 } catch (final PathParsingException pathParsingException) {
302 throw new CpsPathException(pathParsingException.getMessage());
305 Collection<FragmentEntity> fragmentEntities;
306 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity, cpsPathQuery);
307 if (cpsPathQuery.hasAncestorAxis()) {
308 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
309 fragmentEntities = fragmentRepository.findByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
311 fragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption,
313 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
317 @Timed(value = "cps.data.persistence.service.datanode.query.anchors",
318 description = "Time taken to query data nodes across all anchors or list of anchors")
319 public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
320 final FetchDescendantsOption fetchDescendantsOption,
321 final PaginationOption paginationOption) {
322 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
323 final CpsPathQuery cpsPathQuery;
325 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
326 } catch (final PathParsingException e) {
327 throw new CpsPathException(e.getMessage());
330 final List<Long> anchorIds;
331 if (paginationOption == NO_PAGINATION) {
332 anchorIds = Collections.emptyList();
334 anchorIds = getAnchorIdsForPagination(dataspaceEntity, cpsPathQuery, paginationOption);
335 if (anchorIds.isEmpty()) {
336 return Collections.emptyList();
339 Collection<FragmentEntity> fragmentEntities =
340 fragmentRepository.findByDataspaceAndCpsPath(dataspaceEntity, cpsPathQuery, anchorIds);
342 if (cpsPathQuery.hasAncestorAxis()) {
343 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
344 if (anchorIds.isEmpty()) {
345 fragmentEntities = fragmentRepository.findByDataspaceAndXpathIn(dataspaceEntity, ancestorXpaths);
347 fragmentEntities = fragmentRepository.findByAnchorIdsAndXpathIn(
348 anchorIds.toArray(new Long[0]), ancestorXpaths.toArray(new String[0]));
352 fragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(fetchDescendantsOption,
354 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
357 private List<Long> getAnchorIdsForPagination(final DataspaceEntity dataspaceEntity, final CpsPathQuery cpsPathQuery,
358 final PaginationOption paginationOption) {
359 return fragmentRepository.findAnchorIdsForPagination(dataspaceEntity, cpsPathQuery, paginationOption);
362 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
363 final Collection<FragmentEntity> fragmentEntities) {
364 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
365 for (final FragmentEntity fragmentEntity : fragmentEntities) {
366 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
368 return Collections.unmodifiableList(dataNodes);
371 private static String getNormalizedXpath(final String xpathSource) {
372 if (isRootXpath(xpathSource)) {
376 return CpsPathUtil.getNormalizedXpath(xpathSource);
377 } catch (final PathParsingException pathParsingException) {
378 throw new CpsPathException(pathParsingException.getMessage());
382 private static Collection<String> getNormalizedXpaths(final Collection<String> xpaths) {
383 final Collection<String> normalizedXpaths = new HashSet<>(xpaths.size());
384 for (final String xpath : xpaths) {
386 normalizedXpaths.add(getNormalizedXpath(xpath));
387 } catch (final CpsPathException cpsPathException) {
388 log.warn("Error parsing xpath \"{}\": {}", xpath, cpsPathException.getMessage());
391 return normalizedXpaths;
395 public String startSession() {
396 return sessionManager.startSession();
400 public void closeSession(final String sessionId) {
401 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
405 public void lockAnchor(final String sessionId, final String dataspaceName,
406 final String anchorName, final Long timeoutInMilliseconds) {
407 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
411 public Integer countAnchorsForDataspaceAndCpsPath(final String dataspaceName, final String cpsPath) {
412 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
413 final CpsPathQuery cpsPathQuery;
415 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
416 } catch (final PathParsingException e) {
417 throw new CpsPathException(e.getMessage());
419 final List<Long> anchorIdList = getAnchorIdsForPagination(dataspaceEntity, cpsPathQuery, NO_PAGINATION);
420 return anchorIdList.size();
423 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
424 final CpsPathQuery cpsPathQuery) {
425 final Set<String> ancestorXpath = new HashSet<>();
426 final Pattern pattern =
427 Pattern.compile("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
428 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
429 for (final FragmentEntity fragmentEntity : fragmentEntities) {
430 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
431 if (matcher.matches()) {
432 ancestorXpath.add(matcher.group(1));
435 return ancestorXpath;
438 private DataNode toDataNode(final FragmentEntity fragmentEntity,
439 final FetchDescendantsOption fetchDescendantsOption) {
440 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
441 Map<String, Serializable> leaves = new HashMap<>();
442 if (fragmentEntity.getAttributes() != null) {
443 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
445 return new DataNodeBuilder()
446 .withXpath(fragmentEntity.getXpath())
448 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
449 .withAnchor(fragmentEntity.getAnchor().getName())
450 .withChildDataNodes(childDataNodes).build();
453 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
454 final FetchDescendantsOption fetchDescendantsOption) {
455 if (fetchDescendantsOption.hasNext()) {
456 return fragmentEntity.getChildFragments().stream()
457 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
458 .collect(Collectors.toList());
460 return Collections.emptyList();
464 public void batchUpdateDataLeaves(final String dataspaceName, final String anchorName,
465 final Map<String, Map<String, Serializable>> updatedLeavesPerXPath) {
466 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
468 final Collection<String> xpathsOfUpdatedLeaves = updatedLeavesPerXPath.keySet();
469 final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(anchorEntity, xpathsOfUpdatedLeaves);
471 for (final FragmentEntity fragmentEntity : fragmentEntities) {
472 final Map<String, Serializable> updatedLeaves = updatedLeavesPerXPath.get(fragmentEntity.getXpath());
473 final String mergedLeaves = mergeLeaves(updatedLeaves, fragmentEntity.getAttributes());
474 fragmentEntity.setAttributes(mergedLeaves);
478 fragmentRepository.saveAll(fragmentEntities);
479 } catch (final StaleStateException staleStateException) {
480 retryUpdateDataNodesIndividually(anchorEntity, fragmentEntities);
485 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
486 final Collection<DataNode> updatedDataNodes) {
487 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
489 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
490 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
492 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
493 Collection<FragmentEntity> existingFragmentEntities = getFragmentEntities(anchorEntity, xpaths);
494 existingFragmentEntities = fragmentRepository.prefetchDescendantsOfFragmentEntities(
495 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS, existingFragmentEntities);
497 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
498 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
499 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
503 fragmentRepository.saveAll(existingFragmentEntities);
504 } catch (final StaleStateException staleStateException) {
505 retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
509 private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
510 final Collection<FragmentEntity> fragmentEntities) {
511 final Collection<String> failedXpaths = new HashSet<>();
512 for (final FragmentEntity dataNodeFragment : fragmentEntities) {
514 fragmentRepository.save(dataNodeFragment);
515 } catch (final StaleStateException staleStateException) {
516 failedXpaths.add(dataNodeFragment.getXpath());
519 if (!failedXpaths.isEmpty()) {
520 final String failedXpathsConcatenated = String.join(",", failedXpaths);
521 throw new ConcurrencyException("Concurrent Transactions", String.format(
522 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
523 failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
527 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
528 final DataNode newDataNode) {
529 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
531 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
532 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
534 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
535 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
536 final FragmentEntity childFragment;
537 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
538 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
541 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
542 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
544 updatedChildFragments.add(childFragment);
547 existingFragmentEntity.getChildFragments().clear();
548 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
553 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
554 final Collection<DataNode> newListElements) {
555 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
556 final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
557 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
558 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
559 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
560 parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
561 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
562 for (final DataNode newListElement : newListElements) {
563 final FragmentEntity existingListElementEntity =
564 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
565 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
566 existingListElementEntity);
567 updatedChildFragmentEntities.add(entityToBeAdded);
569 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
570 fragmentRepository.save(parentEntity);
575 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
576 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
577 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
578 .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
583 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
584 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
585 final Collection<AnchorEntity> anchorEntities =
586 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
587 fragmentRepository.deleteByAnchorIn(anchorEntities);
592 public void deleteDataNodes(final String dataspaceName, final String anchorName,
593 final Collection<String> xpathsToDelete) {
594 deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
597 private void deleteDataNodes(final String dataspaceName, final String anchorName,
598 final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
599 final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
601 deleteDataNodes(dataspaceName, anchorName);
605 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
607 final Collection<String> deleteChecklist = getNormalizedXpaths(xpathsToDelete);
608 final Collection<String> xpathsToExistingContainers =
609 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
610 if (onlySupportListDeletion) {
611 final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
612 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
613 deleteChecklist.removeAll(xpathsToExistingListElements);
615 deleteChecklist.removeAll(xpathsToExistingContainers);
618 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
619 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
620 .collect(Collectors.toList());
621 deleteChecklist.removeAll(xpathsToExistingLists);
623 if (!deleteChecklist.isEmpty()) {
624 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
627 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
628 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
633 public void deleteListDataNode(final String dataspaceName, final String anchorName,
634 final String targetXpath) {
635 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
640 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
641 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
644 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
645 final boolean onlySupportListNodeDeletion) {
646 final String normalizedXpath = getNormalizedXpath(targetXpath);
648 deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
649 onlySupportListNodeDeletion);
650 } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
651 throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
655 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
656 if (newListElements.isEmpty()) {
657 throw new CpsAdminException("Invalid list replacement",
658 "Cannot replace list elements with empty collection");
660 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
661 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
664 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
665 final DataNode newListElement,
666 final FragmentEntity existingListElementEntity) {
667 if (existingListElementEntity == null) {
668 return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
670 if (newListElement.getChildDataNodes().isEmpty()) {
671 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
672 existingListElementEntity.getChildFragments().clear();
674 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
676 return existingListElementEntity;
679 private static boolean isNewDataNode(final DataNode replacementDataNode,
680 final Map<String, FragmentEntity> existingListElementsByXpath) {
681 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
684 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
685 final DataNode newListElement) {
686 final FragmentEntity replacementFragmentEntity =
687 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
688 newListElement.getLeaves())).build();
689 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
692 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
693 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
694 return childEntities.stream()
695 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
696 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
699 private static boolean isRootXpath(final String xpath) {
700 return "/".equals(xpath) || "".equals(xpath);
703 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
704 Map<String, Serializable> currentLeavesAsMap = new HashMap<>();
705 if (currentLeavesAsString != null) {
706 currentLeavesAsMap = jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
707 currentLeavesAsMap.putAll(updateLeaves);
710 if (currentLeavesAsMap.isEmpty()) {
713 return jsonObjectMapper.asJsonString(currentLeavesAsMap);
716 private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
717 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
718 return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);