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 java.lang.reflect.Type;
24 import java.util.List;
26 import java.util.function.Function;
27 import java.util.function.Supplier;
28 import java.util.stream.Collectors;
30 import org.apache.commons.lang3.tuple.ImmutablePair;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
33 import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
34 import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
35 import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
36 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
37 import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
38 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
39 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
41 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
42 import org.openecomp.sdc.be.model.DataTypeDefinition;
43 import org.openecomp.sdc.be.model.IComplexDefaultValue;
44 import org.openecomp.sdc.be.model.PropertyConstraint;
45 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
46 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
47 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
48 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
49 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
50 import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
51 import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
52 import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
53 import org.openecomp.sdc.be.resources.data.UniqueIdData;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 import com.google.gson.Gson;
58 import com.google.gson.GsonBuilder;
59 import com.google.gson.JsonElement;
60 import com.google.gson.reflect.TypeToken;
61 import com.thinkaurelius.titan.core.TitanVertex;
63 import fj.data.Either;
65 public abstract class AbstractOperation {
66 private static Logger log = LoggerFactory.getLogger(AbstractOperation.class.getName());
67 @javax.annotation.Resource
68 protected TitanGenericDao titanGenericDao;
69 public static final String EMPTY_VALUE = null;
71 protected Gson gson = new Gson();
73 @javax.annotation.Resource
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 TitanOperationStatus operationStatus = relations;
132 BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus, ErrorSeverity.ERROR);
133 return operationStatus;
138 interface NodeElementFetcher<ElementDefinition> {
139 TitanOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill);
142 public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
144 if (log.isTraceEnabled())
145 log.trace("Going to fetch elements under resource {}", resourceId);
146 TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
148 if (resourceAttributesStatus != TitanOperationStatus.OK) {
149 return resourceAttributesStatus;
152 Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
153 ResourceMetadataData.class);
155 if (parentNodes.isRight()) {
156 TitanOperationStatus parentNodesStatus = parentNodes.right().value();
157 if (parentNodesStatus != TitanOperationStatus.NOT_FOUND) {
158 BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR);
159 return parentNodesStatus;
163 if (parentNodes.isLeft()) {
164 ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
165 String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
166 TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher);
168 if (addParentIntStatus != TitanOperationStatus.OK) {
169 BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
171 return addParentIntStatus;
174 return TitanOperationStatus.OK;
177 protected <T, TStatus> void handleTransactionCommitRollback(boolean inTransaction, Either<T, TStatus> result) {
178 if (!inTransaction) {
179 if (result == null || result.isRight()) {
180 log.error("Going to execute rollback on graph.");
181 titanGenericDao.rollback();
183 log.debug("Going to execute commit on graph.");
184 titanGenericDao.commit();
189 public <ElementTypeDefinition> Either<ElementTypeDefinition, StorageOperationStatus> getElementType(Function<String, Either<ElementTypeDefinition, TitanOperationStatus>> elementGetter, String uniqueId, boolean inTransaction) {
190 Either<ElementTypeDefinition, StorageOperationStatus> result = null;
193 Either<ElementTypeDefinition, TitanOperationStatus> ctResult = elementGetter.apply(uniqueId);
195 if (ctResult.isRight()) {
196 TitanOperationStatus status = ctResult.right().value();
197 if (status != TitanOperationStatus.NOT_FOUND) {
198 log.error("Failed to retrieve information on element uniqueId: {}. status is {}", uniqueId, status);
200 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value()));
204 result = Either.left(ctResult.left().value());
208 handleTransactionCommitRollback(inTransaction, result);
215 * @param propertyDefinition
219 protected StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
221 log.trace("Going to validate property type and value. {}", propertyDefinition);
223 String propertyType = propertyDefinition.getType();
224 String value = propertyDefinition.getDefaultValue();
226 ToscaPropertyType type = getType(propertyType);
230 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
231 if (dataTypeDefinition == null) {
232 log.debug("The type {} of property cannot be found.", propertyType);
233 return StorageOperationStatus.INVALID_TYPE;
236 StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
241 String innerType = null;
243 Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema());
244 if (checkInnerType.isRight()) {
245 return StorageOperationStatus.INVALID_TYPE;
247 innerType = checkInnerType.left().value();
249 log.trace("After validating property type {}", propertyType);
251 boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
252 if (false == isValidProperty) {
253 log.info("The value {} of property from type {} is invalid", value, type);
254 return StorageOperationStatus.INVALID_VALUE;
257 PropertyValueConverter converter = type.getConverter();
259 if (isEmptyValue(value)) {
260 log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
261 propertyDefinition.setDefaultValue(EMPTY_VALUE);
262 } else if (false == isEmptyValue(value)) {
263 String convertedValue = converter.convert(value, innerType, dataTypes);
264 propertyDefinition.setDefaultValue(convertedValue);
266 return StorageOperationStatus.OK;
269 protected ToscaPropertyType getType(String propertyType) {
271 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
277 protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
278 if (isEmptyValue(value)) {
282 PropertyTypeValidator validator = type.getValidator();
284 return validator.isValid(value, innerType, dataTypes);
287 public boolean isEmptyValue(String value) {
288 return value == null;
291 public boolean isNullParam(String value) {
292 return value == null;
295 protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
297 String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
299 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
301 if (validateResult.right.booleanValue() == false) {
302 log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
303 return StorageOperationStatus.INVALID_VALUE;
306 JsonElement jsonElement = validateResult.left;
308 log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
310 updateValue(propertyDefinition, jsonElement);
312 return StorageOperationStatus.OK;
315 protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
317 propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
321 protected String getValueFromJsonElement(JsonElement jsonElement) {
324 if (jsonElement == null || jsonElement.isJsonNull()) {
327 value = jsonElement.toString();
333 protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
334 String innerType = null;
335 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
337 SchemaDefinition def = schemeGen.get();// propDataDef.getSchema();
339 log.debug("Schema doesn't exists for property of type {}", type);
340 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
342 PropertyDataDefinition propDef = def.getProperty();
343 if (propDef == null) {
344 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
345 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
347 innerType = propDef.getType();
349 return Either.left(innerType);
353 * Convert Constarint object to json in order to add it to the Graph
358 public List<String> convertConstraintsToString(List<PropertyConstraint> constraints) {
360 if (constraints == null || constraints.isEmpty()) {
364 return constraints.stream().map(gson::toJson).collect(Collectors.toList());
367 public List<PropertyConstraint> convertConstraints(List<String> constraints) {
369 if (constraints == null || constraints.isEmpty()) {
373 Type constraintType = new TypeToken<PropertyConstraint>() {
376 Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
378 return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList());