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 this.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_NODE_KEY = "\\[(\\@([^/]*?))+( 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 var 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 addListDataNodes(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 var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
135 final var anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
136 final var 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 var 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 var 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 var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
199 final var 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 var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
212 final var 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<>();
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 var 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 var 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,
286 final DataNode dataNode) {
287 final var fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
288 replaceDataNodeTree(fragmentEntity, dataNode);
290 fragmentRepository.save(fragmentEntity);
291 } catch (final StaleStateException staleStateException) {
292 throw new ConcurrencyException("Concurrent Transactions",
293 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
294 dataspaceName, anchorName, dataNode.getXpath()),
295 staleStateException);
299 private void replaceDataNodeTree(final FragmentEntity existingFragmentEntity, final DataNode submittedDataNode) {
301 existingFragmentEntity.setAttributes(GSON.toJson(submittedDataNode.getLeaves()));
303 final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
304 .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
306 final var updatedChildFragments = new HashSet<FragmentEntity>();
308 for (final DataNode submittedChildDataNode : submittedDataNode.getChildDataNodes()) {
309 final FragmentEntity childFragment;
310 if (existingChildrenByXpath.containsKey(submittedChildDataNode.getXpath())) {
311 childFragment = existingChildrenByXpath.get(submittedChildDataNode.getXpath());
312 replaceDataNodeTree(childFragment, submittedChildDataNode);
314 childFragment = convertToFragmentWithAllDescendants(
315 existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), submittedChildDataNode);
317 updatedChildFragments.add(childFragment);
319 existingFragmentEntity.setChildFragments(updatedChildFragments);
324 public void replaceListDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
325 final Collection<DataNode> dataNodes) {
326 final var parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
327 final var firstChildNodeXpath = dataNodes.iterator().next().getXpath();
328 final var listNodeXpath = firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf("["));
329 removeListNodeDescendants(parentEntity, listNodeXpath);
330 final Set<FragmentEntity> childFragmentEntities = dataNodes.stream().map(
331 dataNode -> convertToFragmentWithAllDescendants(
332 parentEntity.getDataspace(), parentEntity.getAnchor(), dataNode)
333 ).collect(Collectors.toUnmodifiableSet());
334 parentEntity.getChildFragments().addAll(childFragmentEntities);
335 fragmentRepository.save(parentEntity);
340 public void deleteListDataNodes(final String dataspaceName, final String anchorName, final String listNodeXpath) {
341 final var parentNodeXpath = listNodeXpath.substring(0, listNodeXpath.lastIndexOf('/'));
342 final var parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
343 final var descendantNode = listNodeXpath.substring(listNodeXpath.lastIndexOf('/'));
344 final Matcher descendantNodeHasListNodeKey = Pattern.compile(REG_EX_FOR_LIST_NODE_KEY).matcher(descendantNode);
346 final boolean xpathPointsToAValidChildNodeWithKey = parentEntity.getChildFragments().stream().anyMatch(
347 (fragment) -> fragment.getXpath().equals(listNodeXpath));
349 final boolean xpathPointsToAValidChildNodeWithoutKey = parentEntity.getChildFragments().stream().anyMatch(
350 (fragment) -> fragment.getXpath().replaceAll(REG_EX_FOR_LIST_NODE_KEY, "").equals(listNodeXpath));
352 if ((descendantNodeHasListNodeKey.find() && xpathPointsToAValidChildNodeWithKey)
354 (!descendantNodeHasListNodeKey.find() && xpathPointsToAValidChildNodeWithoutKey)) {
355 removeListNodeDescendants(parentEntity, listNodeXpath);
357 throw new DataNodeNotFoundException(parentEntity.getDataspace().getName(),
358 parentEntity.getAnchor().getName(), listNodeXpath);
362 private void removeListNodeDescendants(final FragmentEntity parentFragmentEntity, final String listNodeXpath) {
363 final Matcher descendantNodeHasListNodeKey = Pattern.compile(REG_EX_FOR_LIST_NODE_KEY).matcher(listNodeXpath);
364 final String listNodeXpathPrefix = listNodeXpath + (descendantNodeHasListNodeKey.find() ? "" : "[");
365 if (parentFragmentEntity.getChildFragments()
366 .removeIf(fragment -> fragment.getXpath().startsWith(listNodeXpathPrefix))) {
367 fragmentRepository.save(parentFragmentEntity);
371 private static boolean isRootXpath(final String xpath) {
372 return "/".equals(xpath) || "".equals(xpath);