Implement cps path query to get ancestor by schema node identifier
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsDataPersistenceServiceImpl.java
1 /*
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
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.spi.impl;
23
24 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
25
26 import com.google.common.collect.ImmutableSet;
27 import com.google.common.collect.ImmutableSet.Builder;
28 import com.google.gson.Gson;
29 import com.google.gson.GsonBuilder;
30 import java.util.Collections;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.regex.Pattern;
36 import java.util.stream.Collectors;
37 import org.onap.cps.spi.CpsDataPersistenceService;
38 import org.onap.cps.spi.FetchDescendantsOption;
39 import org.onap.cps.spi.entities.AnchorEntity;
40 import org.onap.cps.spi.entities.DataspaceEntity;
41 import org.onap.cps.spi.entities.FragmentEntity;
42 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
43 import org.onap.cps.spi.model.DataNode;
44 import org.onap.cps.spi.model.DataNodeBuilder;
45 import org.onap.cps.spi.query.CpsPathQuery;
46 import org.onap.cps.spi.query.CpsPathQueryType;
47 import org.onap.cps.spi.repository.AnchorRepository;
48 import org.onap.cps.spi.repository.DataspaceRepository;
49 import org.onap.cps.spi.repository.FragmentRepository;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.dao.DataIntegrityViolationException;
52 import org.springframework.stereotype.Service;
53
54 @Service
55 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
56
57     @Autowired
58     private DataspaceRepository dataspaceRepository;
59
60     @Autowired
61     private AnchorRepository anchorRepository;
62
63     @Autowired
64     private FragmentRepository fragmentRepository;
65
66     private static final Gson GSON = new GsonBuilder().create();
67     private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@\\S+?]){0,1})";
68
69     @Override
70     public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentXpath,
71         final DataNode dataNode) {
72         final FragmentEntity parentFragment = getFragmentByXpath(dataspaceName, anchorName, parentXpath);
73         final var fragmentEntity =
74             toFragmentEntity(parentFragment.getDataspace(), parentFragment.getAnchor(), dataNode);
75         parentFragment.getChildFragments().add(fragmentEntity);
76         fragmentRepository.save(parentFragment);
77     }
78
79     @Override
80     public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
81         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
82         final var anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
83         final var fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
84             dataNode);
85         try {
86             fragmentRepository.save(fragmentEntity);
87         } catch (final DataIntegrityViolationException exception) {
88             throw AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
89         }
90     }
91
92     /**
93      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
94      * for all DataNode children recursively.
95      *
96      * @param dataspaceEntity       dataspace
97      * @param anchorEntity          anchorEntity
98      * @param dataNodeToBeConverted dataNode
99      * @return a Fragment built from current DataNode
100      */
101     private static FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
102         final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
103         final var parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
104         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
105         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
106             final FragmentEntity childFragment =
107                 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
108                     childDataNode);
109             childFragmentsImmutableSetBuilder.add(childFragment);
110         }
111         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
112         return parentFragment;
113     }
114
115     private static FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
116         final AnchorEntity anchorEntity, final DataNode dataNode) {
117         return FragmentEntity.builder()
118             .dataspace(dataspaceEntity)
119             .anchor(anchorEntity)
120             .xpath(dataNode.getXpath())
121             .attributes(GSON.toJson(dataNode.getLeaves()))
122             .build();
123     }
124
125     @Override
126     public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
127         final FetchDescendantsOption fetchDescendantsOption) {
128         final var fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
129         return toDataNode(fragmentEntity, fetchDescendantsOption);
130     }
131
132     private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
133         final String xpath) {
134         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
135         final var anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
136         if (isRootXpath(xpath)) {
137             return fragmentRepository.getFirstByDataspaceAndAnchor(dataspaceEntity, anchorEntity);
138         } else {
139             return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity,
140                 xpath);
141         }
142     }
143
144     @Override
145     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
146         final FetchDescendantsOption fetchDescendantsOption) {
147         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
148         final var anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
149         final var cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
150         List<FragmentEntity> fragmentEntities;
151         if (CpsPathQueryType.XPATH_LEAF_VALUE.equals(cpsPathQuery.getCpsPathQueryType())) {
152             fragmentEntities = fragmentRepository
153                 .getByAnchorAndXpathAndLeafAttributes(anchorEntity.getId(), cpsPathQuery.getXpathPrefix(),
154                     cpsPathQuery.getLeafName(), cpsPathQuery.getLeafValue());
155         } else if (CpsPathQueryType.XPATH_HAS_DESCENDANT_WITH_LEAF_VALUES.equals(cpsPathQuery.getCpsPathQueryType())) {
156             final String leafDataAsJson = GSON.toJson(cpsPathQuery.getLeavesData());
157             fragmentEntities = fragmentRepository
158                 .getByAnchorAndDescendentNameAndLeafValues(anchorEntity.getId(), cpsPathQuery.getDescendantName(),
159                     leafDataAsJson);
160         } else {
161             fragmentEntities = fragmentRepository
162                 .getByAnchorAndXpathEndsInDescendantName(anchorEntity.getId(), cpsPathQuery.getDescendantName());
163         }
164         if (cpsPathQuery.hasAncestorAxis()) {
165             final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
166             fragmentEntities = ancestorXpaths.isEmpty()
167                 ? Collections.emptyList() : fragmentRepository.findAllByAnchorAndXpathIn(anchorEntity, ancestorXpaths);
168         }
169         return fragmentEntities.stream()
170             .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
171             .collect(Collectors.toUnmodifiableList());
172     }
173
174     private static Set<String> processAncestorXpath(final List<FragmentEntity> fragmentEntities,
175         final CpsPathQuery cpsPathQuery) {
176         final Set<String> ancestorXpath = new HashSet<>();
177         final var pattern =
178             Pattern.compile("(\\S*\\/" + cpsPathQuery.getAncestorSchemaNodeIdentifier() + REG_EX_FOR_OPTIONAL_LIST_INDEX
179                 + "\\/\\S*");
180         for (final FragmentEntity fragmentEntity : fragmentEntities) {
181             final var matcher = pattern.matcher(fragmentEntity.getXpath());
182             if (matcher.matches()) {
183                 ancestorXpath.add(matcher.group(1));
184             }
185         }
186         return ancestorXpath;
187     }
188
189     private static DataNode toDataNode(final FragmentEntity fragmentEntity,
190         final FetchDescendantsOption fetchDescendantsOption) {
191         final Map<String, Object> leaves = GSON.fromJson(fragmentEntity.getAttributes(), Map.class);
192         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
193         return new DataNodeBuilder()
194             .withXpath(fragmentEntity.getXpath())
195             .withLeaves(leaves)
196             .withChildDataNodes(childDataNodes).build();
197     }
198
199     private static List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
200         final FetchDescendantsOption fetchDescendantsOption) {
201         if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
202             return fragmentEntity.getChildFragments().stream()
203                 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
204                 .collect(Collectors.toUnmodifiableList());
205         }
206         return Collections.emptyList();
207     }
208
209     @Override
210     public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
211         final Map<String, Object> leaves) {
212         final var fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
213         fragmentEntity.setAttributes(GSON.toJson(leaves));
214         fragmentRepository.save(fragmentEntity);
215     }
216
217     @Override
218     public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
219         final var fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
220         removeExistingDescendants(fragmentEntity);
221
222         fragmentEntity.setAttributes(GSON.toJson(dataNode.getLeaves()));
223         final Set<FragmentEntity> childFragmentEntities = dataNode.getChildDataNodes().stream().map(
224             childDataNode -> convertToFragmentWithAllDescendants(
225                 fragmentEntity.getDataspace(), fragmentEntity.getAnchor(), childDataNode)
226         ).collect(Collectors.toUnmodifiableSet());
227         fragmentEntity.setChildFragments(childFragmentEntities);
228
229         fragmentRepository.save(fragmentEntity);
230     }
231
232     private void removeExistingDescendants(final FragmentEntity fragmentEntity) {
233         fragmentEntity.setChildFragments(Collections.emptySet());
234         fragmentRepository.save(fragmentEntity);
235     }
236
237     private boolean isRootXpath(final String xpath) {
238         return "/".equals(xpath) || "".equals(xpath);
239     }
240 }