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.base.Strings;
27 import com.google.common.collect.ImmutableSet;
28 import com.google.common.collect.ImmutableSet.Builder;
29 import io.micrometer.core.annotation.Timed;
30 import java.io.Serializable;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.stream.Collectors;
42 import javax.transaction.Transactional;
43 import lombok.RequiredArgsConstructor;
44 import lombok.extern.slf4j.Slf4j;
45 import org.hibernate.StaleStateException;
46 import org.onap.cps.cpspath.parser.CpsPathQuery;
47 import org.onap.cps.cpspath.parser.CpsPathUtil;
48 import org.onap.cps.cpspath.parser.PathParsingException;
49 import org.onap.cps.spi.CpsDataPersistenceService;
50 import org.onap.cps.spi.FetchDescendantsOption;
51 import org.onap.cps.spi.entities.AnchorEntity;
52 import org.onap.cps.spi.entities.DataspaceEntity;
53 import org.onap.cps.spi.entities.FragmentEntity;
54 import org.onap.cps.spi.entities.FragmentEntityArranger;
55 import org.onap.cps.spi.entities.FragmentExtract;
56 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
57 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
58 import org.onap.cps.spi.exceptions.ConcurrencyException;
59 import org.onap.cps.spi.exceptions.CpsAdminException;
60 import org.onap.cps.spi.exceptions.CpsPathException;
61 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
62 import org.onap.cps.spi.exceptions.DataNodeNotFoundExceptionBatch;
63 import org.onap.cps.spi.model.DataNode;
64 import org.onap.cps.spi.model.DataNodeBuilder;
65 import org.onap.cps.spi.repository.AnchorRepository;
66 import org.onap.cps.spi.repository.DataspaceRepository;
67 import org.onap.cps.spi.repository.FragmentQueryBuilder;
68 import org.onap.cps.spi.repository.FragmentRepository;
69 import org.onap.cps.spi.utils.SessionManager;
70 import org.onap.cps.utils.JsonObjectMapper;
71 import org.springframework.dao.DataIntegrityViolationException;
72 import org.springframework.stereotype.Service;
76 @RequiredArgsConstructor
77 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
79 private final DataspaceRepository dataspaceRepository;
80 private final AnchorRepository anchorRepository;
81 private final FragmentRepository fragmentRepository;
82 private final JsonObjectMapper jsonObjectMapper;
83 private final SessionManager sessionManager;
85 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@.+?])?)";
86 private static final String QUERY_ACROSS_ANCHORS = null;
87 private static final AnchorEntity ALL_ANCHORS = null;
90 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
91 final DataNode newChildDataNode) {
92 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
93 addNewChildDataNode(anchorEntity, parentNodeXpath, newChildDataNode);
97 public void addChildDataNodes(final String dataspaceName, final String anchorName,
98 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
99 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
100 addChildrenDataNodes(anchorEntity, parentNodeXpath, dataNodes);
104 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
105 final Collection<DataNode> newListElements) {
106 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
107 addChildrenDataNodes(anchorEntity, parentNodeXpath, newListElements);
111 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
112 final Collection<Collection<DataNode>> newLists) {
113 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
114 final Collection<String> failedXpaths = new HashSet<>();
115 for (final Collection<DataNode> newList : newLists) {
117 addChildrenDataNodes(anchorEntity, parentNodeXpath, newList);
118 } catch (final AlreadyDefinedExceptionBatch e) {
119 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
122 if (!failedXpaths.isEmpty()) {
123 throw new AlreadyDefinedExceptionBatch(failedXpaths);
127 private void addNewChildDataNode(final AnchorEntity anchorEntity, final String parentNodeXpath,
128 final DataNode newChild) {
129 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
130 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, newChild);
131 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
133 fragmentRepository.save(newChildAsFragmentEntity);
134 } catch (final DataIntegrityViolationException e) {
135 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorEntity.getName(), e);
139 private void addChildrenDataNodes(final AnchorEntity anchorEntity, final String parentNodeXpath,
140 final Collection<DataNode> newChildren) {
141 final FragmentEntity parentFragmentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
142 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
144 for (final DataNode newChildAsDataNode : newChildren) {
145 final FragmentEntity newChildAsFragmentEntity =
146 convertToFragmentWithAllDescendants(anchorEntity, newChildAsDataNode);
147 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
148 fragmentEntities.add(newChildAsFragmentEntity);
150 fragmentRepository.saveAll(fragmentEntities);
151 } catch (final DataIntegrityViolationException e) {
152 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
153 e, fragmentEntities.size());
154 retrySavingEachChildIndividually(anchorEntity, parentNodeXpath, newChildren);
158 private void retrySavingEachChildIndividually(final AnchorEntity anchorEntity, final String parentNodeXpath,
159 final Collection<DataNode> newChildren) {
160 final Collection<String> failedXpaths = new HashSet<>();
161 for (final DataNode newChild : newChildren) {
163 addNewChildDataNode(anchorEntity, parentNodeXpath, newChild);
164 } catch (final AlreadyDefinedException e) {
165 failedXpaths.add(newChild.getXpath());
168 if (!failedXpaths.isEmpty()) {
169 throw new AlreadyDefinedExceptionBatch(failedXpaths);
174 public void storeDataNodes(final String dataspaceName, final String anchorName,
175 final Collection<DataNode> dataNodes) {
176 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
177 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
179 for (final DataNode dataNode: dataNodes) {
180 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
181 fragmentEntities.add(fragmentEntity);
183 fragmentRepository.saveAll(fragmentEntities);
184 } catch (final DataIntegrityViolationException exception) {
185 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
186 exception, dataNodes.size());
187 storeDataNodesIndividually(anchorEntity, dataNodes);
191 private void storeDataNodesIndividually(final AnchorEntity anchorEntity, final Collection<DataNode> dataNodes) {
192 final Collection<String> failedXpaths = new HashSet<>();
193 for (final DataNode dataNode: dataNodes) {
195 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(anchorEntity, dataNode);
196 fragmentRepository.save(fragmentEntity);
197 } catch (final DataIntegrityViolationException e) {
198 failedXpaths.add(dataNode.getXpath());
201 if (!failedXpaths.isEmpty()) {
202 throw new AlreadyDefinedExceptionBatch(failedXpaths);
207 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
208 * for all DataNode children recursively.
210 * @param anchorEntity anchorEntity
211 * @param dataNodeToBeConverted dataNode
212 * @return a Fragment built from current DataNode
214 private FragmentEntity convertToFragmentWithAllDescendants(final AnchorEntity anchorEntity,
215 final DataNode dataNodeToBeConverted) {
216 final FragmentEntity parentFragment = toFragmentEntity(anchorEntity, dataNodeToBeConverted);
217 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
218 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
219 final FragmentEntity childFragment = convertToFragmentWithAllDescendants(anchorEntity, childDataNode);
220 childFragmentsImmutableSetBuilder.add(childFragment);
222 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
223 return parentFragment;
226 private FragmentEntity toFragmentEntity(final AnchorEntity anchorEntity, final DataNode dataNode) {
227 return FragmentEntity.builder()
228 .dataspace(anchorEntity.getDataspace())
229 .anchor(anchorEntity)
230 .xpath(dataNode.getXpath())
231 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
236 @Timed(value = "cps.data.persistence.service.datanode.get",
237 description = "Time taken to get a data node")
238 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
240 final FetchDescendantsOption fetchDescendantsOption) {
241 final String targetXpath = getNormalizedXpath(xpath);
242 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
243 Collections.singletonList(targetXpath), fetchDescendantsOption);
244 if (dataNodes.isEmpty()) {
245 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
251 @Timed(value = "cps.data.persistence.service.datanode.batch.get",
252 description = "Time taken to get data nodes")
253 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
254 final Collection<String> xpaths,
255 final FetchDescendantsOption fetchDescendantsOption) {
256 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
257 final Collection<FragmentEntity> fragmentEntities =
258 getFragmentEntities(anchorEntity, xpaths, fetchDescendantsOption);
259 return toDataNodes(fragmentEntities, fetchDescendantsOption);
262 private Collection<FragmentEntity> getFragmentEntities(final AnchorEntity anchorEntity,
263 final Collection<String> xpaths,
264 final FetchDescendantsOption fetchDescendantsOption) {
265 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
266 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
268 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
269 for (final String xpath : nonRootXpaths) {
271 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
272 } catch (final PathParsingException e) {
273 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
277 normalizedXpaths.addAll(fragmentRepository.findAllXpathByAnchorAndParentIdIsNull(anchorEntity));
280 final List<FragmentExtract> fragmentExtracts =
281 fragmentRepository.findExtractsWithDescendants(anchorEntity.getId(), normalizedXpaths,
282 fetchDescendantsOption.getDepth());
284 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
287 private FragmentEntity getFragmentEntity(final AnchorEntity anchorEntity, final String xpath) {
288 final FragmentEntity fragmentEntity;
289 if (isRootXpath(xpath)) {
290 final List<FragmentExtract> fragmentExtracts = fragmentRepository.findAllExtractsByAnchor(anchorEntity);
291 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
292 .stream().findFirst().orElse(null);
294 fragmentEntity = fragmentRepository.getByAnchorAndXpath(anchorEntity, getNormalizedXpath(xpath));
296 if (fragmentEntity == null) {
297 throw new DataNodeNotFoundException(anchorEntity.getDataspace().getName(), anchorEntity.getName(), xpath);
299 return fragmentEntity;
302 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
303 final String normalizedXpath) {
304 final List<FragmentExtract> fragmentExtracts =
305 fragmentRepository.findByAnchorAndParentXpath(anchorEntity, normalizedXpath);
306 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
310 @Timed(value = "cps.data.persistence.service.datanode.query",
311 description = "Time taken to query data nodes")
312 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
313 final FetchDescendantsOption fetchDescendantsOption) {
314 final AnchorEntity anchorEntity = (Strings.isNullOrEmpty(anchorName)) ? ALL_ANCHORS
315 : getAnchorEntity(dataspaceName, anchorName);
316 final CpsPathQuery cpsPathQuery;
318 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
319 } catch (final PathParsingException e) {
320 throw new CpsPathException(e.getMessage());
323 Collection<FragmentEntity> fragmentEntities;
324 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
325 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
327 fragmentEntities = (anchorEntity == ALL_ANCHORS) ? fragmentRepository.findByCpsPath(cpsPathQuery)
328 : fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
329 if (cpsPathQuery.hasAncestorAxis()) {
330 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
331 fragmentEntities = (anchorEntity == ALL_ANCHORS) ? getAncestorFragmentEntitiesAcrossAnchors(cpsPathQuery,
332 fragmentEntities) : getFragmentEntities(anchorEntity, ancestorXpaths, fetchDescendantsOption);
334 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
338 public List<DataNode> queryDataNodesAcrossAnchors(final String dataspaceName, final String cpsPath,
339 final FetchDescendantsOption fetchDescendantsOption) {
340 return queryDataNodes(dataspaceName, QUERY_ACROSS_ANCHORS, cpsPath, fetchDescendantsOption);
343 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
344 final CpsPathQuery cpsPathQuery) {
345 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
346 && !cpsPathQuery.hasLeafConditions()
347 && !cpsPathQuery.hasTextFunctionCondition()
348 && !cpsPathQuery.hasContainsFunctionCondition();
351 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
352 final AnchorEntity anchorEntity,
353 final CpsPathQuery cpsPathQuery) {
354 Collection<FragmentEntity> fragmentEntities;
355 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegexForQuickFindWithDescendants(cpsPathQuery);
356 final List<FragmentExtract> fragmentExtracts = (anchorEntity == ALL_ANCHORS)
357 ? fragmentRepository.quickFindWithDescendantsAcrossAnchor(xpathRegex) :
358 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
359 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
360 if (cpsPathQuery.hasAncestorAxis()) {
361 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
362 fragmentEntities = (anchorEntity == ALL_ANCHORS) ? getAncestorFragmentEntitiesAcrossAnchors(cpsPathQuery,
363 fragmentEntities) : getFragmentEntities(anchorEntity, ancestorXpaths, fetchDescendantsOption);
365 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
368 private Collection<FragmentEntity> getAncestorFragmentEntitiesAcrossAnchors(final CpsPathQuery cpsPathQuery,
369 final Collection<FragmentEntity> fragmentEntities) {
370 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
371 return ancestorXpaths.isEmpty() ? Collections.emptyList() : fragmentRepository.findAllByXpathIn(ancestorXpaths);
374 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
375 final FetchDescendantsOption fetchDescendantsOption,
376 final AnchorEntity anchorEntity,
377 final Collection<FragmentEntity> proxiedFragmentEntities) {
378 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
379 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
380 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
381 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
383 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
384 final AnchorEntity anchorEntityForFragmentExtract = (anchorEntity == ALL_ANCHORS)
385 ? proxiedFragmentEntity.getAnchor() : anchorEntity;
386 final Collection<FragmentEntity> unproxiedFragmentEntities =
387 buildFragmentEntitiesFromFragmentExtracts(anchorEntityForFragmentExtract, normalizedXpath);
388 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
389 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
393 return Collections.unmodifiableList(dataNodes);
396 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
397 final Collection<FragmentEntity> fragmentEntities) {
398 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
399 for (final FragmentEntity fragmentEntity : fragmentEntities) {
400 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
402 return Collections.unmodifiableList(dataNodes);
405 private static String getNormalizedXpath(final String xpathSource) {
406 if (isRootXpath(xpathSource)) {
410 return CpsPathUtil.getNormalizedXpath(xpathSource);
411 } catch (final PathParsingException e) {
412 throw new CpsPathException(e.getMessage());
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("(.*/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
437 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "/.*");
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 .withDataspace(fragmentEntity.getAnchor().getDataspace().getName())
458 .withAnchor(fragmentEntity.getAnchor().getName())
459 .withChildDataNodes(childDataNodes).build();
462 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
463 final FetchDescendantsOption fetchDescendantsOption) {
464 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
465 for (final FragmentEntity fragmentEntity : fragmentEntities) {
466 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
471 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
472 final FetchDescendantsOption fetchDescendantsOption) {
473 if (fetchDescendantsOption.hasNext()) {
474 return fragmentEntity.getChildFragments().stream()
475 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
476 .collect(Collectors.toList());
478 return Collections.emptyList();
482 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
483 final Map<String, Serializable> updateLeaves) {
484 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
485 final FragmentEntity fragmentEntity = getFragmentEntity(anchorEntity, xpath);
486 final String currentLeavesAsString = fragmentEntity.getAttributes();
487 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
488 fragmentEntity.setAttributes(mergedLeaves);
489 fragmentRepository.save(fragmentEntity);
493 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
494 final Collection<DataNode> updatedDataNodes) {
495 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
497 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
498 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
500 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
501 final Collection<FragmentEntity> existingFragmentEntities =
502 getFragmentEntities(anchorEntity, xpaths, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
504 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
505 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
506 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
510 fragmentRepository.saveAll(existingFragmentEntities);
511 } catch (final StaleStateException staleStateException) {
512 retryUpdateDataNodesIndividually(anchorEntity, existingFragmentEntities);
516 private void retryUpdateDataNodesIndividually(final AnchorEntity anchorEntity,
517 final Collection<FragmentEntity> fragmentEntities) {
518 final Collection<String> failedXpaths = new HashSet<>();
519 for (final FragmentEntity dataNodeFragment : fragmentEntities) {
521 fragmentRepository.save(dataNodeFragment);
522 } catch (final StaleStateException e) {
523 failedXpaths.add(dataNodeFragment.getXpath());
526 if (!failedXpaths.isEmpty()) {
527 final String failedXpathsConcatenated = String.join(",", failedXpaths);
528 throw new ConcurrencyException("Concurrent Transactions", String.format(
529 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
530 failedXpathsConcatenated, anchorEntity.getDataspace().getName(), anchorEntity.getName()));
534 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
535 final DataNode newDataNode) {
536 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
538 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
539 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
541 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
542 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
543 final FragmentEntity childFragment;
544 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
545 childFragment = convertToFragmentWithAllDescendants(existingFragmentEntity.getAnchor(),
548 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
549 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
551 updatedChildFragments.add(childFragment);
554 existingFragmentEntity.getChildFragments().clear();
555 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
560 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
561 final Collection<DataNode> newListElements) {
562 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
563 final FragmentEntity parentEntity = getFragmentEntity(anchorEntity, parentNodeXpath);
564 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
565 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
566 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
567 parentEntity.getChildFragments().removeAll(existingListElementFragmentEntitiesByXPath.values());
568 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
569 for (final DataNode newListElement : newListElements) {
570 final FragmentEntity existingListElementEntity =
571 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
572 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
573 existingListElementEntity);
574 updatedChildFragmentEntities.add(entityToBeAdded);
576 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
577 fragmentRepository.save(parentEntity);
582 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
583 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
584 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
585 .ifPresent(anchorEntity -> fragmentRepository.deleteByAnchorIn(Collections.singletonList(anchorEntity)));
590 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
591 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
592 final Collection<AnchorEntity> anchorEntities =
593 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
594 fragmentRepository.deleteByAnchorIn(anchorEntities);
599 public void deleteDataNodes(final String dataspaceName, final String anchorName,
600 final Collection<String> xpathsToDelete) {
601 deleteDataNodes(dataspaceName, anchorName, xpathsToDelete, false);
604 private void deleteDataNodes(final String dataspaceName, final String anchorName,
605 final Collection<String> xpathsToDelete, final boolean onlySupportListDeletion) {
606 final boolean haveRootXpath = xpathsToDelete.stream().anyMatch(CpsDataPersistenceServiceImpl::isRootXpath);
608 deleteDataNodes(dataspaceName, anchorName);
612 final AnchorEntity anchorEntity = getAnchorEntity(dataspaceName, anchorName);
614 final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
615 for (final String xpath : xpathsToDelete) {
617 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
618 } catch (final PathParsingException e) {
619 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
623 final Collection<String> xpathsToExistingContainers =
624 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
625 if (onlySupportListDeletion) {
626 final Collection<String> xpathsToExistingListElements = xpathsToExistingContainers.stream()
627 .filter(CpsPathUtil::isPathToListElement).collect(Collectors.toList());
628 deleteChecklist.removeAll(xpathsToExistingListElements);
630 deleteChecklist.removeAll(xpathsToExistingContainers);
633 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
634 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
635 .collect(Collectors.toList());
636 deleteChecklist.removeAll(xpathsToExistingLists);
638 if (!deleteChecklist.isEmpty()) {
639 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
642 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
643 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
648 public void deleteListDataNode(final String dataspaceName, final String anchorName,
649 final String targetXpath) {
650 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
655 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
656 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
659 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
660 final boolean onlySupportListNodeDeletion) {
661 final String normalizedXpath = getNormalizedXpath(targetXpath);
663 deleteDataNodes(dataspaceName, anchorName, Collections.singletonList(normalizedXpath),
664 onlySupportListNodeDeletion);
665 } catch (final DataNodeNotFoundExceptionBatch dataNodeNotFoundExceptionBatch) {
666 throw new DataNodeNotFoundException(dataspaceName, anchorName, targetXpath);
670 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
671 if (newListElements.isEmpty()) {
672 throw new CpsAdminException("Invalid list replacement",
673 "Cannot replace list elements with empty collection");
675 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
676 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
679 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
680 final DataNode newListElement,
681 final FragmentEntity existingListElementEntity) {
682 if (existingListElementEntity == null) {
683 return convertToFragmentWithAllDescendants(parentEntity.getAnchor(), newListElement);
685 if (newListElement.getChildDataNodes().isEmpty()) {
686 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
687 existingListElementEntity.getChildFragments().clear();
689 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
691 return existingListElementEntity;
694 private static boolean isNewDataNode(final DataNode replacementDataNode,
695 final Map<String, FragmentEntity> existingListElementsByXpath) {
696 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
699 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
700 final DataNode newListElement) {
701 final FragmentEntity replacementFragmentEntity =
702 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
703 newListElement.getLeaves())).build();
704 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
707 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
708 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
709 return childEntities.stream()
710 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
711 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
714 private static boolean isRootXpath(final String xpath) {
715 return "/".equals(xpath) || "".equals(xpath);
718 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
719 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
720 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
721 currentLeavesAsMap.putAll(updateLeaves);
722 if (currentLeavesAsMap.isEmpty()) {
725 return jsonObjectMapper.asJsonString(currentLeavesAsMap);
728 private AnchorEntity getAnchorEntity(final String dataspaceName, final String anchorName) {
729 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
730 return anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);