re base code
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / operations / impl / AbstractOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.model.operations.impl;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonElement;
26 import com.google.gson.reflect.TypeToken;
27 import com.thinkaurelius.titan.core.TitanVertex;
28 import fj.data.Either;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.openecomp.sdc.be.config.BeEcompErrorManager;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
32 import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
33 import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
34 import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
35 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
36 import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
37 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
38 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
39 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
40 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
41 import org.openecomp.sdc.be.model.DataTypeDefinition;
42 import org.openecomp.sdc.be.model.IComplexDefaultValue;
43 import org.openecomp.sdc.be.model.PropertyConstraint;
44 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
47 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
48 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
49 import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
50 import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
51 import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
52 import org.openecomp.sdc.be.resources.data.UniqueIdData;
53 import org.openecomp.sdc.common.log.wrappers.Logger;
54 import org.springframework.beans.factory.annotation.Autowired;
55
56 import java.lang.reflect.Type;
57 import java.util.List;
58 import java.util.Map;
59 import java.util.function.Supplier;
60 import java.util.stream.Collectors;
61
62 public abstract class AbstractOperation {
63
64     private static final Logger log = Logger.getLogger(AbstractOperation.class.getName());
65
66     @Autowired
67     protected TitanGenericDao titanGenericDao;
68
69     public static final String EMPTY_VALUE = null;
70
71     protected Gson gson = new Gson();
72
73     @Autowired
74     protected ApplicationDataTypeCache applicationDataTypeCache;
75
76     protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
77
78     protected <SomeData extends GraphNode, SomeDefenition> Either<SomeData, TitanOperationStatus> addDefinitionToNodeType(SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType,
79             Supplier<SomeData> dataBuilder, Supplier<String> defNameGenerator) {
80         String defName = defNameGenerator.get();
81         log.debug("Got {} {}", defName, someDefinition);
82
83         SomeData someData = dataBuilder.get();
84
85         log.debug("Before adding {} to graph. data = {}", defName, someData);
86
87         @SuppressWarnings("unchecked")
88         Either<SomeData, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData, (Class<SomeData>) someData.getClass());
89
90         log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);
91
92         if (eitherSomeData.isRight()) {
93             TitanOperationStatus operationStatus = eitherSomeData.right().value();
94             log.error("Failed to add {}  to graph. status is {}", defName, operationStatus);
95             return Either.right(operationStatus);
96         }
97         UniqueIdData uniqueIdData = new UniqueIdData(nodeType, nodeUniqueId);
98         log.debug("Before associating {} to {}.", uniqueIdData, defName);
99
100         Either<GraphRelation, TitanOperationStatus> eitherRelations = titanGenericDao.createRelation(uniqueIdData, eitherSomeData.left().value(), edgeType, null);
101         if (eitherRelations.isRight()) {
102             TitanOperationStatus operationStatus = eitherRelations.right().value();
103             BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus, ErrorSeverity.ERROR);
104             return Either.right(operationStatus);
105         }
106         return Either.left(eitherSomeData.left().value());
107     }
108
109     protected <SomeData extends GraphNode, SomeDefenition> TitanOperationStatus addDefinitionToNodeType(TitanVertex vertex, SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType,
110             Supplier<SomeData> dataBuilder, Supplier<String> defNameGenerator) {
111         String defName = defNameGenerator.get();
112         log.debug("Got {} {}", defName, someDefinition);
113
114         SomeData someData = dataBuilder.get();
115
116         log.debug("Before adding {} to graph. data = {}", defName, someData);
117
118         @SuppressWarnings("unchecked")
119         Either<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData);
120
121         log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);
122
123         if (eitherSomeData.isRight()) {
124             TitanOperationStatus operationStatus = eitherSomeData.right().value();
125             log.error("Failed to add {}  to graph. status is {}", defName, operationStatus);
126             return operationStatus;
127         }
128
129         TitanOperationStatus relations = titanGenericDao.createEdge(vertex, eitherSomeData.left().value(), edgeType, null);
130         if (!relations.equals(TitanOperationStatus.OK)) {
131             BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + relations, ErrorSeverity.ERROR);
132             return relations;
133         }
134         return relations;
135     }
136
137     interface NodeElementFetcher<ElementDefinition> {
138         TitanOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill);
139     }
140
141     public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
142
143         if (log.isTraceEnabled())
144             log.trace("Going to fetch elements under resource {}", resourceId);
145         TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
146
147         if (resourceAttributesStatus != TitanOperationStatus.OK) {
148             return resourceAttributesStatus;
149         }
150
151         Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
152                 ResourceMetadataData.class);
153
154         if (parentNodes.isRight()) {
155             TitanOperationStatus parentNodesStatus = parentNodes.right().value();
156             if (parentNodesStatus != TitanOperationStatus.NOT_FOUND) {
157                 BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR);
158                 return parentNodesStatus;
159             }
160         }
161
162         if (parentNodes.isLeft()) {
163             ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
164             String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
165             TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher);
166
167             if (addParentIntStatus != TitanOperationStatus.OK) {
168                 BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
169
170                 return addParentIntStatus;
171             }
172         }
173         return TitanOperationStatus.OK;
174     }
175
176     protected <T, TStatus> void handleTransactionCommitRollback(boolean inTransaction, Either<T, TStatus> result) {
177         if (!inTransaction) {
178             if (result == null || result.isRight()) {
179                 log.error("Going to execute rollback on graph.");
180                 titanGenericDao.rollback();
181             } else {
182                 log.debug("Going to execute commit on graph.");
183                 titanGenericDao.commit();
184             }
185         }
186     }
187
188
189     /**
190      * @param propertyDefinition
191      * @return
192      */
193
194     protected StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
195
196         log.trace("Going to validate property type and value. {}", propertyDefinition);
197
198         String propertyType = propertyDefinition.getType();
199         String value = propertyDefinition.getDefaultValue();
200
201         ToscaPropertyType type = getType(propertyType);
202
203         if (type == null) {
204
205             DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
206             if (dataTypeDefinition == null) {
207                 log.debug("The type {}  of property cannot be found.", propertyType);
208                 return StorageOperationStatus.INVALID_TYPE;
209             }
210
211             return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
212
213         }
214         String innerType = null;
215
216         Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
217         if (checkInnerType.isRight()) {
218             return StorageOperationStatus.INVALID_TYPE;
219         }
220         innerType = checkInnerType.left().value();
221
222         log.trace("After validating property type {}", propertyType);
223
224         boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
225         if (!isValidProperty) {
226             log.info("The value {} of property from type {} is invalid", value, type);
227             return StorageOperationStatus.INVALID_VALUE;
228         }
229
230         PropertyValueConverter converter = type.getConverter();
231
232         if (isEmptyValue(value)) {
233             log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
234             propertyDefinition.setDefaultValue(EMPTY_VALUE);
235         } else if (!isEmptyValue(value)) {
236             String convertedValue = converter.convert(value, innerType, dataTypes);
237             propertyDefinition.setDefaultValue(convertedValue);
238         }
239         return StorageOperationStatus.OK;
240     }
241
242     protected ToscaPropertyType getType(String propertyType) {
243
244         return ToscaPropertyType.isValidType(propertyType);
245
246     }
247
248     protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
249         if (isEmptyValue(value)) {
250             return true;
251         }
252
253         PropertyTypeValidator validator = type.getValidator();
254
255         return validator.isValid(value, innerType, dataTypes);
256     }
257
258     public boolean isEmptyValue(String value) {
259         return value == null;
260     }
261
262     public boolean isNullParam(String value) {
263         return value == null;
264     }
265
266     protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
267
268             String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
269
270         ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
271
272         if (!validateResult.right.booleanValue()) {
273             log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
274             return StorageOperationStatus.INVALID_VALUE;
275         }
276
277         JsonElement jsonElement = validateResult.left;
278
279         log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
280
281         updateValue(propertyDefinition, jsonElement);
282
283         return StorageOperationStatus.OK;
284     }
285
286     protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
287
288         propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
289
290     }
291
292     protected String getValueFromJsonElement(JsonElement jsonElement) {
293         String value = null;
294
295         if (jsonElement == null || jsonElement.isJsonNull()) {
296             value = EMPTY_VALUE;
297         } else {
298             value = jsonElement.toString();
299         }
300
301         return value;
302     }
303
304     protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
305         String innerType = null;
306         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
307
308             SchemaDefinition def = schemeGen.get();
309             if (def == null) {
310                 log.debug("Schema doesn't exists for property of type {}", type);
311                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
312             }
313             PropertyDataDefinition propDef = def.getProperty();
314             if (propDef == null) {
315                 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
316                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
317             }
318             innerType = propDef.getType();
319         }
320         return Either.left(innerType);
321     }
322
323     /**
324      * Convert Constarint object to json in order to add it to the Graph
325      *
326      * @param constraints
327      * @return
328      */
329     public List<String> convertConstraintsToString(List<PropertyConstraint> constraints) {
330
331         if (constraints == null || constraints.isEmpty()) {
332             return null;
333         }
334
335         return constraints.stream().map(gson::toJson).collect(Collectors.toList());
336     }
337
338     public List<PropertyConstraint> convertConstraints(List<String> constraints) {
339
340         if (constraints == null || constraints.isEmpty()) {
341             return null;
342         }
343
344         Type constraintType = new TypeToken<PropertyConstraint>() {
345         }.getType();
346
347         Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
348
349         return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList());
350     }
351
352 }