2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.model.operations.impl;
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;
56 import java.lang.reflect.Type;
57 import java.util.List;
59 import java.util.function.Supplier;
60 import java.util.stream.Collectors;
62 public abstract class AbstractOperation {
64 private static final Logger log = Logger.getLogger(AbstractOperation.class.getName());
67 protected TitanGenericDao titanGenericDao;
69 public static final String EMPTY_VALUE = null;
71 protected Gson gson = new Gson();
74 protected ApplicationDataTypeCache applicationDataTypeCache;
76 protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
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);
83 SomeData someData = dataBuilder.get();
85 log.debug("Before adding {} to graph. data = {}", defName, someData);
87 @SuppressWarnings("unchecked")
88 Either<SomeData, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData, (Class<SomeData>) someData.getClass());
90 log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);
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);
97 UniqueIdData uniqueIdData = new UniqueIdData(nodeType, nodeUniqueId);
98 log.debug("Before associating {} to {}.", uniqueIdData, defName);
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);
106 return Either.left(eitherSomeData.left().value());
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);
114 SomeData someData = dataBuilder.get();
116 log.debug("Before adding {} to graph. data = {}", defName, someData);
118 @SuppressWarnings("unchecked")
119 Either<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData);
121 log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);
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;
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);
137 interface NodeElementFetcher<ElementDefinition> {
138 TitanOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill);
141 public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
143 if (log.isTraceEnabled())
144 log.trace("Going to fetch elements under resource {}", resourceId);
145 TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
147 if (resourceAttributesStatus != TitanOperationStatus.OK) {
148 return resourceAttributesStatus;
151 Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
152 ResourceMetadataData.class);
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;
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);
167 if (addParentIntStatus != TitanOperationStatus.OK) {
168 BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
170 return addParentIntStatus;
173 return TitanOperationStatus.OK;
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();
182 log.debug("Going to execute commit on graph.");
183 titanGenericDao.commit();
190 * @param propertyDefinition
194 protected StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
196 log.trace("Going to validate property type and value. {}", propertyDefinition);
198 String propertyType = propertyDefinition.getType();
199 String value = propertyDefinition.getDefaultValue();
201 ToscaPropertyType type = getType(propertyType);
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;
211 return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
214 String innerType = null;
216 Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
217 if (checkInnerType.isRight()) {
218 return StorageOperationStatus.INVALID_TYPE;
220 innerType = checkInnerType.left().value();
222 log.trace("After validating property type {}", propertyType);
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;
230 PropertyValueConverter converter = type.getConverter();
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);
239 return StorageOperationStatus.OK;
242 protected ToscaPropertyType getType(String propertyType) {
244 return ToscaPropertyType.isValidType(propertyType);
248 protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
249 if (isEmptyValue(value)) {
253 PropertyTypeValidator validator = type.getValidator();
255 return validator.isValid(value, innerType, dataTypes);
258 public boolean isEmptyValue(String value) {
259 return value == null;
262 public boolean isNullParam(String value) {
263 return value == null;
266 protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
268 String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
270 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
272 if (!validateResult.right.booleanValue()) {
273 log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
274 return StorageOperationStatus.INVALID_VALUE;
277 JsonElement jsonElement = validateResult.left;
279 log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
281 updateValue(propertyDefinition, jsonElement);
283 return StorageOperationStatus.OK;
286 protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
288 propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
292 protected String getValueFromJsonElement(JsonElement jsonElement) {
295 if (jsonElement == null || jsonElement.isJsonNull()) {
298 value = jsonElement.toString();
304 protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
305 String innerType = null;
306 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
308 SchemaDefinition def = schemeGen.get();
310 log.debug("Schema doesn't exists for property of type {}", type);
311 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
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);
318 innerType = propDef.getType();
320 return Either.left(innerType);
324 * Convert Constarint object to json in order to add it to the Graph
329 public List<String> convertConstraintsToString(List<PropertyConstraint> constraints) {
331 if (constraints == null || constraints.isEmpty()) {
335 return constraints.stream().map(gson::toJson).collect(Collectors.toList());
338 public List<PropertyConstraint> convertConstraints(List<String> constraints) {
340 if (constraints == null || constraints.isEmpty()) {
344 Type constraintType = new TypeToken<PropertyConstraint>() {
347 Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
349 return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList());