2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2023 Nordix Foundation
4 * Modifications Copyright (C) 2021 Pantheon.tech
5 * Modifications Copyright (C) 2020-2022 Bell Canada.
6 * Modifications Copyright (C) 2022 TechMahindra Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl;
26 import com.google.common.collect.ImmutableSet;
27 import com.google.common.collect.ImmutableSet.Builder;
28 import java.io.Serializable;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
39 import java.util.stream.Collectors;
40 import javax.transaction.Transactional;
41 import lombok.RequiredArgsConstructor;
42 import lombok.extern.slf4j.Slf4j;
43 import org.hibernate.StaleStateException;
44 import org.onap.cps.cpspath.parser.CpsPathQuery;
45 import org.onap.cps.cpspath.parser.CpsPathUtil;
46 import org.onap.cps.cpspath.parser.PathParsingException;
47 import org.onap.cps.spi.CpsDataPersistenceService;
48 import org.onap.cps.spi.FetchDescendantsOption;
49 import org.onap.cps.spi.entities.AnchorEntity;
50 import org.onap.cps.spi.entities.DataspaceEntity;
51 import org.onap.cps.spi.entities.FragmentEntity;
52 import org.onap.cps.spi.entities.FragmentEntityArranger;
53 import org.onap.cps.spi.entities.FragmentExtract;
54 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
55 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
56 import org.onap.cps.spi.exceptions.ConcurrencyException;
57 import org.onap.cps.spi.exceptions.CpsAdminException;
58 import org.onap.cps.spi.exceptions.CpsPathException;
59 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
60 import org.onap.cps.spi.model.DataNode;
61 import org.onap.cps.spi.model.DataNodeBuilder;
62 import org.onap.cps.spi.repository.AnchorRepository;
63 import org.onap.cps.spi.repository.DataspaceRepository;
64 import org.onap.cps.spi.repository.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 DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
253 final FetchDescendantsOption fetchDescendantsOption) {
254 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath,
255 fetchDescendantsOption);
256 return toDataNode(fragmentEntity, fetchDescendantsOption);
260 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
261 final Collection<String> xpaths,
262 final FetchDescendantsOption fetchDescendantsOption) {
263 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
264 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
266 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
267 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
269 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
270 for (final String xpath : nonRootXpaths) {
272 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
273 } catch (final PathParsingException e) {
274 log.warn("Error parsing xpath \"{}\" in getDataNodes: {}", xpath, e.getMessage());
277 final Collection<FragmentEntity> fragmentEntities =
278 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
281 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
283 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
286 return toDataNodes(fragmentEntities, fetchDescendantsOption);
289 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
290 final String anchorName,
291 final String xpath) {
292 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
295 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
296 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
297 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
298 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
299 final FragmentEntity fragmentEntity;
300 if (isRootXpath(xpath)) {
301 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
303 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
304 .stream().findFirst().orElse(null);
306 final String normalizedXpath = getNormalizedXpath(xpath);
307 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
309 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
311 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
312 .stream().findFirst().orElse(null);
315 if (fragmentEntity == null) {
316 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
318 return fragmentEntity;
322 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
323 final String normalizedXpath) {
324 final List<FragmentExtract> fragmentExtracts =
325 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
326 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
327 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
328 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
333 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
334 final FetchDescendantsOption fetchDescendantsOption) {
335 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
336 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
337 final CpsPathQuery cpsPathQuery;
339 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
340 } catch (final PathParsingException e) {
341 throw new CpsPathException(e.getMessage());
344 Collection<FragmentEntity> fragmentEntities;
345 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
346 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
348 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
349 if (cpsPathQuery.hasAncestorAxis()) {
350 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
352 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
355 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
356 final CpsPathQuery cpsPathQuery) {
357 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
358 && !cpsPathQuery.hasLeafConditions()
359 && !cpsPathQuery.hasTextFunctionCondition();
362 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
363 final AnchorEntity anchorEntity,
364 final CpsPathQuery cpsPathQuery) {
365 Collection<FragmentEntity> fragmentEntities;
366 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
367 final List<FragmentExtract> fragmentExtracts =
368 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
369 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
370 if (cpsPathQuery.hasAncestorAxis()) {
371 fragmentEntities = getAncestorFragmentEntities(anchorEntity.getId(), cpsPathQuery, fragmentEntities);
373 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
376 private Collection<FragmentEntity> getAncestorFragmentEntities(final int anchorId,
377 final CpsPathQuery cpsPathQuery,
378 final Collection<FragmentEntity> fragmentEntities) {
379 final Collection<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
380 return ancestorXpaths.isEmpty() ? Collections.emptyList()
381 : fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorId, ancestorXpaths);
384 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
385 final FetchDescendantsOption fetchDescendantsOption,
386 final AnchorEntity anchorEntity,
387 final Collection<FragmentEntity> proxiedFragmentEntities) {
388 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
389 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
390 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
391 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
393 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
394 final Collection<FragmentEntity> unproxiedFragmentEntities =
395 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
396 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
397 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
401 return Collections.unmodifiableList(dataNodes);
404 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
405 final Collection<FragmentEntity> fragmentEntities) {
406 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
407 for (final FragmentEntity fragmentEntity : fragmentEntities) {
408 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
410 return Collections.unmodifiableList(dataNodes);
413 private static String getNormalizedXpath(final String xpathSource) {
414 final String normalizedXpath;
416 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
417 } catch (final PathParsingException e) {
418 throw new CpsPathException(e.getMessage());
420 return normalizedXpath;
424 public String startSession() {
425 return sessionManager.startSession();
429 public void closeSession(final String sessionId) {
430 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
434 public void lockAnchor(final String sessionId, final String dataspaceName,
435 final String anchorName, final Long timeoutInMilliseconds) {
436 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
439 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
440 final CpsPathQuery cpsPathQuery) {
441 final Set<String> ancestorXpath = new HashSet<>();
442 final Pattern pattern =
443 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
444 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
445 for (final FragmentEntity fragmentEntity : fragmentEntities) {
446 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
447 if (matcher.matches()) {
448 ancestorXpath.add(matcher.group(1));
451 return ancestorXpath;
454 private DataNode toDataNode(final FragmentEntity fragmentEntity,
455 final FetchDescendantsOption fetchDescendantsOption) {
456 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
457 Map<String, Serializable> leaves = new HashMap<>();
458 if (fragmentEntity.getAttributes() != null) {
459 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
461 return new DataNodeBuilder()
462 .withXpath(fragmentEntity.getXpath())
464 .withChildDataNodes(childDataNodes).build();
467 private Collection<DataNode> toDataNodes(final Collection<FragmentEntity> fragmentEntities,
468 final FetchDescendantsOption fetchDescendantsOption) {
469 final Collection<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
470 for (final FragmentEntity fragmentEntity : fragmentEntities) {
471 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
476 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
477 final FetchDescendantsOption fetchDescendantsOption) {
478 if (fetchDescendantsOption.hasNext()) {
479 return fragmentEntity.getChildFragments().stream()
480 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
481 .collect(Collectors.toList());
483 return Collections.emptyList();
487 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
488 final Map<String, Serializable> updateLeaves) {
489 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
490 final String currentLeavesAsString = fragmentEntity.getAttributes();
491 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
492 fragmentEntity.setAttributes(mergedLeaves);
493 fragmentRepository.save(fragmentEntity);
497 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
498 final DataNode dataNode) {
499 final FragmentEntity fragmentEntity =
500 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
501 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
503 fragmentRepository.save(fragmentEntity);
504 } catch (final StaleStateException staleStateException) {
505 throw new ConcurrencyException("Concurrent Transactions",
506 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
507 dataspaceName, anchorName, dataNode.getXpath()));
512 public void updateDataNodesAndDescendants(final String dataspaceName,
513 final String anchorName,
514 final List<DataNode> dataNodes) {
516 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
517 .collect(Collectors.toMap(
518 dataNode -> dataNode,
520 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
521 dataNodeFragmentEntityMap.forEach(
522 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
524 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
525 } catch (final StaleStateException staleStateException) {
526 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
530 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
531 final Collection<FragmentEntity> fragmentEntities) {
532 final Collection<String> failedXpaths = new HashSet<>();
534 fragmentEntities.forEach(dataNodeFragment -> {
536 fragmentRepository.save(dataNodeFragment);
537 } catch (final StaleStateException e) {
538 failedXpaths.add(dataNodeFragment.getXpath());
542 if (!failedXpaths.isEmpty()) {
543 final String failedXpathsConcatenated = String.join(",", failedXpaths);
544 throw new ConcurrencyException("Concurrent Transactions", String.format(
545 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
546 failedXpathsConcatenated, dataspaceName, anchorName));
550 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
551 final DataNode newDataNode) {
553 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
555 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
556 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
558 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
560 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
561 final FragmentEntity childFragment;
562 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
563 childFragment = convertToFragmentWithAllDescendants(
564 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
566 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
567 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
569 updatedChildFragments.add(childFragment);
572 existingFragmentEntity.getChildFragments().clear();
573 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
578 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
579 final Collection<DataNode> newListElements) {
580 final FragmentEntity parentEntity =
581 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
582 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
583 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
584 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
585 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
586 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
587 for (final DataNode newListElement : newListElements) {
588 final FragmentEntity existingListElementEntity =
589 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
590 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
591 existingListElementEntity);
593 updatedChildFragmentEntities.add(entityToBeAdded);
595 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
596 fragmentRepository.save(parentEntity);
601 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
602 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
603 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
605 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
610 public void deleteDataNodes(final String dataspaceName, final String anchorName,
611 final Collection<String> xpathsToDelete) {
612 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
613 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
615 final Collection<String> normalizedXpaths = new ArrayList<>(xpathsToDelete.size());
616 for (final String xpath : xpathsToDelete) {
618 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
619 } catch (final PathParsingException e) {
620 log.debug("Error parsing xpath \"{}\" in deleteDataNodes: {}", xpath, e.getMessage());
624 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), normalizedXpaths);
625 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), normalizedXpaths);
630 public void deleteListDataNode(final String dataspaceName, final String anchorName,
631 final String targetXpath) {
632 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
637 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
638 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
641 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
642 final boolean onlySupportListNodeDeletion) {
643 final String parentNodeXpath;
644 FragmentEntity parentFragmentEntity = null;
645 boolean targetDeleted;
646 if (isRootXpath(targetXpath)) {
647 deleteDataNodes(dataspaceName, anchorName);
648 targetDeleted = true;
650 if (isRootContainerNodeXpath(targetXpath)) {
651 parentNodeXpath = targetXpath;
653 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
655 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
656 if (CpsPathUtil.isPathToListElement(targetXpath)) {
657 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
659 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
660 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
661 if (tryToDeleteDataNode) {
662 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
666 if (!targetDeleted) {
667 final String additionalInformation = onlySupportListNodeDeletion
668 ? "The target is probably not a List." : "";
669 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
670 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
674 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
675 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
676 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
677 fragmentRepository.deleteFragmentEntity(parentFragmentEntity.getId());
680 if (parentFragmentEntity.getChildFragments()
681 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
682 fragmentRepository.save(parentFragmentEntity);
688 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
689 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
690 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
691 if (parentFragmentEntity.getChildFragments()
692 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
693 fragmentRepository.save(parentFragmentEntity);
699 private static void deleteListElements(
700 final Collection<FragmentEntity> fragmentEntities,
701 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
702 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
705 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
706 if (newListElements.isEmpty()) {
707 throw new CpsAdminException("Invalid list replacement",
708 "Cannot replace list elements with empty collection");
710 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
711 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
714 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
715 final DataNode newListElement,
716 final FragmentEntity existingListElementEntity) {
717 if (existingListElementEntity == null) {
718 return convertToFragmentWithAllDescendants(
719 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
721 if (newListElement.getChildDataNodes().isEmpty()) {
722 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
723 existingListElementEntity.getChildFragments().clear();
725 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
727 return existingListElementEntity;
730 private static boolean isNewDataNode(final DataNode replacementDataNode,
731 final Map<String, FragmentEntity> existingListElementsByXpath) {
732 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
735 private static boolean isRootContainerNodeXpath(final String xpath) {
736 return 0 == xpath.lastIndexOf('/');
739 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
740 final DataNode newListElement) {
741 final FragmentEntity replacementFragmentEntity =
742 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
743 newListElement.getLeaves())).build();
744 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
747 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
748 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
749 return childEntities.stream()
750 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
751 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
754 private static boolean isRootXpath(final String xpath) {
755 return "/".equals(xpath) || "".equals(xpath);
758 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
759 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
760 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
761 currentLeavesAsMap.putAll(updateLeaves);
762 if (currentLeavesAsMap.isEmpty()) {
765 return jsonObjectMapper.asJsonString(currentLeavesAsMap);