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 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 java.io.Serializable;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
39 import java.util.stream.Collectors;
40 import javax.transaction.Transactional;
41 import lombok.RequiredArgsConstructor;
42 import lombok.extern.slf4j.Slf4j;
43 import org.hibernate.StaleStateException;
44 import org.onap.cps.cpspath.parser.CpsPathQuery;
45 import org.onap.cps.cpspath.parser.CpsPathUtil;
46 import org.onap.cps.cpspath.parser.PathParsingException;
47 import org.onap.cps.spi.CpsDataPersistenceService;
48 import org.onap.cps.spi.FetchDescendantsOption;
49 import org.onap.cps.spi.entities.AnchorEntity;
50 import org.onap.cps.spi.entities.DataspaceEntity;
51 import org.onap.cps.spi.entities.FragmentEntity;
52 import org.onap.cps.spi.entities.FragmentEntityArranger;
53 import org.onap.cps.spi.entities.FragmentExtract;
54 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
55 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
56 import org.onap.cps.spi.exceptions.ConcurrencyException;
57 import org.onap.cps.spi.exceptions.CpsAdminException;
58 import org.onap.cps.spi.exceptions.CpsPathException;
59 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
60 import org.onap.cps.spi.model.DataNode;
61 import org.onap.cps.spi.model.DataNodeBuilder;
62 import org.onap.cps.spi.repository.AnchorRepository;
63 import org.onap.cps.spi.repository.DataspaceRepository;
64 import org.onap.cps.spi.repository.FragmentQueryBuilder;
65 import org.onap.cps.spi.repository.FragmentRepository;
66 import org.onap.cps.spi.utils.SessionManager;
67 import org.onap.cps.utils.JsonObjectMapper;
68 import org.springframework.dao.DataIntegrityViolationException;
69 import org.springframework.stereotype.Service;
73 @RequiredArgsConstructor
74 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
76 private final DataspaceRepository dataspaceRepository;
77 private final AnchorRepository anchorRepository;
78 private final FragmentRepository fragmentRepository;
79 private final JsonObjectMapper jsonObjectMapper;
80 private final SessionManager sessionManager;
82 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
85 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
86 final DataNode newChildDataNode) {
87 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
91 public void addChildDataNodes(final String dataspaceName, final String anchorName,
92 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
93 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
97 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
98 final Collection<DataNode> newListElements) {
99 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
103 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
104 final Collection<Collection<DataNode>> newLists) {
105 final Collection<String> failedXpaths = new HashSet<>();
106 newLists.forEach(newList -> {
108 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
109 } catch (final AlreadyDefinedExceptionBatch e) {
110 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
114 if (!failedXpaths.isEmpty()) {
115 throw new AlreadyDefinedExceptionBatch(failedXpaths);
120 private void addNewChildDataNode(final String dataspaceName, final String anchorName,
121 final String parentNodeXpath, final DataNode newChild) {
122 final FragmentEntity parentFragmentEntity =
123 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
124 final FragmentEntity newChildAsFragmentEntity =
125 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
126 parentFragmentEntity.getAnchor(), newChild);
127 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
129 fragmentRepository.save(newChildAsFragmentEntity);
130 } catch (final DataIntegrityViolationException e) {
131 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
136 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
137 final Collection<DataNode> newChildren) {
138 final FragmentEntity parentFragmentEntity =
139 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
140 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
142 newChildren.forEach(newChildAsDataNode -> {
143 final FragmentEntity newChildAsFragmentEntity =
144 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
145 parentFragmentEntity.getAnchor(), newChildAsDataNode);
146 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
147 fragmentEntities.add(newChildAsFragmentEntity);
149 fragmentRepository.saveAll(fragmentEntities);
150 } catch (final DataIntegrityViolationException e) {
151 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
152 e, fragmentEntities.size());
153 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
157 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
158 final String parentNodeXpath,
159 final Collection<DataNode> newChildren) {
160 final Collection<String> failedXpaths = new HashSet<>();
161 for (final DataNode newChild : newChildren) {
163 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
164 } catch (final AlreadyDefinedException e) {
165 failedXpaths.add(newChild.getXpath());
168 if (!failedXpaths.isEmpty()) {
169 throw new AlreadyDefinedExceptionBatch(failedXpaths);
174 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
175 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
179 public void storeDataNodes(final String dataspaceName, final String anchorName,
180 final Collection<DataNode> dataNodes) {
181 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
182 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
183 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
185 for (final DataNode dataNode: dataNodes) {
186 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
188 fragmentEntities.add(fragmentEntity);
190 fragmentRepository.saveAll(fragmentEntities);
191 } catch (final DataIntegrityViolationException exception) {
192 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
193 exception, dataNodes.size());
194 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
198 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
199 final Collection<DataNode> dataNodes) {
200 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
201 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
202 final Collection<String> failedXpaths = new HashSet<>();
203 for (final DataNode dataNode: dataNodes) {
205 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
207 fragmentRepository.save(fragmentEntity);
208 } catch (final DataIntegrityViolationException e) {
209 failedXpaths.add(dataNode.getXpath());
212 if (!failedXpaths.isEmpty()) {
213 throw new AlreadyDefinedExceptionBatch(failedXpaths);
218 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
219 * for all DataNode children recursively.
221 * @param dataspaceEntity dataspace
222 * @param anchorEntity anchorEntity
223 * @param dataNodeToBeConverted dataNode
224 * @return a Fragment built from current DataNode
226 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
227 final AnchorEntity anchorEntity,
228 final DataNode dataNodeToBeConverted) {
229 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
230 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
231 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
232 final FragmentEntity childFragment =
233 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
235 childFragmentsImmutableSetBuilder.add(childFragment);
237 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
238 return parentFragment;
241 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
242 final AnchorEntity anchorEntity, final DataNode dataNode) {
243 return FragmentEntity.builder()
244 .dataspace(dataspaceEntity)
245 .anchor(anchorEntity)
246 .xpath(dataNode.getXpath())
247 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
252 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
253 final FetchDescendantsOption fetchDescendantsOption) {
254 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
255 fetchDescendantsOption);
256 return toDataNode(fragmentEntity, fetchDescendantsOption);
260 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
261 final Collection<String> xpaths,
262 final FetchDescendantsOption fetchDescendantsOption) {
263 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
264 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
266 final Set<String> normalizedXpaths = new HashSet<>(xpaths.size());
267 for (final String xpath : xpaths) {
269 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
270 } catch (final PathParsingException e) {
271 log.warn("Error parsing xpath \"{}\" in getDataNodes: {}", xpath, e.getMessage());
275 final List<FragmentEntity> fragmentEntities =
276 fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths);
277 return toDataNodes(fragmentEntities, fetchDescendantsOption);
280 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
281 final String anchorName,
282 final String xpath) {
283 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
286 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
287 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
288 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
289 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
290 final FragmentEntity fragmentEntity;
291 if (isRootXpath(xpath)) {
292 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
294 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
295 .stream().findFirst().orElse(null);
297 final String normalizedXpath = getNormalizedXpath(xpath);
298 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
300 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
302 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
303 .stream().findFirst().orElse(null);
306 if (fragmentEntity == null) {
307 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
309 return fragmentEntity;
313 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
314 final String normalizedXpath) {
315 final List<FragmentExtract> fragmentExtracts =
316 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
317 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
318 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
319 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
324 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
325 final FetchDescendantsOption fetchDescendantsOption) {
326 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
327 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
328 final CpsPathQuery cpsPathQuery;
330 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
331 } catch (final PathParsingException e) {
332 throw new CpsPathException(e.getMessage());
335 Collection<FragmentEntity> fragmentEntities;
336 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
337 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
339 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
340 if (cpsPathQuery.hasAncestorAxis()) {
341 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
343 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
346 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
347 final CpsPathQuery cpsPathQuery) {
348 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
349 && !cpsPathQuery.hasLeafConditions()
350 && !cpsPathQuery.hasTextFunctionCondition();
353 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
354 final AnchorEntity anchorEntity,
355 final CpsPathQuery cpsPathQuery) {
356 Collection<FragmentEntity> fragmentEntities;
357 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
358 final List<FragmentExtract> fragmentExtracts =
359 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
360 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
361 if (cpsPathQuery.hasAncestorAxis()) {
362 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
364 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
367 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
368 final CpsPathQuery cpsPathQuery,
369 final Collection<FragmentEntity> fragmentEntities) {
370 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
371 return ancestorXpaths.isEmpty() ? Collections.emptyList()
372 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
375 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
376 final FetchDescendantsOption fetchDescendantsOption,
377 final AnchorEntity anchorEntity,
378 final Collection<FragmentEntity> proxiedFragmentEntities) {
379 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
380 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
381 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
382 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
384 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
385 final Collection<FragmentEntity> unproxiedFragmentEntities =
386 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
387 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
388 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
392 return Collections.unmodifiableList(dataNodes);
395 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
396 final Collection<FragmentEntity> fragmentEntities) {
397 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
398 for (final FragmentEntity fragmentEntity : fragmentEntities) {
399 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
401 return Collections.unmodifiableList(dataNodes);
404 private static String getNormalizedXpath(final String xpathSource) {
405 final String normalizedXpath;
407 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
408 } catch (final PathParsingException e) {
409 throw new CpsPathException(e.getMessage());
411 return normalizedXpath;
415 public String startSession() {
416 return sessionManager.startSession();
420 public void closeSession(final String sessionId) {
421 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
425 public void lockAnchor(final String sessionId, final String dataspaceName,
426 final String anchorName, final Long timeoutInMilliseconds) {
427 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
430 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
431 final CpsPathQuery cpsPathQuery) {
432 final Set<String> ancestorXpath = new HashSet<>();
433 final Pattern pattern =
434 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
435 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
436 for (final FragmentEntity fragmentEntity : fragmentEntities) {
437 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
438 if (matcher.matches()) {
439 ancestorXpath.add(matcher.group(1));
442 return ancestorXpath;
445 private DataNode toDataNode(final FragmentEntity fragmentEntity,
446 final FetchDescendantsOption fetchDescendantsOption) {
447 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
448 Map<String, Serializable> leaves = new HashMap<>();
449 if (fragmentEntity.getAttributes() != null) {
450 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
452 return new DataNodeBuilder()
453 .withXpath(fragmentEntity.getXpath())
455 .withChildDataNodes(childDataNodes).build();
458 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
459 final FetchDescendantsOption fetchDescendantsOption) {
460 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
461 for (final FragmentEntity fragmentEntity : fragmentEntities) {
462 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
467 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
468 final FetchDescendantsOption fetchDescendantsOption) {
469 if (fetchDescendantsOption.hasNext()) {
470 return fragmentEntity.getChildFragments().stream()
471 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
472 .collect(Collectors.toList());
474 return Collections.emptyList();
478 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
479 final Map<String, Serializable> updateLeaves) {
480 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
481 final String currentLeavesAsString = fragmentEntity.getAttributes();
482 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
483 fragmentEntity.setAttributes(mergedLeaves);
484 fragmentRepository.save(fragmentEntity);
488 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
489 final DataNode dataNode) {
490 final FragmentEntity fragmentEntity =
491 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
492 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
494 fragmentRepository.save(fragmentEntity);
495 } catch (final StaleStateException staleStateException) {
496 throw new ConcurrencyException("Concurrent Transactions",
497 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
498 dataspaceName, anchorName, dataNode.getXpath()));
503 public void updateDataNodesAndDescendants(final String dataspaceName,
504 final String anchorName,
505 final List<DataNode> dataNodes) {
507 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
508 .collect(Collectors.toMap(
509 dataNode -> dataNode,
511 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
512 dataNodeFragmentEntityMap.forEach(
513 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
515 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
516 } catch (final StaleStateException staleStateException) {
517 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
521 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
522 final Collection<FragmentEntity> fragmentEntities) {
523 final Collection<String> failedXpaths = new HashSet<>();
525 fragmentEntities.forEach(dataNodeFragment -> {
527 fragmentRepository.save(dataNodeFragment);
528 } catch (final StaleStateException e) {
529 failedXpaths.add(dataNodeFragment.getXpath());
533 if (!failedXpaths.isEmpty()) {
534 final String failedXpathsConcatenated = String.join(",", failedXpaths);
535 throw new ConcurrencyException("Concurrent Transactions", String.format(
536 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
537 failedXpathsConcatenated, dataspaceName, anchorName));
541 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
542 final DataNode newDataNode) {
544 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
546 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
547 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
549 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
551 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
552 final FragmentEntity childFragment;
553 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
554 childFragment = convertToFragmentWithAllDescendants(
555 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
557 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
558 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
560 updatedChildFragments.add(childFragment);
563 existingFragmentEntity.getChildFragments().clear();
564 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
569 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
570 final Collection<DataNode> newListElements) {
571 final FragmentEntity parentEntity =
572 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
573 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
574 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
575 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
576 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
577 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
578 for (final DataNode newListElement : newListElements) {
579 final FragmentEntity existingListElementEntity =
580 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
581 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
582 existingListElementEntity);
584 updatedChildFragmentEntities.add(entityToBeAdded);
586 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
587 fragmentRepository.save(parentEntity);
592 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
593 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
594 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
596 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
601 public void deleteListDataNode(final String dataspaceName, final String anchorName,
602 final String targetXpath) {
603 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
608 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
609 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
612 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
613 final boolean onlySupportListNodeDeletion) {
614 final String parentNodeXpath;
615 FragmentEntity parentFragmentEntity = null;
616 boolean targetDeleted;
617 if (isRootXpath(targetXpath)) {
618 deleteDataNodes(dataspaceName, anchorName);
619 targetDeleted = true;
621 if (isRootContainerNodeXpath(targetXpath)) {
622 parentNodeXpath = targetXpath;
624 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
626 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
627 if (CpsPathUtil.isPathToListElement(targetXpath)) {
628 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
630 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
631 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
632 if (tryToDeleteDataNode) {
633 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
637 if (!targetDeleted) {
638 final String additionalInformation = onlySupportListNodeDeletion
639 ? "The target is probably not a List." : "";
640 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
641 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
645 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
646 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
647 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
648 fragmentRepository.delete(parentFragmentEntity);
651 if (parentFragmentEntity.getChildFragments()
652 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
653 fragmentRepository.save(parentFragmentEntity);
659 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
660 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
661 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
662 if (parentFragmentEntity.getChildFragments()
663 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
664 fragmentRepository.save(parentFragmentEntity);
670 private static void deleteListElements(
671 final Collection<FragmentEntity> fragmentEntities,
672 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
673 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
676 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
677 if (newListElements.isEmpty()) {
678 throw new CpsAdminException("Invalid list replacement",
679 "Cannot replace list elements with empty collection");
681 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
682 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
685 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
686 final DataNode newListElement,
687 final FragmentEntity existingListElementEntity) {
688 if (existingListElementEntity == null) {
689 return convertToFragmentWithAllDescendants(
690 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
692 if (newListElement.getChildDataNodes().isEmpty()) {
693 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
694 existingListElementEntity.getChildFragments().clear();
696 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
698 return existingListElementEntity;
701 private static boolean isNewDataNode(final DataNode replacementDataNode,
702 final Map<String, FragmentEntity> existingListElementsByXpath) {
703 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
706 private static boolean isRootContainerNodeXpath(final String xpath) {
707 return 0 == xpath.lastIndexOf('/');
710 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
711 final DataNode newListElement) {
712 final FragmentEntity replacementFragmentEntity =
713 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
714 newListElement.getLeaves())).build();
715 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
718 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
719 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
720 return childEntities.stream()
721 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
722 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
725 private static boolean isRootXpath(final String xpath) {
726 return "/".equals(xpath) || "".equals(xpath);
729 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
730 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
731 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
732 currentLeavesAsMap.putAll(updateLeaves);
733 if (currentLeavesAsMap.isEmpty()) {
736 return jsonObjectMapper.asJsonString(currentLeavesAsMap);