Fragment handling decreasing performance for large number of cmHandles
[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-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
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.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.utils.JsonObjectMapper;
60 import org.springframework.dao.DataIntegrityViolationException;
61 import org.springframework.stereotype.Service;
62
63 @Service
64 @Slf4j
65 @RequiredArgsConstructor
66 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
67
68     private final DataspaceRepository dataspaceRepository;
69
70     private final AnchorRepository anchorRepository;
71
72     private final FragmentRepository fragmentRepository;
73
74     private final JsonObjectMapper jsonObjectMapper;
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     @Transactional
82     public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentNodeXpath,
83         final DataNode newChildDataNode) {
84         addChildDataNodes(dataspaceName, anchorName, parentNodeXpath,  Collections.singleton(newChildDataNode));
85     }
86
87     @Override
88     @Transactional
89     public void addListElements(final String dataspaceName, final String anchorName, final String parentNodeXpath,
90         final Collection<DataNode> newListElements) {
91         addChildDataNodes(dataspaceName, anchorName, parentNodeXpath, newListElements);
92     }
93
94     private void addChildDataNodes(final String dataspaceName, final String anchorName, final String parentNodeXpath,
95                                 final Collection<DataNode> newChildren) {
96         final FragmentEntity parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
97         try {
98             for (final DataNode newChildAsDataNode : newChildren) {
99                 final FragmentEntity newChildAsFragmentEntity = convertToFragmentWithAllDescendants(
100                     parentFragmentEntity.getDataspace(),
101                     parentFragmentEntity.getAnchor(),
102                     newChildAsDataNode);
103                 newChildAsFragmentEntity.setParentId(parentFragmentEntity.getId());
104                 fragmentRepository.save(newChildAsFragmentEntity);
105             }
106         } catch (final DataIntegrityViolationException exception) {
107             final List<String> conflictXpaths = newChildren.stream()
108                 .map(DataNode::getXpath)
109                 .collect(Collectors.toList());
110             throw AlreadyDefinedException.forDataNodes(conflictXpaths, anchorName, exception);
111         }
112     }
113
114     @Override
115     public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
116         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
117         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
118         final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
119             dataNode);
120         try {
121             fragmentRepository.save(fragmentEntity);
122         } catch (final DataIntegrityViolationException exception) {
123             throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
124         }
125     }
126
127     /**
128      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
129      * for all DataNode children recursively.
130      *
131      * @param dataspaceEntity       dataspace
132      * @param anchorEntity          anchorEntity
133      * @param dataNodeToBeConverted dataNode
134      * @return a Fragment built from current DataNode
135      */
136     private FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
137         final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
138         final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
139         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
140         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
141             final FragmentEntity childFragment =
142                 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
143                     childDataNode);
144             childFragmentsImmutableSetBuilder.add(childFragment);
145         }
146         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
147         return parentFragment;
148     }
149
150     private FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
151         final AnchorEntity anchorEntity, final DataNode dataNode) {
152         return FragmentEntity.builder()
153             .dataspace(dataspaceEntity)
154             .anchor(anchorEntity)
155             .xpath(dataNode.getXpath())
156             .attributes(jsonObjectMapper.asJsonString(dataNode.getLeaves()))
157             .build();
158     }
159
160     @Override
161     public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
162         final FetchDescendantsOption fetchDescendantsOption) {
163         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
164         return toDataNode(fragmentEntity, fetchDescendantsOption);
165     }
166
167     private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
168         final String xpath) {
169         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
170         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
171         if (isRootXpath(xpath)) {
172             return fragmentRepository.findFirstRootByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
173         } else {
174             return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
175                 xpath);
176         }
177     }
178
179     @Override
180     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
181         final FetchDescendantsOption fetchDescendantsOption) {
182         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
183         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
184         final CpsPathQuery cpsPathQuery;
185         try {
186             cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
187         } catch (final IllegalStateException e) {
188             throw new CpsPathException(e.getMessage());
189         }
190         List<FragmentEntity> fragmentEntities =
191             fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
192         if (cpsPathQuery.hasAncestorAxis()) {
193             final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
194             fragmentEntities = ancestorXpaths.isEmpty()
195                 ? Collections.emptyList() : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
196         }
197         return fragmentEntities.stream()
198             .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
199             .collect(Collectors.toUnmodifiableList());
200     }
201
202     private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
203         final CpsPathQuery cpsPathQuery) {
204         final Set<String> ancestorXpath = new HashSet<>();
205         final Pattern pattern =
206             Pattern.compile("([\\s\\S]*\\/" + Pattern.quote(cpsPathQuery.getAncestorSchemaNodeIdentifier())
207                 + REG_EX_FOR_OPTIONAL_LIST_INDEX + "\\/[\\s\\S]*");
208         for (final FragmentEntity fragmentEntity : fragmentEntities) {
209             final Matcher matcher = pattern.matcher(fragmentEntity.getXpath());
210             if (matcher.matches()) {
211                 ancestorXpath.add(matcher.group(1));
212             }
213         }
214         return ancestorXpath;
215     }
216
217     private DataNode toDataNode(final FragmentEntity fragmentEntity,
218         final FetchDescendantsOption fetchDescendantsOption) {
219         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
220         Map<String, Object> leaves = new HashMap<>();
221         if (fragmentEntity.getAttributes() != null) {
222             leaves = jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map.class);
223         }
224         return new DataNodeBuilder()
225             .withXpath(fragmentEntity.getXpath())
226             .withLeaves(leaves)
227             .withChildDataNodes(childDataNodes).build();
228     }
229
230     private List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
231         final FetchDescendantsOption fetchDescendantsOption) {
232         if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
233             return fragmentEntity.getChildFragments().stream()
234                 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
235                 .collect(Collectors.toUnmodifiableList());
236         }
237         return Collections.emptyList();
238     }
239
240     @Override
241     public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
242         final Map<String, Object> leaves) {
243         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
244         fragmentEntity.setAttributes(jsonObjectMapper.asJsonString(leaves));
245         fragmentRepository.save(fragmentEntity);
246     }
247
248     @Override
249     public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
250         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
251         replaceDataNodeTree(fragmentEntity, dataNode);
252         try {
253             fragmentRepository.save(fragmentEntity);
254         } catch (final StaleStateException staleStateException) {
255             throw new ConcurrencyException("Concurrent Transactions",
256                 String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
257                     dataspaceName, anchorName, dataNode.getXpath()),
258                 staleStateException);
259         }
260     }
261
262     private void replaceDataNodeTree(final FragmentEntity existingFragmentEntity,
263                                             final DataNode newDataNode) {
264
265         existingFragmentEntity.setAttributes(jsonObjectMapper.asJsonString(newDataNode.getLeaves()));
266
267         final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
268             .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
269
270         final Collection<FragmentEntity> updatedChildFragments = new HashSet<>();
271
272         for (final DataNode newDataNodeChild : newDataNode.getChildDataNodes()) {
273             final FragmentEntity childFragment;
274             if (isNewDataNode(newDataNodeChild, existingChildrenByXpath)) {
275                 childFragment = convertToFragmentWithAllDescendants(
276                     existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), newDataNodeChild);
277             } else {
278                 childFragment = existingChildrenByXpath.get(newDataNodeChild.getXpath());
279                 replaceDataNodeTree(childFragment, newDataNodeChild);
280             }
281             updatedChildFragments.add(childFragment);
282         }
283         existingFragmentEntity.getChildFragments().clear();
284         existingFragmentEntity.getChildFragments().addAll(updatedChildFragments);
285     }
286
287     @Override
288     @Transactional
289     public void replaceListContent(final String dataspaceName, final String anchorName, final String parentNodeXpath,
290                                    final Collection<DataNode> newListElements) {
291         final FragmentEntity parentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
292         final String listElementXpathPrefix = getListElementXpathPrefix(newListElements);
293         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath =
294             extractListElementFragmentEntitiesByXPath(parentEntity.getChildFragments(), listElementXpathPrefix);
295         deleteListElements(parentEntity.getChildFragments(), existingListElementFragmentEntitiesByXPath);
296         final Set<FragmentEntity> updatedChildFragmentEntities = new HashSet<>();
297         for (final DataNode newListElement : newListElements) {
298             final FragmentEntity existingListElementEntity =
299                 existingListElementFragmentEntitiesByXPath.get(newListElement.getXpath());
300             final FragmentEntity entityToBeAdded = getFragmentForReplacement(parentEntity, newListElement,
301                 existingListElementEntity);
302
303             updatedChildFragmentEntities.add(entityToBeAdded);
304         }
305         parentEntity.getChildFragments().addAll(updatedChildFragmentEntities);
306         fragmentRepository.save(parentEntity);
307     }
308
309     @Override
310     @Transactional
311     public void deleteDataNodes(final String dataspaceName, final String anchorName) {
312         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
313         anchorRepository.findByDataspaceAndName(dataspaceEntity, anchorName)
314             .ifPresent(
315                 anchorEntity -> fragmentRepository.deleteByAnchorIn(Set.of(anchorEntity)));
316     }
317
318     @Override
319     @Transactional
320     public void deleteListDataNode(final String dataspaceName, final String anchorName,
321                                    final String targetXpath) {
322         deleteDataNode(dataspaceName, anchorName, targetXpath, true);
323     }
324
325     @Override
326     @Transactional
327     public void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath) {
328         deleteDataNode(dataspaceName, anchorName, targetXpath, false);
329     }
330
331     private void deleteDataNode(final String dataspaceName, final String anchorName, final String targetXpath,
332                                 final boolean onlySupportListNodeDeletion) {
333         final String parentNodeXpath = targetXpath.substring(0, targetXpath.lastIndexOf('/'));
334         final FragmentEntity parentFragmentEntity = getFragmentByXpath(dataspaceName, anchorName, parentNodeXpath);
335         final String lastXpathElement = targetXpath.substring(targetXpath.lastIndexOf('/'));
336         final boolean isListElement = REG_EX_PATTERN_FOR_LIST_ELEMENT_KEY_PREDICATE.matcher(lastXpathElement).find();
337         boolean targetExist;
338         if (isListElement) {
339             targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
340         } else {
341             targetExist = deleteAllListElements(parentFragmentEntity, targetXpath);
342             final boolean tryToDeleteDataNode = !targetExist && !onlySupportListNodeDeletion;
343             if (tryToDeleteDataNode) {
344                 targetExist = deleteDataNode(parentFragmentEntity, targetXpath);
345             }
346         }
347         if (!targetExist) {
348             final String additionalInformation = onlySupportListNodeDeletion
349                 ? "The target is probably not a List." : "";
350             throw new DataNodeNotFoundException(parentFragmentEntity.getDataspace().getName(),
351                 parentFragmentEntity.getAnchor().getName(), targetXpath, additionalInformation);
352         }
353     }
354
355     private boolean deleteDataNode(final FragmentEntity parentFragmentEntity, final String targetXpath) {
356         if (parentFragmentEntity.getChildFragments()
357             .removeIf(fragment -> fragment.getXpath().equals(targetXpath))) {
358             fragmentRepository.save(parentFragmentEntity);
359             return true;
360         }
361         return false;
362     }
363
364
365     private boolean deleteAllListElements(final FragmentEntity parentFragmentEntity, final String listXpath) {
366         final String deleteTargetXpathPrefix = listXpath + "[";
367         if (parentFragmentEntity.getChildFragments()
368             .removeIf(fragment -> fragment.getXpath().startsWith(deleteTargetXpathPrefix))) {
369             fragmentRepository.save(parentFragmentEntity);
370             return true;
371         }
372         return false;
373     }
374
375     private static void deleteListElements(
376         final Collection<FragmentEntity> fragmentEntities,
377         final Map<String, FragmentEntity> existingListElementFragmentEntitiesByXPath) {
378         fragmentEntities.removeAll(existingListElementFragmentEntitiesByXPath.values());
379     }
380
381     private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) {
382         if (newListElements.isEmpty()) {
383             throw new CpsAdminException("Invalid list replacement",
384                 "Cannot replace list elements with empty collection");
385         }
386         final String firstChildNodeXpath = newListElements.iterator().next().getXpath();
387         return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf("[") + 1);
388     }
389
390     private FragmentEntity getFragmentForReplacement(final FragmentEntity parentEntity,
391                                                             final DataNode newListElement,
392                                                             final FragmentEntity existingListElementEntity) {
393         if (existingListElementEntity == null) {
394             return convertToFragmentWithAllDescendants(
395                 parentEntity.getDataspace(), parentEntity.getAnchor(), newListElement);
396         }
397         if (newListElement.getChildDataNodes().isEmpty()) {
398             copyAttributesFromNewListElement(existingListElementEntity, newListElement);
399             existingListElementEntity.getChildFragments().clear();
400         } else {
401             replaceDataNodeTree(existingListElementEntity, newListElement);
402         }
403         return existingListElementEntity;
404     }
405
406     private static boolean isNewDataNode(final DataNode replacementDataNode,
407                                          final Map<String, FragmentEntity> existingListElementsByXpath) {
408         return !existingListElementsByXpath.containsKey(replacementDataNode.getXpath());
409     }
410
411     private void copyAttributesFromNewListElement(final FragmentEntity existingListElementEntity,
412                                                          final DataNode newListElement) {
413         final FragmentEntity replacementFragmentEntity =
414                 FragmentEntity.builder().attributes(jsonObjectMapper.asJsonString(
415                         newListElement.getLeaves())).build();
416         existingListElementEntity.setAttributes(replacementFragmentEntity.getAttributes());
417     }
418
419     private static Map<String, FragmentEntity> extractListElementFragmentEntitiesByXPath(
420         final Set<FragmentEntity> childEntities, final String listElementXpathPrefix) {
421         return childEntities.stream()
422             .filter(fragmentEntity -> fragmentEntity.getXpath().startsWith(listElementXpathPrefix))
423             .collect(Collectors.toMap(FragmentEntity::getXpath, fragmentEntity -> fragmentEntity));
424     }
425
426     private static boolean isRootXpath(final String xpath) {
427         return "/".equals(xpath) || "".equals(xpath);
428     }
429 }