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.exceptions.DataNodeNotFoundExceptionBatch;
61 import org.onap.cps.spi.model.DataNode;
62 import org.onap.cps.spi.model.DataNodeBuilder;
63 import org.onap.cps.spi.repository.AnchorRepository;
64 import org.onap.cps.spi.repository.DataspaceRepository;
65 import org.onap.cps.spi.repository.FragmentQueryBuilder;
66 import org.onap.cps.spi.repository.FragmentRepository;
67 import org.onap.cps.spi.utils.SessionManager;
68 import org.onap.cps.utils.JsonObjectMapper;
69 import org.springframework.dao.DataIntegrityViolationException;
70 import org.springframework.stereotype.Service;
74 @RequiredArgsConstructor
75 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
77 private final DataspaceRepository dataspaceRepository;
78 private final AnchorRepository anchorRepository;
79 private final FragmentRepository fragmentRepository;
80 private final JsonObjectMapper jsonObjectMapper;
81 private final SessionManager sessionManager;
83 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
86 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
87 final DataNode newChildDataNode) {
88 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
92 public void addChildDataNodes(final String dataspaceName, final String anchorName,
93 final String parentNodeXpath, final Collection<DataNode> dataNodes) {
94 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, dataNodes);
98 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
99 final Collection<DataNode> newListElements) {
100 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
104 public void addMultipleLists(final String dataspaceName, final String anchorName, final String parentNodeXpath,
105 final Collection<Collection<DataNode>> newLists) {
106 final Collection<String> failedXpaths = new HashSet<>();
107 newLists.forEach(newList -> {
109 addChildrenDataNodes(dataspaceName, anchorName, parentNodeXpath, newList);
110 } catch (final AlreadyDefinedExceptionBatch e) {
111 failedXpaths.addAll(e.getAlreadyDefinedXpaths());
115 if (!failedXpaths.isEmpty()) {
116 throw new AlreadyDefinedExceptionBatch(failedXpaths);
121 private void addNewChildDataNode(final String dataspaceName, final String anchorName,
122 final String parentNodeXpath, final DataNode newChild) {
123 final FragmentEntity parentFragmentEntity =
124 getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
125 final FragmentEntity newChildAsFragmentEntity =
126 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
127 parentFragmentEntity.getAnchor(), newChild);
128 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
130 fragmentRepository.save(newChildAsFragmentEntity);
131 } catch (final DataIntegrityViolationException e) {
132 throw AlreadyDefinedException.forDataNode(newChild.getXpath(), anchorName, e);
137 private void addChildrenDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
138 final Collection<DataNode> newChildren) {
139 final FragmentEntity parentFragmentEntity =
140 getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
141 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
143 newChildren.forEach(newChildAsDataNode -> {
144 final FragmentEntity newChildAsFragmentEntity =
145 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
146 parentFragmentEntity.getAnchor(), 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(dataspaceName, anchorName, parentNodeXpath, newChildren);
158 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
159 final String parentNodeXpath,
160 final Collection<DataNode> newChildren) {
161 final Collection<String> failedXpaths = new HashSet<>();
162 for (final DataNode newChild : newChildren) {
164 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
165 } catch (final AlreadyDefinedException e) {
166 failedXpaths.add(newChild.getXpath());
169 if (!failedXpaths.isEmpty()) {
170 throw new AlreadyDefinedExceptionBatch(failedXpaths);
175 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
176 storeDataNodes(dataspaceName, anchorName, Collections.singletonList(dataNode));
180 public void storeDataNodes(final String dataspaceName, final String anchorName,
181 final Collection<DataNode> dataNodes) {
182 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
183 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
184 final List<FragmentEntity> fragmentEntities = new ArrayList<>(dataNodes.size());
186 for (final DataNode dataNode: dataNodes) {
187 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
189 fragmentEntities.add(fragmentEntity);
191 fragmentRepository.saveAll(fragmentEntities);
192 } catch (final DataIntegrityViolationException exception) {
193 log.warn("Exception occurred : {} , While saving : {} data nodes, Retrying saving data nodes individually",
194 exception, dataNodes.size());
195 storeDataNodesIndividually(dataspaceName, anchorName, dataNodes);
199 private void storeDataNodesIndividually(final String dataspaceName, final String anchorName,
200 final Collection<DataNode> dataNodes) {
201 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
202 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
203 final Collection<String> failedXpaths = new HashSet<>();
204 for (final DataNode dataNode: dataNodes) {
206 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
208 fragmentRepository.save(fragmentEntity);
209 } catch (final DataIntegrityViolationException e) {
210 failedXpaths.add(dataNode.getXpath());
213 if (!failedXpaths.isEmpty()) {
214 throw new AlreadyDefinedExceptionBatch(failedXpaths);
219 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
220 * for all DataNode children recursively.
222 * @param dataspaceEntity dataspace
223 * @param anchorEntity anchorEntity
224 * @param dataNodeToBeConverted dataNode
225 * @return a Fragment built from current DataNode
227 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
228 final AnchorEntity anchorEntity,
229 final DataNode dataNodeToBeConverted) {
230 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
231 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
232 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
233 final FragmentEntity childFragment =
234 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
236 childFragmentsImmutableSetBuilder.add(childFragment);
238 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
239 return parentFragment;
242 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
243 final AnchorEntity anchorEntity, final DataNode dataNode) {
244 return FragmentEntity.builder()
245 .dataspace(dataspaceEntity)
246 .anchor(anchorEntity)
247 .xpath(dataNode.getXpath())
248 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
253 public Collection<DataNode> getDataNodes(final String dataspaceName, final String anchorName,
255 final FetchDescendantsOption fetchDescendantsOption) {
256 final String targetXpath = isRootXpath(xpath) ? xpath : CpsPathUtil.getNormalizedXpath(xpath);
257 final Collection<DataNode> dataNodes = getDataNodesForMultipleXpaths(dataspaceName, anchorName,
258 Collections.singletonList(targetXpath), fetchDescendantsOption);
259 if (dataNodes.isEmpty()) {
260 throw new DataNodeNotFoundException(dataspaceName, anchorName, xpath);
266 public Collection<DataNode> getDataNodesForMultipleXpaths(final String dataspaceName, final String anchorName,
267 final Collection<String> xpaths,
268 final FetchDescendantsOption fetchDescendantsOption) {
269 final Collection<FragmentEntity> fragmentEntities = getFragmentEntities(dataspaceName, anchorName, xpaths);
270 return toDataNodes(fragmentEntities, fetchDescendantsOption);
273 private Collection<FragmentEntity> getFragmentEntities(final String dataspaceName, final String anchorName,
274 final Collection<String> xpaths) {
275 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
276 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
278 final Collection<String> nonRootXpaths = new HashSet<>(xpaths);
279 final boolean haveRootXpath = nonRootXpaths.removeIf(CpsDataPersistenceServiceImpl::isRootXpath);
281 final Collection<String> normalizedXpaths = new HashSet<>(nonRootXpaths.size());
282 for (final String xpath : nonRootXpaths) {
284 normalizedXpaths.add(CpsPathUtil.getNormalizedXpath(xpath));
285 } catch (final PathParsingException e) {
286 log.warn("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
289 final Collection<FragmentEntity> fragmentEntities =
290 new HashSet<>(fragmentRepository.findByAnchorAndMultipleCpsPaths(anchorEntity.getId(), normalizedXpaths));
293 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
295 fragmentEntities.addAll(FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts));
298 return fragmentEntities;
301 private FragmentEntity getFragmentEntity(final String dataspaceName, final String anchorName, final String xpath) {
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);
313 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
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 = getFragmentEntity(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 = getFragmentEntity(dataspaceName, anchorName, dataNode.getXpath());
500 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
502 fragmentRepository.save(fragmentEntity);
503 } catch (final StaleStateException staleStateException) {
504 throw new ConcurrencyException("Concurrent Transactions",
505 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
506 dataspaceName, anchorName, dataNode.getXpath()));
511 public void updateDataNodesAndDescendants(final String dataspaceName, final String anchorName,
512 final List<DataNode> updatedDataNodes) {
513 final Map<String, DataNode> xpathToUpdatedDataNode = updatedDataNodes.stream()
514 .collect(Collectors.toMap(DataNode::getXpath, dataNode -> dataNode));
516 final Collection<String> xpaths = xpathToUpdatedDataNode.keySet();
517 final Collection<FragmentEntity> existingFragmentEntities =
518 getFragmentEntities(dataspaceName, anchorName, xpaths);
520 for (final FragmentEntity existingFragmentEntity : existingFragmentEntities) {
521 final DataNode updatedDataNode = xpathToUpdatedDataNode.get(existingFragmentEntity.getXpath());
522 updateFragmentEntityAndDescendantsWithDataNode(existingFragmentEntity, updatedDataNode);
526 fragmentRepository.saveAll(existingFragmentEntities);
527 } catch (final StaleStateException staleStateException) {
528 retryUpdateDataNodesIndividually(dataspaceName, anchorName, existingFragmentEntities);
532 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
533 final Collection<FragmentEntity> fragmentEntities) {
534 final Collection<String> failedXpaths = new HashSet<>();
536 fragmentEntities.forEach(dataNodeFragment -> {
538 fragmentRepository.save(dataNodeFragment);
539 } catch (final StaleStateException e) {
540 failedXpaths.add(dataNodeFragment.getXpath());
544 if (!failedXpaths.isEmpty()) {
545 final String failedXpathsConcatenated = String.join(",", failedXpaths);
546 throw new ConcurrencyException("Concurrent Transactions", String.format(
547 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
548 failedXpathsConcatenated, dataspaceName, anchorName));
552 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
553 final DataNode newDataNode) {
555 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
557 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
558 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
560 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
562 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
563 final FragmentEntity childFragment;
564 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
565 childFragment = convertToFragmentWithAllDescendants(
566 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
568 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
569 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
571 updatedChildFragments.add(childFragment);
574 existingFragmentEntity.getChildFragments().clear();
575 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
580 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
581 final Collection<DataNode> newListElements) {
582 final FragmentEntity parentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
583 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
584 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
585 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
586 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
587 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
588 for (final DataNode newListElement : newListElements) {
589 final FragmentEntity existingListElementEntity =
590 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
591 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
592 existingListElementEntity);
594 updatedChildFragmentEntities.add(entityToBeAdded);
596 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
597 fragmentRepository.save(parentEntity);
602 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
603 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
604 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
606 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
611 public void deleteDataNodes(final String dataspaceName, final Collection<String> anchorNames) {
612 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
613 final Collection<AnchorEntity> anchorEntities =
614 anchorRepository.findAllByDataspaceAndNameIn(dataspaceEntity, anchorNames);
615 fragmentRepository.deleteByAnchorIn(anchorEntities);
620 public void deleteDataNodes(final String dataspaceName, final String anchorName,
621 final Collection<String> xpathsToDelete) {
622 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
623 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
625 final Collection<String> deleteChecklist = new HashSet<>(xpathsToDelete.size());
626 for (final String xpath : xpathsToDelete) {
628 deleteChecklist.add(CpsPathUtil.getNormalizedXpath(xpath));
629 } catch (final PathParsingException e) {
630 log.debug("Error parsing xpath \"{}\": {}", xpath, e.getMessage());
634 final Collection<String> xpathsToExistingContainers =
635 fragmentRepository.findAllXpathByAnchorAndXpathIn(anchorEntity, deleteChecklist);
636 deleteChecklist.removeAll(xpathsToExistingContainers);
638 final Collection<String> xpathsToExistingLists = deleteChecklist.stream()
639 .filter(xpath -> fragmentRepository.existsByAnchorAndXpathStartsWith(anchorEntity, xpath + "["))
640 .collect(Collectors.toList());
641 deleteChecklist.removeAll(xpathsToExistingLists);
643 if (!deleteChecklist.isEmpty()) {
644 throw new DataNodeNotFoundExceptionBatch(dataspaceName, anchorName, deleteChecklist);
647 fragmentRepository.deleteByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingContainers);
648 fragmentRepository.deleteListsByAnchorIdAndXpaths(anchorEntity.getId(), xpathsToExistingLists);
653 public void deleteListDataNode(final String dataspaceName, final String anchorName,
654 final String targetXpath) {
655 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
660 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
661 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
664 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
665 final boolean onlySupportListNodeDeletion) {
666 final String parentNodeXpath;
667 FragmentEntity parentFragmentEntity = null;
668 boolean targetDeleted;
669 if (isRootXpath(targetXpath)) {
670 deleteDataNodes(dataspaceName, anchorName);
671 targetDeleted = true;
673 if (isRootContainerNodeXpath(targetXpath)) {
674 parentNodeXpath = targetXpath;
676 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
678 parentFragmentEntity = getFragmentEntity(dataspaceName, anchorName, parentNodeXpath);
679 if (CpsPathUtil.isPathToListElement(targetXpath)) {
680 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
682 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
683 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
684 if (tryToDeleteDataNode) {
685 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
689 if (!targetDeleted) {
690 final String additionalInformation = onlySupportListNodeDeletion
691 ? "The target is probably not a List." : "";
692 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
693 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
697 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
698 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
699 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
700 fragmentRepository.deleteFragmentEntity(parentFragmentEntity.getId());
703 if (parentFragmentEntity.getChildFragments()
704 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
705 fragmentRepository.save(parentFragmentEntity);
711 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
712 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
713 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
714 if (parentFragmentEntity.getChildFragments()
715 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
716 fragmentRepository.save(parentFragmentEntity);
722 private static void deleteListElements(
723 final Collection<FragmentEntity> fragmentEntities,
724 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
725 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
728 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
729 if (newListElements.isEmpty()) {
730 throw new CpsAdminException("Invalid list replacement",
731 "Cannot replace list elements with empty collection");
733 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
734 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
737 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
738 final DataNode newListElement,
739 final FragmentEntity existingListElementEntity) {
740 if (existingListElementEntity == null) {
741 return convertToFragmentWithAllDescendants(
742 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
744 if (newListElement.getChildDataNodes().isEmpty()) {
745 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
746 existingListElementEntity.getChildFragments().clear();
748 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
750 return existingListElementEntity;
753 private static boolean isNewDataNode(final DataNode replacementDataNode,
754 final Map<String, FragmentEntity> existingListElementsByXpath) {
755 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
758 private static boolean isRootContainerNodeXpath(final String xpath) {
759 return 0 == xpath.lastIndexOf('/');
762 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
763 final DataNode newListElement) {
764 final FragmentEntity replacementFragmentEntity =
765 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
766 newListElement.getLeaves())).build();
767 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
770 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
771 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
772 return childEntities.stream()
773 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
774 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
777 private static boolean isRootXpath(final String xpath) {
778 return "/".equals(xpath) || "".equals(xpath);
781 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
782 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
783 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
784 currentLeavesAsMap.putAll(updateLeaves);
785 if (currentLeavesAsMap.isEmpty()) {
788 return jsonObjectMapper.asJsonString(currentLeavesAsMap);