Internal Server Error when creating the same data node twice
[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  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.spi.impl;
22
23 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
24
25 import com.google.common.collect.ImmutableSet;
26 import com.google.common.collect.ImmutableSet.Builder;
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.stream.Collectors;
34 import org.onap.cps.spi.CpsDataPersistenceService;
35 import org.onap.cps.spi.FetchDescendantsOption;
36 import org.onap.cps.spi.entities.AnchorEntity;
37 import org.onap.cps.spi.entities.DataspaceEntity;
38 import org.onap.cps.spi.entities.FragmentEntity;
39 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
40 import org.onap.cps.spi.model.DataNode;
41 import org.onap.cps.spi.model.DataNodeBuilder;
42 import org.onap.cps.spi.query.CpsPathQuery;
43 import org.onap.cps.spi.query.CpsPathQueryType;
44 import org.onap.cps.spi.repository.AnchorRepository;
45 import org.onap.cps.spi.repository.DataspaceRepository;
46 import org.onap.cps.spi.repository.FragmentRepository;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.dao.DataIntegrityViolationException;
49 import org.springframework.stereotype.Service;
50
51 @Service
52 public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
53
54     @Autowired
55     private DataspaceRepository dataspaceRepository;
56
57     @Autowired
58     private AnchorRepository anchorRepository;
59
60     @Autowired
61     private FragmentRepository fragmentRepository;
62
63     private static final Gson GSON = new GsonBuilder().create();
64
65     @Override
66     public void addChildDataNode(final String dataspaceName, final String anchorName, final String parentXpath,
67         final DataNode dataNode) {
68         final FragmentEntity parentFragment = getFragmentByXpath(dataspaceName, anchorName, parentXpath);
69         final FragmentEntity fragmentEntity =
70             toFragmentEntity(parentFragment.getDataspace(), parentFragment.getAnchor(), dataNode);
71         parentFragment.getChildFragments().add(fragmentEntity);
72         fragmentRepository.save(parentFragment);
73     }
74
75     @Override
76     public void storeDataNode(final String dataspaceName, final String anchorName, final DataNode dataNode) {
77         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
78         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
79         final FragmentEntity fragmentEntity = convertToFragmentWithAllDescendants(dataspaceEntity, anchorEntity,
80             dataNode);
81         try {
82             fragmentRepository.save(fragmentEntity);
83         } catch (final DataIntegrityViolationException exception) {
84             throw  AlreadyDefinedException.forDataNode(dataNode.getXpath(), anchorName, exception);
85         }
86     }
87
88     /**
89      * Convert DataNode object into Fragment and places the result in the fragments placeholder. Performs same action
90      * for all DataNode children recursively.
91      *
92      * @param dataspaceEntity       dataspace
93      * @param anchorEntity          anchorEntity
94      * @param dataNodeToBeConverted dataNode
95      * @return a Fragment built from current DataNode
96      */
97     private static FragmentEntity convertToFragmentWithAllDescendants(final DataspaceEntity dataspaceEntity,
98         final AnchorEntity anchorEntity, final DataNode dataNodeToBeConverted) {
99         final FragmentEntity parentFragment = toFragmentEntity(dataspaceEntity, anchorEntity, dataNodeToBeConverted);
100         final Builder<FragmentEntity> childFragmentsImmutableSetBuilder = ImmutableSet.builder();
101         for (final DataNode childDataNode : dataNodeToBeConverted.getChildDataNodes()) {
102             final FragmentEntity childFragment =
103                 convertToFragmentWithAllDescendants(parentFragment.getDataspace(), parentFragment.getAnchor(),
104                     childDataNode);
105             childFragmentsImmutableSetBuilder.add(childFragment);
106         }
107         parentFragment.setChildFragments(childFragmentsImmutableSetBuilder.build());
108         return parentFragment;
109     }
110
111     private static FragmentEntity toFragmentEntity(final DataspaceEntity dataspaceEntity,
112         final AnchorEntity anchorEntity, final DataNode dataNode) {
113         return FragmentEntity.builder()
114             .dataspace(dataspaceEntity)
115             .anchor(anchorEntity)
116             .xpath(dataNode.getXpath())
117             .attributes(GSON.toJson(dataNode.getLeaves()))
118             .build();
119     }
120
121     @Override
122     public DataNode getDataNode(final String dataspaceName, final String anchorName, final String xpath,
123         final FetchDescendantsOption fetchDescendantsOption) {
124         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
125         return toDataNode(fragmentEntity, fetchDescendantsOption);
126     }
127
128     private FragmentEntity getFragmentByXpath(final String dataspaceName, final String anchorName,
129         final String xpath) {
130         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
131         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
132         return fragmentRepository.getByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, xpath);
133     }
134
135     @Override
136     public List<DataNode> queryDataNodes(final String dataspaceName, final String anchorName, final String cpsPath,
137         final FetchDescendantsOption fetchDescendantsOption) {
138         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
139         final AnchorEntity anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, anchorName);
140         final CpsPathQuery cpsPathQuery = CpsPathQuery.createFrom(cpsPath);
141         final List<FragmentEntity> fragmentEntities;
142         if (CpsPathQueryType.XPATH_LEAF_VALUE.equals(cpsPathQuery.getCpsPathQueryType())) {
143             fragmentEntities = fragmentRepository
144                 .getByAnchorAndXpathAndLeafAttributes(anchorEntity.getId(), cpsPathQuery.getXpathPrefix(), cpsPathQuery
145                     .getLeafName(), cpsPathQuery.getLeafValue());
146         } else {
147             fragmentEntities = fragmentRepository
148                 .getByAnchorAndEndsWithXpath(anchorEntity.getId(), cpsPathQuery.getEndsWith());
149         }
150         return fragmentEntities.stream()
151             .map(fragmentEntity -> toDataNode(fragmentEntity, fetchDescendantsOption))
152             .collect(Collectors.toUnmodifiableList());
153     }
154
155     private static DataNode toDataNode(final FragmentEntity fragmentEntity,
156         final FetchDescendantsOption fetchDescendantsOption) {
157         final Map<String, Object> leaves = GSON.fromJson(fragmentEntity.getAttributes(), Map.class);
158         final List<DataNode> childDataNodes = getChildDataNodes(fragmentEntity, fetchDescendantsOption);
159         return new DataNodeBuilder()
160             .withXpath(fragmentEntity.getXpath())
161             .withLeaves(leaves)
162             .withChildDataNodes(childDataNodes).build();
163     }
164
165     private static List<DataNode> getChildDataNodes(final FragmentEntity fragmentEntity,
166         final FetchDescendantsOption fetchDescendantsOption) {
167         if (fetchDescendantsOption == INCLUDE_ALL_DESCENDANTS) {
168             return fragmentEntity.getChildFragments().stream()
169                 .map(childFragmentEntity -> toDataNode(childFragmentEntity, fetchDescendantsOption))
170                 .collect(Collectors.toUnmodifiableList());
171         }
172         return Collections.emptyList();
173     }
174
175     @Override
176     public void updateDataLeaves(final String dataspaceName, final String anchorName, final String xpath,
177         final Map<String, Object> leaves) {
178         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, xpath);
179         fragmentEntity.setAttributes(GSON.toJson(leaves));
180         fragmentRepository.save(fragmentEntity);
181     }
182
183     @Override
184     public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
185         final FragmentEntity fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
186         removeExistingDescendants(fragmentEntity);
187
188         fragmentEntity.setAttributes(GSON.toJson(dataNode.getLeaves()));
189         final Set<FragmentEntity> childFragmentEntities = dataNode.getChildDataNodes().stream().map(
190             childDataNode -> convertToFragmentWithAllDescendants(
191                 fragmentEntity.getDataspace(), fragmentEntity.getAnchor(), childDataNode)
192         ).collect(Collectors.toUnmodifiableSet());
193         fragmentEntity.setChildFragments(childFragmentEntities);
194
195         fragmentRepository.save(fragmentEntity);
196     }
197
198     private void removeExistingDescendants(final FragmentEntity fragmentEntity) {
199         fragmentEntity.setChildFragments(Collections.emptySet());
200         fragmentRepository.save(fragmentEntity);
201     }
202 }