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.FragmentNativeRepository;
65 import org.onap.cps.spi.repository.FragmentQueryBuilder;
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;
82 private final FragmentNativeRepository fragmentNativeRepositoryImpl;
84 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
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 getFragmentWithoutDescendantsByXpath(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 getFragmentWithoutDescendantsByXpath(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 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
255 final FetchDescendantsOption fetchDescendantsOption) {
256 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
257 fetchDescendantsOption);
258 return toDataNode(fragmentEntity, fetchDescendantsOption);
262 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
263 final Collection<String> xpaths,
264 final FetchDescendantsOption fetchDescendantsOption) {
265 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
266 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
268 final Set<String> normalizedXpaths = new HashSet<>(xpaths.size());
269 for (final String xpath : xpaths) {
271 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
272 } catch (final PathParsingException e) {
273 log.warn("Error parsing xpath \"{}\" in getDataNodes: {}", xpath, e.getMessage());
277 final List<FragmentEntity> fragmentEntities =
278 fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths);
279 return toDataNodes(fragmentEntities, fetchDescendantsOption);
282 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
283 final String anchorName,
284 final String xpath) {
285 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
288 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
289 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
290 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
291 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
292 final FragmentEntity fragmentEntity;
293 if (isRootXpath(xpath)) {
294 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
296 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
297 .stream().findFirst().orElse(null);
299 final String normalizedXpath = getNormalizedXpath(xpath);
300 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
302 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
304 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
305 .stream().findFirst().orElse(null);
308 if (fragmentEntity == null) {
309 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
311 return fragmentEntity;
315 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
316 final String normalizedXpath) {
317 final List<FragmentExtract> fragmentExtracts =
318 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
319 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
320 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
321 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
326 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
327 final FetchDescendantsOption fetchDescendantsOption) {
328 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
329 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
330 final CpsPathQuery cpsPathQuery;
332 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
333 } catch (final PathParsingException e) {
334 throw new CpsPathException(e.getMessage());
337 Collection<FragmentEntity> fragmentEntities;
338 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
339 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
341 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
342 if (cpsPathQuery.hasAncestorAxis()) {
343 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
345 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
348 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
349 final CpsPathQuery cpsPathQuery) {
350 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
351 && !cpsPathQuery.hasLeafConditions()
352 && !cpsPathQuery.hasTextFunctionCondition();
355 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
356 final AnchorEntity anchorEntity,
357 final CpsPathQuery cpsPathQuery) {
358 Collection<FragmentEntity> fragmentEntities;
359 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
360 final List<FragmentExtract> fragmentExtracts =
361 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
362 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
363 if (cpsPathQuery.hasAncestorAxis()) {
364 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
366 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
369 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
370 final CpsPathQuery cpsPathQuery,
371 final Collection<FragmentEntity> fragmentEntities) {
372 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
373 return ancestorXpaths.isEmpty() ? Collections.emptyList()
374 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
377 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
378 final FetchDescendantsOption fetchDescendantsOption,
379 final AnchorEntity anchorEntity,
380 final Collection<FragmentEntity> proxiedFragmentEntities) {
381 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
382 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
383 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
384 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
386 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
387 final Collection<FragmentEntity> unproxiedFragmentEntities =
388 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
389 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
390 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
394 return Collections.unmodifiableList(dataNodes);
397 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
398 final Collection<FragmentEntity> fragmentEntities) {
399 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
400 for (final FragmentEntity fragmentEntity : fragmentEntities) {
401 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
403 return Collections.unmodifiableList(dataNodes);
406 private static String getNormalizedXpath(final String xpathSource) {
407 final String normalizedXpath;
409 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
410 } catch (final PathParsingException e) {
411 throw new CpsPathException(e.getMessage());
413 return normalizedXpath;
417 public String startSession() {
418 return sessionManager.startSession();
422 public void closeSession(final String sessionId) {
423 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
427 public void lockAnchor(final String sessionId, final String dataspaceName,
428 final String anchorName, final Long timeoutInMilliseconds) {
429 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
432 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
433 final CpsPathQuery cpsPathQuery) {
434 final Set<String> ancestorXpath = new HashSet<>();
435 final Pattern pattern =
436 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
437 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
438 for (final FragmentEntity fragmentEntity : fragmentEntities) {
439 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
440 if (matcher.matches()) {
441 ancestorXpath.add(matcher.group(1));
444 return ancestorXpath;
447 private DataNode toDataNode(final FragmentEntity fragmentEntity,
448 final FetchDescendantsOption fetchDescendantsOption) {
449 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
450 Map<String, Serializable> leaves = new HashMap<>();
451 if (fragmentEntity.getAttributes() != null) {
452 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
454 return new DataNodeBuilder()
455 .withXpath(fragmentEntity.getXpath())
457 .withChildDataNodes(childDataNodes).build();
460 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
461 final FetchDescendantsOption fetchDescendantsOption) {
462 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
463 for (final FragmentEntity fragmentEntity : fragmentEntities) {
464 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
469 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
470 final FetchDescendantsOption fetchDescendantsOption) {
471 if (fetchDescendantsOption.hasNext()) {
472 return fragmentEntity.getChildFragments().stream()
473 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
474 .collect(Collectors.toList());
476 return Collections.emptyList();
480 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
481 final Map<String, Serializable> updateLeaves) {
482 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
483 final String currentLeavesAsString = fragmentEntity.getAttributes();
484 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
485 fragmentEntity.setAttributes(mergedLeaves);
486 fragmentRepository.save(fragmentEntity);
490 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
491 final DataNode dataNode) {
492 final FragmentEntity fragmentEntity =
493 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
494 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
496 fragmentRepository.save(fragmentEntity);
497 } catch (final StaleStateException staleStateException) {
498 throw new ConcurrencyException("Concurrent Transactions",
499 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
500 dataspaceName, anchorName, dataNode.getXpath()));
505 public void updateDataNodesAndDescendants(final String dataspaceName,
506 final String anchorName,
507 final List<DataNode> dataNodes) {
509 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
510 .collect(Collectors.toMap(
511 dataNode -> dataNode,
513 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
514 dataNodeFragmentEntityMap.forEach(
515 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
517 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
518 } catch (final StaleStateException staleStateException) {
519 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
523 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
524 final Collection<FragmentEntity> fragmentEntities) {
525 final Collection<String> failedXpaths = new HashSet<>();
527 fragmentEntities.forEach(dataNodeFragment -> {
529 fragmentRepository.save(dataNodeFragment);
530 } catch (final StaleStateException e) {
531 failedXpaths.add(dataNodeFragment.getXpath());
535 if (!failedXpaths.isEmpty()) {
536 final String failedXpathsConcatenated = String.join(",", failedXpaths);
537 throw new ConcurrencyException("Concurrent Transactions", String.format(
538 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
539 failedXpathsConcatenated, dataspaceName, anchorName));
543 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
544 final DataNode newDataNode) {
546 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
548 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
549 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
551 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
553 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
554 final FragmentEntity childFragment;
555 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
556 childFragment = convertToFragmentWithAllDescendants(
557 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
559 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
560 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
562 updatedChildFragments.add(childFragment);
565 existingFragmentEntity.getChildFragments().clear();
566 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
571 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
572 final Collection<DataNode> newListElements) {
573 final FragmentEntity parentEntity =
574 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
575 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
576 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
577 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
578 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
579 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
580 for (final DataNode newListElement : newListElements) {
581 final FragmentEntity existingListElementEntity =
582 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
583 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
584 existingListElementEntity);
586 updatedChildFragmentEntities.add(entityToBeAdded);
588 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
589 fragmentRepository.save(parentEntity);
594 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
595 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
596 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
598 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
603 public void deleteListDataNode(final String dataspaceName, final String anchorName,
604 final String targetXpath) {
605 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
610 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
611 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
614 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
615 final boolean onlySupportListNodeDeletion) {
616 final String parentNodeXpath;
617 FragmentEntity parentFragmentEntity = null;
618 boolean targetDeleted;
619 if (isRootXpath(targetXpath)) {
620 deleteDataNodes(dataspaceName, anchorName);
621 targetDeleted = true;
623 if (isRootContainerNodeXpath(targetXpath)) {
624 parentNodeXpath = targetXpath;
626 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
628 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
629 if (CpsPathUtil.isPathToListElement(targetXpath)) {
630 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
632 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
633 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
634 if (tryToDeleteDataNode) {
635 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
639 if (!targetDeleted) {
640 final String additionalInformation = onlySupportListNodeDeletion
641 ? "The target is probably not a List." : "";
642 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
643 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
647 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
648 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
649 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
650 fragmentNativeRepositoryImpl.deleteFragmentEntity(parentFragmentEntity.getId());
653 if (parentFragmentEntity.getChildFragments()
654 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
655 fragmentRepository.save(parentFragmentEntity);
661 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
662 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
663 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
664 if (parentFragmentEntity.getChildFragments()
665 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
666 fragmentRepository.save(parentFragmentEntity);
672 private static void deleteListElements(
673 final Collection<FragmentEntity> fragmentEntities,
674 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
675 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
678 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
679 if (newListElements.isEmpty()) {
680 throw new CpsAdminException("Invalid list replacement",
681 "Cannot replace list elements with empty collection");
683 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
684 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
687 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
688 final DataNode newListElement,
689 final FragmentEntity existingListElementEntity) {
690 if (existingListElementEntity == null) {
691 return convertToFragmentWithAllDescendants(
692 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
694 if (newListElement.getChildDataNodes().isEmpty()) {
695 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
696 existingListElementEntity.getChildFragments().clear();
698 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
700 return existingListElementEntity;
703 private static boolean isNewDataNode(final DataNode replacementDataNode,
704 final Map<String, FragmentEntity> existingListElementsByXpath) {
705 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
708 private static boolean isRootContainerNodeXpath(final String xpath) {
709 return 0 == xpath.lastIndexOf('/');
712 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
713 final DataNode newListElement) {
714 final FragmentEntity replacementFragmentEntity =
715 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
716 newListElement.getLeaves())).build();
717 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
720 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
721 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
722 return childEntities.stream()
723 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
724 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
727 private static boolean isRootXpath(final String xpath) {
728 return "/".equals(xpath) || "".equals(xpath);
731 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
732 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
733 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
734 currentLeavesAsMap.putAll(updateLeaves);
735 if (currentLeavesAsMap.isEmpty()) {
738 return jsonObjectMapper.asJsonString(currentLeavesAsMap);