2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2023 Nordix Foundation
4 * Modifications Copyright (C) 2021 Pantheon.tech
5 * Modifications Copyright (C) 2020-2022 Bell Canada.
6 * Modifications Copyright (C) 2022-2023 TechMahindra Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl;
26 import com.google.common.collect.ImmutableSet;
27 import com.google.common.collect.ImmutableSet.Builder;
28 import io.micrometer.core.annotation.Timed;
29 import java.io.Serializable;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40 import java.util.stream.Collectors;
41 import javax.transaction.Transactional;
42 import lombok.RequiredArgsConstructor;
43 import lombok.extern.slf4j.Slf4j;
44 import org.hibernate.StaleStateException;
45 import org.onap.cps.cpspath.parser.CpsPathQuery;
46 import org.onap.cps.cpspath.parser.CpsPathUtil;
47 import org.onap.cps.cpspath.parser.PathParsingException;
48 import org.onap.cps.spi.CpsDataPersistenceService;
49 import org.onap.cps.spi.FetchDescendantsOption;
50 import org.onap.cps.spi.entities.AnchorEntity;
51 import org.onap.cps.spi.entities.DataspaceEntity;
52 import org.onap.cps.spi.entities.FragmentEntity;
53 import org.onap.cps.spi.entities.FragmentEntityArranger;
54 import org.onap.cps.spi.entities.FragmentExtract;
55 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
56 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
57 import org.onap.cps.spi.exceptions.ConcurrencyException;
58 import org.onap.cps.spi.exceptions.CpsAdminException;
59 import org.onap.cps.spi.exceptions.CpsPathException;
60 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
61 import org.onap.cps.spi.exceptions.DataNodeNotFoundExceptionBatch;
62 import org.onap.cps.spi.model.DataNode;
63 import org.onap.cps.spi.model.DataNodeBuilder;
64 import org.onap.cps.spi.repository.AnchorRepository;
65 import org.onap.cps.spi.repository.DataspaceRepository;
66 import org.onap.cps.spi.repository.FragmentQueryBuilder;
67 import org.onap.cps.spi.repository.FragmentRepository;
68 import org.onap.cps.spi.utils.SessionManager;
69 import org.onap.cps.utils.JsonObjectMapper;
70 import org.springframework.dao.DataIntegrityViolationException;
71 import org.springframework.stereotype.Service;
75 @RequiredArgsConstructor
76 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
78 private final DataspaceRepository dataspaceRepository;
79 private final AnchorRepository anchorRepository;
80 private final FragmentRepository fragmentRepository;
81 private final JsonObjectMapper jsonObjectMapper;
82 private final SessionManager sessionManager;
84 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?])?)";
87 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
88 final DataNode newChildDataNode) {
89 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
93 public void addChildDataNodes(final String dataspaceName, final String anchorName,
94 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
95 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
99 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
100 final Collection<DataNode> newListElements) {
101 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
105 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
106 final Collection<Collection<DataNode>> newLists) {
107 final Collection<String> failedXpaths = new HashSet<>();
108 newLists.forEach(newList -> {
110 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
111 } catch (final AlreadyDefinedExceptionBatch e) {
112 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
116 if (!failedXpaths.isEmpty()) {
117 throw new AlreadyDefinedExceptionBatch(failedXpaths);
122 private void addNewChildDataNode(final String dataspaceName, final String anchorName,
123 final String parentNodeXpath, final DataNode newChild) {
124 final FragmentEntity parentFragmentEntity =
125 getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
126 final FragmentEntity newChildAsFragmentEntity =
127 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
128 parentFragmentEntity.getAnchor(), newChild);
129 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
131 fragmentRepository.save(newChildAsFragmentEntity);
132 } catch (final DataIntegrityViolationException e) {
133 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
138 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
139 final Collection<DataNode> newChildren) {
140 final FragmentEntity parentFragmentEntity =
141 getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
142 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
144 newChildren.forEach(newChildAsDataNode -> {
145 final FragmentEntity newChildAsFragmentEntity =
146 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
147 parentFragmentEntity.getAnchor(), newChildAsDataNode);
148 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
149 fragmentEntities.add(newChildAsFragmentEntity);
151 fragmentRepository.saveAll(fragmentEntities);
152 } catch (final DataIntegrityViolationException e) {
153 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
154 e, fragmentEntities.size());
155 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
159 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
160 final String parentNodeXpath,
161 final Collection<DataNode> newChildren) {
162 final Collection<String> failedXpaths = new HashSet<>();
163 for (final DataNode newChild : newChildren) {
165 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
166 } catch (final AlreadyDefinedException e) {
167 failedXpaths.add(newChild.getXpath());
170 if (!failedXpaths.isEmpty()) {
171 throw new AlreadyDefinedExceptionBatch(failedXpaths);
176 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
177 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
181 public void storeDataNodes(final String dataspaceName, final String anchorName,
182 final Collection<DataNode> dataNodes) {
183 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
184 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
185 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
187 for (final DataNode dataNode: dataNodes) {
188 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
190 fragmentEntities.add(fragmentEntity);
192 fragmentRepository.saveAll(fragmentEntities);
193 } catch (final DataIntegrityViolationException exception) {
194 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
195 exception, dataNodes.size());
196 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
200 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
201 final Collection<DataNode> dataNodes) {
202 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
203 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
204 final Collection<String> failedXpaths = new HashSet<>();
205 for (final DataNode dataNode: dataNodes) {
207 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
209 fragmentRepository.save(fragmentEntity);
210 } catch (final DataIntegrityViolationException e) {
211 failedXpaths.add(dataNode.getXpath());
214 if (!failedXpaths.isEmpty()) {
215 throw new AlreadyDefinedExceptionBatch(failedXpaths);
220 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
221 * for all DataNode children recursively.
223 * @param dataspaceEntity dataspace
224 * @param anchorEntity anchorEntity
225 * @param dataNodeToBeConverted dataNode
226 * @return a Fragment built from current DataNode
228 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
229 final AnchorEntity anchorEntity,
230 final DataNode dataNodeToBeConverted) {
231 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
232 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
233 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
234 final FragmentEntity childFragment =
235 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
237 childFragmentsImmutableSetBuilder.add(childFragment);
239 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
240 return parentFragment;
243 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
244 final AnchorEntity anchorEntity, final DataNode dataNode) {
245 return FragmentEntity.builder()
246 .dataspace(dataspaceEntity)
247 .anchor(anchorEntity)
248 .xpath(dataNode.getXpath())
249 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
254 @Timed(value = "cps.data.persistence.service.datanode.get",
255 description = "Time taken to get a data node")
256 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
258 final FetchDescendantsOption fetchDescendantsOption) {
259 final String targetXpath = isRootXpath(xpath) ? xpath : CpsPathUtil.getNormalizedXpath(xpath);
260 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
261 Collections.singletonList(targetXpath), fetchDescendantsOption);
262 if (dataNodes.isEmpty()) {
263 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
269 @Timed(value = "cps.data.persistence.service.datanode.batch.get",
270 description = "Time taken to get data nodes")
271 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
272 final Collection<String> xpaths,
273 final FetchDescendantsOption fetchDescendantsOption) {
274 final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(dataspaceName, anchorName, xpaths);
275 return toDataNodes(fragmentEntities, fetchDescendantsOption);
278 private Collection<FragmentEntity> getFragmentEntities(final String dataspaceName, final String anchorName,
279 final Collection<String> xpaths) {
280 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
281 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
283 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
284 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
286 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
287 for (final String xpath : nonRootXpaths) {
289 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
290 } catch (final PathParsingException e) {
291 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
294 final Collection<FragmentEntity> fragmentEntities =
295 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
298 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
300 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
303 return fragmentEntities;
306 private FragmentEntity getFragmentEntity(final String dataspaceName, final String anchorName, final String xpath) {
307 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
308 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
309 final FragmentEntity fragmentEntity;
310 if (isRootXpath(xpath)) {
311 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
313 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
314 .stream().findFirst().orElse(null);
316 final String normalizedXpath = getNormalizedXpath(xpath);
318 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
320 if (fragmentEntity == null) {
321 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
323 return fragmentEntity;
327 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
328 final String normalizedXpath) {
329 final List<FragmentExtract> fragmentExtracts =
330 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
331 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
332 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
333 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
338 @Timed(value = "cps.data.persistence.service.datanode.query",
339 description = "Time taken to query data nodes")
340 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
341 final FetchDescendantsOption fetchDescendantsOption) {
342 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
343 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
344 final CpsPathQuery cpsPathQuery;
346 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
347 } catch (final PathParsingException e) {
348 throw new CpsPathException(e.getMessage());
351 Collection<FragmentEntity> fragmentEntities;
352 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
353 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
355 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
356 if (cpsPathQuery.hasAncestorAxis()) {
357 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
359 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
362 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
363 final CpsPathQuery cpsPathQuery) {
364 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
365 && !cpsPathQuery.hasLeafConditions()
366 && !cpsPathQuery.hasTextFunctionCondition();
369 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
370 final AnchorEntity anchorEntity,
371 final CpsPathQuery cpsPathQuery) {
372 Collection<FragmentEntity> fragmentEntities;
373 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
374 final List<FragmentExtract> fragmentExtracts =
375 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
376 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
377 if (cpsPathQuery.hasAncestorAxis()) {
378 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
380 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
383 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
384 final CpsPathQuery cpsPathQuery,
385 final Collection<FragmentEntity> fragmentEntities) {
386 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
387 return ancestorXpaths.isEmpty() ? Collections.emptyList()
388 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
391 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
392 final FetchDescendantsOption fetchDescendantsOption,
393 final AnchorEntity anchorEntity,
394 final Collection<FragmentEntity> proxiedFragmentEntities) {
395 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
396 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
397 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
398 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
400 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
401 final Collection<FragmentEntity> unproxiedFragmentEntities =
402 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
403 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
404 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
408 return Collections.unmodifiableList(dataNodes);
411 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
412 final Collection<FragmentEntity> fragmentEntities) {
413 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
414 for (final FragmentEntity fragmentEntity : fragmentEntities) {
415 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
417 return Collections.unmodifiableList(dataNodes);
420 private static String getNormalizedXpath(final String xpathSource) {
421 final String normalizedXpath;
423 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
424 } catch (final PathParsingException e) {
425 throw new CpsPathException(e.getMessage());
427 return normalizedXpath;
431 public String startSession() {
432 return sessionManager.startSession();
436 public void closeSession(final String sessionId) {
437 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
441 public void lockAnchor(final String sessionId, final String dataspaceName,
442 final String anchorName, final Long timeoutInMilliseconds) {
443 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
446 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
447 final CpsPathQuery cpsPathQuery) {
448 final Set<String> ancestorXpath = new HashSet<>();
449 final Pattern pattern =
450 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
451 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
452 for (final FragmentEntity fragmentEntity : fragmentEntities) {
453 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
454 if (matcher.matches()) {
455 ancestorXpath.add(matcher.group(1));
458 return ancestorXpath;
461 private DataNode toDataNode(final FragmentEntity fragmentEntity,
462 final FetchDescendantsOption fetchDescendantsOption) {
463 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
464 Map<String, Serializable> leaves = new HashMap<>();
465 if (fragmentEntity.getAttributes() != null) {
466 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
468 return new DataNodeBuilder()
469 .withXpath(fragmentEntity.getXpath())
471 .withChildDataNodes(childDataNodes).build();
474 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
475 final FetchDescendantsOption fetchDescendantsOption) {
476 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
477 for (final FragmentEntity fragmentEntity : fragmentEntities) {
478 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
483 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
484 final FetchDescendantsOption fetchDescendantsOption) {
485 if (fetchDescendantsOption.hasNext()) {
486 return fragmentEntity.getChildFragments().stream()
487 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
488 .collect(Collectors.toList());
490 return Collections.emptyList();
494 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
495 final Map<String, Serializable> updateLeaves) {
496 final FragmentEntity fragmentEntity = getFragmentEntity(dataspaceName, anchorName, xpath);
497 final String currentLeavesAsString = fragmentEntity.getAttributes();
498 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
499 fragmentEntity.setAttributes(mergedLeaves);
500 fragmentRepository.save(fragmentEntity);
504 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
505 final DataNode dataNode) {
506 final FragmentEntity fragmentEntity = getFragmentEntity(dataspaceName, anchorName, dataNode.getXpath());
507 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
509 fragmentRepository.save(fragmentEntity);
510 } catch (final StaleStateException staleStateException) {
511 throw new ConcurrencyException("Concurrent Transactions",
512 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
513 dataspaceName, anchorName, dataNode.getXpath()));
518 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
519 final List<DataNode> updatedDataNodes) {
520 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
521 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
523 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
524 final Collection<FragmentEntity> existingFragmentEntities =
525 getFragmentEntities(dataspaceName, anchorName, xpaths);
527 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
528 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
529 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
533 fragmentRepository.saveAll(existingFragmentEntities);
534 } catch (final StaleStateException staleStateException) {
535 retryUpdateDataNodesIndividually(dataspaceName, anchorName, existingFragmentEntities);
539 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
540 final Collection<FragmentEntity> fragmentEntities) {
541 final Collection<String> failedXpaths = new HashSet<>();
543 fragmentEntities.forEach(dataNodeFragment -> {
545 fragmentRepository.save(dataNodeFragment);
546 } catch (final StaleStateException e) {
547 failedXpaths.add(dataNodeFragment.getXpath());
551 if (!failedXpaths.isEmpty()) {
552 final String failedXpathsConcatenated = String.join(",", failedXpaths);
553 throw new ConcurrencyException("Concurrent Transactions", String.format(
554 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
555 failedXpathsConcatenated, dataspaceName, anchorName));
559 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
560 final DataNode newDataNode) {
562 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
564 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
565 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
567 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
569 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
570 final FragmentEntity childFragment;
571 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
572 childFragment = convertToFragmentWithAllDescendants(
573 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
575 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
576 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
578 updatedChildFragments.add(childFragment);
581 existingFragmentEntity.getChildFragments().clear();
582 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
587 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
588 final Collection<DataNode> newListElements) {
589 final FragmentEntity parentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
590 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
591 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
592 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
593 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
594 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
595 for (final DataNode newListElement : newListElements) {
596 final FragmentEntity existingListElementEntity =
597 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
598 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
599 existingListElementEntity);
601 updatedChildFragmentEntities.add(entityToBeAdded);
603 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
604 fragmentRepository.save(parentEntity);
609 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
610 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
611 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
613 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
618 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
619 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
620 final Collection<AnchorEntity> anchorEntities =
621 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
622 fragmentRepository.deleteByAnchorIn(anchorEntities);
627 public void deleteDataNodes(final String dataspaceName, final String anchorName,
628 final Collection<String> xpathsToDelete) {
629 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
630 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
632 final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
633 for (final String xpath : xpathsToDelete) {
635 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
636 } catch (final PathParsingException e) {
637 log.debug("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
641 final Collection<String> xpathsToExistingContainers =
642 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
643 deleteChecklist.removeAll(xpathsToExistingContainers);
645 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
646 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
647 .collect(Collectors.toList());
648 deleteChecklist.removeAll(xpathsToExistingLists);
650 if (!deleteChecklist.isEmpty()) {
651 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
654 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
655 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
660 public void deleteListDataNode(final String dataspaceName, final String anchorName,
661 final String targetXpath) {
662 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
667 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
668 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
671 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
672 final boolean onlySupportListNodeDeletion) {
673 final String parentNodeXpath;
674 FragmentEntity parentFragmentEntity = null;
675 boolean targetDeleted;
676 if (isRootXpath(targetXpath)) {
677 deleteDataNodes(dataspaceName, anchorName);
678 targetDeleted = true;
680 if (isRootContainerNodeXpath(targetXpath)) {
681 parentNodeXpath = targetXpath;
683 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
685 parentFragmentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
686 if (CpsPathUtil.isPathToListElement(targetXpath)) {
687 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
689 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
690 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
691 if (tryToDeleteDataNode) {
692 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
696 if (!targetDeleted) {
697 final String additionalInformation = onlySupportListNodeDeletion
698 ? "The target is probably not a List." : "";
699 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
700 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
704 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
705 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
706 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
707 fragmentRepository.deleteFragmentEntity(parentFragmentEntity.getId());
710 if (parentFragmentEntity.getChildFragments()
711 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
712 fragmentRepository.save(parentFragmentEntity);
718 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
719 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
720 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
721 if (parentFragmentEntity.getChildFragments()
722 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
723 fragmentRepository.save(parentFragmentEntity);
729 private static void deleteListElements(
730 final Collection<FragmentEntity> fragmentEntities,
731 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
732 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
735 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
736 if (newListElements.isEmpty()) {
737 throw new CpsAdminException("Invalid list replacement",
738 "Cannot replace list elements with empty collection");
740 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
741 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
744 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
745 final DataNode newListElement,
746 final FragmentEntity existingListElementEntity) {
747 if (existingListElementEntity == null) {
748 return convertToFragmentWithAllDescendants(
749 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
751 if (newListElement.getChildDataNodes().isEmpty()) {
752 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
753 existingListElementEntity.getChildFragments().clear();
755 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
757 return existingListElementEntity;
760 private static boolean isNewDataNode(final DataNode replacementDataNode,
761 final Map<String, FragmentEntity> existingListElementsByXpath) {
762 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
765 private static boolean isRootContainerNodeXpath(final String xpath) {
766 return 0 == xpath.lastIndexOf('/');
769 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
770 final DataNode newListElement) {
771 final FragmentEntity replacementFragmentEntity =
772 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
773 newListElement.getLeaves())).build();
774 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
777 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
778 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
779 return childEntities.stream()
780 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
781 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
784 private static boolean isRootXpath(final String xpath) {
785 return "/".equals(xpath) || "".equals(xpath);
788 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
789 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
790 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
791 currentLeavesAsMap.putAll(updateLeaves);
792 if (currentLeavesAsMap.isEmpty()) {
795 return jsonObjectMapper.asJsonString(currentLeavesAsMap);