2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 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.fasterxml.jackson.core.JsonProcessingException;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.google.common.collect.ImmutableSet;
30 import com.google.common.collect.ImmutableSet.Builder;
31 import com.google.gson.Gson;
32 import com.google.gson.GsonBuilder;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.List;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
43 import javax.transaction.Transactional;
44 import lombok.extern.slf4j.Slf4j;
45 import org.hibernate.StaleStateException;
46 import org.onap.cps.cpspath.parser.CpsPathQuery;
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.exceptions.AlreadyDefinedException;
53 import org.onap.cps.spi.exceptions.ConcurrencyException;
54 import org.onap.cps.spi.exceptions.CpsPathException;
55 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
56 import org.onap.cps.spi.exceptions.DataValidationException;
57 import org.onap.cps.spi.model.DataNode;
58 import org.onap.cps.spi.model.DataNodeBuilder;
59 import org.onap.cps.spi.repository.AnchorRepository;
60 import org.onap.cps.spi.repository.DataspaceRepository;
61 import org.onap.cps.spi.repository.FragmentRepository;
62 import org.springframework.dao.DataIntegrityViolationException;
63 import org.springframework.stereotype.Service;
67 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
69 private DataspaceRepository dataspaceRepository;
71 private AnchorRepository anchorRepository;
73 private FragmentRepository fragmentRepository;
75 private final ObjectMapper objectMapper;
80 * @param dataspaceRepository dataspaceRepository
81 * @param anchorRepository anchorRepository
82 * @param fragmentRepository fragmentRepository
84 public CpsDataPersistenceServiceImpl(final DataspaceRepository dataspaceRepository,
85 final AnchorRepository anchorRepository, final FragmentRepository fragmentRepository) {
86 this.dataspaceRepository = dataspaceRepository;
87 this.anchorRepository = anchorRepository;
88 this.fragmentRepository = fragmentRepository;
89 objectMapper = new ObjectMapper();
92 private static final Gson GSON = new GsonBuilder().create();
93 private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@[\\s\\S]+?]){0,1})";
94 private static final String REG_EX_FOR_LIST_ELEMENT_KEY_PREDICATE = "\\[(\\@([^/]*?)){0,99}( and)*\\]$";
97 public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentXpath,
98 final DataNode dataNode) {
99 final FragmentEntity parentFragment = getFragmentByXpath(dataspaceName, anchorName, parentXpath);
100 final FragmentEntity fragmentEntity =
101 toFragmentEntity(parentFragment.getDataspace(), parentFragment.getAnchor(), dataNode);
102 parentFragment.getChildFragments().add(fragmentEntity);
104 fragmentRepository.save(parentFragment);
105 } catch (final DataIntegrityViolationException exception) {
106 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
111 public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
112 final Collection<DataNode> dataNodes) {
113 final FragmentEntity parentFragment = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
114 final List<FragmentEntity> newFragmentEntities =
115 dataNodes.stream().map(
116 dataNode -> toFragmentEntity(parentFragment.getDataspace(), parentFragment.getAnchor(), dataNode)
117 ).collect(Collectors.toUnmodifiableList());
118 parentFragment.getChildFragments().addAll(newFragmentEntities);
120 fragmentRepository.save(parentFragment);
122 dataNode -> getChildFragments(dataspaceName, anchorName, dataNode)
124 } catch (final DataIntegrityViolationException exception) {
125 final List<String> conflictXpaths = dataNodes.stream()
126 .map(DataNode::getXpath)
127 .collect(Collectors.toList());
128 throw AlreadyDefinedException.forDataNodes(conflictXpaths, anchorName, exception);
133 public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
134 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
135 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
136 final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
139 fragmentRepository.save(fragmentEntity);
140 } catch (final DataIntegrityViolationException exception) {
141 throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
146 * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
147 * for all DataNode children recursively.
149 * @param dataspaceEntity dataspace
150 * @param anchorEntity anchorEntity
151 * @param dataNodeToBeConverted dataNode
152 * @return a Fragment built from current DataNode
154 private static FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
155 final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
156 final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
157 final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
158 for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
159 final FragmentEntity childFragment =
160 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
162 childFragmentsImmutableSetBuilder.add(childFragment);
164 parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
165 return parentFragment;
168 private void getChildFragments(final String dataspaceName, final String anchorName, final DataNode dataNode) {
169 for (final DataNode childDataNode: dataNode.getChildDataNodes()) {
170 final FragmentEntity getChildsParentFragmentByXPath =
171 getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
172 final FragmentEntity childFragmentEntity = toFragmentEntity(getChildsParentFragmentByXPath.getDataspace(),
173 getChildsParentFragmentByXPath.getAnchor(), childDataNode);
174 getChildsParentFragmentByXPath.getChildFragments().add(childFragmentEntity);
175 fragmentRepository.save(getChildsParentFragmentByXPath);
179 private static FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
180 final AnchorEntity anchorEntity, final DataNode dataNode) {
181 return FragmentEntity.builder()
182 .dataspace(dataspaceEntity)
183 .anchor(anchorEntity)
184 .xpath(dataNode.getXpath())
185 .attributes(GSON.toJson(dataNode.getLeaves()))
190 public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
191 final FetchDescendantsOption fetchDescendantsOption) {
192 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
193 return toDataNode(fragmentEntity, fetchDescendantsOption);
196 private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
197 final String xpath) {
198 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
199 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
200 if (isRootXpath(xpath)) {
201 return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
203 return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
209 public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
210 final FetchDescendantsOption fetchDescendantsOption) {
211 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
212 final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
213 final CpsPathQuery cpsPathQuery;
215 cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
216 } catch (final IllegalStateException e) {
217 throw new CpsPathException(e.getMessage());
219 List<FragmentEntity> fragmentEntities =
220 fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
221 if (cpsPathQuery.hasAncestorAxis()) {
222 final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
223 fragmentEntities = ancestorXpaths.isEmpty()
224 ? Collections.emptyList() : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
226 return fragmentEntities.stream()
227 .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
228 .collect(Collectors.toUnmodifiableList());
231 private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
232 final CpsPathQuery cpsPathQuery) {
233 final Set<String> ancestorXpath = new HashSet<>();
234 final Pattern pattern =
235 Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
236 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
237 for (final FragmentEntity fragmentEntity : fragmentEntities) {
238 final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
239 if (matcher.matches()) {
240 ancestorXpath.add(matcher.group(1));
243 return ancestorXpath;
246 private DataNode toDataNode(final FragmentEntity fragmentEntity,
247 final FetchDescendantsOption fetchDescendantsOption) {
248 final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
249 Map<String, Object> leaves = new HashMap<>();
250 if (fragmentEntity.getAttributes() != null) {
252 leaves = objectMapper.readValue(fragmentEntity.getAttributes(), Map.class);
253 } catch (final JsonProcessingException jsonProcessingException) {
254 final String message = "Parsing error occurred while processing fragmentEntity attributes.";
256 throw new DataValidationException(message,
257 jsonProcessingException.getMessage(), jsonProcessingException);
260 return new DataNodeBuilder()
261 .withXpath(fragmentEntity.getXpath())
263 .withChildDataNodes(childDataNodes).build();
266 private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
267 final FetchDescendantsOption fetchDescendantsOption) {
268 if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
269 return fragmentEntity.getChildFragments().stream()
270 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
271 .collect(Collectors.toUnmodifiableList());
273 return Collections.emptyList();
277 public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
278 final Map<String, Object> leaves) {
279 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
280 fragmentEntity.setAttributes(GSON.toJson(leaves));
281 fragmentRepository.save(fragmentEntity);
285 public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
286 final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
287 replaceDataNodeTree(fragmentEntity, dataNode);
289 fragmentRepository.save(fragmentEntity);
290 } catch (final StaleStateException staleStateException) {
291 throw new ConcurrencyException("Concurrent Transactions",
292 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
293 dataspaceName, anchorName, dataNode.getXpath()),
294 staleStateException);
298 private static void replaceDataNodeTree(final FragmentEntity existingFragmentEntity,
299 final DataNode newDataNode) {
301 existingFragmentEntity.setAttributes(GSON.toJson(newDataNode.getLeaves()));
303 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
304 .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
306 final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
308 for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
309 final FragmentEntity childFragment;
310 if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
311 childFragment = convertToFragmentWithAllDescendants(
312 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
314 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
315 replaceDataNodeTree(childFragment, newDataNodeChild);
317 updatedChildFragments.add(childFragment);
319 existingFragmentEntity.getChildFragments().clear();
320 existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
325 public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
326 final Collection<DataNode> newListElements) {
327 final FragmentEntity parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
328 final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
329 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
330 extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
331 deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
332 final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
333 for (final DataNode newListElement : newListElements) {
334 final FragmentEntity existingListElementEntity =
335 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
336 final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
337 existingListElementEntity);
339 updatedChildFragmentEntities.add(entityToBeAdded);
341 parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
342 fragmentRepository.save(parentEntity);
348 public void deleteListDataNode(final String dataspaceName, final String anchorName,
349 final String targetXpath) {
350 deleteDataNode(dataspaceName, anchorName, targetXpath, true);
355 public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
356 deleteDataNode(dataspaceName, anchorName, targetXpath, false);
359 private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
360 final boolean onlySupportListNodeDeletion) {
361 final String parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
362 final FragmentEntity parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
363 final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
364 final boolean isListElement = Pattern.compile(REG_EX_FOR_LIST_ELEMENT_KEY_PREDICATE)
365 .matcher(lastXpathElement).find();
368 targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
370 targetExist = deleteAllListElements(parentFragmentEntity, targetXpath);
371 final boolean tryToDeleteDataNode = !targetExist && !onlySupportListNodeDeletion;
372 if (tryToDeleteDataNode) {
373 targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
377 final String additionalInformation = onlySupportListNodeDeletion
378 ? "The target is probably not a List." : "";
379 throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
380 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
384 private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
385 if (parentFragmentEntity.getChildFragments()
386 .removeIf(fragment -> fragment.getXpath().equals(targetXpath))) {
387 fragmentRepository.save(parentFragmentEntity);
394 private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
395 final String deleteTargetXpathPrefix = listXpath + "[";
396 if (parentFragmentEntity.getChildFragments()
397 .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
398 fragmentRepository.save(parentFragmentEntity);
404 private static void deleteListElements(
405 final Collection<FragmentEntity> fragmentEntities,
406 final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
407 fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
410 private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
411 final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
412 return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf("[") + 1);
415 private static FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
416 final DataNode newListElement,
417 final FragmentEntity existingListElementEntity) {
418 if (existingListElementEntity == null) {
419 return convertToFragmentWithAllDescendants(
420 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
422 if (newListElement.getChildDataNodes().isEmpty()) {
423 copyAttributesFromNewListElement(existingListElementEntity, newListElement);
424 existingListElementEntity.getChildFragments().clear();
426 replaceDataNodeTree(existingListElementEntity, newListElement);
428 return existingListElementEntity;
431 private static boolean isNewDataNode(final DataNode replacementDataNode,
432 final Map<String, FragmentEntity> existingListElementsByXpath) {
433 return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
436 private static void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
437 final DataNode newListElement) {
438 final FragmentEntity replacementFragmentEntity =
439 FragmentEntity.builder().attributes(GSON.toJson(newListElement.getLeaves())).build();
440 existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
443 private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
444 final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
445 return childEntities.stream()
446 .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
447 .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
450 private static boolean isRootXpath(final String xpath) {
451 return "/".equals(xpath) || "".equals(xpath);