2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2022 Nordix Foundation
4 * Modifications Copyright (C) 2021 Pantheon.tech
5 * Modifications Copyright (C) 2020-2021 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.CpsPathException;
52 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
53 import org.onap.cps.spi.model.DataNode;
54 import org.onap.cps.spi.model.DataNodeBuilder;
55 import org.onap.cps.spi.repository.AnchorRepository;
56 import org.onap.cps.spi.repository.DataspaceRepository;
57 import org.onap.cps.spi.repository.FragmentRepository;
58 import org.onap.cps.utils.JsonObjectMapper;
59 import org.springframework.dao.DataIntegrityViolationException;
60 import org.springframework.stereotype.Service;
64 @RequiredArgsConstructor
65 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
67 private final DataspaceRepository dataspaceRepository;
69 private final AnchorRepository anchorRepository;
71 private final FragmentRepository fragmentRepository;
73 private final JsonObjectMapper jsonObjectMapper;
76 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
77 private static final Pattern REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE =
78 Pattern.compile("\\[(\\@([^\\/]{0,9999}))\\]$");
81 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentXpath,
82 final DataNode dataNode) {
83 final FragmentEntity parentFragment = getFragmentByXpath(dataspaceName, anchorName, parentXpath);
84 final FragmentEntity fragmentEntity =
85 toFragmentEntity(parentFragment.getDataspace(), parentFragment.getAnchor(), dataNode);
86 parentFragment.getChildFragments().add(fragmentEntity);
88 fragmentRepository.save(parentFragment);
89 } catch (final DataIntegrityViolationException exception) {
90 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
95 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
96 final Collection<DataNode> dataNodes) {
97 final FragmentEntity parentFragment = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
98 final List<FragmentEntity> newFragmentEntities =
99 dataNodes.stream().map(
100 dataNode -> toFragmentEntity(parentFragment.getDataspace(), parentFragment.getAnchor(), dataNode)
101 ).collect(Collectors.toUnmodifiableList());
102 parentFragment.getChildFragments().addAll(newFragmentEntities);
104 fragmentRepository.save(parentFragment);
106 dataNode -> getChildFragments(dataspaceName, anchorName, dataNode)
108 } catch (final DataIntegrityViolationException exception) {
109 final List<String> conflictXpaths = dataNodes.stream()
110 .map(DataNode::getXpath)
111 .collect(Collectors.toList());
112 throw AlreadyDefinedException.forDataNodes(conflictXpaths, anchorName, exception);
117 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
118 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
119 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
120 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
123 fragmentRepository.save(fragmentEntity);
124 } catch (final DataIntegrityViolationException exception) {
125 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
130 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
131 * for all DataNode children recursively.
133 * @param dataspaceEntity dataspace
134 * @param anchorEntity anchorEntity
135 * @param dataNodeToBeConverted dataNode
136 * @return a Fragment built from current DataNode
138 private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
139 final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
140 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
141 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
142 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
143 final FragmentEntity childFragment =
144 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
146 childFragmentsImmutableSetBuilder.add(childFragment);
148 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
149 return parentFragment;
152 private void getChildFragments(final String dataspaceName, final String anchorName, final DataNode dataNode) {
153 for (final DataNode childDataNode: dataNode.getChildDataNodes()) {
154 final FragmentEntity getChildsParentFragmentByXPath =
155 getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
156 final FragmentEntity childFragmentEntity = toFragmentEntity(getChildsParentFragmentByXPath.getDataspace(),
157 getChildsParentFragmentByXPath.getAnchor(), childDataNode);
158 getChildsParentFragmentByXPath.getChildFragments().add(childFragmentEntity);
159 fragmentRepository.save(getChildsParentFragmentByXPath);
163 private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
164 final AnchorEntity anchorEntity, final DataNode dataNode) {
165 return FragmentEntity.builder()
166 .dataspace(dataspaceEntity)
167 .anchor(anchorEntity)
168 .xpath(dataNode.getXpath())
169 .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
174 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
175 final FetchDescendantsOption fetchDescendantsOption) {
176 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
177 return toDataNode(fragmentEntity, fetchDescendantsOption);
180 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
181 final String xpath) {
182 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
183 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
184 if (isRootXpath(xpath)) {
185 return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
187 return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
193 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
194 final FetchDescendantsOption fetchDescendantsOption) {
195 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
196 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
197 final CpsPathQuery cpsPathQuery;
199 cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
200 } catch (final IllegalStateException e) {
201 throw new CpsPathException(e.getMessage());
203 List<FragmentEntity> fragmentEntities =
204 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
205 if (cpsPathQuery.hasAncestorAxis()) {
206 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
207 fragmentEntities = ancestorXpaths.isEmpty()
208 ? Collections.emptyList() : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
210 return fragmentEntities.stream()
211 .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
212 .collect(Collectors.toUnmodifiableList());
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);
325 public void deleteListDataNode(final String dataspaceName, final String anchorName,
326 final String targetXpath) {
327 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
332 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
333 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
336 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
337 final boolean onlySupportListNodeDeletion) {
338 final String parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
339 final FragmentEntity parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
340 final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
341 final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE.matcher(lastXpathElement).find();
344 targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
346 targetExist = deleteAllListElements(parentFragmentEntity, targetXpath);
347 final boolean tryToDeleteDataNode = !targetExist && !onlySupportListNodeDeletion;
348 if (tryToDeleteDataNode) {
349 targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
353 final String additionalInformation = onlySupportListNodeDeletion
354 ? "The target is probably not a List." : "";
355 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
356 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
360 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
361 if (parentFragmentEntity.getChildFragments()
362 .removeIf(fragment -> fragment.getXpath().equals(targetXpath))) {
363 fragmentRepository.save(parentFragmentEntity);
370 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
371 final String deleteTargetXpathPrefix = listXpath + "[";
372 if (parentFragmentEntity.getChildFragments()
373 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
374 fragmentRepository.save(parentFragmentEntity);
380 private static void deleteListElements(
381 final Collection<FragmentEntity> fragmentEntities,
382 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
383 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
386 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
387 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
388 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf("[") + 1);
391 private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
392 final DataNode newListElement,
393 final FragmentEntity existingListElementEntity) {
394 if (existingListElementEntity == null) {
395 return convertToFragmentWithAllDescendants(
396 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
398 if (newListElement.getChildDataNodes().isEmpty()) {
399 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
400 existingListElementEntity.getChildFragments().clear();
402 replaceDataNodeTree(existingListElementEntity, newListElement);
404 return existingListElementEntity;
407 private static boolean isNewDataNode(final DataNode replacementDataNode,
408 final Map<String, FragmentEntity> existingListElementsByXpath) {
409 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
412 private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
413 final DataNode newListElement) {
414 final FragmentEntity replacementFragmentEntity =
415 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
416 newListElement.getLeaves())).build();
417 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
420 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
421 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
422 return childEntities.stream()
423 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
424 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
427 private static boolean isRootXpath(final String xpath) {
428 return "/".equals(xpath) || "".equals(xpath);