2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2023 Nordix Foundation
4 * Modifications Copyright (C) 2021 Pantheon.tech
5 * Modifications Copyright (C) 2020-2022 Bell Canada.
6 * Modifications Copyright (C) 2022-2023 TechMahindra Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl;
26 import com.google.common.collect.ImmutableSet;
27 import com.google.common.collect.ImmutableSet.Builder;
28 import 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 getFragmentEntity(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 getFragmentEntity(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 Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
254 final FetchDescendantsOption fetchDescendantsOption) {
255 final String targetXpath = isRootXpath(xpath) ? xpath : CpsPathUtil.getNormalizedXpath(xpath);
256 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
257 Collections.singletonList(targetXpath), fetchDescendantsOption);
258 if (dataNodes.isEmpty()) {
259 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
265 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
266 final Collection<String> xpaths,
267 final FetchDescendantsOption fetchDescendantsOption) {
268 final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(dataspaceName, anchorName, xpaths);
269 return toDataNodes(fragmentEntities, fetchDescendantsOption);
272 private Collection<FragmentEntity> getFragmentEntities(final String dataspaceName, final String anchorName,
273 final Collection<String> xpaths) {
274 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
275 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
277 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
278 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
280 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
281 for (final String xpath : nonRootXpaths) {
283 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
284 } catch (final PathParsingException e) {
285 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
288 final Collection<FragmentEntity> fragmentEntities =
289 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
292 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
294 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
297 return fragmentEntities;
300 private FragmentEntity getFragmentEntity(final String dataspaceName, final String anchorName, final String xpath) {
301 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
302 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
303 final FragmentEntity fragmentEntity;
304 if (isRootXpath(xpath)) {
305 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
307 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
308 .stream().findFirst().orElse(null);
310 final String normalizedXpath = getNormalizedXpath(xpath);
312 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
314 if (fragmentEntity == null) {
315 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
317 return fragmentEntity;
321 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
322 final String normalizedXpath) {
323 final List<FragmentExtract> fragmentExtracts =
324 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
325 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
326 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
327 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
332 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
333 final FetchDescendantsOption fetchDescendantsOption) {
334 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
335 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
336 final CpsPathQuery cpsPathQuery;
338 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
339 } catch (final PathParsingException e) {
340 throw new CpsPathException(e.getMessage());
343 Collection<FragmentEntity> fragmentEntities;
344 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
345 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
347 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
348 if (cpsPathQuery.hasAncestorAxis()) {
349 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
351 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
354 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
355 final CpsPathQuery cpsPathQuery) {
356 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
357 && !cpsPathQuery.hasLeafConditions()
358 && !cpsPathQuery.hasTextFunctionCondition();
361 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
362 final AnchorEntity anchorEntity,
363 final CpsPathQuery cpsPathQuery) {
364 Collection<FragmentEntity> fragmentEntities;
365 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
366 final List<FragmentExtract> fragmentExtracts =
367 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
368 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
369 if (cpsPathQuery.hasAncestorAxis()) {
370 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
372 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
375 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
376 final CpsPathQuery cpsPathQuery,
377 final Collection<FragmentEntity> fragmentEntities) {
378 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
379 return ancestorXpaths.isEmpty() ? Collections.emptyList()
380 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
383 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
384 final FetchDescendantsOption fetchDescendantsOption,
385 final AnchorEntity anchorEntity,
386 final Collection<FragmentEntity> proxiedFragmentEntities) {
387 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
388 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
389 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
390 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
392 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
393 final Collection<FragmentEntity> unproxiedFragmentEntities =
394 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
395 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
396 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
400 return Collections.unmodifiableList(dataNodes);
403 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
404 final Collection<FragmentEntity> fragmentEntities) {
405 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
406 for (final FragmentEntity fragmentEntity : fragmentEntities) {
407 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
409 return Collections.unmodifiableList(dataNodes);
412 private static String getNormalizedXpath(final String xpathSource) {
413 final String normalizedXpath;
415 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
416 } catch (final PathParsingException e) {
417 throw new CpsPathException(e.getMessage());
419 return normalizedXpath;
423 public String startSession() {
424 return sessionManager.startSession();
428 public void closeSession(final String sessionId) {
429 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
433 public void lockAnchor(final String sessionId, final String dataspaceName,
434 final String anchorName, final Long timeoutInMilliseconds) {
435 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
438 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
439 final CpsPathQuery cpsPathQuery) {
440 final Set<String> ancestorXpath = new HashSet<>();
441 final Pattern pattern =
442 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
443 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
444 for (final FragmentEntity fragmentEntity : fragmentEntities) {
445 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
446 if (matcher.matches()) {
447 ancestorXpath.add(matcher.group(1));
450 return ancestorXpath;
453 private DataNode toDataNode(final FragmentEntity fragmentEntity,
454 final FetchDescendantsOption fetchDescendantsOption) {
455 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
456 Map<String, Serializable> leaves = new HashMap<>();
457 if (fragmentEntity.getAttributes() != null) {
458 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
460 return new DataNodeBuilder()
461 .withXpath(fragmentEntity.getXpath())
463 .withChildDataNodes(childDataNodes).build();
466 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
467 final FetchDescendantsOption fetchDescendantsOption) {
468 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
469 for (final FragmentEntity fragmentEntity : fragmentEntities) {
470 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
475 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
476 final FetchDescendantsOption fetchDescendantsOption) {
477 if (fetchDescendantsOption.hasNext()) {
478 return fragmentEntity.getChildFragments().stream()
479 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
480 .collect(Collectors.toList());
482 return Collections.emptyList();
486 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
487 final Map<String, Serializable> updateLeaves) {
488 final FragmentEntity fragmentEntity = getFragmentEntity(dataspaceName, anchorName, xpath);
489 final String currentLeavesAsString = fragmentEntity.getAttributes();
490 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
491 fragmentEntity.setAttributes(mergedLeaves);
492 fragmentRepository.save(fragmentEntity);
496 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
497 final DataNode dataNode) {
498 final FragmentEntity fragmentEntity = getFragmentEntity(dataspaceName, anchorName, dataNode.getXpath());
499 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
501 fragmentRepository.save(fragmentEntity);
502 } catch (final StaleStateException staleStateException) {
503 throw new ConcurrencyException("Concurrent Transactions",
504 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
505 dataspaceName, anchorName, dataNode.getXpath()));
510 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
511 final List<DataNode> updatedDataNodes) {
512 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
513 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
515 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
516 final Collection<FragmentEntity> existingFragmentEntities =
517 getFragmentEntities(dataspaceName, anchorName, xpaths);
519 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
520 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
521 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
525 fragmentRepository.saveAll(existingFragmentEntities);
526 } catch (final StaleStateException staleStateException) {
527 retryUpdateDataNodesIndividually(dataspaceName, anchorName, existingFragmentEntities);
531 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
532 final Collection<FragmentEntity> fragmentEntities) {
533 final Collection<String> failedXpaths = new HashSet<>();
535 fragmentEntities.forEach(dataNodeFragment -> {
537 fragmentRepository.save(dataNodeFragment);
538 } catch (final StaleStateException e) {
539 failedXpaths.add(dataNodeFragment.getXpath());
543 if (!failedXpaths.isEmpty()) {
544 final String failedXpathsConcatenated = String.join(",", failedXpaths);
545 throw new ConcurrencyException("Concurrent Transactions", String.format(
546 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
547 failedXpathsConcatenated, dataspaceName, anchorName));
551 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
552 final DataNode newDataNode) {
554 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
556 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
557 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
559 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
561 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
562 final FragmentEntity childFragment;
563 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
564 childFragment = convertToFragmentWithAllDescendants(
565 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
567 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
568 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
570 updatedChildFragments.add(childFragment);
573 existingFragmentEntity.getChildFragments().clear();
574 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
579 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
580 final Collection<DataNode> newListElements) {
581 final FragmentEntity parentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
582 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
583 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
584 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
585 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
586 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
587 for (final DataNode newListElement : newListElements) {
588 final FragmentEntity existingListElementEntity =
589 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
590 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
591 existingListElementEntity);
593 updatedChildFragmentEntities.add(entityToBeAdded);
595 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
596 fragmentRepository.save(parentEntity);
601 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
602 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
603 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
605 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
610 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
611 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
612 final Collection<AnchorEntity> anchorEntities =
613 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
614 fragmentRepository.deleteByAnchorIn(anchorEntities);
619 public void deleteDataNodes(final String dataspaceName, final String anchorName,
620 final Collection<String> xpathsToDelete) {
621 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
622 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
624 final Collection<String> normalizedXPathsToDelete = new ArrayList<>(xpathsToDelete.size());
625 final Collection<String> normalizedXpathsToPotentialLists = new ArrayList<>();
626 for (final String xpath : xpathsToDelete) {
628 final CpsPathQuery cpsPathQuery = CpsPathUtil.getCpsPathQuery(xpath);
629 final String normalizedXpath = cpsPathQuery.getNormalizedXpath();
630 normalizedXPathsToDelete.add(normalizedXpath);
631 if (!cpsPathQuery.isPathToListElement()) {
632 normalizedXpathsToPotentialLists.add(normalizedXpath);
634 } catch (final PathParsingException e) {
635 log.debug("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
639 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), normalizedXPathsToDelete);
640 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), normalizedXpathsToPotentialLists);
645 public void deleteListDataNode(final String dataspaceName, final String anchorName,
646 final String targetXpath) {
647 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
652 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
653 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
656 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
657 final boolean onlySupportListNodeDeletion) {
658 final String parentNodeXpath;
659 FragmentEntity parentFragmentEntity = null;
660 boolean targetDeleted;
661 if (isRootXpath(targetXpath)) {
662 deleteDataNodes(dataspaceName, anchorName);
663 targetDeleted = true;
665 if (isRootContainerNodeXpath(targetXpath)) {
666 parentNodeXpath = targetXpath;
668 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
670 parentFragmentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
671 if (CpsPathUtil.isPathToListElement(targetXpath)) {
672 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
674 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
675 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
676 if (tryToDeleteDataNode) {
677 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
681 if (!targetDeleted) {
682 final String additionalInformation = onlySupportListNodeDeletion
683 ? "The target is probably not a List." : "";
684 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
685 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
689 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
690 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
691 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
692 fragmentRepository.deleteFragmentEntity(parentFragmentEntity.getId());
695 if (parentFragmentEntity.getChildFragments()
696 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
697 fragmentRepository.save(parentFragmentEntity);
703 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
704 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
705 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
706 if (parentFragmentEntity.getChildFragments()
707 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
708 fragmentRepository.save(parentFragmentEntity);
714 private static void deleteListElements(
715 final Collection<FragmentEntity> fragmentEntities,
716 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
717 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
720 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
721 if (newListElements.isEmpty()) {
722 throw new CpsAdminException("Invalid list replacement",
723 "Cannot replace list elements with empty collection");
725 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
726 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
729 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
730 final DataNode newListElement,
731 final FragmentEntity existingListElementEntity) {
732 if (existingListElementEntity == null) {
733 return convertToFragmentWithAllDescendants(
734 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
736 if (newListElement.getChildDataNodes().isEmpty()) {
737 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
738 existingListElementEntity.getChildFragments().clear();
740 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
742 return existingListElementEntity;
745 private static boolean isNewDataNode(final DataNode replacementDataNode,
746 final Map<String, FragmentEntity> existingListElementsByXpath) {
747 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
750 private static boolean isRootContainerNodeXpath(final String xpath) {
751 return 0 == xpath.lastIndexOf('/');
754 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
755 final DataNode newListElement) {
756 final FragmentEntity replacementFragmentEntity =
757 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
758 newListElement.getLeaves())).build();
759 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
762 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
763 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
764 return childEntities.stream()
765 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
766 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
769 private static boolean isRootXpath(final String xpath) {
770 return "/".equals(xpath) || "".equals(xpath);
773 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
774 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
775 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
776 currentLeavesAsMap.putAll(updateLeaves);
777 if (currentLeavesAsMap.isEmpty()) {
780 return jsonObjectMapper.asJsonString(currentLeavesAsMap);