2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2022 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);
259 private FragmentEntity getFragmentWithoutDescendantsByXpath(final String dataspaceName,
260 final String anchorName,
261 final String xpath) {
262 return getFragmentByXpath(dataspaceName, anchorName, xpath, FetchDescendantsOption.OMIT_DESCENDANTS);
265 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
266 final String xpath, final FetchDescendantsOption fetchDescendantsOption) {
267 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
268 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
269 final FragmentEntity fragmentEntity;
270 if (isRootXpath(xpath)) {
271 final List<FragmentExtract> fragmentExtracts = fragmentRepository.getTopLevelFragments(dataspaceEntity,
273 fragmentEntity = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts)
274 .stream().findFirst().orElse(null);
276 final String normalizedXpath = getNormalizedXpath(xpath);
277 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
279 fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
281 fragmentEntity = buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath)
282 .stream().findFirst().orElse(null);
285 if (fragmentEntity == null) {
286 throw new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath);
288 return fragmentEntity;
292 private Collection<FragmentEntity> buildFragmentEntitiesFromFragmentExtracts(final AnchorEntity anchorEntity,
293 final String normalizedXpath) {
294 final List<FragmentExtract> fragmentExtracts =
295 fragmentRepository.findByAnchorIdAndParentXpath(anchorEntity.getId(), normalizedXpath);
296 log.debug("Fetched {} fragment entities by anchor {} and cps path {}.",
297 fragmentExtracts.size(), anchorEntity.getName(), normalizedXpath);
298 return FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
303 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
304 final FetchDescendantsOption fetchDescendantsOption) {
305 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
306 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
307 final CpsPathQuery cpsPathQuery;
309 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
310 } catch (final PathParsingException e) {
311 throw new CpsPathException(e.getMessage());
314 Collection<FragmentEntity> fragmentEntities;
315 if (canUseRegexQuickFind(fetchDescendantsOption, cpsPathQuery)) {
316 return getDataNodesUsingRegexQuickFind(fetchDescendantsOption, anchorEntity, cpsPathQuery);
318 fragmentEntities = fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
319 if (cpsPathQuery.hasAncestorAxis()) {
320 fragmentEntities = getAncestorFragmentEntities(anchorEntity, cpsPathQuery, fragmentEntities);
322 return createDataNodesFromProxiedFragmentEntities(fetchDescendantsOption, anchorEntity, fragmentEntities);
325 private static boolean canUseRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
326 final CpsPathQuery cpsPathQuery) {
327 return fetchDescendantsOption.equals(FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
328 && !cpsPathQuery.hasLeafConditions()
329 && !cpsPathQuery.hasTextFunctionCondition();
332 private List<DataNode> getDataNodesUsingRegexQuickFind(final FetchDescendantsOption fetchDescendantsOption,
333 final AnchorEntity anchorEntity,
334 final CpsPathQuery cpsPathQuery) {
335 Collection<FragmentEntity> fragmentEntities;
336 final String xpathRegex = FragmentQueryBuilder.getXpathSqlRegex(cpsPathQuery, true);
337 final List<FragmentExtract> fragmentExtracts =
338 fragmentRepository.quickFindWithDescendants(anchorEntity.getId(), xpathRegex);
339 fragmentEntities = FragmentEntityArranger.toFragmentEntityTrees(anchorEntity, fragmentExtracts);
340 if (cpsPathQuery.hasAncestorAxis()) {
341 fragmentEntities = getAncestorFragmentEntities(anchorEntity, cpsPathQuery, fragmentEntities);
343 return createDataNodesFromFragmentEntities(fetchDescendantsOption, fragmentEntities);
346 private Collection<FragmentEntity> getAncestorFragmentEntities(final AnchorEntity anchorEntity,
347 final CpsPathQuery cpsPathQuery,
348 Collection<FragmentEntity> fragmentEntities) {
349 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
350 fragmentEntities = ancestorXpaths.isEmpty() ? Collections.emptyList()
351 : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
352 return fragmentEntities;
355 private List<DataNode> createDataNodesFromProxiedFragmentEntities(
356 final FetchDescendantsOption fetchDescendantsOption,
357 final AnchorEntity anchorEntity,
358 final Collection<FragmentEntity> proxiedFragmentEntities) {
359 final List<DataNode> dataNodes = new ArrayList<>(proxiedFragmentEntities.size());
360 for (final FragmentEntity proxiedFragmentEntity : proxiedFragmentEntities) {
361 if (FetchDescendantsOption.OMIT_DESCENDANTS.equals(fetchDescendantsOption)) {
362 dataNodes.add(toDataNode(proxiedFragmentEntity, fetchDescendantsOption));
364 final String normalizedXpath = getNormalizedXpath(proxiedFragmentEntity.getXpath());
365 final Collection<FragmentEntity> unproxiedFragmentEntities =
366 buildFragmentEntitiesFromFragmentExtracts(anchorEntity, normalizedXpath);
367 for (final FragmentEntity unproxiedFragmentEntity : unproxiedFragmentEntities) {
368 dataNodes.add(toDataNode(unproxiedFragmentEntity, fetchDescendantsOption));
372 return Collections.unmodifiableList(dataNodes);
375 private List<DataNode> createDataNodesFromFragmentEntities(final FetchDescendantsOption fetchDescendantsOption,
376 final Collection<FragmentEntity> fragmentEntities) {
377 final List<DataNode> dataNodes = new ArrayList<>(fragmentEntities.size());
378 for (final FragmentEntity fragmentEntity : fragmentEntities) {
379 dataNodes.add(toDataNode(fragmentEntity, fetchDescendantsOption));
381 return Collections.unmodifiableList(dataNodes);
384 private static String getNormalizedXpath(final String xpathSource) {
385 final String normalizedXpath;
387 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpathSource);
388 } catch (final PathParsingException e) {
389 throw new CpsPathException(e.getMessage());
391 return normalizedXpath;
395 public String startSession() {
396 return sessionManager.startSession();
400 public void closeSession(final String sessionId) {
401 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
405 public void lockAnchor(final String sessionId, final String dataspaceName,
406 final String anchorName, final Long timeoutInMilliseconds) {
407 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
410 private static Set<String> processAncestorXpath(final Collection<FragmentEntity> fragmentEntities,
411 final CpsPathQuery cpsPathQuery) {
412 final Set<String> ancestorXpath = new HashSet<>();
413 final Pattern pattern =
414 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
415 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
416 for (final FragmentEntity fragmentEntity : fragmentEntities) {
417 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
418 if (matcher.matches()) {
419 ancestorXpath.add(matcher.group(1));
422 return ancestorXpath;
425 private DataNode toDataNode(final FragmentEntity fragmentEntity,
426 final FetchDescendantsOption fetchDescendantsOption) {
427 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
428 Map<String, Serializable> leaves = new HashMap<>();
429 if (fragmentEntity.getAttributes() != null) {
430 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
432 return new DataNodeBuilder()
433 .withXpath(fragmentEntity.getXpath())
435 .withChildDataNodes(childDataNodes).build();
438 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
439 final FetchDescendantsOption fetchDescendantsOption) {
440 if (fetchDescendantsOption.hasNext()) {
441 return fragmentEntity.getChildFragments().stream()
442 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption.next()))
443 .collect(Collectors.toList());
445 return Collections.emptyList();
449 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
450 final Map<String, Serializable> updateLeaves) {
451 final FragmentEntity fragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, xpath);
452 final String currentLeavesAsString = fragmentEntity.getAttributes();
453 final String mergedLeaves = mergeLeaves(updateLeaves, currentLeavesAsString);
454 fragmentEntity.setAttributes(mergedLeaves);
455 fragmentRepository.save(fragmentEntity);
459 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
460 final DataNode dataNode) {
461 final FragmentEntity fragmentEntity =
462 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath());
463 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
465 fragmentRepository.save(fragmentEntity);
466 } catch (final StaleStateException staleStateException) {
467 throw new ConcurrencyException("Concurrent Transactions",
468 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
469 dataspaceName, anchorName, dataNode.getXpath()));
474 public void updateDataNodesAndDescendants(final String dataspaceName,
475 final String anchorName,
476 final List<DataNode> dataNodes) {
478 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
479 .collect(Collectors.toMap(
480 dataNode -> dataNode,
482 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, dataNode.getXpath())));
483 dataNodeFragmentEntityMap.forEach(
484 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
486 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
487 } catch (final StaleStateException staleStateException) {
488 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
492 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
493 final Collection<FragmentEntity> fragmentEntities) {
494 final Collection<String> failedXpaths = new HashSet<>();
496 fragmentEntities.forEach(dataNodeFragment -> {
498 fragmentRepository.save(dataNodeFragment);
499 } catch (final StaleStateException e) {
500 failedXpaths.add(dataNodeFragment.getXpath());
504 if (!failedXpaths.isEmpty()) {
505 final String failedXpathsConcatenated = String.join(",", failedXpaths);
506 throw new ConcurrencyException("Concurrent Transactions", String.format(
507 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
508 failedXpathsConcatenated, dataspaceName, anchorName));
512 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
513 final DataNode newDataNode) {
515 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
517 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
518 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
520 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
522 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
523 final FragmentEntity childFragment;
524 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
525 childFragment = convertToFragmentWithAllDescendants(
526 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
528 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
529 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
531 updatedChildFragments.add(childFragment);
534 existingFragmentEntity.getChildFragments().clear();
535 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
540 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
541 final Collection<DataNode> newListElements) {
542 final FragmentEntity parentEntity =
543 getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
544 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
545 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
546 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
547 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
548 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
549 for (final DataNode newListElement : newListElements) {
550 final FragmentEntity existingListElementEntity =
551 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
552 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
553 existingListElementEntity);
555 updatedChildFragmentEntities.add(entityToBeAdded);
557 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
558 fragmentRepository.save(parentEntity);
563 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
564 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
565 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
567 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
572 public void deleteListDataNode(final String dataspaceName, final String anchorName,
573 final String targetXpath) {
574 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
579 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
580 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
583 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
584 final boolean onlySupportListNodeDeletion) {
585 final String parentNodeXpath;
586 FragmentEntity parentFragmentEntity = null;
587 boolean targetDeleted;
588 if (isRootXpath(targetXpath)) {
589 deleteDataNodes(dataspaceName, anchorName);
590 targetDeleted = true;
592 if (isRootContainerNodeXpath(targetXpath)) {
593 parentNodeXpath = targetXpath;
595 parentNodeXpath = CpsPathUtil.getNormalizedParentXpath(targetXpath);
597 parentFragmentEntity = getFragmentWithoutDescendantsByXpath(dataspaceName, anchorName, parentNodeXpath);
598 if (CpsPathUtil.isPathToListElement(targetXpath)) {
599 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
601 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
602 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
603 if (tryToDeleteDataNode) {
604 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
608 if (!targetDeleted) {
609 final String additionalInformation = onlySupportListNodeDeletion
610 ? "The target is probably not a List." : "";
611 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
612 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
616 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
617 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
618 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
619 fragmentRepository.delete(parentFragmentEntity);
622 if (parentFragmentEntity.getChildFragments()
623 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
624 fragmentRepository.save(parentFragmentEntity);
630 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
631 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
632 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
633 if (parentFragmentEntity.getChildFragments()
634 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
635 fragmentRepository.save(parentFragmentEntity);
641 private static void deleteListElements(
642 final Collection<FragmentEntity> fragmentEntities,
643 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
644 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
647 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
648 if (newListElements.isEmpty()) {
649 throw new CpsAdminException("Invalid list replacement",
650 "Cannot replace list elements with empty collection");
652 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
653 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
656 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
657 final DataNode newListElement,
658 final FragmentEntity existingListElementEntity) {
659 if (existingListElementEntity == null) {
660 return convertToFragmentWithAllDescendants(
661 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
663 if (newListElement.getChildDataNodes().isEmpty()) {
664 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
665 existingListElementEntity.getChildFragments().clear();
667 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
669 return existingListElementEntity;
672 private static boolean isNewDataNode(final DataNode replacementDataNode,
673 final Map<String, FragmentEntity> existingListElementsByXpath) {
674 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
677 private static boolean isRootContainerNodeXpath(final String xpath) {
678 return 0 == xpath.lastIndexOf('/');
681 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
682 final DataNode newListElement) {
683 final FragmentEntity replacementFragmentEntity =
684 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
685 newListElement.getLeaves())).build();
686 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
689 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
690 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
691 return childEntities.stream()
692 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
693 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
696 private static boolean isRootXpath(final String xpath) {
697 return "/".equals(xpath) || "".equals(xpath);
700 private String mergeLeaves(final Map<String, Serializable> updateLeaves, final String currentLeavesAsString) {
701 final Map<String, Serializable> currentLeavesAsMap = currentLeavesAsString.isEmpty()
702 ? new HashMap<>() : jsonObjectMapper.convertJsonString(currentLeavesAsString, Map.class);
703 currentLeavesAsMap.putAll(updateLeaves);
704 if (currentLeavesAsMap.isEmpty()) {
707 return jsonObjectMapper.asJsonString(currentLeavesAsMap);