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.Collection;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import javax.transaction.Transactional;
40 import lombok.RequiredArgsConstructor;
41 import lombok.extern.slf4j.Slf4j;
42 import org.hibernate.StaleStateException;
43 import org.onap.cps.cpspath.parser.CpsPathQuery;
44 import org.onap.cps.spi.CpsDataPersistenceService;
45 import org.onap.cps.spi.FetchDescendantsOption;
46 import org.onap.cps.spi.entities.AnchorEntity;
47 import org.onap.cps.spi.entities.DataspaceEntity;
48 import org.onap.cps.spi.entities.FragmentEntity;
49 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
50 import org.onap.cps.spi.exceptions.ConcurrencyException;
51 import org.onap.cps.spi.exceptions.CpsAdminException;
52 import org.onap.cps.spi.exceptions.CpsPathException;
53 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
54 import org.onap.cps.spi.model.DataNode;
55 import org.onap.cps.spi.model.DataNodeBuilder;
56 import org.onap.cps.spi.repository.AnchorRepository;
57 import org.onap.cps.spi.repository.DataspaceRepository;
58 import org.onap.cps.spi.repository.FragmentRepository;
59 import org.onap.cps.spi.utils.SessionManager;
60 import org.onap.cps.utils.JsonObjectMapper;
61 import org.springframework.dao.DataIntegrityViolationException;
62 import org.springframework.stereotype.Service;
66 @RequiredArgsConstructor
67 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
69 private final DataspaceRepository dataspaceRepository;
71 private final AnchorRepository anchorRepository;
73 private final FragmentRepository fragmentRepository;
75 private final JsonObjectMapper jsonObjectMapper;
77 private final SessionManager sessionManager;
79 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
80 private static final Pattern REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE =
81 Pattern.compile("\\[(\\@([^\\/]{0,9999}))\\]$");
85 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
86 final DataNode newChildDataNode) {
87 addChildDataNodes(dataspaceName, anchorName, parentNodeXpath, Collections.singleton(newChildDataNode));
92 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
93 final Collection<DataNode> newListElements) {
94 addChildDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
97 private void addChildDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
98 final Collection<DataNode> newChildren) {
99 final FragmentEntity parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
101 for (final DataNode newChildAsDataNode : newChildren) {
102 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(
103 parentFragmentEntity.getDataspace(),
104 parentFragmentEntity.getAnchor(),
106 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
107 fragmentRepository.save(newChildAsFragmentEntity);
109 } catch (final DataIntegrityViolationException exception) {
110 final List<String> conflictXpaths = newChildren.stream()
111 .map(DataNode::getXpath)
112 .collect(Collectors.toList());
113 throw AlreadyDefinedException.forDataNodes(conflictXpaths, anchorName, exception);
118 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
119 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
120 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
121 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
124 fragmentRepository.save(fragmentEntity);
125 } catch (final DataIntegrityViolationException exception) {
126 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
131 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
132 * for all DataNode children recursively.
134 * @param dataspaceEntity dataspace
135 * @param anchorEntity anchorEntity
136 * @param dataNodeToBeConverted dataNode
137 * @return a Fragment built from current DataNode
139 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
140 final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
141 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
142 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
143 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
144 final FragmentEntity childFragment =
145 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
147 childFragmentsImmutableSetBuilder.add(childFragment);
149 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
150 return parentFragment;
153 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
154 final AnchorEntity anchorEntity, final DataNode dataNode) {
155 return FragmentEntity.builder()
156 .dataspace(dataspaceEntity)
157 .anchor(anchorEntity)
158 .xpath(dataNode.getXpath())
159 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
164 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
165 final FetchDescendantsOption fetchDescendantsOption) {
166 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
167 return toDataNode(fragmentEntity, fetchDescendantsOption);
170 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
171 final String xpath) {
172 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
173 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
174 if (isRootXpath(xpath)) {
175 return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
177 return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
183 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
184 final FetchDescendantsOption fetchDescendantsOption) {
185 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
186 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
187 final CpsPathQuery cpsPathQuery;
189 cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
190 } catch (final IllegalStateException e) {
191 throw new CpsPathException(e.getMessage());
193 List<FragmentEntity> fragmentEntities =
194 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
195 if (cpsPathQuery.hasAncestorAxis()) {
196 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
197 fragmentEntities = ancestorXpaths.isEmpty()
198 ? Collections.emptyList() : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
200 return fragmentEntities.stream()
201 .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
202 .collect(Collectors.toUnmodifiableList());
206 public String startSession() {
207 return sessionManager.startSession();
211 public void closeSession(final String sessionId) {
212 sessionManager.closeSession(sessionId);
215 private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
216 final CpsPathQuery cpsPathQuery) {
217 final Set<String> ancestorXpath = new HashSet<>();
218 final Pattern pattern =
219 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
220 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
221 for (final FragmentEntity fragmentEntity : fragmentEntities) {
222 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
223 if (matcher.matches()) {
224 ancestorXpath.add(matcher.group(1));
227 return ancestorXpath;
230 private DataNode toDataNode(final FragmentEntity fragmentEntity,
231 final FetchDescendantsOption fetchDescendantsOption) {
232 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
233 Map<String, Object> leaves = new HashMap<>();
234 if (fragmentEntity.getAttributes() != null) {
235 leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
237 return new DataNodeBuilder()
238 .withXpath(fragmentEntity.getXpath())
240 .withChildDataNodes(childDataNodes).build();
243 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
244 final FetchDescendantsOption fetchDescendantsOption) {
245 if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
246 return fragmentEntity.getChildFragments().stream()
247 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
248 .collect(Collectors.toUnmodifiableList());
250 return Collections.emptyList();
254 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
255 final Map<String, Object> leaves) {
256 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
257 fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
258 fragmentRepository.save(fragmentEntity);
262 public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
263 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
264 replaceDataNodeTree(fragmentEntity, dataNode);
266 fragmentRepository.save(fragmentEntity);
267 } catch (final StaleStateException staleStateException) {
268 throw new ConcurrencyException("Concurrent Transactions",
269 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
270 dataspaceName, anchorName, dataNode.getXpath()),
271 staleStateException);
275 private void replaceDataNodeTree(final FragmentEntity existingFragmentEntity,
276 final DataNode newDataNode) {
278 existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
280 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
281 .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
283 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
285 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
286 final FragmentEntity childFragment;
287 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
288 childFragment = convertToFragmentWithAllDescendants(
289 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
291 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
292 replaceDataNodeTree(childFragment, newDataNodeChild);
294 updatedChildFragments.add(childFragment);
296 existingFragmentEntity.getChildFragments().clear();
297 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
302 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
303 final Collection<DataNode> newListElements) {
304 final FragmentEntity parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
305 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
306 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
307 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
308 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
309 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
310 for (final DataNode newListElement : newListElements) {
311 final FragmentEntity existingListElementEntity =
312 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
313 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
314 existingListElementEntity);
316 updatedChildFragmentEntities.add(entityToBeAdded);
318 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
319 fragmentRepository.save(parentEntity);
324 public void deleteDataNodes(final String dataspaceName, final String anchorName) {
325 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
326 anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
328 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
333 public void deleteListDataNode(final String dataspaceName, final String anchorName,
334 final String targetXpath) {
335 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
340 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
341 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
344 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
345 final boolean onlySupportListNodeDeletion) {
346 final String parentNodeXpath;
347 FragmentEntity parentFragmentEntity = null;
348 boolean targetDeleted = false;
349 if (isRootXpath(targetXpath)) {
350 deleteDataNodes(dataspaceName, anchorName);
351 targetDeleted = true;
353 if (isRootContainerNodeXpath(targetXpath)) {
354 parentNodeXpath = targetXpath;
356 parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
358 parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
359 final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
360 final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE
361 .matcher(lastXpathElement).find();
363 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
365 targetDeleted = deleteAllListElements(parentFragmentEntity, targetXpath);
366 final boolean tryToDeleteDataNode = !targetDeleted && !onlySupportListNodeDeletion;
367 if (tryToDeleteDataNode) {
368 targetDeleted = deleteDataNode(parentFragmentEntity, targetXpath);
372 if (!targetDeleted) {
373 final String additionalInformation = onlySupportListNodeDeletion
374 ? "The target is probably not a List." : "";
375 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
376 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
380 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
381 if (parentFragmentEntity.getXpath().equals(targetXpath)) {
382 fragmentRepository.delete(parentFragmentEntity);
385 if (parentFragmentEntity.getChildFragments()
386 .removeIf(fragment -> fragment.getXpath().equals(targetXpath))) {
387 fragmentRepository.save(parentFragmentEntity);
393 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
394 final String deleteTargetXpathPrefix = listXpath + "[";
395 if (parentFragmentEntity.getChildFragments()
396 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
397 fragmentRepository.save(parentFragmentEntity);
403 private static void deleteListElements(
404 final Collection<FragmentEntity> fragmentEntities,
405 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
406 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
409 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
410 if (newListElements.isEmpty()) {
411 throw new CpsAdminException("Invalid list replacement",
412 "Cannot replace list elements with empty collection");
414 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
415 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf('[') + 1);
418 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
419 final DataNode newListElement,
420 final FragmentEntity existingListElementEntity) {
421 if (existingListElementEntity == null) {
422 return convertToFragmentWithAllDescendants(
423 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
425 if (newListElement.getChildDataNodes().isEmpty()) {
426 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
427 existingListElementEntity.getChildFragments().clear();
429 replaceDataNodeTree(existingListElementEntity, newListElement);
431 return existingListElementEntity;
434 private static boolean isNewDataNode(final DataNode replacementDataNode,
435 final Map<String, FragmentEntity> existingListElementsByXpath) {
436 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
439 private static boolean isRootContainerNodeXpath(final String xpath) {
440 return 0 == xpath.lastIndexOf('/');
443 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
444 final DataNode newListElement) {
445 final FragmentEntity replacementFragmentEntity =
446 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
447 newListElement.getLeaves())).build();
448 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
451 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
452 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
453 return childEntities.stream()
454 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
455 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
458 private static boolean isRootXpath(final String xpath) {
459 return "/".equals(xpath) || "".equals(xpath);