26fe1e262d8aa8a5ed39b10d7ceeb6ab717e87db
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.model.jsontitan.operations;
22
23 import com.google.gson.reflect.TypeToken;
24 import fj.data.Either;
25 import org.apache.commons.collections.MapUtils;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.tinkerpop.gremlin.structure.Direction;
28 import org.apache.tinkerpop.gremlin.structure.Edge;
29 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
30 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
31 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
32 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
33 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
34 import org.openecomp.sdc.be.datatypes.elements.*;
35 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
36 import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
37 import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
38 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
39 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
40 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
41 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.be.model.category.CategoryDefinition;
44 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
45 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
46 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
47 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
48 import org.openecomp.sdc.be.model.operations.StorageException;
49 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
50 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
51 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
52 import org.openecomp.sdc.be.model.utils.ComponentUtilities;
53 import org.openecomp.sdc.common.api.Constants;
54 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
55 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
56 import org.openecomp.sdc.common.log.wrappers.Logger;
57 import org.openecomp.sdc.common.util.ValidationUtils;
58 import org.springframework.beans.factory.annotation.Autowired;
59
60 import java.lang.reflect.Type;
61 import java.util.*;
62 import java.util.Map.Entry;
63 import java.util.stream.Collectors;
64
65 @org.springframework.stereotype.Component("topology-template-operation")
66 public class TopologyTemplateOperation extends ToscaElementOperation {
67
68     private static final Logger log = Logger.getLogger(TopologyTemplateOperation.class);
69
70     @Autowired
71     private ArchiveOperation archiveOperation;
72
73     public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) {
74         Either<TopologyTemplate, StorageOperationStatus> result = null;
75
76         topologyTemplate.generateUUID();
77
78         topologyTemplate = getResourceMetaDataFromResource(topologyTemplate);
79         String resourceUniqueId = topologyTemplate.getUniqueId();
80         if (resourceUniqueId == null) {
81             resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
82             topologyTemplate.setUniqueId(resourceUniqueId);
83         }
84
85         GraphVertex topologyTemplateVertex = new GraphVertex();
86         topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll);
87
88         Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(topologyTemplateVertex);
89         if (createdVertex.isRight()) {
90             TitanOperationStatus status = createdVertex.right().value();
91             log.debug( "Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status);
92             result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
93             return result;
94         }
95
96         topologyTemplateVertex = createdVertex.left().value();
97
98         StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null);
99         if (assosiateCommon != StorageOperationStatus.OK) {
100             result = Either.right(assosiateCommon);
101             return result;
102         }
103
104         StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate);
105         if (associateCategory != StorageOperationStatus.OK) {
106             result = Either.right(associateCategory);
107             return result;
108         }
109
110         StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate);
111         if (associateInputs != StorageOperationStatus.OK) {
112             result = Either.right(associateInputs);
113             return result;
114         }
115         StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate);
116         if (associateGroups != StorageOperationStatus.OK) {
117             result = Either.right(associateGroups);
118             return result;
119         }
120         StorageOperationStatus associatePolicies = associatePoliciesToComponent(topologyTemplateVertex, topologyTemplate);
121         if (associatePolicies != StorageOperationStatus.OK) {
122             result = Either.right(associatePolicies);
123             return result;
124         }
125         StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate);
126         if (associateInstAttr != StorageOperationStatus.OK) {
127             result = Either.right(associateInstAttr);
128             return result;
129         }
130         StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate);
131         if (associateInstProperties != StorageOperationStatus.OK) {
132             result = Either.right(associateInstProperties);
133             return result;
134         }
135         StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate);
136         if (associateInstProperties != StorageOperationStatus.OK) {
137             result = Either.right(associateInstInputs);
138             return result;
139         }
140         StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate);
141         if (associateInstGroups != StorageOperationStatus.OK) {
142             result = Either.right(associateInstInputs);
143             return result;
144         }
145
146         StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate);
147         if (associateRequirements != StorageOperationStatus.OK) {
148             result = Either.right(associateRequirements);
149             return result;
150         }
151
152         StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate);
153         if (associateCapabilities != StorageOperationStatus.OK) {
154             result = Either.right(associateCapabilities);
155             return result;
156         }
157
158         StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate);
159         if (associateArtifacts != StorageOperationStatus.OK) {
160             result = Either.right(associateArtifacts);
161             return result;
162         }
163
164         StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate);
165         if (addAdditionalInformation != StorageOperationStatus.OK) {
166             result = Either.right(addAdditionalInformation);
167             return result;
168         }
169         StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate);
170         if (associateCapProperties != StorageOperationStatus.OK) {
171             result = Either.right(associateCapProperties);
172             return result;
173         }
174
175         StorageOperationStatus associateInterfaces = associateInterfacesToComponent(topologyTemplateVertex, topologyTemplate);
176         if (associateInterfaces != StorageOperationStatus.OK) {
177             result = Either.right(associateInterfaces);
178         return result;
179         }
180
181         StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate);
182         if (associateCapProperties != StorageOperationStatus.OK) {
183             result = Either.right(associatePathProperties);
184             return result;
185         }
186
187
188         return Either.left(topologyTemplate);
189
190     }
191
192     private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
193         return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies());
194     }
195
196     private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex,    Map<String, PolicyDataDefinition> policies) {
197         if (policies != null && !policies.isEmpty()) {
198             policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
199                 String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
200                 p.setUniqueId(uid);
201             });
202             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies);
203             if (assosiateElementToData.isRight()) {
204                 return assosiateElementToData.right().value();
205             }
206         }
207         return StorageOperationStatus.OK;
208     }
209
210     private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
211         Map<String, ForwardingPathDataDefinition> forwardingPaths = topologyTemplate.getForwardingPaths();
212         return associateForwardingPathToComponent(topologyTemplateVertex,forwardingPaths);
213     }
214
215     private StorageOperationStatus associateNodeFilterToResource(GraphVertex topologyTemplateVertex,
216             TopologyTemplate topologyTemplate) {
217         Map<String, CINodeFilterDataDefinition> nodeFilters =
218                 topologyTemplate.getNodeFilterComponents();
219         return associateNodeFiltersToComponent(topologyTemplateVertex, nodeFilters);
220     }
221
222     private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
223         Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
224         if (calculatedCapProperties != null && !calculatedCapProperties.isEmpty()) {
225             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties);
226             if (assosiateElementToData.isRight()) {
227                 return assosiateElementToData.right().value();
228             }
229         }
230         return StorageOperationStatus.OK;
231     }
232
233     private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
234         Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = topologyTemplate.getCalculatedCapabilities();
235         if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) {
236             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities);
237             if (assosiateElementToData.isRight()) {
238                 return assosiateElementToData.right().value();
239             }
240         }
241         Map<String, MapListCapabilityDataDefinition> fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities();
242         if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) {
243             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities);
244             if (assosiateElementToData.isRight()) {
245                 return assosiateElementToData.right().value();
246             }
247         }
248         return StorageOperationStatus.OK;
249
250     }
251
252     private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
253         Map<String, MapListRequirementDataDefinition> calculatedRequirements = topologyTemplate.getCalculatedRequirements();
254         if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) {
255             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements);
256             if (assosiateElementToData.isRight()) {
257                 return assosiateElementToData.right().value();
258             }
259         }
260         Map<String, MapListRequirementDataDefinition> fullfilledRequirements = topologyTemplate.getFullfilledRequirements();
261         if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) {
262             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements);
263             if (assosiateElementToData.isRight()) {
264                 return assosiateElementToData.right().value();
265             }
266         }
267         return StorageOperationStatus.OK;
268     }
269
270     private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
271         Map<String, ArtifactDataDefinition> addInformation = topologyTemplate.getServiceApiArtifacts();
272
273         if (addInformation != null && !addInformation.isEmpty()) {
274             addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
275                 String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
276                 a.setUniqueId(uniqueId);
277             });
278             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation);
279             if (assosiateElementToData.isRight()) {
280                 return assosiateElementToData.right().value();
281             }
282         }
283         Map<String, MapArtifactDataDefinition> instArtifacts = topologyTemplate.getInstDeploymentArtifacts();
284
285         if (instArtifacts != null && !instArtifacts.isEmpty()) {
286             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts);
287             if (assosiateElementToData.isRight()) {
288                 return assosiateElementToData.right().value();
289             }
290         }
291         Map<String, MapArtifactDataDefinition> instInfoArtifacts = topologyTemplate.getInstanceArtifacts();
292
293         if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) {
294             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts);
295             if (assosiateElementToData.isRight()) {
296                 return assosiateElementToData.right().value();
297             }
298         }
299         return StorageOperationStatus.OK;
300     }
301
302     private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
303
304         Map<String, AdditionalInfoParameterDataDefinition> addInformation = topologyTemplate.getAdditionalInformation();
305
306         if (addInformation != null && !addInformation.isEmpty()) {
307             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation);
308             if (assosiateElementToData.isRight()) {
309                 return assosiateElementToData.right().value();
310             }
311         }
312         return StorageOperationStatus.OK;
313     }
314
315     public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
316         Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstProperties();
317         return associateInstPropertiesToComponent(nodeTypeVertex, instProps);
318     }
319
320     public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
321         Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstInputs();
322         return associateInstInputsToComponent(nodeTypeVertex, instProps);
323     }
324
325     public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
326         Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups();
327         return associateInstGroupsToComponent(nodeTypeVertex, instGroups);
328     }
329
330
331     public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instProps) {
332         if (instProps != null && !instProps.isEmpty()) {
333             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps);
334             if (assosiateElementToData.isRight()) {
335                 return assosiateElementToData.right().value();
336             }
337         }
338         return StorageOperationStatus.OK;
339     }
340
341     public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
342         if (instInputs != null && !instInputs.isEmpty()) {
343             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs);
344             if (assosiateElementToData.isRight()) {
345                 return assosiateElementToData.right().value();
346             }
347         }
348         return StorageOperationStatus.OK;
349     }
350
351     public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, MapGroupsDataDefinition> instGroups) {
352         if (instGroups != null && !instGroups.isEmpty()) {
353             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups);
354             if (assosiateElementToData.isRight()) {
355                 return assosiateElementToData.right().value();
356             }
357         }
358         return StorageOperationStatus.OK;
359     }
360
361
362     public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
363
364         if (instInputs != null && !instInputs.isEmpty()) {
365             instInputs.entrySet().forEach(i -> {
366                 List<String> uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet());
367                 List<String> pathKeys = new ArrayList<>();
368                 pathKeys.add(i.getKey());
369
370                 StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME);
371                 if (status != StorageOperationStatus.OK) {
372                     return;
373                 }
374             });
375         }
376
377         return StorageOperationStatus.OK;
378     }
379
380     public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
381
382         if (instInputs != null && !instInputs.isEmpty()) {
383             instInputs.entrySet().forEach(i -> {
384                 StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey());
385                 if (status != StorageOperationStatus.OK) {
386                     return;
387                 }
388             });
389         }
390
391         return StorageOperationStatus.OK;
392     }
393
394     public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
395         return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
396     }
397
398     public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
399         return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS);
400     }
401
402     private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) {
403         if (instProps != null && !instProps.isEmpty()) {
404             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps);
405             if (assosiateElementToData.isRight()) {
406                 return assosiateElementToData.right().value();
407             }
408         }
409         return StorageOperationStatus.OK;
410     }
411
412     public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabilityDataDefinition> calcCapabilty, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
413         if (calcRequirements != null && !calcRequirements.isEmpty()) {
414             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements);
415             if (assosiateElementToData.isRight()) {
416                 return assosiateElementToData.right().value();
417             }
418             Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>();
419             assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled);
420             if (assosiateElementToData.isRight()) {
421                 return assosiateElementToData.right().value();
422             }
423         }
424         if (calcCapabilty != null && !calcCapabilty.isEmpty()) {
425             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES ,EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty);
426             if (assosiateElementToData.isRight()) {
427                 return assosiateElementToData.right().value();
428             }
429             Map<String, MapListCapabilityDataDefinition> fullFilled = new HashMap<>();
430             assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled);
431             if (assosiateElementToData.isRight()) {
432                 return assosiateElementToData.right().value();
433             }
434         }
435         if ( calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty() ){
436             return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
437                     EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties)
438                     .right()
439                     .on(v -> StorageOperationStatus.OK);
440         }
441         return StorageOperationStatus.OK;
442     }
443
444     private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap){
445         return titanDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson)
446                 .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap),
447                         status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap));
448     }
449     
450     private Either<GraphVertex, StorageOperationStatus> associateElementToDataIfNotFound(TitanOperationStatus status, GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, ? extends ToscaDataDefinition> dataMap) {
451         if(status == TitanOperationStatus.NOT_FOUND){
452             return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap);
453         }
454         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
455     }
456
457     private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> addElementsToComponent(GraphVertex nodeTypeVertex, GraphVertex dataVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap) {
458         Optional<StorageOperationStatus> error = dataMap.entrySet()
459                 .stream()
460                 .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e))
461                 .filter(s -> s != StorageOperationStatus.OK)
462                 .findFirst();
463         if(error.isPresent()){
464             return Either.right(error.get());
465         }
466         return Either.left(dataVertex);
467     }
468
469     private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
470         Map<String, MapPropertiesDataDefinition> instAttr = topologyTemplate.getInstAttributes();
471         return associateInstAttributeToComponent(nodeTypeVertex, instAttr);
472     }
473
474     public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map<String, ForwardingPathDataDefinition> forwardingPathMap) {
475         if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) {
476             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap);
477             if (assosiateElementToData.isRight()) {
478                 return assosiateElementToData.right().value();
479             }
480         }
481         return StorageOperationStatus.OK;
482     }
483
484     public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instAttr) {
485         if (instAttr != null && !instAttr.isEmpty()) {
486             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
487             if (assosiateElementToData.isRight()) {
488                 return assosiateElementToData.right().value();
489             }
490         }
491         return StorageOperationStatus.OK;
492     }
493
494     public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) {
495
496         if (groups != null && !groups.isEmpty()) {
497             groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
498                 String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
499                 p.setUniqueId(uid);
500             });
501             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
502             if (assosiateElementToData.isRight()) {
503                 return assosiateElementToData.right().value();
504             }
505         }
506         return StorageOperationStatus.OK;
507     }
508
509     private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
510         return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups());
511     }
512
513     public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
514         Map<String, PropertyDataDefinition> inputs = topologyTemplate.getInputs();
515         return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId());
516     }
517
518     public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) {
519         if (inputs != null && !inputs.isEmpty()) {
520             inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
521
522             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs);
523             if (assosiateElementToData.isRight()) {
524                 return assosiateElementToData.right().value();
525             }
526         }
527         return StorageOperationStatus.OK;
528     }
529
530     private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) {
531         nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
532         fillCommonMetadata(nodeTypeVertex, topologyTemplate);
533         if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) {
534             nodeTypeVertex.setJson(topologyTemplate.getCompositions());
535         }
536         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID));
537         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS));
538
539         return nodeTypeVertex;
540
541     }
542
543     private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
544         if (topologyTemplate.getResourceType() == null) {
545             // service
546             return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate);
547         } else {
548             // VF
549             return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate);
550         }
551     }
552
553     private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
554         String categoryName = topologyTemplate.getCategories().get(0).getName();
555         Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY);
556         if (category.isRight()) {
557             log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId());
558             return StorageOperationStatus.CATEGORY_NOT_FOUND;
559         }
560         GraphVertex categoryV = category.left().value();
561         TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
562         if (createEdge != TitanOperationStatus.OK) {
563             log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId());
564             return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
565         }
566         return StorageOperationStatus.OK;
567     }
568
569     @Override
570     public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
571         JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag();
572
573         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, parseFlag);
574         if (componentByLabelAndId.isRight()) {
575             return Either.right(componentByLabelAndId.right().value());
576         }
577         GraphVertex componentV = componentByLabelAndId.left().value();
578
579         return getToscaElement(componentV, componentParametersView);
580
581     }
582     // -------------------------------------------------------------
583
584     public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) {
585         TopologyTemplate toscaElement;
586
587         toscaElement = convertToTopologyTemplate(componentV);
588         TitanOperationStatus status;
589         if (!componentParametersView.isIgnoreUsers()) {
590             status = setCreatorFromGraph(componentV, toscaElement);
591             if (status != TitanOperationStatus.OK) {
592                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
593             }
594
595             status = setLastModifierFromGraph(componentV, toscaElement);
596             if (status != TitanOperationStatus.OK) {
597                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
598             }
599         }
600         if (!componentParametersView.isIgnoreCategories()) {
601             status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement);
602             if (status != TitanOperationStatus.OK) {
603                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
604
605             }
606         }
607         if (!componentParametersView.isIgnoreArtifacts()) {
608             TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement);
609             if (storageStatus != TitanOperationStatus.OK) {
610                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus));
611             }
612         }
613         if (!componentParametersView.isIgnoreComponentInstancesProperties()) {
614             status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement);
615             if (status != TitanOperationStatus.OK) {
616                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
617             }
618         }
619         if (!componentParametersView.isIgnoreCapabilities()) {
620             status = setCapabilitiesFromGraph(componentV, toscaElement);
621             if (status != TitanOperationStatus.OK) {
622                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
623             }
624         }
625         if (!componentParametersView.isIgnoreRequirements()) {
626             status = setRequirementsFromGraph(componentV, toscaElement);
627             if (status != TitanOperationStatus.OK) {
628                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
629             }
630         }
631         if (!componentParametersView.isIgnoreAllVersions()) {
632             status = setAllVersions(componentV, toscaElement);
633             if (status != TitanOperationStatus.OK) {
634                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
635             }
636         }
637         if (!componentParametersView.isIgnoreAdditionalInformation()) {
638             status = setAdditionalInformationFromGraph(componentV, toscaElement);
639             if (status != TitanOperationStatus.OK) {
640                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
641             }
642         }
643
644         if (!componentParametersView.isIgnoreGroups()) {
645             status = setGroupsFromGraph(componentV, toscaElement);
646             if (status != TitanOperationStatus.OK) {
647                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
648             }
649
650         }
651         if (!componentParametersView.isIgnorePolicies()) {
652             status = setPoliciesFromGraph(componentV, toscaElement);
653             if (status != TitanOperationStatus.OK) {
654                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
655             }
656
657         }
658         if (!componentParametersView.isIgnoreComponentInstances()) {
659             status = setInstGroupsFromGraph(componentV, toscaElement);
660
661             //Mark all CIs that has archived origins
662             archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV);
663
664             if (status != TitanOperationStatus.OK) {
665                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
666             }
667
668         }
669         if (!componentParametersView.isIgnoreInputs()) {
670             status = setInputsFromGraph(componentV, toscaElement);
671             if (status != TitanOperationStatus.OK) {
672                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
673             }
674
675         }
676         if (!componentParametersView.isIgnoreProperties()) {
677             status = setPropertiesFromGraph(componentV, toscaElement);
678             if (status != TitanOperationStatus.OK) {
679                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
680             }
681
682         }
683
684         if (!componentParametersView.isIgnoreComponentInstancesInputs()) {
685             status = setComponentInstancesInputsFromGraph(componentV, toscaElement);
686             if (status != TitanOperationStatus.OK) {
687                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
688
689             }
690         }
691
692         if (!componentParametersView.isIgnoreCapabiltyProperties()) {
693             status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement);
694             if (status != TitanOperationStatus.OK) {
695                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
696
697             }
698         }
699
700         if (!componentParametersView.isIgnoreForwardingPath()) {
701             status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement);
702             if (status != TitanOperationStatus.OK) {
703                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
704
705             }
706         }
707
708         if (!componentParametersView.isIgnoreNodeFilter()) {
709             status = setNodeFilterComponentFromGraph(componentV, toscaElement);
710             if (status != TitanOperationStatus.OK) {
711                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
712
713             }
714         }
715
716         if (!componentParametersView.isIgnoreInterfaces()) {
717             TitanOperationStatus storageStatus = setInterfcesFromGraph(componentV, toscaElement);
718             if (storageStatus != TitanOperationStatus.OK) {
719                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus));
720                 
721             }
722         }
723
724         return Either.left(toscaElement);
725     }
726
727     private TitanOperationStatus setInterfcesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
728       Either<Map<String, InterfaceDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE);
729       if (result.isLeft()) {
730         topologyTemplate.setInterfaces(result.left().value());
731       } else {
732         if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
733           return result.right().value();
734         }
735       }
736       return TitanOperationStatus.OK;
737     }
738
739     private StorageOperationStatus associateInterfacesToComponent(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
740       Map<String, InterfaceDataDefinition> interfaceMap = topologyTemplate.getInterfaces();
741       if (interfaceMap != null && !interfaceMap.isEmpty()) {
742         Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap);
743         if (assosiateElementToData.isRight()) {
744           return assosiateElementToData.right().value();
745         }
746       }
747       return StorageOperationStatus.OK;
748     }
749
750     private TitanOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
751         Either<Map<String, PolicyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES);
752         if (result.isLeft()) {
753             toscaElement.setPolicies(result.left().value());
754         } else {
755             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
756                 return result.right().value();
757             }
758         }
759         return TitanOperationStatus.OK;
760     }
761
762     public StorageOperationStatus associateNodeFiltersToComponent(GraphVertex nodeTypeVertex,
763             Map<String, CINodeFilterDataDefinition> filterMaps) {
764         if (filterMaps != null && !filterMaps.isEmpty()) {
765             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData
766                                                                                          (nodeTypeVertex, VertexTypeEnum.NODE_FILTER_TEMPLATE,
767                                                                                                  EdgeLabelEnum.NODE_FILTER_TEMPLATE, filterMaps);
768             if (assosiateElementToData.isRight()) {
769                 return assosiateElementToData.right().value();
770             }
771         }
772         return StorageOperationStatus.OK;
773     }
774
775     private TitanOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
776         Either<Map<String, ForwardingPathDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH);
777         if (result.isLeft()) {
778             topologyTemplate.setForwardingPaths(result.left().value());
779         } else {
780             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
781                 return result.right().value();
782             }
783         }
784         return TitanOperationStatus.OK;
785     }
786
787
788     private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
789         Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
790         if (result.isLeft()) {
791             topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value());
792         } else {
793             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
794                 return result.right().value();
795             }
796         }
797         return TitanOperationStatus.OK;
798     }
799
800     private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
801         Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES);
802         if (result.isLeft()) {
803             toscaElement.setProperties(result.left().value());
804         } else {
805             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
806                 return result.right().value();
807             }
808         }
809         return TitanOperationStatus.OK;
810     }
811
812     private TitanOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
813         Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS);
814         if (result.isLeft()) {
815             topologyTemplate.setInstGroups(result.left().value());
816         } else {
817             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
818                 return result.right().value();
819             }
820         }
821         return TitanOperationStatus.OK;
822     }
823
824     private TitanOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
825         Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES);
826         if (result.isLeft()) {
827             topologyTemplate.setInstProperties(result.left().value());
828         } else {
829             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
830                 return result.right().value();
831             }
832         }
833         return TitanOperationStatus.OK;
834     }
835
836     private TitanOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
837         Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS);
838         if (result.isLeft()) {
839             topologyTemplate.setInstInputs(result.left().value());
840         } else {
841             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
842                 return result.right().value();
843             }
844         }
845         return TitanOperationStatus.OK;
846     }
847
848     private TitanOperationStatus setNodeFilterComponentFromGraph(GraphVertex componentV,
849             TopologyTemplate topologyTemplate) {
850         Either<Map<String, CINodeFilterDataDefinition>, TitanOperationStatus> result =
851                 getDataFromGraph(componentV,
852                         EdgeLabelEnum.NODE_FILTER_TEMPLATE);
853         if (result.isLeft()) {
854             topologyTemplate.setNodeFilterComponents(result.left().value());
855         } else {
856             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
857                 return result.right().value();
858             }
859         }
860         return TitanOperationStatus.OK;
861     }
862
863     @Override
864     protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
865         Either<Map<String, MapListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
866         if (result.isLeft()) {
867             ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value());
868         } else {
869             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
870                 return result.right().value();
871             }
872         }
873         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
874         if (result.isLeft()) {
875             ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value());
876         } else {
877             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
878                 return result.right().value();
879             }
880         }
881         return TitanOperationStatus.OK;
882
883     }
884
885     protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
886         Either<Map<String, MapListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
887         if (result.isLeft()) {
888             ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value());
889         } else {
890             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
891                 return result.right().value();
892             }
893         }
894         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
895         if (result.isLeft()) {
896             ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value());
897         } else {
898             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
899                 return result.right().value();
900             }
901         }
902         return TitanOperationStatus.OK;
903     }
904
905     private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
906         TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement);
907         if (storageStatus != TitanOperationStatus.OK) {
908             return storageStatus;
909         }
910         Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
911         if (result.isLeft()) {
912             toscaElement.setServiceApiArtifacts(result.left().value());
913         } else {
914             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
915                 return result.right().value();
916             }
917         }
918         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
919         if (resultInstArt.isLeft()) {
920             toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value());
921         } else {
922             if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) {
923                 return resultInstArt.right().value();
924             }
925         }
926         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS);
927         if (instanceArt.isLeft()) {
928             toscaElement.setInstanceArtifacts(instanceArt.left().value());
929         } else {
930             if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) {
931                 return instanceArt.right().value();
932             }
933         }
934         return TitanOperationStatus.OK;
935     }
936
937     private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
938         Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS);
939         if (result.isLeft()) {
940             toscaElement.setInputs(result.left().value());
941         } else {
942             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
943                 return result.right().value();
944             }
945         }
946         return TitanOperationStatus.OK;
947     }
948
949     private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
950         Either<Map<String, GroupDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS);
951         if (result.isLeft()) {
952             toscaElement.setGroups(result.left().value());
953         } else {
954             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
955                 return result.right().value();
956             }
957         }
958         return TitanOperationStatus.OK;
959     }
960
961     private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
962         List<CategoryDefinition> categories = new ArrayList<>();
963
964         switch (componentV.getType()) {
965         case RESOURCE:
966             return setResourceCategoryFromGraph(componentV, toscaElement);
967         case SERVICE:
968             return setServiceCategoryFromGraph(componentV, toscaElement, categories);
969
970         default:
971             log.debug("Not supported component type {} ", componentV.getType());
972             break;
973         }
974         return TitanOperationStatus.OK;
975     }
976
977     private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) {
978         Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
979         if (childVertex.isRight()) {
980             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
981             return childVertex.right().value();
982         }
983         GraphVertex categoryV = childVertex.left().value();
984         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
985         CategoryDefinition category = new CategoryDefinition();
986         category.setUniqueId(categoryV.getUniqueId());
987         category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
988         category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
989
990         Type listTypeCat = new TypeToken<List<String>>() {}.getType();
991         List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
992         category.setIcons(iconsfromJsonCat);
993         categories.add(category);
994         toscaElement.setCategories(categories);
995
996         return TitanOperationStatus.OK;
997     }
998
999     @SuppressWarnings("unchecked")
1000     private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
1001
1002         TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
1003
1004         Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson();
1005         topologyTemplate.setCompositions(json);
1006
1007         return topologyTemplate;
1008     }
1009
1010     @Override
1011     public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
1012         Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView());
1013         if (nodeType.isRight()) {
1014             log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value());
1015             return nodeType;
1016         }
1017         TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex);
1018         if (status != TitanOperationStatus.OK) {
1019             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1020         }
1021         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES);
1022         if (status != TitanOperationStatus.OK) {
1023             log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
1024             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1025         }
1026         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES);
1027         if (status != TitanOperationStatus.OK) {
1028             log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1029             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1030         }
1031
1032         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1033         if (status != TitanOperationStatus.OK) {
1034             log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1035             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1036         }
1037
1038         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS);
1039         if (status != TitanOperationStatus.OK) {
1040             log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1041             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1042         }
1043         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS);
1044         if (status != TitanOperationStatus.OK) {
1045             log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1046             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1047         }
1048         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS);
1049         if (status != TitanOperationStatus.OK) {
1050             log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1051             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1052         }
1053         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1054         if (status != TitanOperationStatus.OK) {
1055             log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1056             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1057         }
1058         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES);
1059         if (status != TitanOperationStatus.OK) {
1060             log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status);
1061             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1062         }
1063         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
1064         if (status != TitanOperationStatus.OK) {
1065             log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
1066             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1067         }
1068         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1069         if (status != TitanOperationStatus.OK) {
1070             log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1071             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1072         }
1073         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
1074         if (status != TitanOperationStatus.OK) {
1075             log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1076             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1077         }
1078         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
1079         if (status != TitanOperationStatus.OK) {
1080             log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1081             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1082         }
1083         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
1084         if (status != TitanOperationStatus.OK) {
1085             log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1086             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1087         }
1088         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
1089         if (status != TitanOperationStatus.OK) {
1090             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1091             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1092         }
1093         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
1094         if (status != TitanOperationStatus.OK) {
1095             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1096             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1097         }
1098         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE);
1099         if (status != TitanOperationStatus.OK) {
1100             log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status);
1101             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1102         }
1103         titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS);
1104         if (status != TitanOperationStatus.OK) {
1105             log.debug("Failed to disassociate instance artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
1106             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1107         }
1108
1109         toscaElementVertex.getVertex().remove();
1110         log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
1111
1112         return nodeType;
1113     }
1114
1115     @SuppressWarnings("unchecked")
1116     @Override
1117     public Either<TopologyTemplate, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
1118         return createTopologyTemplate((TopologyTemplate) toscaElement);
1119     }
1120
1121     @Override
1122     protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
1123         return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement);
1124     }
1125
1126     @Override
1127     protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
1128         // Product isn't supported now!!
1129         // TODO add for Product
1130         if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) {
1131             return validateServiceCategory(toscaElementToUpdate, elementV);
1132         } else {
1133             // Resource
1134             return validateResourceCategory(toscaElementToUpdate, elementV);
1135         }
1136     }
1137
1138     @Override
1139     protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) {
1140         // not relevant now for topology template
1141         return StorageOperationStatus.OK;
1142     }
1143
1144     @Override
1145     public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
1146         fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag);
1147     }
1148
1149     private <T extends ToscaElement> StorageOperationStatus validateServiceCategory(T toscaElementToUpdate, GraphVertex elementV) {
1150         StorageOperationStatus status = StorageOperationStatus.OK;
1151         List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
1152         CategoryDefinition newCategory = newCategoryList.get(0);
1153
1154         Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1155         if (childVertex.isRight()) {
1156             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
1157             return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value());
1158         }
1159
1160         GraphVertex categoryV = childVertex.left().value();
1161         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
1162         String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1163
1164         String newCategoryName = newCategory.getName();
1165         if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
1166             // the category was changed
1167             Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY);
1168
1169             if (getCategoryVertex.isRight()) {
1170                 return getCategoryVertex.right().value();
1171             }
1172             GraphVertex newCategoryV = getCategoryVertex.left().value();
1173             status = moveCategoryEdge(elementV, newCategoryV);
1174             log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
1175         }
1176         return status;
1177     }
1178
1179     public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) {
1180
1181         Either<GraphVertex, StorageOperationStatus> result = null;
1182         String userId = user.getUserId();
1183         Either<GraphVertex, TitanOperationStatus> getRes = findUserVertex(userId);
1184         GraphVertex userVertex = null;
1185         GraphVertex serviceVertex = null;
1186         if (getRes.isRight()) {
1187             TitanOperationStatus status = getRes.right().value();
1188             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status);
1189             result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1190         }
1191         if (result == null) {
1192             userVertex = getRes.left().value();
1193             getRes = titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata);
1194             if (getRes.isRight()) {
1195                 TitanOperationStatus status = getRes.right().value();
1196                 log.debug( "Cannot find service {} in the graph. status is {}", uniqueId, status);
1197                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1198             }
1199         }
1200         if (result == null) {
1201             serviceVertex = getRes.left().value();
1202             Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name());
1203             if (edgeIterator.hasNext()) {
1204                 log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
1205                 edgeIterator.next().remove();
1206             }
1207         }
1208         if (result == null) {
1209             TitanOperationStatus status = titanDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null);
1210             if (status != TitanOperationStatus.OK) {
1211                 log.debug( "Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
1212                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1213             }
1214         }
1215         if (result == null) {
1216             serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name());
1217             long lastUpdateDate = System.currentTimeMillis();
1218             serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1219             Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(serviceVertex);
1220             if (updateRes.isRight()) {
1221                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1222             }
1223         }
1224         if (result == null) {
1225             result = Either.left(serviceVertex);
1226         }
1227         return result;
1228     }
1229     /**
1230      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
1231      * @param componentId
1232      * @param instanceId
1233      * @param capabilityName
1234      * @param capabilityType
1235      * @param ownerId
1236      * @return
1237      */
1238     public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
1239
1240         Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null;
1241         Map<String, MapCapabilityProperty> mapPropertiesDataDefinition = null;
1242         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse);
1243         if (componentByLabelAndId.isRight()) {
1244             result = Either.right(componentByLabelAndId.right().value());
1245         }
1246         if(componentByLabelAndId.isLeft()){
1247             Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1248             if (getDataRes.isRight()) {
1249                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getDataRes.right().value()));
1250             } else {
1251                 mapPropertiesDataDefinition = getDataRes.left().value();
1252             }
1253         }
1254         if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){
1255             result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
1256         }
1257         return result;
1258     }
1259
1260     public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) {
1261         return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId);
1262     }
1263
1264
1265     private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> mapPropertiesDataDefinition) {
1266         return  MapUtils.isNotEmpty(mapPropertiesDataDefinition) &&
1267                 mapPropertiesDataDefinition.get(instanceId) != null &&
1268                 MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
1269     }
1270
1271     private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) {
1272         List<ComponentInstanceProperty> capPropsList = null;
1273         for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){
1274             if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) {
1275                 Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition();
1276                 if (capMap != null && !capMap.isEmpty()) {
1277                     capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList());
1278                     break;
1279                 }
1280             }
1281         }
1282         if(capPropsList == null){
1283             capPropsList = new ArrayList<>();
1284         }
1285         return capPropsList;
1286     }
1287
1288     private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) {
1289         if (capProp != null) {
1290             String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM );
1291             if (path.length < 4) {
1292                 log.debug("wrong key format for capabilty, key {}", capProp);
1293                 return false;
1294             }
1295             return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId);
1296         }
1297         return false;
1298     }
1299
1300     public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1301         fillPolicyDefinition(componentV, policyDefinition, counter);
1302         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
1303     }
1304
1305     public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List<PolicyDefinition> policies) {
1306         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, JsonPresentationFields.UNIQUE_ID);
1307     }
1308
1309     public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) {
1310         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
1311     }
1312
1313     public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) {
1314         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID);
1315     }
1316
1317     public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) {
1318         return  deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
1319     }
1320
1321         public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) {
1322                 return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME);
1323         }
1324
1325         private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1326                 String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter);
1327                 policyDefinition.setName(policyName);
1328                 policyDefinition.setInvariantName(policyName);
1329                 policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME));
1330                 policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName));
1331                 policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1332                 policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID());
1333         }
1334         
1335         public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) {
1336         String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName);
1337                 String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length());
1338                 return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter;
1339         }
1340
1341     void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1342         if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){
1343             GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
1344                     .left()
1345                     .on(this::throwStorageException);
1346             if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){
1347                 toscaElement.getComponentInstances().values().forEach(i -> revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId()));
1348             }
1349             if(MapUtils.isNotEmpty(toscaElement.getGroups())){
1350                 toscaElement.getGroups().values().forEach(g -> revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId()));
1351             }
1352             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,  toscaElement.getCalculatedCapabilities());
1353             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,  toscaElement.getCalculatedRequirements());
1354             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,  toscaElement.getCalculatedCapabilitiesProperties());
1355         }
1356     }
1357
1358     public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1359         if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){
1360             GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
1361                     .left()
1362                     .on(this::throwStorageException);
1363             if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){
1364                 toscaElement.getComponentInstances().values().forEach(i -> updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName()));
1365             }
1366             if(MapUtils.isNotEmpty(toscaElement.getGroups())){
1367                 toscaElement.getGroups().values().forEach(g -> updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName()));
1368             }
1369             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,  toscaElement.getCalculatedCapabilities());
1370             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,  toscaElement.getCalculatedRequirements());
1371             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,  toscaElement.getCalculatedCapabilitiesProperties());
1372         }
1373     }
1374
1375     private void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName) {
1376         updateCalculatedCapabilitiesNames(toscaElement, ownerId, ownerName);
1377         updateCalculatedRequirementsNames(toscaElement, ownerId, ownerName);
1378         updateCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId);
1379     }
1380
1381     private void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) {
1382         if(toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().containsKey(ownerId)){
1383             MapCapabilityProperty newProps =  new MapCapabilityProperty();
1384             toscaElement.getCalculatedCapabilitiesProperties().get(ownerId)
1385                     .getMapToscaDataDefinition()
1386                     .forEach((k, v)-> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
1387             if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
1388                 toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps);
1389             }
1390         }
1391     }
1392
1393     private void updateCalculatedRequirementsNames(TopologyTemplate toscaElement, String ownerId, String ownerName) {
1394         if(toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().containsKey(ownerId)){
1395             String prefix = ownerName + ".";
1396             toscaElement.getCalculatedRequirements().get(ownerId)
1397                 .getMapToscaDataDefinition().values().stream()
1398                 .flatMap(l -> l.getListToscaDataDefinition().stream())
1399                 .forEach(r -> {
1400                     if(ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
1401                         if(StringUtils.isNotEmpty(r.getPreviousName())){
1402                             r.setParentName(r.getPreviousName());
1403                         }
1404                         r.setPreviousName(r.getName());
1405                     }
1406                     r.setName(prefix + r.getPreviousName());
1407                 });
1408         }
1409     }
1410
1411     private void updateCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId, String ownerName) {
1412         if(toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().containsKey(ownerId)){
1413             String prefix = ownerName + ".";
1414             toscaElement.getCalculatedCapabilities().get(ownerId)
1415                 .getMapToscaDataDefinition().values().stream()
1416                 .flatMap(l -> l.getListToscaDataDefinition().stream())
1417                 .forEach(c -> {
1418                     if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) {
1419                         if(StringUtils.isNotEmpty(c.getPreviousName())){
1420                             c.setParentName(c.getPreviousName());
1421                         }
1422                         c.setPreviousName(c.getName());
1423                     }
1424                     c.setName(prefix + c.getPreviousName());
1425                 });
1426         }
1427     }
1428
1429     private void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) {
1430         String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM);
1431         String capType = key[key.length - 2];
1432         String capName = key[key.length - 1];
1433         Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType)
1434                 .getListToscaDataDefinition().stream()
1435                 .filter(c -> c.getPreviousName().equals(capName))
1436                 .findFirst();
1437         if(foundCapOpt.isPresent()){
1438             key[key.length - 1] = foundCapOpt.get().getName();
1439             newProps.put(buildCaLCapPropKey(key),properties);
1440         }
1441     }
1442
1443     private void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId) {
1444         revertCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId);
1445         revertCalculatedCapabilitiesNames(toscaElement, ownerId);
1446         revertCalculatedRequirementsNames(toscaElement, ownerId);
1447     }
1448
1449     private void revertCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) {
1450         if(toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().containsKey(ownerId)){
1451             MapCapabilityProperty newProps =  new MapCapabilityProperty();
1452             toscaElement.getCalculatedCapabilitiesProperties().get(ownerId)
1453                     .getMapToscaDataDefinition()
1454                     .forEach((k,v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
1455             if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
1456                 toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps);
1457             }
1458         }
1459     }
1460
1461     private void revertCalculatedRequirementsNames(TopologyTemplate toscaElement, String ownerId) {
1462         if(toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().containsKey(ownerId)){
1463             toscaElement.getCalculatedRequirements().get(ownerId)
1464                     .getMapToscaDataDefinition().values().stream()
1465                     .flatMap(l -> l.getListToscaDataDefinition().stream())
1466                     .forEach(r -> {r.setName(r.getPreviousName());r.setPreviousName(r.getParentName());});
1467         }
1468     }
1469
1470     private void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) {
1471         if(toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().containsKey(ownerId)){
1472             toscaElement.getCalculatedCapabilities().get(ownerId)
1473                     .getMapToscaDataDefinition().values().stream()
1474                     .flatMap(l -> l.getListToscaDataDefinition().stream())
1475                     .forEach(c -> {c.setName(c.getPreviousName());c.setPreviousName(c.getParentName());});
1476         }
1477     }
1478
1479     private void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) {
1480         String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM);
1481         String capType = key[key.length - 2];
1482         String capName = key[key.length - 1];
1483         Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType)
1484                 .getListToscaDataDefinition().stream()
1485                 .filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName()))
1486                 .findFirst();
1487         if(foundCapOpt.isPresent()){
1488             key[key.length - 1] = foundCapOpt.get().getPreviousName();
1489         }
1490         newProps.put(buildCaLCapPropKey(key), properties);
1491     }
1492
1493     private String buildCaLCapPropKey(String[] keyArray) {
1494         StringBuilder key = new StringBuilder();
1495         for(int i = 0; i< keyArray.length; ++i){
1496             key.append(keyArray[i]);
1497             if(i < keyArray.length - 1){
1498                 key.append(ModelConverter.CAP_PROP_DELIM);
1499             }
1500         }
1501         return key.toString();
1502     }
1503
1504     private GraphVertex throwStorageException(TitanOperationStatus status) {
1505         throw new StorageException(status);
1506     }
1507
1508 }