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 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.spi.impl;
25 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
27 import com.google.common.collect.ImmutableSet;
28 import com.google.common.collect.ImmutableSet.Builder;
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.SchemaSetEntity;
53 import org.onap.cps.spi.entities.YangResourceEntity;
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.FragmentRepository;
65 import org.onap.cps.spi.utils.SessionManager;
66 import org.onap.cps.utils.JsonObjectMapper;
67 import org.onap.cps.yang.YangTextSchemaSourceSetBuilder;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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;
79 private final AnchorRepository anchorRepository;
81 private final FragmentRepository fragmentRepository;
83 private final JsonObjectMapper jsonObjectMapper;
85 private final SessionManager sessionManager;
87 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
88 private static final Pattern REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE =
89 Pattern.compile("\\[(\\@([^\\/]{0,9999}))\\]$");
92 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
93 final DataNode newChildDataNode) {
94 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChildDataNode);
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 = getFragmentByXpath(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 = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
139 final List<FragmentEntity> fragmentEntities = new ArrayList<>(newChildren.size());
141 newChildren.forEach(newChildAsDataNode -> {
142 final FragmentEntity newChildAsFragmentEntity =
143 convertToFragmentWithAllDescendants(parentFragmentEntity.getDataspace(),
144 parentFragmentEntity.getAnchor(), newChildAsDataNode);
145 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
146 fragmentEntities.add(newChildAsFragmentEntity);
148 fragmentRepository.saveAll(fragmentEntities);
149 } catch (final DataIntegrityViolationException e) {
150 log.warn("Exception occurred : {} , While saving : {} children, retrying using individual save operations",
151 e, fragmentEntities.size());
152 retrySavingEachChildIndividually(dataspaceName, anchorName, parentNodeXpath, newChildren);
156 private void retrySavingEachChildIndividually(final String dataspaceName, final String anchorName,
157 final String parentNodeXpath, final Collection<DataNode> newChildren) {
158 final Collection<String> failedXpaths = new HashSet<>();
159 for (final DataNode newChild : newChildren) {
161 addNewChildDataNode(dataspaceName, anchorName, parentNodeXpath, newChild);
162 } catch (final AlreadyDefinedException e) {
163 failedXpaths.add(newChild.getXpath());
166 if (!failedXpaths.isEmpty()) {
167 throw new AlreadyDefinedExceptionBatch(failedXpaths);
172 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
173 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
174 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
175 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
178 fragmentRepository.save(fragmentEntity);
179 } catch (final DataIntegrityViolationException exception) {
180 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
185 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
186 * for all DataNode children recursively.
188 * @param dataspaceEntity dataspace
189 * @param anchorEntity anchorEntity
190 * @param dataNodeToBeConverted dataNode
191 * @return a Fragment built from current DataNode
193 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
194 final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
195 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
196 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
197 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
198 final FragmentEntity childFragment =
199 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
201 childFragmentsImmutableSetBuilder.add(childFragment);
203 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
204 return parentFragment;
207 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
208 final AnchorEntity anchorEntity, final DataNode dataNode) {
209 return FragmentEntity.builder()
210 .dataspace(dataspaceEntity)
211 .anchor(anchorEntity)
212 .xpath(dataNode.getXpath())
213 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
218 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
219 final FetchDescendantsOption fetchDescendantsOption) {
220 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
221 return toDataNode(fragmentEntity, fetchDescendantsOption);
224 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
225 final String xpath) {
226 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
227 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
228 if (isRootXpath(xpath)) {
229 return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
231 final String normalizedXpath;
233 normalizedXpath = CpsPathUtil.getNormalizedXpath(xpath);
234 } catch (final PathParsingException e) {
235 throw new CpsPathException(e.getMessage());
238 return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, normalizedXpath);
243 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
244 final FetchDescendantsOption fetchDescendantsOption) {
245 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
246 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
247 final CpsPathQuery cpsPathQuery;
249 cpsPathQuery = CpsPathUtil.getCpsPathQuery(cpsPath);
250 } catch (final PathParsingException e) {
251 throw new CpsPathException(e.getMessage());
253 List<FragmentEntity> fragmentEntities =
254 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
255 if (cpsPathQuery.hasAncestorAxis()) {
256 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
257 fragmentEntities = ancestorXpaths.isEmpty() ? Collections.emptyList()
258 : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
260 return fragmentEntities.stream()
261 .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
262 .collect(Collectors.toUnmodifiableList());
266 public String startSession() {
267 return sessionManager.startSession();
271 public void closeSession(final String sessionId) {
272 sessionManager.closeSession(sessionId, SessionManager.WITH_COMMIT);
276 public void lockAnchor(final String sessionId, final String dataspaceName,
277 final String anchorName, final Long timeoutInMilliseconds) {
278 sessionManager.lockAnchor(sessionId, dataspaceName, anchorName, timeoutInMilliseconds);
281 private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
282 final CpsPathQuery cpsPathQuery) {
283 final Set<String> ancestorXpath = new HashSet<>();
284 final Pattern pattern =
285 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
286 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
287 for (final FragmentEntity fragmentEntity : fragmentEntities) {
288 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
289 if (matcher.matches()) {
290 ancestorXpath.add(matcher.group(1));
293 return ancestorXpath;
296 private DataNode toDataNode(final FragmentEntity fragmentEntity,
297 final FetchDescendantsOption fetchDescendantsOption) {
298 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
299 Map<String, Object> leaves = new HashMap<>();
300 if (fragmentEntity.getAttributes() != null) {
301 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
303 return new DataNodeBuilder()
304 .withModuleNamePrefix(getFirstModuleName(fragmentEntity))
305 .withXpath(fragmentEntity.getXpath())
307 .withChildDataNodes(childDataNodes).build();
310 private String getFirstModuleName(final FragmentEntity fragmentEntity) {
311 final SchemaSetEntity schemaSetEntity = fragmentEntity.getAnchor().getSchemaSet();
312 final Map<String, String> yangResourceNameToContent =
313 schemaSetEntity.getYangResources().stream().collect(
314 Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent));
315 final SchemaContext schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent)
317 return schemaContext.getModules().iterator().next().getName();
320 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
321 final FetchDescendantsOption fetchDescendantsOption) {
322 if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
323 return fragmentEntity.getChildFragments().stream()
324 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
325 .collect(Collectors.toUnmodifiableList());
327 return Collections.emptyList();
331 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
332 final Map<String, Object> leaves) {
333 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
334 fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
335 fragmentRepository.save(fragmentEntity);
339 public void updateDataNodeAndDescendants(final String dataspaceName, final String anchorName,
340 final DataNode dataNode) {
341 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
342 updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode);
344 fragmentRepository.save(fragmentEntity);
345 } catch (final StaleStateException staleStateException) {
346 throw new ConcurrencyException("Concurrent Transactions",
347 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
348 dataspaceName, anchorName, dataNode.getXpath()));
353 public void updateDataNodesAndDescendants(final String dataspaceName,
354 final String anchorName,
355 final List<DataNode> dataNodes) {
357 final Map<DataNode, FragmentEntity> dataNodeFragmentEntityMap = dataNodes.stream()
358 .collect(Collectors.toMap(
359 dataNode -> dataNode, dataNode -> getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath())));
360 dataNodeFragmentEntityMap.forEach(
361 (dataNode, fragmentEntity) -> updateFragmentEntityAndDescendantsWithDataNode(fragmentEntity, dataNode));
363 fragmentRepository.saveAll(dataNodeFragmentEntityMap.values());
364 } catch (final StaleStateException staleStateException) {
365 retryUpdateDataNodesIndividually(dataspaceName, anchorName, dataNodeFragmentEntityMap.values());
369 private void retryUpdateDataNodesIndividually(final String dataspaceName, final String anchorName,
370 final Collection<FragmentEntity> fragmentEntities) {
371 final Collection<String> failedXpaths = new HashSet<>();
373 fragmentEntities.forEach(dataNodeFragment -> {
375 fragmentRepository.save(dataNodeFragment);
376 } catch (final StaleStateException e) {
377 failedXpaths.add(dataNodeFragment.getXpath());
381 if (!failedXpaths.isEmpty()) {
382 final String failedXpathsConcatenated = String.join(",", failedXpaths);
383 throw new ConcurrencyException("Concurrent Transactions", String.format(
384 "DataNodes : %s in Dataspace :'%s' with Anchor : '%s' are updated by another transaction.",
385 failedXpathsConcatenated, dataspaceName, anchorName));
389 private void updateFragmentEntityAndDescendantsWithDataNode(final FragmentEntity existingFragmentEntity,
390 final DataNode newDataNode) {
392 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
394 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments().stream()
395 .collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
397 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
399 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
400 final FragmentEntity childFragment;
401 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
402 childFragment = convertToFragmentWithAllDescendants(
403 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
405 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
406 updateFragmentEntityAndDescendantsWithDataNode(childFragment, newDataNodeChild);
408 updatedChildFragments.add(childFragment);
411 existingFragmentEntity.getChildFragments().clear();
412 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
417 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
418 final Collection<DataNode> newListElements) {
419 final FragmentEntity parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
420 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
421 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
422 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
423 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
424 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
425 for (final DataNode newListElement : newListElements) {
426 final FragmentEntity existingListElementEntity =
427 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
428 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
429 existingListElementEntity);
431 updatedChildFragmentEntities.add(entityToBeAdded);
433 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
434 fragmentRepository.save(parentEntity);
439 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
440 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
441 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
443 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
448 public void deleteListDataNode(final String dataspaceName, final String anchorName,
449 final String targetXpath) {
450 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
455 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
456 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
459 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
460 final boolean onlySupportListNodeDeletion) {
461 final String parentNodeXpath;
462 FragmentEntity parentFragmentEntity = null;
463 boolean targetDeleted = false;
464 if (isRootXpath(targetXpath)) {
465 deleteDataNodes(dataspaceName, anchorName);
466 targetDeleted = true;
468 if (isRootContainerNodeXpath(targetXpath)) {
469 parentNodeXpath = targetXpath;
471 parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
473 parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
474 final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
475 final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE
476 .matcher(lastXpathElement).find();
478 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
480 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
481 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
482 if (tryToDeleteDataNode) {
483 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
487 if (!targetDeleted) {
488 final String additionalInformation = onlySupportListNodeDeletion
489 ? "The target is probably not a List." : "";
490 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
491 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
495 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
496 final String normalizedTargetXpath = CpsPathUtil.getNormalizedXpath(targetXpath);
497 if (parentFragmentEntity.getXpath().equals(normalizedTargetXpath)) {
498 fragmentRepository.delete(parentFragmentEntity);
501 if (parentFragmentEntity.getChildFragments()
502 .removeIf(fragment -> fragment.getXpath().equals(normalizedTargetXpath))) {
503 fragmentRepository.save(parentFragmentEntity);
509 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
510 final String normalizedListXpath = CpsPathUtil.getNormalizedXpath(listXpath);
511 final String deleteTargetXpathPrefix = normalizedListXpath + "[";
512 if (parentFragmentEntity.getChildFragments()
513 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
514 fragmentRepository.save(parentFragmentEntity);
520 private static void deleteListElements(
521 final Collection<FragmentEntity> fragmentEntities,
522 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
523 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
526 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
527 if (newListElements.isEmpty()) {
528 throw new CpsAdminException("Invalid list replacement",
529 "Cannot replace list elements with empty collection");
531 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
532 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
535 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
536 final DataNode newListElement,
537 final FragmentEntity existingListElementEntity) {
538 if (existingListElementEntity == null) {
539 return convertToFragmentWithAllDescendants(
540 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
542 if (newListElement.getChildDataNodes().isEmpty()) {
543 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
544 existingListElementEntity.getChildFragments().clear();
546 updateFragmentEntityAndDescendantsWithDataNode(existingListElementEntity, newListElement);
548 return existingListElementEntity;
551 private static boolean isNewDataNode(final DataNode replacementDataNode,
552 final Map<String, FragmentEntity> existingListElementsByXpath) {
553 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
556 private static boolean isRootContainerNodeXpath(final String xpath) {
557 return 0 == xpath.lastIndexOf('/');
560 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
561 final DataNode newListElement) {
562 final FragmentEntity replacementFragmentEntity =
563 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
564 newListElement.getLeaves())).build();
565 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
568 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
569 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
570 return childEntities.stream()
571 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
572 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
575 private static boolean isRootXpath(final String xpath) {
576 return "/".equals(xpath) || "".equals(xpath);