c6e28aba91df892cb7f92dc11a1466db056bc4da
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsDataPersistenceServiceImpl.java
1 /*
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
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.spi.impl;
24
25 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
26
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;
34 import java.util.Map;
35 import java.util.Set;
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;
61
62 @Service
63 @Slf4j
64 @RequiredArgsConstructor
65 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
66
67     private final DataspaceRepository dataspaceRepository;
68
69     private final AnchorRepository anchorRepository;
70
71     private final FragmentRepository fragmentRepository;
72
73     private final JsonObjectMapper jsonObjectMapper;
74
75
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}))\\]$");
79
80     @Override
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);
87         try {
88             fragmentRepository.save(parentFragment);
89         } catch (final DataIntegrityViolationException exception) {
90             throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
91         }
92     }
93
94     @Override
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);
103         try {
104             fragmentRepository.save(parentFragment);
105             dataNodes.forEach(
106                 dataNode -> getChildFragments(dataspaceName, anchorName, dataNode)
107             );
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);
113         }
114     }
115
116     @Override
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,
121             dataNode);
122         try {
123             fragmentRepository.save(fragmentEntity);
124         } catch (final DataIntegrityViolationException exception) {
125             throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
126         }
127     }
128
129     /**
130      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
131      * for all DataNode children recursively.
132      *
133      * @param dataspaceEntity       dataspace
134      * @param anchorEntity          anchorEntity
135      * @param dataNodeToBeConverted dataNode
136      * @return a Fragment built from current DataNode
137      */
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(),
145                     childDataNode);
146             childFragmentsImmutableSetBuilder.add(childFragment);
147         }
148         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
149         return parentFragment;
150     }
151
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);
160         }
161     }
162
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()))
170             .build();
171     }
172
173     @Override
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);
178     }
179
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);
186         } else {
187             return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
188                 xpath);
189         }
190     }
191
192     @Override
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;
198         try {
199             cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
200         } catch (final IllegalStateException e) {
201             throw new CpsPathException(e.getMessage());
202         }
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);
209         }
210         return fragmentEntities.stream()
211             .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
212             .collect(Collectors.toUnmodifiableList());
213     }
214
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));
225             }
226         }
227         return ancestorXpath;
228     }
229
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);
236         }
237         return new DataNodeBuilder()
238             .withXpath(fragmentEntity.getXpath())
239             .withLeaves(leaves)
240             .withChildDataNodes(childDataNodes).build();
241     }
242
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());
249         }
250         return Collections.emptyList();
251     }
252
253     @Override
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);
259     }
260
261     @Override
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);
265         try {
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);
272         }
273     }
274
275     private void replaceDataNodeTree(final FragmentEntity existingFragmentEntity,
276                                             final DataNode newDataNode) {
277
278         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
279
280         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
281             .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
282
283         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
284
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);
290             } else {
291                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
292                 replaceDataNodeTree(childFragment, newDataNodeChild);
293             }
294             updatedChildFragments.add(childFragment);
295         }
296         existingFragmentEntity.getChildFragments().clear();
297         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
298     }
299
300     @Override
301     @Transactional
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);
315
316             updatedChildFragmentEntities.add(entityToBeAdded);
317         }
318         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
319         fragmentRepository.save(parentEntity);
320     }
321
322
323     @Override
324     @Transactional
325     public void deleteListDataNode(final String dataspaceName, final String anchorName,
326                                    final String targetXpath) {
327         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
328     }
329
330     @Override
331     @Transactional
332     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
333         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
334     }
335
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();
342         boolean targetExist;
343         if (isListElement) {
344             targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
345         } else {
346             targetExist = deleteAllListElements(parentFragmentEntity, targetXpath);
347             final boolean tryToDeleteDataNode = !targetExist && !onlySupportListNodeDeletion;
348             if (tryToDeleteDataNode) {
349                 targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
350             }
351         }
352         if (!targetExist) {
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);
357         }
358     }
359
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);
364             return true;
365         }
366         return false;
367     }
368
369
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);
375             return true;
376         }
377         return false;
378     }
379
380     private static void deleteListElements(
381         final Collection<FragmentEntity> fragmentEntities,
382         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
383         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
384     }
385
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);
389     }
390
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);
397         }
398         if (newListElement.getChildDataNodes().isEmpty()) {
399             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
400             existingListElementEntity.getChildFragments().clear();
401         } else {
402             replaceDataNodeTree(existingListElementEntity, newListElement);
403         }
404         return existingListElementEntity;
405     }
406
407     private static boolean isNewDataNode(final DataNode replacementDataNode,
408                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
409         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
410     }
411
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());
418     }
419
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));
425     }
426
427     private static boolean isRootXpath(final String xpath) {
428         return "/".equals(xpath) || "".equals(xpath);
429     }
430 }