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 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
124 final FragmentEntity newChildAsFragmentEntity =
125 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
126 parentFragmentEntity.getAnchor(), newChild);
127 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
129 fragmentRepository.save(newChildAsFragmentEntity);
130 } catch (final DataIntegrityViolationException e) {
131 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
136 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
137 final Collection<DataNode> newChildren) {
138 final FragmentEntity parentFragmentEntity =
139 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
140 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
142 newChildren.forEach(newChildAsDataNode -> {
143 final FragmentEntity newChildAsFragmentEntity =
144 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
145 parentFragmentEntity.getAnchor(), newChildAsDataNode);
146 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
147 fragmentEntities.add(newChildAsFragmentEntity);
149 fragmentRepository.saveAll(fragmentEntities);
150 } catch (final DataIntegrityViolationException e) {
151 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
152 e, fragmentEntities.size());
153 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
157 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
158 final String parentNodeXpath,
159 final Collection<DataNode> newChildren) {
160 final Collection<String> failedXpaths = new HashSet<>();
161 for (final DataNode newChild : newChildren) {
163 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
164 } catch (final AlreadyDefinedException e) {
165 failedXpaths.add(newChild.getXpath());
168 if (!failedXpaths.isEmpty()) {
169 throw new AlreadyDefinedExceptionBatch(failedXpaths);
174 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
175 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
179 public void storeDataNodes(final String dataspaceName, final String anchorName,
180 final Collection<DataNode> dataNodes) {
181 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
182 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
183 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
185 for (final DataNode dataNode: dataNodes) {
186 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
188 fragmentEntities.add(fragmentEntity);
190 fragmentRepository.saveAll(fragmentEntities);
191 } catch (final DataIntegrityViolationException exception) {
192 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
193 exception, dataNodes.size());
194 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
198 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
199 final Collection<DataNode> dataNodes) {
200 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
201 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
202 final Collection<String> failedXpaths = new HashSet<>();
203 for (final DataNode dataNode: dataNodes) {
205 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
207 fragmentRepository.save(fragmentEntity);
208 } catch (final DataIntegrityViolationException e) {
209 failedXpaths.add(dataNode.getXpath());
212 if (!failedXpaths.isEmpty()) {
213 throw new AlreadyDefinedExceptionBatch(failedXpaths);
218 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
219 * for all DataNode children recursively.
221 * @param dataspaceEntity dataspace
222 * @param anchorEntity anchorEntity
223 * @param dataNodeToBeConverted dataNode
224 * @return a Fragment built from current DataNode
226 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
227 final AnchorEntity anchorEntity,
228 final DataNode dataNodeToBeConverted) {
229 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
230 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
231 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
232 final FragmentEntity childFragment =
233 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
235 childFragmentsImmutableSetBuilder.add(childFragment);
237 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
238 return parentFragment;
241 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
242 final AnchorEntity anchorEntity, final DataNode dataNode) {
243 return FragmentEntity.builder()
244 .dataspace(dataspaceEntity)
245 .anchor(anchorEntity)
246 .xpath(dataNode.getXpath())
247 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
252 public 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 DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
269 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
271 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
272 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
274 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
275 for (final String xpath : nonRootXpaths) {
277 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
278 } catch (final PathParsingException e) {
279 log.warn("Error parsing xpath \"{}\" in getDataNodesForMultipleXpaths: {}", xpath, e.getMessage());
282 final Collection<FragmentEntity> fragmentEntities =
283 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
286 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
288 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
291 return toDataNodes(fragmentEntities, fetchDescendantsOption);
294 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
295 final String anchorName,
296 final String xpath) {
297 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
300 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
301 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
302 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
303 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
304 final FragmentEntity fragmentEntity;
305 if (isRootXpath(xpath)) {
306 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
308 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
309 .stream().findFirst().orElse(null);
311 final String normalizedXpath = getNormalizedXpath(xpath);
312 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
314 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
316 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
317 .stream().findFirst().orElse(null);
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 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
339 final FetchDescendantsOption fetchDescendantsOption) {
340 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
341 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
342 final CpsPathQuery cpsPathQuery;
344 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
345 } catch (final PathParsingException e) {
346 throw new CpsPathException(e.getMessage());
349 Collection<FragmentEntity> fragmentEntities;
350 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
351 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
353 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
354 if (cpsPathQuery.hasAncestorAxis()) {
355 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
357 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
360 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
361 final CpsPathQuery cpsPathQuery) {
362 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
363 && !cpsPathQuery.hasLeafConditions()
364 && !cpsPathQuery.hasTextFunctionCondition();
367 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
368 final AnchorEntity anchorEntity,
369 final CpsPathQuery cpsPathQuery) {
370 Collection<FragmentEntity> fragmentEntities;
371 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
372 final List<FragmentExtract> fragmentExtracts =
373 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
374 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
375 if (cpsPathQuery.hasAncestorAxis()) {
376 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
378 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
381 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
382 final CpsPathQuery cpsPathQuery,
383 final Collection<FragmentEntity> fragmentEntities) {
384 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
385 return ancestorXpaths.isEmpty() ? Collections.emptyList()
386 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
389 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
390 final FetchDescendantsOption fetchDescendantsOption,
391 final AnchorEntity anchorEntity,
392 final Collection<FragmentEntity> proxiedFragmentEntities) {
393 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
394 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
395 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
396 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
398 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
399 final Collection<FragmentEntity> unproxiedFragmentEntities =
400 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
401 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
402 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
406 return Collections.unmodifiableList(dataNodes);
409 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
410 final Collection<FragmentEntity> fragmentEntities) {
411 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
412 for (final FragmentEntity fragmentEntity : fragmentEntities) {
413 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
415 return Collections.unmodifiableList(dataNodes);
418 private static String getNormalizedXpath(final String xpathSource) {
419 final String normalizedXpath;
421 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
422 } catch (final PathParsingException e) {
423 throw new CpsPathException(e.getMessage());
425 return normalizedXpath;
429 public String startSession() {
430 return sessionManager.startSession();
434 public void closeSession(final String sessionId) {
435 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
439 public void lockAnchor(final String sessionId, final String dataspaceName,
440 final String anchorName, final Long timeoutInMilliseconds) {
441 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
444 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
445 final CpsPathQuery cpsPathQuery) {
446 final Set<String> ancestorXpath = new HashSet<>();
447 final Pattern pattern =
448 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
449 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
450 for (final FragmentEntity fragmentEntity : fragmentEntities) {
451 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
452 if (matcher.matches()) {
453 ancestorXpath.add(matcher.group(1));
456 return ancestorXpath;
459 private DataNode toDataNode(final FragmentEntity fragmentEntity,
460 final FetchDescendantsOption fetchDescendantsOption) {
461 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
462 Map<String, Serializable> leaves = new HashMap<>();
463 if (fragmentEntity.getAttributes() != null) {
464 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
466 return new DataNodeBuilder()
467 .withXpath(fragmentEntity.getXpath())
469 .withChildDataNodes(childDataNodes).build();
472 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
473 final FetchDescendantsOption fetchDescendantsOption) {
474 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
475 for (final FragmentEntity fragmentEntity : fragmentEntities) {
476 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
481 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
482 final FetchDescendantsOption fetchDescendantsOption) {
483 if (fetchDescendantsOption.hasNext()) {
484 return fragmentEntity.getChildFragments().stream()
485 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
486 .collect(Collectors.toList());
488 return Collections.emptyList();
492 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
493 final Map<String, Serializable> updateLeaves) {
494 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
495 final String currentLeavesAsString = fragmentEntity.getAttributes();
496 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
497 fragmentEntity.setAttributes(mergedLeaves);
498 fragmentRepository.save(fragmentEntity);
502 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
503 final DataNode dataNode) {
504 final FragmentEntity fragmentEntity =
505 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
506 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
508 fragmentRepository.save(fragmentEntity);
509 } catch (final StaleStateException staleStateException) {
510 throw new ConcurrencyException("Concurrent Transactions",
511 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
512 dataspaceName, anchorName, dataNode.getXpath()));
517 public void updateDataNodesAndDescendants(final String dataspaceName,
518 final String anchorName,
519 final List<DataNode> dataNodes) {
521 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
522 .collect(Collectors.toMap(
523 dataNode -> dataNode,
525 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
526 dataNodeFragmentEntityMap.forEach(
527 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
529 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
530 } catch (final StaleStateException staleStateException) {
531 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
535 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
536 final Collection<FragmentEntity> fragmentEntities) {
537 final Collection<String> failedXpaths = new HashSet<>();
539 fragmentEntities.forEach(dataNodeFragment -> {
541 fragmentRepository.save(dataNodeFragment);
542 } catch (final StaleStateException e) {
543 failedXpaths.add(dataNodeFragment.getXpath());
547 if (!failedXpaths.isEmpty()) {
548 final String failedXpathsConcatenated = String.join(",", failedXpaths);
549 throw new ConcurrencyException("Concurrent Transactions", String.format(
550 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
551 failedXpathsConcatenated, dataspaceName, anchorName));
555 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
556 final DataNode newDataNode) {
558 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
560 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
561 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
563 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
565 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
566 final FragmentEntity childFragment;
567 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
568 childFragment = convertToFragmentWithAllDescendants(
569 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
571 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
572 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
574 updatedChildFragments.add(childFragment);
577 existingFragmentEntity.getChildFragments().clear();
578 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
583 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
584 final Collection<DataNode> newListElements) {
585 final FragmentEntity parentEntity =
586 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
587 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
588 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
589 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
590 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
591 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
592 for (final DataNode newListElement : newListElements) {
593 final FragmentEntity existingListElementEntity =
594 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
595 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
596 existingListElementEntity);
598 updatedChildFragmentEntities.add(entityToBeAdded);
600 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
601 fragmentRepository.save(parentEntity);
606 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
607 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
608 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
610 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
615 public void deleteDataNodes(final String dataspaceName, final String anchorName,
616 final Collection<String> xpathsToDelete) {
617 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
618 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
620 final Collection<String> normalizedXpaths = new ArrayList<>(xpathsToDelete.size());
621 for (final String xpath : xpathsToDelete) {
623 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
624 } catch (final PathParsingException e) {
625 log.debug("Error parsing xpath \"{}\" in deleteDataNodes: {}", xpath, e.getMessage());
629 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), normalizedXpaths);
630 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), normalizedXpaths);
635 public void deleteListDataNode(final String dataspaceName, final String anchorName,
636 final String targetXpath) {
637 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
642 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
643 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
646 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
647 final boolean onlySupportListNodeDeletion) {
648 final String parentNodeXpath;
649 FragmentEntity parentFragmentEntity = null;
650 boolean targetDeleted;
651 if (isRootXpath(targetXpath)) {
652 deleteDataNodes(dataspaceName, anchorName);
653 targetDeleted = true;
655 if (isRootContainerNodeXpath(targetXpath)) {
656 parentNodeXpath = targetXpath;
658 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
660 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
661 if (CpsPathUtil.isPathToListElement(targetXpath)) {
662 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
664 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
665 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
666 if (tryToDeleteDataNode) {
667 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
671 if (!targetDeleted) {
672 final String additionalInformation = onlySupportListNodeDeletion
673 ? "The target is probably not a List." : "";
674 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
675 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
679 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
680 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
681 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
682 fragmentRepository.deleteFragmentEntity(parentFragmentEntity.getId());
685 if (parentFragmentEntity.getChildFragments()
686 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
687 fragmentRepository.save(parentFragmentEntity);
693 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
694 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
695 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
696 if (parentFragmentEntity.getChildFragments()
697 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
698 fragmentRepository.save(parentFragmentEntity);
704 private static void deleteListElements(
705 final Collection<FragmentEntity> fragmentEntities,
706 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
707 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
710 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
711 if (newListElements.isEmpty()) {
712 throw new CpsAdminException("Invalid list replacement",
713 "Cannot replace list elements with empty collection");
715 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
716 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
719 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
720 final DataNode newListElement,
721 final FragmentEntity existingListElementEntity) {
722 if (existingListElementEntity == null) {
723 return convertToFragmentWithAllDescendants(
724 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
726 if (newListElement.getChildDataNodes().isEmpty()) {
727 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
728 existingListElementEntity.getChildFragments().clear();
730 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
732 return existingListElementEntity;
735 private static boolean isNewDataNode(final DataNode replacementDataNode,
736 final Map<String, FragmentEntity> existingListElementsByXpath) {
737 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
740 private static boolean isRootContainerNodeXpath(final String xpath) {
741 return 0 == xpath.lastIndexOf('/');
744 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
745 final DataNode newListElement) {
746 final FragmentEntity replacementFragmentEntity =
747 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
748 newListElement.getLeaves())).build();
749 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
752 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
753 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
754 return childEntities.stream()
755 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
756 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
759 private static boolean isRootXpath(final String xpath) {
760 return "/".equals(xpath) || "".equals(xpath);
763 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
764 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
765 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
766 currentLeavesAsMap.putAll(updateLeaves);
767 if (currentLeavesAsMap.isEmpty()) {
770 return jsonObjectMapper.asJsonString(currentLeavesAsMap);