9dc28cb2b4e11de977a3505b9c1b82dbd308d507
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / operations / impl / PropertyOperation.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 package org.openecomp.sdc.be.model.operations.impl;
21
22 import static org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.convertToComparable;
23 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
24
25 import com.fasterxml.jackson.core.ObjectCodec;
26 import com.fasterxml.jackson.databind.DeserializationContext;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.node.ArrayNode;
29 import com.google.common.collect.Lists;
30 import com.google.common.collect.Maps;
31 import com.google.gson.JsonArray;
32 import com.google.gson.JsonDeserializationContext;
33 import com.google.gson.JsonDeserializer;
34 import com.google.gson.JsonElement;
35 import com.google.gson.JsonObject;
36 import com.google.gson.JsonParseException;
37 import com.google.gson.JsonParser;
38 import com.google.gson.JsonPrimitive;
39 import com.google.gson.JsonSerializationContext;
40 import com.google.gson.JsonSerializer;
41 import com.google.gson.JsonSyntaxException;
42 import fj.data.Either;
43 import java.io.IOException;
44 import java.lang.reflect.InvocationTargetException;
45 import java.lang.reflect.Type;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.Collections;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.Map.Entry;
54 import java.util.Set;
55 import java.util.function.Consumer;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
58 import java.util.stream.Collectors;
59 import org.apache.commons.collections.CollectionUtils;
60 import org.apache.commons.collections.MapUtils;
61 import org.apache.commons.lang3.StringUtils;
62 import org.apache.commons.lang3.tuple.ImmutablePair;
63 import org.apache.tinkerpop.gremlin.structure.Edge;
64 import org.apache.tinkerpop.gremlin.structure.Vertex;
65 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
66 import org.janusgraph.core.JanusGraph;
67 import org.janusgraph.core.JanusGraphVertex;
68 import org.janusgraph.core.JanusGraphVertexProperty;
69 import org.openecomp.sdc.be.config.BeEcompErrorManager;
70 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
71 import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
72 import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
73 import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
74 import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
75 import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
76 import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
77 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
78 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
79 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
80 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
81 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
82 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
83 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
84 import org.openecomp.sdc.be.datatypes.enums.ConstraintType;
85 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
86 import org.openecomp.sdc.be.model.Component;
87 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
88 import org.openecomp.sdc.be.model.DataTypeDefinition;
89 import org.openecomp.sdc.be.model.IComplexDefaultValue;
90 import org.openecomp.sdc.be.model.PropertyConstraint;
91 import org.openecomp.sdc.be.model.PropertyDefinition;
92 import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation;
93 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
94 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
95 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
96 import org.openecomp.sdc.be.model.tosca.ToscaType;
97 import org.openecomp.sdc.be.model.tosca.constraints.EqualConstraint;
98 import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
99 import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
100 import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
101 import org.openecomp.sdc.be.model.tosca.constraints.LengthConstraint;
102 import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
103 import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint;
104 import org.openecomp.sdc.be.model.tosca.constraints.MaxLengthConstraint;
105 import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint;
106 import org.openecomp.sdc.be.model.tosca.constraints.PatternConstraint;
107 import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint;
108 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
109 import org.openecomp.sdc.be.model.validation.ToscaFunctionValidator;
110 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
111 import org.openecomp.sdc.be.resources.data.DataTypeData;
112 import org.openecomp.sdc.be.resources.data.ModelData;
113 import org.openecomp.sdc.be.resources.data.PropertyData;
114 import org.openecomp.sdc.be.resources.data.PropertyValueData;
115 import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
116 import org.openecomp.sdc.be.resources.data.UniqueIdData;
117 import org.openecomp.sdc.common.log.wrappers.Logger;
118 import org.springframework.beans.factory.annotation.Autowired;
119
120 @org.springframework.stereotype.Component("property-operation")
121 public class PropertyOperation extends AbstractOperation implements IPropertyOperation {
122
123     private static final String AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS = "After retrieving DERIVED_FROM node of {}. status is {}";
124     private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}";
125     private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph. status is {}";
126     private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph.";
127     private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph.";
128     private static final String FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS = "Failed to associate resource {} to property {} in graph. status is {}";
129     private static final String AFTER_ADDING_PROPERTY_TO_GRAPH = "After adding property to graph {}";
130     private static final String BEFORE_ADDING_PROPERTY_TO_GRAPH = "Before adding property to graph {}";
131     private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid";
132     private static final String PROPERTY = "Property";
133     private static final String UPDATE_DATA_TYPE = "UpdateDataType";
134     private static final Logger log = Logger.getLogger(PropertyOperation.class.getName());
135     private final DerivedFromOperation derivedFromOperation;
136     private ToscaFunctionValidator toscaFunctionValidator;
137     private DataTypeOperation dataTypeOperation;
138
139     @Autowired
140     public PropertyOperation(final HealingJanusGraphGenericDao janusGraphGenericDao, final DerivedFromOperation derivedFromOperation) {
141         this.janusGraphGenericDao = janusGraphGenericDao;
142         this.derivedFromOperation = derivedFromOperation;
143     }
144
145     @Autowired
146     public void setToscaFunctionValidator(final ToscaFunctionValidator toscaFunctionValidator) {
147         this.toscaFunctionValidator = toscaFunctionValidator;
148     }
149
150     //circular dependency DataTypeOperation->ModelOperation->ModelElementOperation->PropertyOperation
151     @Autowired
152     public void setDataTypeOperation(DataTypeOperation dataTypeOperation) {
153         this.dataTypeOperation = dataTypeOperation;
154     }
155
156     public PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
157         log.debug("The object returned after create property is {}", propertyDataResult);
158         PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
159         propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
160         propertyDefResult.setName(propertyName);
161         return propertyDefResult;
162     }
163
164     public Either<PropertyData, StorageOperationStatus> addProperty(String propertyName, PropertyDefinition propertyDefinition, String resourceId) {
165         Either<PropertyData, JanusGraphOperationStatus> either = addPropertyToGraph(propertyName, propertyDefinition, resourceId);
166         if (either.isRight()) {
167             StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
168             return Either.right(storageStatus);
169         }
170         return Either.left(either.left().value());
171     }
172
173     /**
174      * @param propertyDefinition
175      * @return
176      */
177     @Override
178     public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
179         log.trace("Going to validate property type and value. {}", propertyDefinition);
180         String propertyType = propertyDefinition.getType();
181         String value = propertyDefinition.getDefaultValue();
182         ToscaPropertyType type = getType(propertyType);
183         if (type == null) {
184             DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
185             if (dataTypeDefinition == null) {
186                 log.debug("The type {} of property cannot be found.", propertyType);
187                 return StorageOperationStatus.INVALID_TYPE;
188             }
189             return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
190         }
191         String innerType = null;
192         Either<String, JanusGraphOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
193         if (checkInnerType.isRight()) {
194             return StorageOperationStatus.INVALID_TYPE;
195         }
196         innerType = checkInnerType.left().value();
197         log.trace("After validating property type {}", propertyType);
198         boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
199         if (!isValidProperty) {
200             log.info(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
201             return StorageOperationStatus.INVALID_VALUE;
202         }
203         PropertyValueConverter converter = type.getConverter();
204         if (isEmptyValue(value)) {
205             log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
206             propertyDefinition.setDefaultValue(EMPTY_VALUE);
207         } else if (!isEmptyValue(value)) {
208             String convertedValue = converter.convert(value, innerType, dataTypes);
209             propertyDefinition.setDefaultValue(convertedValue);
210         }
211         return StorageOperationStatus.OK;
212     }
213
214     public Either<PropertyData, JanusGraphOperationStatus> addPropertyToGraph(String propertyName, PropertyDefinition propertyDefinition,
215                                                                               String resourceId) {
216         ResourceMetadataData resourceData = new ResourceMetadataData();
217         resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
218         List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
219         propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
220         PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
221         log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
222         Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData, PropertyData.class);
223         log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
224         if (createNodeResult.isRight()) {
225             JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
226             log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
227             return Either.right(operationStatus);
228         }
229         Map<String, Object> props = new HashMap<>();
230         props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
231         Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
232             .createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props);
233         if (createRelResult.isRight()) {
234             JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
235             log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, operationStatus);
236             return Either.right(operationStatus);
237         }
238         return Either.left(createNodeResult.left().value());
239     }
240
241     public JanusGraphOperationStatus addPropertyToGraphByVertex(JanusGraphVertex metadataVertex, String propertyName,
242                                                                 PropertyDefinition propertyDefinition, String resourceId) {
243         List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
244         propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
245         PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
246         log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
247         Either<JanusGraphVertex, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData);
248         log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
249         if (createNodeResult.isRight()) {
250             JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
251             log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus);
252             return operationStatus;
253         }
254         Map<String, Object> props = new HashMap<>();
255         props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
256         JanusGraphVertex propertyVertex = createNodeResult.left().value();
257         JanusGraphOperationStatus createRelResult = janusGraphGenericDao.createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props);
258         if (!createRelResult.equals(JanusGraphOperationStatus.OK)) {
259             log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, createRelResult);
260             return createRelResult;
261         }
262         return createRelResult;
263     }
264
265     public JanusGraphGenericDao getJanusGraphGenericDao() {
266         return janusGraphGenericDao;
267     }
268
269     /**
270      * FOR TEST ONLY
271      *
272      * @param janusGraphGenericDao
273      */
274     public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) {
275         this.janusGraphGenericDao = janusGraphGenericDao;
276     }
277
278     public Either<PropertyData, JanusGraphOperationStatus> deletePropertyFromGraph(String propertyId) {
279         log.debug("Before deleting property from graph {}", propertyId);
280         return janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
281     }
282
283     public Either<PropertyData, StorageOperationStatus> updateProperty(String propertyId, PropertyDefinition newPropertyDefinition,
284                                                                        Map<String, DataTypeDefinition> dataTypes) {
285         StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
286         if (validateAndUpdateProperty != StorageOperationStatus.OK) {
287             return Either.right(validateAndUpdateProperty);
288         }
289         Either<PropertyData, JanusGraphOperationStatus> either = updatePropertyFromGraph(propertyId, newPropertyDefinition);
290         if (either.isRight()) {
291             StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
292             return Either.right(storageStatus);
293         }
294         return Either.left(either.left().value());
295     }
296
297     public Either<PropertyData, JanusGraphOperationStatus> updatePropertyFromGraph(String propertyId, PropertyDefinition propertyDefinition) {
298         if (log.isDebugEnabled()) {
299             log.debug("Before updating property on graph {}", propertyId);
300         }
301         // get the original property data
302         Either<PropertyData, JanusGraphOperationStatus> statusProperty = janusGraphGenericDao
303             .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
304         if (statusProperty.isRight()) {
305             log.debug("Problem while get property with id {}. Reason - {}", propertyId, statusProperty.right().value().name());
306             return Either.right(statusProperty.right().value());
307         }
308         PropertyData orgPropertyData = statusProperty.left().value();
309         PropertyDataDefinition orgPropertyDataDefinition = orgPropertyData.getPropertyDataDefinition();
310         // create new property data to update
311         PropertyData newPropertyData = new PropertyData();
312         newPropertyData.setPropertyDataDefinition(propertyDefinition);
313         PropertyDataDefinition newPropertyDataDefinition = newPropertyData.getPropertyDataDefinition();
314         // update the original property data with new values
315         if (orgPropertyDataDefinition.getDefaultValue() == null) {
316             orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
317         } else {
318             if (!orgPropertyDataDefinition.getDefaultValue().equals(newPropertyDataDefinition.getDefaultValue())) {
319                 orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
320             }
321         }
322         if (orgPropertyDataDefinition.getDescription() == null) {
323             orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
324         } else {
325             if (!orgPropertyDataDefinition.getDescription().equals(newPropertyDataDefinition.getDescription())) {
326                 orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
327             }
328         }
329         if (!orgPropertyDataDefinition.getType().equals(newPropertyDataDefinition.getType())) {
330             orgPropertyDataDefinition.setType(newPropertyDataDefinition.getType());
331         }
332         if (newPropertyData.getConstraints() != null) {
333             orgPropertyData.setConstraints(newPropertyData.getConstraints());
334         }
335         orgPropertyDataDefinition.setSchema(newPropertyDataDefinition.getSchema());
336         return janusGraphGenericDao.updateNode(orgPropertyData, PropertyData.class);
337     }
338
339     public Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType(String propertyName, PropertyDefinition propertyDefinition,
340                                                                                  NodeTypeEnum nodeType, String uniqueId) {
341         return addPropertyToNodeType(propertyName, propertyDefinition, nodeType, uniqueId, true);
342     }
343
344     public Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType(final String propertyName,
345                                                                                  final PropertyDefinition propertyDefinition,
346                                                                                  final NodeTypeEnum nodeType, final String uniqueId,
347                                                                                  final boolean inTransaction) {
348         List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
349         propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(uniqueId, propertyName));
350         PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
351         log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
352         Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData, PropertyData.class);
353         log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
354         if (createNodeResult.isRight()) {
355             if (!inTransaction) {
356                 janusGraphGenericDao.rollback();
357             }
358             JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
359             log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
360             return Either.right(operationStatus);
361         }
362         Map<String, Object> props = new HashMap<>();
363         props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
364         UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId);
365         log.debug("Before associating {} to property {}", uniqueIdData, propertyName);
366         Either<GraphRelation, JanusGraphOperationStatus> createRelResult =
367             janusGraphGenericDao.createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props);
368         if (createRelResult.isRight()) {
369             if (!inTransaction) {
370                 janusGraphGenericDao.rollback();
371             }
372             JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
373             log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, uniqueId, propertyName, operationStatus);
374             return Either.right(operationStatus);
375         }
376         if (!inTransaction) {
377             janusGraphGenericDao.commit();
378         }
379         return Either.left(createNodeResult.left().value());
380     }
381
382     public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) {
383         Map<String, PropertyDefinition> resourceProps = new HashMap<>();
384         Either<List<ImmutablePair<PropertyData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
385             .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property,
386                 PropertyData.class);
387         if (childrenNodes.isRight()) {
388             JanusGraphOperationStatus operationStatus = childrenNodes.right().value();
389             return Either.right(operationStatus);
390         }
391         List<ImmutablePair<PropertyData, GraphEdge>> values = childrenNodes.left().value();
392         if (values != null) {
393             for (ImmutablePair<PropertyData, GraphEdge> immutablePair : values) {
394                 GraphEdge edge = immutablePair.getValue();
395                 String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
396                 log.debug("Property {} is associated to node {}", propertyName, uniqueId);
397                 PropertyData propertyData = immutablePair.getKey();
398                 PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId);
399                 resourceProps.put(propertyName, propertyDefinition);
400             }
401         }
402         log.debug("The properties associated to node {} are {}", uniqueId, resourceProps);
403         return Either.left(resourceProps);
404     }
405
406     public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deletePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
407         return deleteAllPropertiesAssociatedToNode(nodeType, uniqueId).right()
408             .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err));
409     }
410
411     public Either<Map<String, PropertyData>, JanusGraphOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId,
412                                                                                                         Map<String, PropertyDefinition> newProperties) {
413         Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> oldPropertiesRes = findPropertiesOfNode(nodeType, uniqueId);
414         Map<String, PropertyDefinition> reallyNewProperties;
415         Map<String, PropertyData> unchangedPropsData;
416         if (oldPropertiesRes.isRight()) {
417             JanusGraphOperationStatus err = oldPropertiesRes.right().value();
418             if (err == JanusGraphOperationStatus.NOT_FOUND) {
419                 reallyNewProperties = newProperties;
420                 unchangedPropsData = Collections.emptyMap();
421             } else {
422                 return Either.right(err);
423             }
424         } else {
425             Map<String, PropertyDefinition> oldProperties = oldPropertiesRes.left().value();
426             reallyNewProperties = collectReallyNewProperties(newProperties, oldProperties);
427             for (Entry<String, PropertyDefinition> oldEntry : oldProperties.entrySet()) {
428                 String key = oldEntry.getKey();
429                 PropertyDefinition newPropDef = newProperties != null ? newProperties.get(key) : null;
430                 PropertyDefinition oldPropDef = oldEntry.getValue();
431                 JanusGraphOperationStatus status = updateOldProperty(newPropDef, oldPropDef);
432                 if (status != JanusGraphOperationStatus.OK) {
433                     return Either.right(status);
434                 }
435             }
436             unchangedPropsData = oldProperties.entrySet().stream()
437                 .collect(Collectors.toMap(Entry::getKey, e -> new PropertyData(e.getValue(), null)));
438         }
439         // add other properties
440         return addPropertiesToElementType(nodeType, uniqueId, reallyNewProperties, unchangedPropsData);
441     }
442
443     /**
444      * @param newProperties
445      * @param oldProperties
446      * @return
447      */
448     private Map<String, PropertyDefinition> collectReallyNewProperties(Map<String, PropertyDefinition> newProperties,
449                                                                        Map<String, PropertyDefinition> oldProperties) {
450         return newProperties != null ? newProperties.entrySet().stream().filter(entry -> !oldProperties.containsKey(entry.getKey()))
451             .collect(Collectors.toMap(Entry::getKey, Entry::getValue)) : null;
452     }
453
454     /**
455      * @param newPropDef
456      * @param oldPropDef
457      */
458     private JanusGraphOperationStatus updateOldProperty(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
459         if (!isUpdateAllowed(newPropDef, oldPropDef)) {
460             return JanusGraphOperationStatus.MATCH_NOT_FOUND;
461         }
462         if (isUpdateRequired(newPropDef, oldPropDef)) {
463             modifyOldPropByNewOne(newPropDef, oldPropDef);
464             List<PropertyConstraint> constraints = oldPropDef.getConstraints();
465             PropertyData node = new PropertyData(oldPropDef, convertConstraintsToString(constraints));
466             Either<PropertyData, JanusGraphOperationStatus> updateResult = janusGraphGenericDao.updateNode(node, PropertyData.class);
467             if (updateResult.isRight()) {
468                 return updateResult.right().value();
469             }
470         }
471         return JanusGraphOperationStatus.OK;
472     }
473
474     /**
475      * @param newPropDef
476      * @param oldPropDef
477      */
478     private boolean isUpdateAllowed(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
479         if (newPropDef == null) {
480             log.error("#mergePropertiesAssociatedToNode - Failed due attempt to delete the property with id {}", oldPropDef.getUniqueId());
481             return false;
482         }
483         // If the property type is missing it's something that we could want to fix
484         if (oldPropDef.getType() != null && !oldPropDef.getType().equals(newPropDef.getType())) {
485             log.error("#mergePropertiesAssociatedToNode - Failed due attempt to change type of the property with id {}", oldPropDef.getUniqueId());
486             return false;
487         }
488         return true;
489     }
490
491     /**
492      * Update only fields which modification is permitted.
493      *
494      * @param newPropDef
495      * @param oldPropDef
496      */
497     private void modifyOldPropByNewOne(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
498         oldPropDef.setDefaultValue(newPropDef.getDefaultValue());
499         oldPropDef.setDescription(newPropDef.getDescription());
500         oldPropDef.setRequired(newPropDef.isRequired());
501         // Type is updated to fix possible null type issue in janusGraph DB
502         oldPropDef.setType(newPropDef.getType());
503     }
504
505     private boolean isUpdateRequired(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
506         return !StringUtils.equals(oldPropDef.getDefaultValue(), newPropDef.getDefaultValue()) || !StringUtils
507             .equals(oldPropDef.getDescription(), newPropDef.getDescription()) || oldPropDef.isRequired() != newPropDef.isRequired();
508     }
509
510     /**
511      * Adds newProperties and returns in case of success (left part of Either) map of all properties i. e. added ones and contained in
512      * unchangedPropsData
513      *
514      * @param nodeType
515      * @param uniqueId
516      * @param newProperties
517      * @param unchangedPropsData
518      * @return
519      */
520     private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId,
521                                                                                                     Map<String, PropertyDefinition> newProperties,
522                                                                                                     Map<String, PropertyData> unchangedPropsData) {
523         return addPropertiesToElementType(uniqueId, nodeType, newProperties).left().map(m -> {
524             m.putAll(unchangedPropsData);
525             return m;
526         });
527     }
528
529     public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType,
530                                                                                                                String uniqueId) {
531         Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId);
532         if (propertiesOfNodeRes.isRight()) {
533             JanusGraphOperationStatus status = propertiesOfNodeRes.right().value();
534             if (status == JanusGraphOperationStatus.NOT_FOUND) {
535                 return Either.right(StorageOperationStatus.OK);
536             }
537             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
538         }
539         Map<String, PropertyDefinition> value = propertiesOfNodeRes.left().value();
540         for (PropertyDefinition propertyDefinition : value.values()) {
541             String propertyUid = propertyDefinition.getUniqueId();
542             Either<PropertyData, JanusGraphOperationStatus> deletePropertyRes = deletePropertyFromGraph(propertyUid);
543             if (deletePropertyRes.isRight()) {
544                 log.error("Failed to delete property with id {}", propertyUid);
545                 JanusGraphOperationStatus status = deletePropertyRes.right().value();
546                 if (status == JanusGraphOperationStatus.NOT_FOUND) {
547                     status = JanusGraphOperationStatus.INVALID_ID;
548                 }
549                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
550             }
551         }
552         log.debug("The properties deleted from node {} are {}", uniqueId, value);
553         return Either.left(value);
554     }
555
556     /**
557      * Checks existence of a property with the same name belonging to the same resource or existence of property with the same name and different type
558      * (including derived from hierarchy)
559      *
560      * @param properties
561      * @param resourceUid
562      * @param propertyName
563      * @param propertyType
564      * @return
565      */
566     public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
567         boolean result = false;
568         if (!CollectionUtils.isEmpty(properties)) {
569             for (PropertyDefinition propertyDefinition : properties) {
570                 if (propertyDefinition.getName().equals(propertyName) && (propertyDefinition.getParentUniqueId().equals(resourceUid)
571                     || !propertyDefinition.getType().equals(propertyType))) {
572                     result = true;
573                     break;
574                 }
575             }
576         }
577         return result;
578     }
579
580     public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
581                                                                  Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
582         if (rules == null || rules.isEmpty()) {
583             return new ImmutablePair<>(null, true);
584         }
585         for (PropertyRule rule : rules) {
586             String value = rule.getValue();
587             Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
588             if (updateResult.isRight()) {
589                 Boolean status = updateResult.right().value();
590                 if (!status) {
591                     return new ImmutablePair<>(value, status);
592                 }
593             } else {
594                 String newValue = null;
595                 Object object = updateResult.left().value();
596                 if (object != null) {
597                     newValue = object.toString();
598                 }
599                 rule.setValue(newValue);
600             }
601         }
602         return new ImmutablePair<>(null, true);
603     }
604
605     public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
606                                            String resourceInstanceId) {
607         List<PropertyRule> rules = resourceInstanceProperty.getRules();
608         if (rules == null) {
609             PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
610             rules = new ArrayList<>();
611             rules.add(propertyRule);
612         } else {
613             rules = sortRules(rules);
614         }
615         propertyValueData.setRules(rules);
616     }
617
618     private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
619                                            String resourceInstanceId) {
620         List<String> path = resourceInstanceProperty.getPath();
621         // FOR BC. Since old Property values on VFC/VF does not have rules on
622
623         // graph.
624
625         // Update could be done on one level only, thus we can use this
626
627         // operation to avoid migration.
628         if (path == null || path.isEmpty()) {
629             path = new ArrayList<>();
630             path.add(resourceInstanceId);
631         }
632         PropertyRule propertyRule = new PropertyRule();
633         propertyRule.setRule(path);
634         propertyRule.setValue(propertyValueData.getValue());
635         return propertyRule;
636     }
637
638     private List<PropertyRule> sortRules(List<PropertyRule> rules) {
639         // TODO: sort the rules by size and binary representation.
640
641         // (x, y, .+) --> 110 6 priority 1
642
643         // (x, .+, z) --> 101 5 priority 2
644         return rules;
645     }
646
647     public ImmutablePair<JanusGraphOperationStatus, String> findPropertyValue(String resourceInstanceId, String propertyId) {
648         log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId);
649         Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllRes = this
650             .getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceId);
651         if (getAllRes.isRight()) {
652             JanusGraphOperationStatus status = getAllRes.right().value();
653             log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status);
654             return new ImmutablePair<>(status, null);
655         }
656         List<ComponentInstanceProperty> list = getAllRes.left().value();
657         if (list != null) {
658             for (ComponentInstanceProperty instanceProperty : list) {
659                 String propertyUniqueId = instanceProperty.getUniqueId();
660                 String valueUniqueUid = instanceProperty.getValueUniqueUid();
661                 log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid);
662                 if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) {
663                     log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId);
664                     return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid);
665                 }
666             }
667         }
668         return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null);
669     }
670
671     public void updateRulesInPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
672                                            String resourceInstanceId) {
673         List<PropertyRule> currentRules = propertyValueData.getRules();
674         List<PropertyRule> rules = resourceInstanceProperty.getRules();
675         // if rules are not supported.
676         if (rules == null) {
677             PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
678             rules = new ArrayList<>();
679             rules.add(propertyRule);
680             if (currentRules != null) {
681                 rules = mergeRules(currentRules, rules);
682             }
683         } else {
684             // Full mode. all rules are sent in update operation.
685             rules = sortRules(rules);
686         }
687         propertyValueData.setRules(rules);
688     }
689
690     private List<PropertyRule> mergeRules(List<PropertyRule> currentRules, List<PropertyRule> newRules) {
691         List<PropertyRule> mergedRules = new ArrayList<>();
692         if (newRules == null || newRules.isEmpty()) {
693             return currentRules;
694         }
695         for (PropertyRule rule : currentRules) {
696             PropertyRule propertyRule = new PropertyRule(rule.getRule(), rule.getValue());
697             mergedRules.add(propertyRule);
698         }
699         for (PropertyRule rule : newRules) {
700             PropertyRule foundRule = findRuleInList(rule, mergedRules);
701             if (foundRule != null) {
702                 foundRule.setValue(rule.getValue());
703             } else {
704                 mergedRules.add(rule);
705             }
706         }
707         return mergedRules;
708     }
709
710     private PropertyRule findRuleInList(PropertyRule rule, List<PropertyRule> rules) {
711         if (rules == null || rules.isEmpty() || rule.getRule() == null || rule.getRule().isEmpty()) {
712             return null;
713         }
714         PropertyRule foundRule = null;
715         for (PropertyRule propertyRule : rules) {
716             if (rule.getRuleSize() != propertyRule.getRuleSize()) {
717                 continue;
718             }
719             boolean equals = propertyRule.compareRule(rule);
720             if (equals) {
721                 foundRule = propertyRule;
722                 break;
723             }
724         }
725         return foundRule;
726     }
727
728     /**
729      * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value...
730      *
731      * @param resourceInstanceUid
732      * @return
733      */
734     public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(
735         String resourceInstanceUid) {
736         return getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance);
737     }
738
739     public Either<PropertyValueData, JanusGraphOperationStatus> removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) {
740         Either<ComponentInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
741             .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
742         if (findResInstanceRes.isRight()) {
743             JanusGraphOperationStatus status = findResInstanceRes.right().value();
744             if (status == JanusGraphOperationStatus.NOT_FOUND) {
745                 status = JanusGraphOperationStatus.INVALID_ID;
746             }
747             return Either.right(status);
748         }
749         Either<PropertyValueData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
750             .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, PropertyValueData.class);
751         if (findPropertyDefRes.isRight()) {
752             JanusGraphOperationStatus status = findPropertyDefRes.right().value();
753             if (status == JanusGraphOperationStatus.NOT_FOUND) {
754                 status = JanusGraphOperationStatus.INVALID_ID;
755             }
756             return Either.right(status);
757         }
758         Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
759             .getRelation(findResInstanceRes.left().value(), findPropertyDefRes.left().value(), GraphEdgeLabels.PROPERTY_VALUE);
760         if (relation.isRight()) {
761             // TODO: add error in case of error
762             JanusGraphOperationStatus status = relation.right().value();
763             if (status == JanusGraphOperationStatus.NOT_FOUND) {
764                 status = JanusGraphOperationStatus.INVALID_ID;
765             }
766             return Either.right(status);
767         }
768         Either<PropertyValueData, JanusGraphOperationStatus> deleteNode = janusGraphGenericDao
769             .deleteNode(findPropertyDefRes.left().value(), PropertyValueData.class);
770         if (deleteNode.isRight()) {
771             return Either.right(deleteNode.right().value());
772         }
773         PropertyValueData value = deleteNode.left().value();
774         return Either.left(value);
775     }
776
777     public Either<ComponentInstanceProperty, StorageOperationStatus> removePropertyValueFromResourceInstance(String propertyValueUid,
778                                                                                                              String resourceInstanceId,
779                                                                                                              boolean inTransaction) {
780         Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
781         try {
782             Either<PropertyValueData, JanusGraphOperationStatus> eitherStatus = this
783                 .removePropertyOfResourceInstance(propertyValueUid, resourceInstanceId);
784             if (eitherStatus.isRight()) {
785                 log.error("Failed to remove property value {} from resource instance {} in Graph. status is {}", propertyValueUid, resourceInstanceId,
786                     eitherStatus.right().value().name());
787                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
788                 return result;
789             } else {
790                 PropertyValueData propertyValueData = eitherStatus.left().value();
791                 ComponentInstanceProperty propertyValueResult = new ComponentInstanceProperty();
792                 propertyValueResult.setUniqueId(resourceInstanceId);
793                 propertyValueResult.setValue(propertyValueData.getValue());
794                 log.debug("The returned ResourceInstanceProperty is  {}", propertyValueResult);
795                 result = Either.left(propertyValueResult);
796                 return result;
797             }
798         } finally {
799             if (!inTransaction) {
800                 if (result == null || result.isRight()) {
801                     log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
802                     janusGraphGenericDao.rollback();
803                 } else {
804                     log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
805                     janusGraphGenericDao.commit();
806                 }
807             }
808         }
809     }
810
811     public ComponentInstanceProperty buildResourceInstanceProperty(PropertyValueData propertyValueData,
812                                                                    ComponentInstanceProperty resourceInstanceProperty) {
813         String value = propertyValueData.getValue();
814         String uid = propertyValueData.getUniqueId();
815         ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(resourceInstanceProperty, value, uid);
816         instanceProperty.setPath(resourceInstanceProperty.getPath());
817         return instanceProperty;
818     }
819
820     @Override
821     public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
822         if (propertyDefinition == null) {
823             return false;
824         }
825         String innerType = null;
826         String propertyType = propertyDefinition.getType();
827         ToscaPropertyType type = getType(propertyType);
828         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
829             SchemaDefinition def = propertyDefinition.getSchema();
830             if (def == null) {
831                 return false;
832             }
833             PropertyDataDefinition propDef = def.getProperty();
834             if (propDef == null) {
835                 return false;
836             }
837             innerType = propDef.getType();
838         }
839         String value = propertyDefinition.getDefaultValue();
840         if (type != null) {
841             return isValidValue(type, value, innerType, dataTypes);
842         } else {
843             log.trace("The given type {} is not a pre defined one.", propertyType);
844             DataTypeDefinition foundDt = dataTypes.get(propertyType);
845             if (foundDt != null) {
846                 return isValidComplexValue(foundDt, value, dataTypes);
847             } else {
848                 return false;
849             }
850         }
851     }
852
853     public boolean isPropertyTypeValid(final IComplexDefaultValue property, final String model) {
854         if (property == null) {
855             return false;
856         }
857         if (ToscaPropertyType.isValidType(property.getType()) == null) {
858             Either<Boolean, JanusGraphOperationStatus> definedInDataTypes = isDefinedInDataTypes(property.getType(), model);
859             if (definedInDataTypes.isRight()) {
860                 return false;
861             } else {
862                 Boolean isExist = definedInDataTypes.left().value();
863                 return isExist.booleanValue();
864             }
865         }
866         return true;
867     }
868
869     public boolean isPropertyTypeValid(final IComplexDefaultValue property, final Map<String, DataTypeDefinition> dataTypes) {
870         if (property == null) {
871             return false;
872         }
873         return ToscaPropertyType.isValidType(property.getType()) != null || dataTypes.containsKey(property.getType());
874     }
875
876     @Override
877     public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
878         if (property == null) {
879             return new ImmutablePair<>(null, false);
880         }
881         SchemaDefinition schema;
882         PropertyDataDefinition innerProp;
883         String innerType = null;
884         if ((schema = property.getSchema()) != null) {
885             if ((innerProp = schema.getProperty()) != null) {
886                 innerType = innerProp.getType();
887             }
888         }
889         ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
890         if (innerToscaType == null) {
891             DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
892             if (dataTypeDefinition == null) {
893                 log.debug("The inner type {} is not a data type.", innerType);
894                 return new ImmutablePair<>(innerType, false);
895             } else {
896                 log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition);
897             }
898         }
899         return new ImmutablePair<>(innerType, true);
900     }
901
902     private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) {
903         ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter.validateAndUpdate(value, foundDt, dataTypes);
904         log.trace("The result after validating complex value of type {} is {}", foundDt.getName(), validateAndUpdate);
905         return validateAndUpdate.right.booleanValue();
906     }
907
908     public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(
909         String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
910         Either<JanusGraphVertex, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
911             .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid);
912         if (findResInstanceRes.isRight()) {
913             JanusGraphOperationStatus status = findResInstanceRes.right().value();
914             if (status == JanusGraphOperationStatus.NOT_FOUND) {
915                 status = JanusGraphOperationStatus.INVALID_ID;
916             }
917             return Either.right(status);
918         }
919         Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao
920             .getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE);
921         if (propertyImplNodes.isRight()) {
922             JanusGraphOperationStatus status = propertyImplNodes.right().value();
923             return Either.right(status);
924         }
925         List<ImmutablePair<JanusGraphVertex, Edge>> list = propertyImplNodes.left().value();
926         if (list == null || list.isEmpty()) {
927             return Either.right(JanusGraphOperationStatus.NOT_FOUND);
928         }
929         List<ComponentInstanceProperty> result = new ArrayList<>();
930         for (ImmutablePair<JanusGraphVertex, Edge> propertyValue : list) {
931             JanusGraphVertex propertyValueDataVertex = propertyValue.getLeft();
932             String propertyValueUid = (String) janusGraphGenericDao
933                 .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
934             String value = (String) janusGraphGenericDao.getProperty(propertyValueDataVertex, GraphPropertiesDictionary.VALUE.getProperty());
935             ImmutablePair<JanusGraphVertex, Edge> propertyDefPair = janusGraphGenericDao
936                 .getChildVertex(propertyValueDataVertex, GraphEdgeLabels.PROPERTY_IMPL);
937             if (propertyDefPair == null) {
938                 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
939             }
940             Map<String, Object> properties = janusGraphGenericDao.getProperties(propertyValueDataVertex);
941             PropertyValueData propertyValueData = GraphElementFactory
942                 .createElement(NodeTypeEnum.PropertyValue.getName(), GraphElementTypeEnum.Node, properties, PropertyValueData.class);
943             String propertyUniqueId = (String) janusGraphGenericDao
944                 .getProperty(propertyDefPair.left, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
945             ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
946             // set property original unique id
947             resourceInstanceProperty.setUniqueId(propertyUniqueId);
948             // set resource id
949
950             // TODO: esofer add resource id
951             resourceInstanceProperty.setParentUniqueId(null);
952             // set value
953             resourceInstanceProperty.setValue(value);
954             // set property value unique id
955             resourceInstanceProperty.setValueUniqueUid(propertyValueUid);
956             // set rules
957             resourceInstanceProperty.setRules(propertyValueData.getRules());
958             result.add(resourceInstanceProperty);
959         }
960         return Either.left(result);
961     }
962
963     /**
964      * Find the default value from the list of component instances. Start the search from the second component instance
965      *
966      * @param pathOfComponentInstances
967      * @param propertyUniqueId
968      * @param defaultValue
969      * @return
970      */
971     public Either<String, JanusGraphOperationStatus> findDefaultValueFromSecondPosition(List<String> pathOfComponentInstances,
972                                                                                         String propertyUniqueId, String defaultValue) {
973         log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue);
974         if (pathOfComponentInstances == null || pathOfComponentInstances.size() < 2) {
975             return Either.left(defaultValue);
976         }
977         String result = defaultValue;
978         for (int i = 1; i < pathOfComponentInstances.size(); i++) {
979             String compInstanceId = pathOfComponentInstances.get(i);
980             Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> propertyValuesResult = this
981                 .getAllPropertiesOfResourceInstanceOnlyPropertyDefId(compInstanceId, NodeTypeEnum.ResourceInstance);
982             log.trace("After fetching properties values of component instance {}. {}", compInstanceId, propertyValuesResult);
983             if (propertyValuesResult.isRight()) {
984                 JanusGraphOperationStatus status = propertyValuesResult.right().value();
985                 if (status != JanusGraphOperationStatus.NOT_FOUND) {
986                     return Either.right(status);
987                 } else {
988                     continue;
989                 }
990             }
991             ComponentInstanceProperty foundCompInstanceProperty = fetchByPropertyUid(propertyValuesResult.left().value(), propertyUniqueId);
992             log.trace("After finding the component instance property on{} . {}", compInstanceId, foundCompInstanceProperty);
993             if (foundCompInstanceProperty == null) {
994                 continue;
995             }
996             List<PropertyRule> rules = getOrBuildRulesIfNotExists(pathOfComponentInstances.size() - i, pathOfComponentInstances.get(i),
997                 foundCompInstanceProperty.getRules(), foundCompInstanceProperty.getValue());
998             log.trace("Rules of property {} on component instance {} are {}", propertyUniqueId, compInstanceId, rules);
999             PropertyRule matchedRule = findMatchRule(pathOfComponentInstances, i, rules);
1000             log.trace("Match rule is {}", matchedRule);
1001             if (matchedRule != null) {
1002                 result = matchedRule.getValue();
1003                 break;
1004             }
1005         }
1006         return Either.left(result);
1007     }
1008
1009     private ComponentInstanceProperty fetchByPropertyUid(List<ComponentInstanceProperty> list, String propertyUniqueId) {
1010         ComponentInstanceProperty result = null;
1011         if (list == null) {
1012             return null;
1013         }
1014         for (ComponentInstanceProperty instProperty : list) {
1015             if (instProperty.getUniqueId().equals(propertyUniqueId)) {
1016                 result = instProperty;
1017                 break;
1018             }
1019         }
1020         return result;
1021     }
1022
1023     private List<PropertyRule> getOrBuildRulesIfNotExists(int ruleSize, String compInstanceId, List<PropertyRule> rules, String value) {
1024         if (rules != null) {
1025             return rules;
1026         }
1027         rules = buildDefaultRule(compInstanceId, ruleSize, value);
1028         return rules;
1029     }
1030
1031     private List<PropertyRule> getRulesOfPropertyValue(int size, String instanceId, ComponentInstanceProperty componentInstanceProperty) {
1032         List<PropertyRule> rules = componentInstanceProperty.getRules();
1033         if (rules == null) {
1034             rules = buildDefaultRule(instanceId, size, componentInstanceProperty.getValue());
1035         }
1036         return rules;
1037     }
1038
1039     private List<PropertyRule> buildDefaultRule(String componentInstanceId, int size, String value) {
1040         List<PropertyRule> rules = new ArrayList<>();
1041         List<String> rule = new ArrayList<>();
1042         rule.add(componentInstanceId);
1043         for (int i = 0; i < size - 1; i++) {
1044             rule.add(PropertyRule.getRuleAnyMatch());
1045         }
1046         PropertyRule propertyRule = new PropertyRule(rule, value);
1047         rules.add(propertyRule);
1048         return rules;
1049     }
1050
1051     private PropertyRule findMatchRule(List<String> pathOfInstances, int level, List<PropertyRule> rules) {
1052         PropertyRule propertyRule = null;
1053         String stringForMatch = buildStringForMatch(pathOfInstances, level);
1054         String firstCompInstance = pathOfInstances.get(level);
1055         if (rules != null) {
1056             for (PropertyRule rule : rules) {
1057                 int ruleSize = rule.getRule().size();
1058                 // check the length of the rule equals to the length of the
1059
1060                 // instances path.
1061                 if (ruleSize != pathOfInstances.size() - level) {
1062                     continue;
1063                 }
1064                 // check that the rule starts with correct component instance id
1065                 if (!checkFirstItem(firstCompInstance, rule.getFirstToken())) {
1066                     continue;
1067                 }
1068                 String secondToken = rule.getToken(2);
1069                 if (secondToken != null && (secondToken.equals(PropertyRule.getForceAll()) || secondToken.equals(PropertyRule.getALL()))) {
1070                     propertyRule = rule;
1071                     break;
1072                 }
1073                 String patternStr = buildStringForMatch(rule.getRule(), 0);
1074                 Pattern pattern = Pattern.compile(patternStr);
1075                 Matcher matcher = pattern.matcher(stringForMatch);
1076                 if (matcher.matches()) {
1077                     if (log.isTraceEnabled()) {
1078                         log.trace("{} matches the rule {}", stringForMatch, patternStr);
1079                     }
1080                     propertyRule = rule;
1081                     break;
1082                 }
1083             }
1084         }
1085         return propertyRule;
1086     }
1087
1088     private boolean checkFirstItem(String left, String right) {
1089         return left != null && left.equals(right);
1090     }
1091
1092     private String buildStringForMatch(List<String> pathOfInstances, int level) {
1093         StringBuilder builder = new StringBuilder();
1094         for (int i = level; i < pathOfInstances.size(); i++) {
1095             builder.append(pathOfInstances.get(i));
1096             if (i < pathOfInstances.size() - 1) {
1097                 builder.append("#");
1098             }
1099         }
1100         return builder.toString();
1101     }
1102
1103     public void updatePropertyByBestMatch(String propertyUniqueId, ComponentInstanceProperty instanceProperty,
1104                                           Map<String, ComponentInstanceProperty> instanceIdToValue) {
1105         List<String> pathOfInstances = instanceProperty.getPath();
1106         int level = 0;
1107         int size = pathOfInstances.size();
1108         int numberOfMatches = 0;
1109         for (String instanceId : pathOfInstances) {
1110             ComponentInstanceProperty componentInstanceProperty = instanceIdToValue.get(instanceId);
1111             if (componentInstanceProperty != null) {
1112                 List<PropertyRule> rules = getRulesOfPropertyValue(size - level, instanceId, componentInstanceProperty);
1113                 // If it is the first level instance, then update valueUniuqeId
1114
1115                 // parameter in order to know on update that
1116
1117                 // we should update and not create new node on graph.
1118                 if (level == 0) {
1119                     instanceProperty.setValueUniqueUid(componentInstanceProperty.getValueUniqueUid());
1120                     instanceProperty.setRules(rules);
1121                 }
1122                 PropertyRule rule = findMatchRule(pathOfInstances, level, rules);
1123                 if (rule != null) {
1124                     numberOfMatches++;
1125                     String value = rule.getValue();
1126                     if (numberOfMatches == 1) {
1127                         instanceProperty.setValue(value);
1128                         if (log.isDebugEnabled()) {
1129                             log.debug("Set the value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(),
1130                                 pathOfInstances, value);
1131                         }
1132                     } else if (numberOfMatches == 2) {
1133                         // In case of another property value match, then use the
1134
1135                         // value to be the default value of the property.
1136                         instanceProperty.setDefaultValue(value);
1137                         if (log.isDebugEnabled()) {
1138                             log.debug("Set the default value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(),
1139                                 pathOfInstances, value);
1140                         }
1141                         break;
1142                     }
1143                 }
1144             }
1145             level++;
1146         }
1147     }
1148
1149     /**
1150      * Add data type to graph.
1151      * <p>
1152      * 1. Add data type node
1153      * <p>
1154      * 2. Add edge between the former node to its parent(if exists)
1155      * <p>
1156      * 3. Add property node and associate it to the node created at #1. (per property & if exists)
1157      *
1158      * @param dataTypeDefinition
1159      * @return
1160      */
1161     private Either<DataTypeData, JanusGraphOperationStatus> addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) {
1162         log.debug("Got data type {}", dataTypeDefinition);
1163         String dtUniqueId = UniqueIdBuilder.buildDataTypeUid(dataTypeDefinition.getModel(), dataTypeDefinition.getName());
1164         DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId);
1165         log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData);
1166         Either<DataTypeData, JanusGraphOperationStatus> createDataTypeResult = janusGraphGenericDao.createNode(dataTypeData, DataTypeData.class);
1167         log.debug("After adding data type to graph. status is = {}", createDataTypeResult);
1168         if (createDataTypeResult.isRight()) {
1169             JanusGraphOperationStatus operationStatus = createDataTypeResult.right().value();
1170             log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus);
1171             BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName());
1172             return Either.right(operationStatus);
1173         }
1174         DataTypeData resultCTD = createDataTypeResult.left().value();
1175         List<PropertyDefinition> properties = dataTypeDefinition.getProperties();
1176         Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(),
1177             dataTypeDefinition.getModel(),
1178             properties);
1179         if (addPropertiesToDataType.isRight()) {
1180             log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName());
1181             return Either.right(addPropertiesToDataType.right().value());
1182         }
1183
1184         final Either<GraphRelation, JanusGraphOperationStatus> modelRelationship = addDataTypeToModel(dataTypeDefinition);
1185         if (modelRelationship.isRight()) {
1186             return Either.right(modelRelationship.right().value());
1187         }
1188
1189         String derivedFrom = dataTypeDefinition.getDerivedFromName();
1190         if (derivedFrom != null) {
1191             final Either<DataTypeDefinition, JanusGraphOperationStatus> derivedFromDataType = getDataTypeByNameValidForModel(derivedFrom,
1192                 dataTypeDefinition.getModel());
1193             if (derivedFromDataType.isRight()) {
1194                 return Either.right(derivedFromDataType.right().value());
1195             }
1196
1197             log.debug("Before creating relation between data type {} to its parent {}", dtUniqueId, derivedFrom);
1198             UniqueIdData from = new UniqueIdData(NodeTypeEnum.DataType, dtUniqueId);
1199             final String deriveFromUid = derivedFromDataType.left().value().getUniqueId();
1200             UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid);
1201             Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
1202                 .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
1203             log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation);
1204             if (createRelation.isRight()) {
1205                 return Either.right(createRelation.right().value());
1206             }
1207         }
1208         return Either.left(createDataTypeResult.left().value());
1209     }
1210
1211     private Either<GraphRelation, JanusGraphOperationStatus> addDataTypeToModel(final DataTypeDefinition dataTypeDefinition) {
1212         final String model = dataTypeDefinition.getModel();
1213         if (model == null) {
1214             return Either.left(null);
1215         }
1216         final GraphNode from = new UniqueIdData(NodeTypeEnum.Model, UniqueIdBuilder.buildModelUid(model));
1217         final GraphNode to = new UniqueIdData(NodeTypeEnum.DataType, dataTypeDefinition.getUniqueId());
1218         log.info("Connecting model {} to type {}", from, to);
1219         return janusGraphGenericDao.createRelation(from, to, GraphEdgeLabels.MODEL_ELEMENT, Collections.emptyMap());
1220     }
1221
1222     private DataTypeData buildDataTypeData(DataTypeDefinition dataTypeDefinition, String ctUniqueId) {
1223         DataTypeData dataTypeData = new DataTypeData(dataTypeDefinition);
1224         dataTypeData.getDataTypeDataDefinition().setUniqueId(ctUniqueId);
1225         Long creationDate = dataTypeData.getDataTypeDataDefinition().getCreationTime();
1226         if (creationDate == null) {
1227             creationDate = System.currentTimeMillis();
1228         }
1229         dataTypeData.getDataTypeDataDefinition().setCreationTime(creationDate);
1230         dataTypeData.getDataTypeDataDefinition().setModificationTime(creationDate);
1231         return dataTypeData;
1232     }
1233
1234     /**
1235      * add properties to capability type.
1236      * <p>
1237      * Per property, add a property node and associate it to the capability type
1238      *
1239      * @param uniqueId
1240      * @param properties
1241      * @return
1242      */
1243     private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType(final String uniqueId, final String modelName,
1244                                                                                                  final List<PropertyDefinition> properties) {
1245         Map<String, PropertyData> propertiesData = new HashMap<>();
1246         if (properties != null && !properties.isEmpty()) {
1247             for (PropertyDefinition propertyDefinition : properties) {
1248                 String propertyName = propertyDefinition.getName();
1249                 String propertyType = propertyDefinition.getType();
1250                 Either<Boolean, JanusGraphOperationStatus> validPropertyType = isValidPropertyType(propertyType, modelName);
1251                 if (validPropertyType.isRight()) {
1252                     log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
1253                     return Either.right(validPropertyType.right().value());
1254                 }
1255                 Boolean isValid = validPropertyType.left().value();
1256                 if (isValid == null || !isValid.booleanValue()) {
1257                     log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
1258                     return Either.right(JanusGraphOperationStatus.INVALID_TYPE);
1259                 }
1260                 Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this
1261                     .addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId);
1262                 if (addPropertyToNodeType.isRight()) {
1263                     JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
1264                     log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus);
1265                     BeEcompErrorManager.getInstance()
1266                         .logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus,
1267                             ErrorSeverity.ERROR);
1268                     return Either.right(operationStatus);
1269                 }
1270                 propertiesData.put(propertyName, addPropertyToNodeType.left().value());
1271             }
1272             DataTypeData dataTypeData = new DataTypeData();
1273             dataTypeData.getDataTypeDataDefinition().setUniqueId(uniqueId);
1274             long modificationTime = System.currentTimeMillis();
1275             dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime);
1276             Either<DataTypeData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao.updateNode(dataTypeData, DataTypeData.class);
1277             if (updateNode.isRight()) {
1278                 JanusGraphOperationStatus operationStatus = updateNode.right().value();
1279                 log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus);
1280                 BeEcompErrorManager.getInstance()
1281                     .logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
1282                 return Either.right(operationStatus);
1283             } else {
1284                 log.debug("Update data type uid {}. Set modification time to {}", uniqueId, modificationTime);
1285             }
1286         }
1287         return Either.left(propertiesData);
1288     }
1289
1290     public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByNameValidForModel(final String name, final String modelName) {
1291         final Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1292             .getNode(GraphPropertiesDictionary.NAME.getProperty(), name, DataTypeData.class, modelName);
1293         if (dataTypesRes.isRight()) {
1294             final JanusGraphOperationStatus status = dataTypesRes.right().value();
1295             log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, name, status);
1296             return Either.right(status);
1297         }
1298         final DataTypeData dataType = dataTypesRes.left().value();
1299         final DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(dataType.getDataTypeDataDefinition());
1300         final JanusGraphOperationStatus propertiesStatus = fillProperties(dataTypeDefinition.getUniqueId(), dataTypeDefinition);
1301         if (propertiesStatus != JanusGraphOperationStatus.OK) {
1302             log.error(BUSINESS_PROCESS_ERROR, FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, dataTypeDefinition.getUniqueId());
1303             return Either.right(propertiesStatus);
1304         }
1305         final Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
1306             .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), dataTypeDefinition.getUniqueId(), GraphEdgeLabels.DERIVED_FROM,
1307                 NodeTypeEnum.DataType,
1308                 DataTypeData.class);
1309         log.debug(AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS, dataTypeDefinition.getUniqueId(), parentNode);
1310         if (parentNode.isRight()) {
1311             final JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
1312             if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
1313                 log.error(BUSINESS_PROCESS_ERROR, "Failed to find the parent data type of data type {}. status is {}",
1314                     dataTypeDefinition.getUniqueId(), janusGraphOperationStatus);
1315                 return Either.right(janusGraphOperationStatus);
1316             }
1317         } else {
1318             // derived from node was found
1319             final ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
1320             final DataTypeData parentDataType = immutablePair.getKey();
1321             final Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentDataType.getUniqueId());
1322             if (dataTypeByUid.isRight()) {
1323                 return Either.right(dataTypeByUid.right().value());
1324             }
1325             DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
1326             dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1327         }
1328         return Either.left(dataTypeDefinition);
1329     }
1330
1331     /**
1332      * Build Data type object from graph by unique id
1333      *
1334      * @param uniqueId
1335      * @return
1336      */
1337     public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUid(String uniqueId) {
1338         Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
1339         Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1340             .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
1341         if (dataTypesRes.isRight()) {
1342             JanusGraphOperationStatus status = dataTypesRes.right().value();
1343             log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
1344             return Either.right(status);
1345         }
1346         DataTypeData ctData = dataTypesRes.left().value();
1347         DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
1348         JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
1349         if (propertiesStatus != JanusGraphOperationStatus.OK) {
1350             log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
1351             return Either.right(propertiesStatus);
1352         }
1353         Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
1354             .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
1355                 DataTypeData.class);
1356         log.debug(AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS, uniqueId, parentNode);
1357         if (parentNode.isRight()) {
1358             JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
1359             if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
1360                 log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, janusGraphOperationStatus);
1361                 result = Either.right(janusGraphOperationStatus);
1362                 return result;
1363             }
1364         } else {
1365             // derived from node was found
1366             ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
1367             DataTypeData parentCT = immutablePair.getKey();
1368             String parentUniqueId = parentCT.getUniqueId();
1369             Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
1370             if (dataTypeByUid.isRight()) {
1371                 return Either.right(dataTypeByUid.right().value());
1372             }
1373             DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
1374             dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1375         }
1376         result = Either.left(dataTypeDefinition);
1377         return result;
1378     }
1379
1380     private JanusGraphOperationStatus fillProperties(String uniqueId, DataTypeDefinition dataTypeDefinition) {
1381         Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this
1382             .findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId);
1383         if (findPropertiesOfNode.isRight()) {
1384             JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value();
1385             log.debug("After looking for properties of vertex {}. status is {}", uniqueId, janusGraphOperationStatus);
1386             if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) {
1387                 return JanusGraphOperationStatus.OK;
1388             } else {
1389                 return janusGraphOperationStatus;
1390             }
1391         } else {
1392             Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value();
1393             if (properties != null && !properties.isEmpty()) {
1394                 List<PropertyDefinition> listOfProps = new ArrayList<>();
1395                 for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
1396                     String propName = entry.getKey();
1397                     PropertyDefinition propertyDefinition = entry.getValue();
1398                     PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
1399                     newPropertyDefinition.setName(propName);
1400                     listOfProps.add(newPropertyDefinition);
1401                 }
1402                 dataTypeDefinition.setProperties(listOfProps);
1403             }
1404             return JanusGraphOperationStatus.OK;
1405         }
1406     }
1407
1408     private Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) {
1409         Either<DataTypeDefinition, StorageOperationStatus> result = null;
1410         try {
1411             Either<DataTypeData, JanusGraphOperationStatus> eitherStatus = addDataTypeToGraph(dataTypeDefinition);
1412             if (eitherStatus.isRight()) {
1413                 log.debug("Failed to add data type {} to Graph. status is {}", dataTypeDefinition, eitherStatus.right().value().name());
1414                 BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", "DataType");
1415                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
1416                 return result;
1417             } else {
1418                 DataTypeData capabilityTypeData = eitherStatus.left().value();
1419                 DataTypeDefinition dataTypeDefResult = convertDTDataToDTDefinition(capabilityTypeData);
1420                 log.debug("The returned CapabilityTypeDefinition is {}", dataTypeDefResult);
1421                 result = Either.left(dataTypeDefResult);
1422                 return result;
1423             }
1424         } finally {
1425             if (!inTransaction) {
1426                 if (result == null || result.isRight()) {
1427                     log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1428                     janusGraphGenericDao.rollback();
1429                 } else {
1430                     log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1431                     janusGraphGenericDao.commit();
1432                 }
1433             }
1434         }
1435     }
1436
1437     @Override
1438     public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition) {
1439         return addDataType(dataTypeDefinition, true);
1440     }
1441
1442     @Override
1443     public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(final String name, final String validForModel,
1444                                                                                 final boolean inTransaction) {
1445         Either<DataTypeDefinition, StorageOperationStatus> result = null;
1446         try {
1447             Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByNameValidForModel(name, validForModel);
1448             if (ctResult.isRight()) {
1449                 JanusGraphOperationStatus status = ctResult.right().value();
1450                 if (status != JanusGraphOperationStatus.NOT_FOUND) {
1451                     log.error("Failed to retrieve information on capability type {} status is {}", name, status);
1452                 }
1453                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
1454                 return result;
1455             }
1456             result = Either.left(ctResult.left().value());
1457             return result;
1458         } finally {
1459             if (!inTransaction) {
1460                 if (result == null || result.isRight()) {
1461                     log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1462                     janusGraphGenericDao.rollback();
1463                 } else {
1464                     log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1465                     janusGraphGenericDao.commit();
1466                 }
1467             }
1468         }
1469     }
1470
1471     @Override
1472     public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(final String name, final String validForModel) {
1473         return getDataTypeByName(name, validForModel, true);
1474     }
1475
1476     public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByUidWithoutDerived(String uid, boolean inTransaction) {
1477         Either<DataTypeDefinition, StorageOperationStatus> result = null;
1478         try {
1479             Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByUidWithoutDerivedDataTypes(uid);
1480             if (ctResult.isRight()) {
1481                 JanusGraphOperationStatus status = ctResult.right().value();
1482                 if (status != JanusGraphOperationStatus.NOT_FOUND) {
1483                     log.error(BUSINESS_PROCESS_ERROR, "Failed to retrieve information on data type {} status is {}", uid, status);
1484                 }
1485                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
1486                 return result;
1487             }
1488             result = Either.left(ctResult.left().value());
1489             return result;
1490         } finally {
1491             if (!inTransaction) {
1492                 if (result == null || result.isRight()) {
1493                     log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1494                     janusGraphGenericDao.rollback();
1495                 } else {
1496                     log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1497                     janusGraphGenericDao.commit();
1498                 }
1499             }
1500         }
1501     }
1502
1503     public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUidWithoutDerivedDataTypes(String uniqueId) {
1504         Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1505             .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
1506         if (dataTypesRes.isRight()) {
1507             JanusGraphOperationStatus status = dataTypesRes.right().value();
1508             log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
1509             return Either.right(status);
1510         }
1511         DataTypeData ctData = dataTypesRes.left().value();
1512         DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
1513         JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
1514         if (propertiesStatus != JanusGraphOperationStatus.OK) {
1515             log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
1516             return Either.right(propertiesStatus);
1517         }
1518         return Either.left(dataTypeDefinition);
1519     }
1520
1521     /**
1522      * convert between graph Node object to Java object
1523      *
1524      * @param dataTypeData
1525      * @return
1526      */
1527     protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) {
1528         log.debug("The object returned after create data type is {}", dataTypeData);
1529         return new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition());
1530     }
1531
1532     private Either<Boolean, JanusGraphOperationStatus> isValidPropertyType(String propertyType, final String modelName) {
1533         if (propertyType == null || propertyType.isEmpty()) {
1534             return Either.left(false);
1535         }
1536         ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(propertyType);
1537         if (toscaPropertyType == null) {
1538             return isDefinedInDataTypes(propertyType, modelName);
1539         } else {
1540             return Either.left(true);
1541         }
1542     }
1543
1544     public Either<Boolean, JanusGraphOperationStatus> isDefinedInDataTypes(final String propertyType, final String modelName) {
1545         Either<DataTypeDefinition, JanusGraphOperationStatus> dataType = getDataTypeByNameValidForModel(propertyType, modelName);
1546         if (dataType.isRight()) {
1547             JanusGraphOperationStatus status = dataType.right().value();
1548             if (status == JanusGraphOperationStatus.NOT_FOUND) {
1549                 return Either.left(false);
1550             }
1551             return Either.right(status);
1552         }
1553         return Either.left(true);
1554     }
1555
1556     public Either<Map<String, Map<String, DataTypeDefinition>>, JanusGraphOperationStatus> getAllDataTypes() {
1557         final Map<String, Map<String, DataTypeDefinition>> dataTypes = new HashMap<>();
1558         Either<Map<String, Map<String, DataTypeDefinition>>, JanusGraphOperationStatus> result = Either.left(dataTypes);
1559         final Map<String, DataTypeDefinition> allDataTypesFound = new HashMap<>();
1560
1561         final Map<String, List<String>> dataTypeUidstoModels = dataTypeOperation.getAllDataTypeUidsToModels();
1562
1563         if (dataTypeUidstoModels != null) {
1564             log.trace("Number of data types to load is {}", dataTypeUidstoModels.size());
1565             for (final Map.Entry<String, List<String>> entry : dataTypeUidstoModels.entrySet()) {
1566                 final String key = entry.getKey();
1567                 log.trace("Going to fetch data type with uid {}", key);
1568                 final Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this.getAndAddDataTypeByUid(key, allDataTypesFound);
1569                 if (dataTypeByUid.isRight()) {
1570                     JanusGraphOperationStatus status = dataTypeByUid.right().value();
1571                     if (status == JanusGraphOperationStatus.NOT_FOUND) {
1572                         status = JanusGraphOperationStatus.INVALID_ID;
1573                     }
1574                     return Either.right(status);
1575                 }
1576                 for (final String model : entry.getValue()) {
1577                     if (!dataTypes.containsKey(model)) {
1578                         dataTypes.put(model, new HashMap<>());
1579                     }
1580                     DataTypeDefinition dataTypeDefinition = allDataTypesFound.get(entry.getKey());
1581                     dataTypes.get(model).put(dataTypeDefinition.getName(), dataTypeDefinition);
1582                 }
1583             }
1584         }
1585         if (log.isTraceEnabled()) {
1586             if (result.isRight()) {
1587                 log.trace("After fetching all data types {}", result);
1588             } else {
1589                 Map<String, Map<String, DataTypeDefinition>> map = result.left().value();
1590                 if (map != null) {
1591                     String types = map.keySet().stream().collect(Collectors.joining(",", "[", "]"));
1592                     log.trace("After fetching all data types {} ", types);
1593                 }
1594             }
1595         }
1596         return result;
1597     }
1598
1599     /**
1600      * Build Data type object from graph by unique id
1601      *
1602      * @param uniqueId
1603      * @return
1604      */
1605     private Either<DataTypeDefinition, JanusGraphOperationStatus> getAndAddDataTypeByUid(String uniqueId,
1606                                                                                          Map<String, DataTypeDefinition> allDataTypes) {
1607         Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
1608         if (allDataTypes.containsKey(uniqueId)) {
1609             return Either.left(allDataTypes.get(uniqueId));
1610         }
1611         Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1612             .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
1613         if (dataTypesRes.isRight()) {
1614             JanusGraphOperationStatus status = dataTypesRes.right().value();
1615             log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
1616             return Either.right(status);
1617         }
1618         DataTypeData ctData = dataTypesRes.left().value();
1619         DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
1620         JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
1621         if (propertiesStatus != JanusGraphOperationStatus.OK) {
1622             log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
1623             return Either.right(propertiesStatus);
1624         }
1625         allDataTypes.put(dataTypeDefinition.getUniqueId(), dataTypeDefinition);
1626         String derivedFrom = dataTypeDefinition.getDerivedFromName();
1627         if (allDataTypes.containsKey(derivedFrom)) {
1628             DataTypeDefinition parentDataTypeDefinition = allDataTypes.get(derivedFrom);
1629             dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1630             return Either.left(dataTypeDefinition);
1631         }
1632         Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
1633             .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
1634                 DataTypeData.class);
1635         log.debug(AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS, uniqueId, parentNode);
1636         if (parentNode.isRight()) {
1637             JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
1638             if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
1639                 log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, janusGraphOperationStatus);
1640                 result = Either.right(janusGraphOperationStatus);
1641                 return result;
1642             }
1643         } else {
1644             // derived from node was found
1645             ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
1646             DataTypeData parentCT = immutablePair.getKey();
1647             String parentUniqueId = parentCT.getUniqueId();
1648             Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
1649             if (dataTypeByUid.isRight()) {
1650                 return Either.right(dataTypeByUid.right().value());
1651             }
1652             DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
1653             dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1654             final var model = getModel(uniqueId);
1655             if (StringUtils.isNotEmpty(model)) {
1656                 dataTypeDefinition.setModel(model);
1657             }
1658         }
1659         result = Either.left(dataTypeDefinition);
1660         return result;
1661     }
1662
1663     private String getModel(final String uniqueId) {
1664         final Either<ImmutablePair<ModelData, GraphEdge>, JanusGraphOperationStatus> model = janusGraphGenericDao.getParentNode(
1665             UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.MODEL_ELEMENT,
1666             NodeTypeEnum.Model, ModelData.class);
1667         return model.isLeft() ? model.left().value().getLeft().getName() : StringUtils.EMPTY;
1668     }
1669
1670     public Either<String, JanusGraphOperationStatus> checkInnerType(PropertyDataDefinition propDataDef) {
1671         String propertyType = propDataDef.getType();
1672         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1673         return getInnerType(type, propDataDef::getSchema);
1674     }
1675
1676     public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
1677                                                                   Map<String, DataTypeDefinition> dataTypes) {
1678         log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
1679         final ToscaPropertyType type = getType(propertyType);
1680         if (isValidate) {
1681             if (type == null) {
1682                 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
1683                 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
1684                     .validateAndUpdate(value, dataTypeDefinition, dataTypes);
1685                 if (Boolean.FALSE.equals(validateResult.right)) {
1686                     log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
1687                     return Either.right(false);
1688                 }
1689                 JsonElement jsonElement = validateResult.left;
1690                 String valueFromJsonElement = getValueFromJsonElement(jsonElement);
1691                 return Either.left(valueFromJsonElement);
1692             }
1693             log.trace("before validating property type {}", propertyType);
1694             boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
1695             if (!isValidProperty) {
1696                 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
1697                 return Either.right(false);
1698             }
1699         }
1700         Object convertedValue = value;
1701         if (!isEmptyValue(value) && isValidate) {
1702             PropertyValueConverter converter = type.getConverter();
1703             convertedValue = converter.convert(value, innerType, dataTypes);
1704         }
1705         return Either.left(convertedValue);
1706     }
1707
1708     public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, String innerType,
1709                                                                   Map<String, DataTypeDefinition> dataTypes) {
1710         return validateAndUpdatePropertyValue(propertyType, value, true, innerType, dataTypes);
1711     }
1712
1713     public Either<Object, Boolean> validateAndUpdatePropertyValue(final Component containerComponent, final PropertyDataDefinition property,
1714                                                                   final Map<String, DataTypeDefinition> dataTypes) {
1715         if (property.isToscaFunction()) {
1716             toscaFunctionValidator.validate(property, containerComponent);
1717             property.setValue(property.getToscaFunction().getValue());
1718             return Either.left(property.getValue());
1719         }
1720         Either<String, JanusGraphOperationStatus> checkInnerType = checkInnerType(property);
1721         if (checkInnerType.isRight()) {
1722             return Either.right(false);
1723         }
1724         final String innerType = checkInnerType.left().value();
1725         return validateAndUpdatePropertyValue(property.getType(), property.getValue(), true, innerType, dataTypes);
1726     }
1727
1728     public <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllPropertiesRec(String uniqueId, NodeTypeEnum nodeType,
1729                                                                                                               Class<T> clazz) {
1730         return this.findPropertiesOfNode(nodeType, uniqueId).right().bind(this::handleNotFoundProperties).left()
1731             .bind(props -> getAllDerivedFromChainProperties(uniqueId, nodeType, clazz, props.values()));
1732     }
1733
1734     private Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleNotFoundProperties(
1735         JanusGraphOperationStatus janusGraphOperationStatus) {
1736         if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
1737             return Either.left(new HashMap<>());
1738         }
1739         return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
1740     }
1741
1742     private <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllDerivedFromChainProperties(String uniqueId,
1743                                                                                                                             NodeTypeEnum nodeType,
1744                                                                                                                             Class<T> clazz,
1745                                                                                                                             Collection<PropertyDefinition> nodeProps) {
1746         List<PropertyDefinition> accumulatedProps = new ArrayList<>(nodeProps);
1747         String currentNodeUid = uniqueId;
1748         Either<T, StorageOperationStatus> derivedFrom;
1749         while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) {
1750             currentNodeUid = derivedFrom.left().value().getUniqueId();
1751             JanusGraphOperationStatus janusGraphOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll);
1752             if (janusGraphOperationStatus != JanusGraphOperationStatus.OK) {
1753                 log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid);
1754                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
1755             }
1756         }
1757         StorageOperationStatus getDerivedResult = derivedFrom.right().value();
1758         return isReachedEndOfDerivedFromChain(getDerivedResult) ? Either.left(accumulatedProps) : Either.right(getDerivedResult);
1759     }
1760
1761     private boolean isReachedEndOfDerivedFromChain(StorageOperationStatus getDerivedResult) {
1762         return getDerivedResult == StorageOperationStatus.NOT_FOUND;
1763     }
1764
1765     public JanusGraphOperationStatus fillPropertiesList(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) {
1766         Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType);
1767         if (findPropertiesRes.isRight()) {
1768             return findPropertiesRes.right().value();
1769         }
1770         Map<String, PropertyDefinition> properties = findPropertiesRes.left().value();
1771         if (properties != null) {
1772             List<PropertyDefinition> propertiesAsList = properties.entrySet().stream().map(Entry::getValue).collect(Collectors.toList());
1773             propertySetter.accept(propertiesAsList);
1774         }
1775         return JanusGraphOperationStatus.OK;
1776     }
1777
1778     Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType) {
1779         Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId);
1780         if (findPropertiesOfNode.isRight()) {
1781             log.debug("After looking for properties of vertex {}. status is {}", uniqueId, findPropertiesOfNode.right().value());
1782             if (findPropertiesOfNode.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
1783                 return Either.left(Maps.newHashMap());
1784             }
1785             return findPropertiesOfNode;
1786         }
1787         return findPropertiesOfNode;
1788     }
1789
1790     /**
1791      * add properties to element type.
1792      * <p>
1793      * Per property, add a property node and associate it to the element type
1794      *
1795      * @param uniqueId
1796      * @param propertiesMap
1797      * @return
1798      */
1799     protected Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType,
1800                                                                                                       Map<String, PropertyDefinition> propertiesMap) {
1801         Map<String, PropertyData> propertiesData = new HashMap<>();
1802         if (propertiesMap != null) {
1803             for (Entry<String, PropertyDefinition> propertyDefinitionEntry : propertiesMap.entrySet()) {
1804                 String propertyName = propertyDefinitionEntry.getKey();
1805                 Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this
1806                     .addPropertyToNodeType(propertyName, propertyDefinitionEntry.getValue(), nodeType, uniqueId);
1807                 if (addPropertyToNodeType.isRight()) {
1808                     JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
1809                     log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName,
1810                         operationStatus);
1811                     return Either.right(operationStatus);
1812                 }
1813                 propertiesData.put(propertyName, addPropertyToNodeType.left().value());
1814             }
1815         }
1816         return Either.left(propertiesData);
1817     }
1818
1819     public Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum elementType,
1820                                                                                                    List<PropertyDefinition> properties) {
1821         Map<String, PropertyDefinition> propMap;
1822         if (properties == null) {
1823             propMap = null;
1824         } else {
1825             propMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, propDef -> propDef));
1826         }
1827         return addPropertiesToElementType(uniqueId, elementType, propMap);
1828     }
1829
1830     @Override
1831     public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
1832                                                                              DataTypeDefinition oldDataTypeDefinition) {
1833         return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true);
1834     }
1835
1836     private Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
1837                                                                               DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) {
1838         Either<DataTypeDefinition, StorageOperationStatus> result = null;
1839         try {
1840             List<PropertyDefinition> newProperties = newDataTypeDefinition.getProperties();
1841             List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties();
1842             String newDerivedFromName = newDataTypeDefinition.getDerivedFromName();
1843             String oldDerivedFromName = oldDataTypeDefinition.getDerivedFromName();
1844             String dataTypeName = newDataTypeDefinition.getName();
1845             List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
1846             if (isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd)
1847                 || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
1848                 log.debug("The new data type {} is invalid.", dataTypeName);
1849                 result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
1850                 return result;
1851             }
1852             if (CollectionUtils.isEmpty(propertiesToAdd)) {
1853                 log.debug("No new properties has been defined in the new data type {}", newDataTypeDefinition);
1854                 result = Either.right(StorageOperationStatus.OK);
1855                 return result;
1856             }
1857             Map<String, String> newDescriptions = getPropertyDescriptionsToUpdate(oldProperties, newProperties);
1858             if (MapUtils.isNotEmpty(newDescriptions)) {
1859                 JanusGraphOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(),
1860                     newDescriptions);
1861                 if (updatePropertiesStatus != JanusGraphOperationStatus.OK) {
1862                     log.debug("#updateDataType - Failed to update the descriptions of the properties of the data type {}. Status is {}",
1863                         oldDataTypeDefinition, updatePropertiesStatus);
1864                     BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
1865                     result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatePropertiesStatus));
1866                     return result;
1867                 }
1868             }
1869             Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(
1870                 oldDataTypeDefinition.getUniqueId(), oldDataTypeDefinition.getModel(), propertiesToAdd);
1871             if (addPropertiesToDataType.isRight()) {
1872                 log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition,
1873                     addPropertiesToDataType.right().value().name());
1874                 BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
1875                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToDataType.right().value()));
1876                 return result;
1877             } else {
1878                 Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId());
1879                 if (dataTypeByUid.isRight()) {
1880                     JanusGraphOperationStatus status = addPropertiesToDataType.right().value();
1881                     log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name());
1882                     BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(UPDATE_DATA_TYPE, PROPERTY, status.name());
1883                     result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1884                 } else {
1885                     result = Either.left(dataTypeByUid.left().value());
1886                 }
1887             }
1888             return result;
1889         } finally {
1890             if (!inTransaction) {
1891                 if (result == null || result.isRight()) {
1892                     log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1893                     janusGraphGenericDao.rollback();
1894                 } else {
1895                     log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1896                     janusGraphGenericDao.commit();
1897                 }
1898             }
1899         }
1900     }
1901
1902     private boolean isPropertyTypeChanged(String dataTypeName, List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties,
1903                                           List<PropertyDefinition> outputPropertiesToAdd) {
1904         if (newProperties != null && oldProperties != null) {
1905             Map<String, PropertyDefinition> newPropsMapper = newProperties.stream()
1906                 .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
1907             Map<String, PropertyDefinition> oldPropsMapper = oldProperties.stream()
1908                 .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
1909             for (Entry<String, PropertyDefinition> newPropertyEntry : newPropsMapper.entrySet()) {
1910                 String propName = newPropertyEntry.getKey();
1911                 PropertyDefinition propDef = newPropertyEntry.getValue();
1912                 PropertyDefinition oldPropertyDefinition = oldPropsMapper.get(propName);
1913                 if (oldPropertyDefinition == null) {
1914                     log.debug("New property {} received in the data type {}", propName, dataTypeName);
1915                     outputPropertiesToAdd.add(propDef);
1916                     continue;
1917                 }
1918                 String oldType = oldPropertyDefinition.getType();
1919                 String oldEntryType = getEntryType(oldPropertyDefinition);
1920                 String newType = propDef.getType();
1921                 String newEntryType = getEntryType(propDef);
1922                 if (!oldType.equals(newType)) {
1923                     log.debug("Existing property {} in data type {} has a differnet type {} than the new one {}", propName, dataTypeName, oldType,
1924                         newType);
1925                     return true;
1926                 }
1927                 if (!equalsEntryTypes(oldEntryType, newEntryType)) {
1928                     log.debug("Existing property {} in data type {} has a differnet entry type {} than the new one {}", propName, dataTypeName,
1929                         oldEntryType, newEntryType);
1930                     return true;
1931                 }
1932             }
1933         }
1934         return false;
1935     }
1936
1937     private boolean equalsEntryTypes(String oldEntryType, String newEntryType) {
1938         if (oldEntryType == null && newEntryType == null) {
1939             return true;
1940         } else if (oldEntryType != null && newEntryType != null) {
1941             return oldEntryType.equals(newEntryType);
1942         } else {
1943             return false;
1944         }
1945     }
1946
1947     private String getEntryType(PropertyDefinition oldPropertyDefinition) {
1948         String entryType = null;
1949         SchemaDefinition schema = oldPropertyDefinition.getSchema();
1950         if (schema != null) {
1951             PropertyDataDefinition schemaProperty = schema.getProperty();
1952             if (schemaProperty != null) {
1953                 entryType = schemaProperty.getType();
1954             }
1955         }
1956         return entryType;
1957     }
1958
1959     private boolean isDerivedFromNameChanged(String dataTypeName, String newDerivedFromName, String oldDerivedFromName) {
1960         if (newDerivedFromName != null) {
1961             boolean isEqual = newDerivedFromName.equals(oldDerivedFromName);
1962             if (!isEqual) {
1963                 log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName,
1964                     oldDerivedFromName);
1965             }
1966             return !isEqual;
1967         } else if (oldDerivedFromName == null) {
1968             return false;
1969         } else {// new=null, old != null
1970             log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName,
1971                 oldDerivedFromName);
1972             return true;
1973         }
1974     }
1975
1976     /**
1977      * @param instanceId
1978      * @param nodeType
1979      * @return
1980      */
1981     public Either<Integer, StorageOperationStatus> increaseAndGetObjInstancePropertyCounter(String instanceId, NodeTypeEnum nodeType) {
1982         Either<JanusGraph, JanusGraphOperationStatus> graphResult = janusGraphGenericDao.getGraph();
1983         if (graphResult.isRight()) {
1984             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value()));
1985         }
1986         Either<JanusGraphVertex, JanusGraphOperationStatus> vertexService = janusGraphGenericDao
1987             .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId);
1988         if (vertexService.isRight()) {
1989             log.debug("failed to fetch vertex of resource instance for id = {}", instanceId);
1990             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value()));
1991         }
1992         Vertex vertex = vertexService.left().value();
1993         VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty());
1994         Integer counter = 0;
1995         if (vertexProperty.isPresent() && vertexProperty.value() != null) {
1996             counter = (Integer) vertexProperty.value();
1997         }
1998         counter++;
1999         vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter);
2000         return Either.left(counter);
2001     }
2002
2003     public Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesUniqueness(
2004         Map<String, PropertyDefinition> inheritedProperties, List<PropertyDefinition> properties) {
2005         Either<List<PropertyDefinition>, JanusGraphOperationStatus> result = Either.left(properties);
2006         for (PropertyDefinition property : properties) {
2007             JanusGraphOperationStatus status = validatePropertyUniqueness(inheritedProperties, property);
2008             if (status != JanusGraphOperationStatus.OK) {
2009                 result = Either.right(status);
2010                 break;
2011             }
2012         }
2013         return result;
2014     }
2015
2016     /**
2017      * Validates uniqueness of examined property by comparing it with properties in propertiesOfType and updates if need type and inner type of the
2018      * property.
2019      */
2020     private JanusGraphOperationStatus validatePropertyUniqueness(Map<String, PropertyDefinition> inheritedProperties, PropertyDefinition property) {
2021         String propertyName = property.getName();
2022         String propertyType = property.getType();
2023         JanusGraphOperationStatus result = JanusGraphOperationStatus.OK;
2024         if (inheritedProperties.containsKey(propertyName)) {
2025             PropertyDefinition defaultProperty = inheritedProperties.get(propertyName);
2026             if (typesMismatch(propertyType, defaultProperty.getType())) {
2027                 log.error("#validatePropertyUniqueness - Property with name {} and different type already exists.", propertyName);
2028                 result = JanusGraphOperationStatus.PROPERTY_NAME_ALREADY_EXISTS;
2029             } else {
2030                 property.setType(defaultProperty.getType());
2031                 String innerType = defaultProperty.getSchemaType();
2032                 PropertyDataDefinition schemaProperty = property.getSchemaProperty();
2033                 if (schemaProperty != null) {
2034                     schemaProperty.setType(innerType);
2035                 }
2036             }
2037         }
2038         return result;
2039     }
2040
2041     private boolean typesMismatch(String type1, String type2) {
2042         return type1 != null && type2 != null && !type2.equals(type1);
2043     }
2044
2045     public <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllTypePropertiesFromAllDerivedFrom(
2046         String nextParentUid, NodeTypeEnum nodeType, Class<T> clazz) {
2047         Map<String, PropertyDefinition> allProperies = new HashMap<>();
2048         return getTypePropertiesFromDerivedFromRecursively(nextParentUid, allProperies, nodeType, clazz);
2049     }
2050
2051     private <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getTypePropertiesFromDerivedFromRecursively(
2052         String nextParentUid, Map<String, PropertyDefinition> allProperies, NodeTypeEnum nodeType, Class<T> clazz) {
2053         JanusGraphOperationStatus error;
2054         Either<List<ImmutablePair<T, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
2055             .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), nextParentUid, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz);
2056         if (childrenNodes.isRight()) {
2057             if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2058                 error = childrenNodes.right().value();
2059                 log.debug("#getTypePropertiesFromDerivedFromRecursively - Couldn't fetch derived from node with UID {}, error: {}", nextParentUid,
2060                     error);
2061                 return Either.right(error);
2062             } else {
2063                 log.debug("#getTypePropertiesFromDerivedFromRecursively - Derived from node is not found with UID {} - this is OK for root.",
2064                     nextParentUid);
2065                 return Either.left(allProperies);
2066             }
2067         } else {
2068             Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesOfTypeRes = findPropertiesOfNode(nodeType, nextParentUid);
2069             if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
2070                 error = allPropertiesOfTypeRes.right().value();
2071                 log.error(
2072                     "#getTypePropertiesFromDerivedFromRecursively - Failed to retrieve properties for node with UID {} from graph. status is {}",
2073                     nextParentUid, error);
2074                 return Either.right(error);
2075             } else if (allPropertiesOfTypeRes.isLeft()) {
2076                 if (allProperies.isEmpty()) {
2077                     allProperies.putAll(allPropertiesOfTypeRes.left().value());
2078                 } else {
2079                     allProperies.putAll(allPropertiesOfTypeRes.left().value().entrySet().stream().filter(e -> !allProperies.containsKey(e.getKey()))
2080                         .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
2081                 }
2082             }
2083             return getTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies, nodeType,
2084                 clazz);
2085         }
2086     }
2087
2088     private JanusGraphOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map<String, String> newDescriptions) {
2089         if (MapUtils.isNotEmpty(newDescriptions)) {
2090             Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> getDataTypePropertiesRes = janusGraphGenericDao
2091                 .getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY);
2092             if (getDataTypePropertiesRes.isRight()) {
2093                 log.debug("#updateDataTypePropertiesDescriptions - Failed to fetch the property verticies of the Data type {} ", uniqueId);
2094                 return getDataTypePropertiesRes.right().value();
2095             }
2096             getDataTypePropertiesRes.left().value().stream().filter(pair -> newDescriptions.containsKey(getPropertyNameFromEdge(pair)))
2097                 .forEach(pair -> setNewDescriptionToVertex(newDescriptions.get(getPropertyNameFromEdge(pair)), pair));
2098         }
2099         return JanusGraphOperationStatus.OK;
2100     }
2101
2102     private JanusGraphVertexProperty<String> setNewDescriptionToVertex(String newDescription, ImmutablePair<JanusGraphVertex, Edge> pair) {
2103         return pair.getLeft().property(GraphPropertiesDictionary.DESCRIPTION.getProperty(), newDescription);
2104     }
2105
2106     private String getPropertyNameFromEdge(ImmutablePair<JanusGraphVertex, Edge> pair) {
2107         return (String) pair.getRight().property(GraphPropertiesDictionary.NAME.getProperty()).value();
2108     }
2109
2110     private Map<String, String> getPropertyDescriptionsToUpdate(List<PropertyDefinition> oldProperties, List<PropertyDefinition> newProperties) {
2111         Map<String, PropertyDefinition> newPropertiesMap = newProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
2112         return oldProperties.stream()
2113             .filter(p -> newPropertiesMap.containsKey(p.getName()) && !descriptionsEqual(p, newPropertiesMap.get(p.getName())))
2114             .collect(Collectors.toMap(PropertyDefinition::getName, p -> newPropertiesMap.get(p.getName()).getDescription()));
2115     }
2116
2117     private boolean descriptionsEqual(PropertyDefinition property, PropertyDefinition otherProperty) {
2118         if (StringUtils.isEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())) {
2119             return true;
2120         }
2121         if (StringUtils.isNotEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())) {
2122             return false;
2123         }
2124         if (StringUtils.isEmpty(property.getDescription()) && StringUtils.isNotEmpty(otherProperty.getDescription())) {
2125             return false;
2126         }
2127         return property.getDescription().equals(otherProperty.getDescription());
2128     }
2129
2130     public static class PropertyConstraintSerialiser implements JsonSerializer<PropertyConstraint> {
2131
2132         @Override
2133         public JsonElement serialize(PropertyConstraint src, Type typeOfSrc, JsonSerializationContext context) {
2134             JsonObject result = new JsonObject();
2135             JsonArray jsonArray = new JsonArray();
2136             if (src instanceof InRangeConstraint) {
2137                 InRangeConstraint rangeConstraint = (InRangeConstraint) src;
2138                 jsonArray.add(JsonParser.parseString(String.valueOf(rangeConstraint.getMin())));
2139                 jsonArray.add(JsonParser.parseString(String.valueOf(rangeConstraint.getMax())));
2140                 result.add("inRange", jsonArray);
2141             } else if (src instanceof GreaterThanConstraint) {
2142                 GreaterThanConstraint greaterThanConstraint = (GreaterThanConstraint) src;
2143                 jsonArray.add(JsonParser.parseString(String.valueOf(greaterThanConstraint.getGreaterThan())));
2144                 result.add("greaterThan", jsonArray);
2145             } else if (src instanceof LessThanConstraint) {
2146                 LessThanConstraint lessThanConstraint = (LessThanConstraint) src;
2147                 jsonArray.add(JsonParser.parseString(String.valueOf(lessThanConstraint.getLessThan())));
2148                 result.add("lessThan", jsonArray);
2149             } else if (src instanceof LessOrEqualConstraint) {
2150                 LessOrEqualConstraint lessOrEqualConstraint = (LessOrEqualConstraint) src;
2151                 jsonArray.add(JsonParser.parseString(String.valueOf(lessOrEqualConstraint.getLessOrEqual())));
2152                 result.add("lessOrEqual", jsonArray);
2153             } else {
2154                 log.warn("PropertyConstraint {} is not supported. Ignored.", src.getClass().getName());
2155             }
2156             return result;
2157         }
2158     }
2159
2160     public static class PropertyConstraintDeserialiser implements JsonDeserializer<PropertyConstraint> {
2161
2162         @Override
2163         public PropertyConstraint deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
2164             PropertyConstraint propertyConstraint = null;
2165             final Set<Entry<String, JsonElement>> set = json.getAsJsonObject().entrySet();
2166             if (!set.isEmpty()) {
2167                 final Entry<String, JsonElement> element = set.iterator().next();
2168                 final String key = element.getKey();
2169                 final ConstraintType constraintType = ConstraintType.findByType(key).orElse(null);
2170                 if (constraintType == null) {
2171                     log.warn("ConstraintType was not found for constraint name:{}", key);
2172                 } else {
2173                     if (set.size() == 1 || (set.size() == 2 && ConstraintType.PATTERN == constraintType)) {
2174                         final JsonElement value = element.getValue();
2175                         final Object typedValue = getTypedValue(value);
2176                         switch (constraintType) {
2177                             case EQUAL:
2178                                 if (typedValue != null) {
2179                                     log.debug("Before adding value to EqualConstraint object. value = {}", typedValue);
2180                                     propertyConstraint = new EqualConstraint(typedValue);
2181                                 } else {
2182                                     log.warn("The value of EqualConstraint is null");
2183                                 }
2184                                 break;
2185                             case IN_RANGE:
2186                                 if (typedValue instanceof ArrayList) {
2187                                     List<Object> rangeArray = (ArrayList<Object>) typedValue;
2188                                     if (rangeArray.size() != 2 || rangeArray.contains("")) {
2189                                         log.error("The range constraint content is invalid. value = {}", typedValue);
2190                                         throw new JsonSyntaxException("The range constraint content is invalid");
2191                                     } else {
2192                                         Object minValue = rangeArray.get(0);
2193                                         Object maxValue = rangeArray.get(1);
2194                                         InRangeConstraint rangeConstraint = new InRangeConstraint(Lists.newArrayList(minValue, maxValue));
2195                                         rangeConstraint.setMin(convertToComparable(ToscaType.RANGE, String.valueOf(minValue)));
2196                                         rangeConstraint.setMax(convertToComparable(ToscaType.RANGE, String.valueOf(maxValue)));
2197                                         propertyConstraint = rangeConstraint;
2198                                     }
2199                                 } else {
2200                                     log.warn("The value of InRangeConstraint is null");
2201                                 }
2202                                 break;
2203                             case GREATER_THAN:
2204                                 if (typedValue != null) {
2205                                     log.debug("Before adding value to GreaterThanConstraint object. value = {}", typedValue);
2206                                     propertyConstraint = new GreaterThanConstraint(typedValue);
2207                                 } else {
2208                                     log.warn("The value of GreaterThanConstraint is null");
2209                                 }
2210                                 break;
2211                             case LESS_THAN:
2212                                 if (typedValue != null) {
2213                                     log.debug("Before adding value to LessThanConstraint object. value = {}", typedValue);
2214                                     propertyConstraint = new LessThanConstraint(typedValue);
2215                                 } else {
2216                                     log.warn("The value of LessThanConstraint is null");
2217                                 }
2218                                 break;
2219                             case GREATER_OR_EQUAL:
2220                                 if (typedValue != null) {
2221                                     log.debug("Before adding value to GreaterThanConstraint object. value = {}", typedValue);
2222                                     propertyConstraint = new GreaterOrEqualConstraint(typedValue);
2223                                 } else {
2224                                     log.warn("The value of GreaterOrEqualConstraint is null");
2225                                 }
2226                                 break;
2227                             case LESS_OR_EQUAL:
2228                                 if (typedValue != null) {
2229                                     log.debug("Before adding value to LessOrEqualConstraint object. value = {}", typedValue);
2230                                     propertyConstraint = new LessOrEqualConstraint(typedValue);
2231                                 } else {
2232                                     log.warn("The value of LessOrEqualConstraint is null");
2233                                 }
2234                                 break;
2235                             case VALID_VALUES:
2236                                 if (typedValue instanceof ArrayList) {
2237                                     List<Object> validValuesArray = (ArrayList<Object>) typedValue;
2238                                     if (validValuesArray.size() == 0 || validValuesArray.contains("")) {
2239                                         log.error("The valid values constraint content is invalid. value = {}", typedValue);
2240                                         throw new JsonSyntaxException("The valid values constraint content is invalid");
2241                                     } else {
2242                                         ValidValuesConstraint vvConstraint = new ValidValuesConstraint();
2243                                         vvConstraint.setValidValues(validValuesArray);
2244                                         propertyConstraint = vvConstraint;
2245                                     }
2246                                 } else {
2247                                     log.warn("The value of ValidValuesConstraint is null");
2248                                 }
2249                                 break;
2250                             case LENGTH:
2251                                 if (value != null) {
2252                                     int asInt = value.getAsInt();
2253                                     log.debug("Before adding value to length constraint. value = {}", asInt);
2254                                     propertyConstraint = new LengthConstraint(asInt);
2255                                 } else {
2256                                     log.warn("The value of LengthConstraint is null");
2257                                 }
2258                                 break;
2259                             case MIN_LENGTH:
2260                                 if (value != null) {
2261                                     int asInt = value.getAsInt();
2262                                     log.debug("Before adding value to Min Length object. value = {}", asInt);
2263                                     propertyConstraint = new MinLengthConstraint(asInt);
2264                                 } else {
2265                                     log.warn("The value of MinLengthConstraint is null");
2266                                 }
2267                                 break;
2268                             case MAX_LENGTH:
2269                                 if (value != null) {
2270                                     int asInt = value.getAsInt();
2271                                     log.debug("Before adding value to max length constraint. value = {}", asInt);
2272                                     propertyConstraint = new MaxLengthConstraint(asInt);
2273                                 } else {
2274                                     log.warn("The value of MaxLengthConstraint is null");
2275                                 }
2276                                 break;
2277                             case PATTERN:
2278                                 if (value != null) {
2279                                     String asString = value.getAsString();
2280                                     log.debug("Before adding value to PatternConstraint object. value = {}", asString);
2281                                     propertyConstraint = new PatternConstraint(asString);
2282                                 } else {
2283                                     log.warn("The value of PatternConstraint is null");
2284                                 }
2285                                 break;
2286                             default:
2287                                 log.warn("Key {} is not supported. Ignored.", key);
2288                         }
2289                     }
2290                 }
2291             }
2292             return propertyConstraint;
2293         }
2294
2295         private Object getTypedValue(JsonElement je) {
2296             if (je == null || je.isJsonNull()) {
2297                 return null;
2298             }
2299             if (je.isJsonPrimitive()) {
2300                 return getJsonPrimitive(je.getAsJsonPrimitive());
2301             }
2302             if (je.isJsonArray()) {
2303                 ArrayList<Object> array = new ArrayList<>();
2304                 for (JsonElement e : je.getAsJsonArray()) {
2305                     array.add(getJsonPrimitive(e.getAsJsonPrimitive()));
2306                 }
2307                 return array;
2308             }
2309             return je;
2310         }
2311
2312         private Object getJsonPrimitive(JsonPrimitive je) {
2313             if (je.isBoolean()) {
2314                 return je.getAsBoolean();
2315             }
2316             if (je.isString()) {
2317                 return je.getAsString();
2318             }
2319             if (je.isNumber()) {
2320                 double number = je.getAsNumber().floatValue();
2321                 if ((number % 1) == 0) {
2322                     return je.getAsNumber().intValue();
2323                 }
2324                 return number;
2325             }
2326             return null;
2327         }
2328     }
2329
2330     public static class PropertyConstraintJacksonDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<PropertyConstraint> {
2331
2332         @Override
2333         public PropertyConstraint deserialize(com.fasterxml.jackson.core.JsonParser json, DeserializationContext context) throws IOException {
2334             ObjectCodec oc = json.getCodec();
2335             JsonNode node = oc.readTree(json);
2336             PropertyConstraint propertyConstraint = null;
2337
2338             Iterator<Entry<String, JsonNode>> fieldsIterator = node.fields();
2339             while (fieldsIterator.hasNext()) {
2340                 Entry<String, JsonNode> field = fieldsIterator.next();
2341                 ConstraintType constraintType = ConstraintType.findByType(field.getKey()).orElse(null);
2342                 JsonNode value = field.getValue();
2343
2344                 if (constraintType == null) {
2345                     log.warn("ConstraintType was not found for constraint name:{}", field.getKey());
2346                 } else {
2347                     if (value == null) {
2348                         log.warn("The value of {} constraint is null", constraintType);
2349                     } else {
2350                         switch (constraintType) {
2351                             case EQUAL:
2352                                 propertyConstraint = deserializeConstraintWithStringOperand(value, EqualConstraint.class);
2353                                 break;
2354                             case IN_RANGE:
2355                                 propertyConstraint = deserializeInRangeConstraintConstraint(value);
2356                                 break;
2357                             case GREATER_THAN:
2358                                 propertyConstraint = deserializeConstraintWithStringOperand(value, GreaterThanConstraint.class);
2359                                 break;
2360                             case LESS_THAN:
2361                                 propertyConstraint = deserializeConstraintWithStringOperand(value, LessThanConstraint.class);
2362                                 break;
2363                             case GREATER_OR_EQUAL:
2364                                 propertyConstraint = deserializeConstraintWithStringOperand(value, GreaterOrEqualConstraint.class);
2365                                 break;
2366                             case LESS_OR_EQUAL:
2367                                 propertyConstraint = deserializeConstraintWithStringOperand(value, LessOrEqualConstraint.class);
2368                                 break;
2369                             case VALID_VALUES:
2370                                 propertyConstraint = deserializeValidValuesConstraint(value);
2371                                 break;
2372                             case LENGTH:
2373                                 propertyConstraint = deserializeConstraintWithIntegerOperand(value, LengthConstraint.class);
2374                                 break;
2375                             case MIN_LENGTH:
2376                                 propertyConstraint = deserializeConstraintWithIntegerOperand(value, MinLengthConstraint.class);
2377                                 break;
2378                             case MAX_LENGTH:
2379                                 propertyConstraint = deserializeConstraintWithIntegerOperand(value, MaxLengthConstraint.class);
2380                                 break;
2381                             case PATTERN:
2382                                 propertyConstraint = deserializeConstraintWithStringPatternOperand(value, PatternConstraint.class);
2383                                 break;
2384                             default:
2385                                 log.warn("Key {} is not supported. Ignored.", field.getKey());
2386                         }
2387                     }
2388                 }
2389             }
2390
2391             return propertyConstraint;
2392         }
2393
2394         private PropertyConstraint deserializeConstraintWithStringOperand(JsonNode value, Class<? extends PropertyConstraint> constraintClass) {
2395             String asString = value.asText();
2396             log.debug("Before adding value to {} object. value = {}", constraintClass, asString);
2397             try {
2398                 return constraintClass.getConstructor(Object.class).newInstance(asString);
2399             } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
2400                      | SecurityException exception) {
2401                 log.error("Error deserializing constraint", exception);
2402                 return null;
2403             }
2404         }
2405
2406         private PropertyConstraint deserializeConstraintWithStringPatternOperand(JsonNode value,
2407                                                                                  Class<? extends PropertyConstraint> constraintClass) {
2408             String asString = value.asText();
2409             log.debug("Before adding value to {} object. value = {}", constraintClass, asString);
2410             try {
2411                 return constraintClass.getConstructor(String.class).newInstance(asString);
2412             } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
2413                      | SecurityException exception) {
2414                 log.error("Error deserializing constraint", exception);
2415                 return null;
2416             }
2417         }
2418
2419         private PropertyConstraint deserializeConstraintWithIntegerOperand(JsonNode value, Class<? extends PropertyConstraint> constraintClass) {
2420             Integer asInt = value.asInt();
2421             log.debug("Before adding value to {} object. value = {}", constraintClass, asInt);
2422             try {
2423                 return constraintClass.getConstructor(Integer.class).newInstance(asInt);
2424             } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
2425                      | SecurityException exception) {
2426                 log.error("Error deserializing constraint", exception);
2427                 return null;
2428             }
2429         }
2430
2431         private PropertyConstraint deserializeInRangeConstraintConstraint(JsonNode value) {
2432             if (value instanceof ArrayNode) {
2433                 ArrayNode rangeArray = (ArrayNode) value;
2434                 if (rangeArray.size() != 2) {
2435                     log.error("The range constraint content is invalid. value = {}", value);
2436                 } else {
2437                     String minValue = rangeArray.get(0).asText();
2438                     String maxValue = rangeArray.get(1).asText();
2439                     InRangeConstraint rangeConstraint = new InRangeConstraint(Lists.newArrayList(minValue, maxValue));
2440                     rangeConstraint.setMin(convertToComparable(ToscaType.RANGE, minValue));
2441                     rangeConstraint.setMax(convertToComparable(ToscaType.RANGE, maxValue));
2442                     return rangeConstraint;
2443                 }
2444             }
2445             return null;
2446         }
2447
2448         private PropertyConstraint deserializeValidValuesConstraint(JsonNode value) {
2449             ArrayNode rangeArray = (ArrayNode) value;
2450             if (rangeArray.size() == 0) {
2451                 log.error("The valid values constraint content is invalid. value = {}", value);
2452             } else {
2453                 ValidValuesConstraint vvConstraint = new ValidValuesConstraint();
2454                 List<Object> validValues = new ArrayList<>();
2455                 for (JsonNode jsonElement : rangeArray) {
2456                     String item = jsonElement.asText();
2457                     validValues.add(item);
2458                 }
2459                 vvConstraint.setValidValues(validValues);
2460                 return vvConstraint;
2461             }
2462             return null;
2463         }
2464
2465     }
2466
2467 }