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