Revert "Interface operation feature enhancements"
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / jsontitan / operations / TopologyTemplateOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
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 = associateInterfacesToComponent(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 associateInterfacesToComponent(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
726       Map<String, InterfaceDataDefinition> interfaceMap = topologyTemplate.getInterfaces();
727       if (interfaceMap != null && !interfaceMap.isEmpty()) {
728         Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap);
729         if (assosiateElementToData.isRight()) {
730           return assosiateElementToData.right().value();
731         }
732         else {
733           Map<String, OperationDataDefinition> operationMap = interfaceMap.values().stream().filter(op -> MapUtils.isNotEmpty(op.getOperations())).flatMap(a -> a.getOperations().entrySet().stream()).collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
734           if(MapUtils.isNotEmpty(operationMap)) {
735             Either<GraphVertex, StorageOperationStatus> assosiateOpToInterface = associateElementToData(assosiateElementToData.left().value(), VertexTypeEnum.INTERFACE_OPERATION, EdgeLabelEnum.INTERFACE_OPERATION, operationMap);
736             if (assosiateOpToInterface.isRight()) {
737               return assosiateOpToInterface.right().value();
738             }
739           }
740         }
741       }
742       return StorageOperationStatus.OK;
743     }
744
745     private TitanOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
746         Either<Map<String, PolicyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES);
747         if (result.isLeft()) {
748             toscaElement.setPolicies(result.left().value());
749         } else {
750             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
751                 return result.right().value();
752             }
753         }
754         return TitanOperationStatus.OK;
755     }
756
757     private TitanOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
758         Either<Map<String, ForwardingPathDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH);
759         if (result.isLeft()) {
760             topologyTemplate.setForwardingPaths(result.left().value());
761         } else {
762             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
763                 return result.right().value();
764             }
765         }
766         return TitanOperationStatus.OK;
767     }
768
769
770     private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
771         Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
772         if (result.isLeft()) {
773             topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value());
774         } else {
775             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
776                 return result.right().value();
777             }
778         }
779         return TitanOperationStatus.OK;
780     }
781
782     private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
783         Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES);
784         if (result.isLeft()) {
785             toscaElement.setProperties(result.left().value());
786         } else {
787             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
788                 return result.right().value();
789             }
790         }
791         return TitanOperationStatus.OK;
792     }
793
794     private TitanOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
795         Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS);
796         if (result.isLeft()) {
797             topologyTemplate.setInstGroups(result.left().value());
798         } else {
799             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
800                 return result.right().value();
801             }
802         }
803         return TitanOperationStatus.OK;
804     }
805
806     private TitanOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
807         Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES);
808         if (result.isLeft()) {
809             topologyTemplate.setInstProperties(result.left().value());
810         } else {
811             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
812                 return result.right().value();
813             }
814         }
815         return TitanOperationStatus.OK;
816     }
817
818     private TitanOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
819         Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS);
820         if (result.isLeft()) {
821             topologyTemplate.setInstInputs(result.left().value());
822         } else {
823             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
824                 return result.right().value();
825             }
826         }
827         return TitanOperationStatus.OK;
828     }
829
830     @Override
831     protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
832         Either<Map<String, MapListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
833         if (result.isLeft()) {
834             ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value());
835         } else {
836             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
837                 return result.right().value();
838             }
839         }
840         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
841         if (result.isLeft()) {
842             ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value());
843         } else {
844             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
845                 return result.right().value();
846             }
847         }
848         return TitanOperationStatus.OK;
849
850     }
851
852     protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
853         Either<Map<String, MapListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
854         if (result.isLeft()) {
855             ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value());
856         } else {
857             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
858                 return result.right().value();
859             }
860         }
861         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
862         if (result.isLeft()) {
863             ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value());
864         } else {
865             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
866                 return result.right().value();
867             }
868         }
869         return TitanOperationStatus.OK;
870     }
871
872     private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
873         TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement);
874         if (storageStatus != TitanOperationStatus.OK) {
875             return storageStatus;
876         }
877         Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
878         if (result.isLeft()) {
879             toscaElement.setServiceApiArtifacts(result.left().value());
880         } else {
881             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
882                 return result.right().value();
883             }
884         }
885         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
886         if (resultInstArt.isLeft()) {
887             toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value());
888         } else {
889             if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) {
890                 return resultInstArt.right().value();
891             }
892         }
893         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS);
894         if (instanceArt.isLeft()) {
895             toscaElement.setInstanceArtifacts(instanceArt.left().value());
896         } else {
897             if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) {
898                 return instanceArt.right().value();
899             }
900         }
901         return TitanOperationStatus.OK;
902     }
903
904     private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
905         Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS);
906         if (result.isLeft()) {
907             toscaElement.setInputs(result.left().value());
908         } else {
909             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
910                 return result.right().value();
911             }
912         }
913         return TitanOperationStatus.OK;
914     }
915
916     private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
917         Either<Map<String, GroupDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS);
918         if (result.isLeft()) {
919             toscaElement.setGroups(result.left().value());
920         } else {
921             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
922                 return result.right().value();
923             }
924         }
925         return TitanOperationStatus.OK;
926     }
927
928     private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
929         List<CategoryDefinition> categories = new ArrayList<>();
930
931         switch (componentV.getType()) {
932         case RESOURCE:
933             return setResourceCategoryFromGraph(componentV, toscaElement);
934         case SERVICE:
935             return setServiceCategoryFromGraph(componentV, toscaElement, categories);
936
937         default:
938             log.debug("Not supported component type {} ", componentV.getType());
939             break;
940         }
941         return TitanOperationStatus.OK;
942     }
943
944     private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) {
945         Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
946         if (childVertex.isRight()) {
947             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
948             return childVertex.right().value();
949         }
950         GraphVertex categoryV = childVertex.left().value();
951         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
952         CategoryDefinition category = new CategoryDefinition();
953         category.setUniqueId(categoryV.getUniqueId());
954         category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
955         category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
956
957         Type listTypeCat = new TypeToken<List<String>>() {}.getType();
958         List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
959         category.setIcons(iconsfromJsonCat);
960         categories.add(category);
961         toscaElement.setCategories(categories);
962
963         return TitanOperationStatus.OK;
964     }
965
966     @SuppressWarnings("unchecked")
967     private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
968
969         TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
970
971         Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson();
972         topologyTemplate.setCompositions(json);
973
974         return topologyTemplate;
975     }
976
977     @Override
978     public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
979         Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView());
980         if (nodeType.isRight()) {
981             log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value());
982             return nodeType;
983         }
984         TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex);
985         if (status != TitanOperationStatus.OK) {
986             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
987         }
988         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES);
989         if (status != TitanOperationStatus.OK) {
990             log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
991             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
992         }
993         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES);
994         if (status != TitanOperationStatus.OK) {
995             log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status);
996             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
997         }
998
999         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1000         if (status != TitanOperationStatus.OK) {
1001             log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1002             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1003         }
1004
1005         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS);
1006         if (status != TitanOperationStatus.OK) {
1007             log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1008             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1009         }
1010         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS);
1011         if (status != TitanOperationStatus.OK) {
1012             log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1013             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1014         }
1015         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS);
1016         if (status != TitanOperationStatus.OK) {
1017             log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1018             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1019         }
1020         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1021         if (status != TitanOperationStatus.OK) {
1022             log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1023             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1024         }
1025         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES);
1026         if (status != TitanOperationStatus.OK) {
1027             log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status);
1028             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1029         }
1030         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
1031         if (status != TitanOperationStatus.OK) {
1032             log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
1033             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1034         }
1035         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1036         if (status != TitanOperationStatus.OK) {
1037             log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1038             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1039         }
1040         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
1041         if (status != TitanOperationStatus.OK) {
1042             log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1043             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1044         }
1045         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
1046         if (status != TitanOperationStatus.OK) {
1047             log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1048             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1049         }
1050         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
1051         if (status != TitanOperationStatus.OK) {
1052             log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1053             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1054         }
1055         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
1056         if (status != TitanOperationStatus.OK) {
1057             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1058             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1059         }
1060         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
1061         if (status != TitanOperationStatus.OK) {
1062             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1063             Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1064         }
1065
1066         Either<GraphVertex, TitanOperationStatus> getInterfaceVertex = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INTERFACE, JsonParseFlagEnum.NoParse);
1067         if (getInterfaceVertex.isLeft()) {
1068             status = titanDao.disassociateAndDeleteLast(getInterfaceVertex.left().value(), Direction.OUT, EdgeLabelEnum.INTERFACE_OPERATION);
1069             if (status != TitanOperationStatus.OK) {
1070                 log.debug("Failed to disassociate interface operations for {} error {}", getInterfaceVertex.left().value().getUniqueId(), status);
1071                 Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1072             }
1073             else {
1074                 status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE);
1075                 if (status != TitanOperationStatus.OK) {
1076                     log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status);
1077                     Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1078                 }
1079             }
1080
1081         }
1082
1083         titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS);
1084         toscaElementVertex.getVertex().remove();
1085         log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
1086
1087         return nodeType;
1088     }
1089
1090     @SuppressWarnings("unchecked")
1091     @Override
1092     public Either<TopologyTemplate, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
1093         return createTopologyTemplate((TopologyTemplate) toscaElement);
1094     }
1095
1096     @Override
1097     protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
1098         return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement);
1099     }
1100
1101     @Override
1102     protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
1103         // Product isn't supported now!!
1104         // TODO add for Product
1105         if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) {
1106             return validateServiceCategory(toscaElementToUpdate, elementV);
1107         } else {
1108             // Resource
1109             return validateResourceCategory(toscaElementToUpdate, elementV);
1110         }
1111     }
1112
1113     @Override
1114     protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) {
1115         // not relevant now for topology template
1116         return StorageOperationStatus.OK;
1117     }
1118
1119     @Override
1120     public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
1121         fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag);
1122     }
1123
1124     private <T extends ToscaElement> StorageOperationStatus validateServiceCategory(T toscaElementToUpdate, GraphVertex elementV) {
1125         StorageOperationStatus status = StorageOperationStatus.OK;
1126         List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
1127         CategoryDefinition newCategory = newCategoryList.get(0);
1128
1129         Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1130         if (childVertex.isRight()) {
1131             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
1132             return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value());
1133         }
1134
1135         GraphVertex categoryV = childVertex.left().value();
1136         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
1137         String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1138
1139         String newCategoryName = newCategory.getName();
1140         if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
1141             // the category was changed
1142             Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY);
1143
1144             if (getCategoryVertex.isRight()) {
1145                 return getCategoryVertex.right().value();
1146             }
1147             GraphVertex newCategoryV = getCategoryVertex.left().value();
1148             status = moveCategoryEdge(elementV, newCategoryV);
1149             log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
1150         }
1151         return status;
1152     }
1153
1154     public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) {
1155
1156         Either<GraphVertex, StorageOperationStatus> result = null;
1157         String userId = user.getUserId();
1158         Either<GraphVertex, TitanOperationStatus> getRes = findUserVertex(userId);
1159         GraphVertex userVertex = null;
1160         GraphVertex serviceVertex = null;
1161         if (getRes.isRight()) {
1162             TitanOperationStatus status = getRes.right().value();
1163             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status);
1164             result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1165         }
1166         if (result == null) {
1167             userVertex = getRes.left().value();
1168             getRes = titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata);
1169             if (getRes.isRight()) {
1170                 TitanOperationStatus status = getRes.right().value();
1171                 log.debug( "Cannot find service {} in the graph. status is {}", uniqueId, status);
1172                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1173             }
1174         }
1175         if (result == null) {
1176             serviceVertex = getRes.left().value();
1177             Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name());
1178             if (edgeIterator.hasNext()) {
1179                 log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
1180                 edgeIterator.next().remove();
1181             }
1182         }
1183         if (result == null) {
1184             TitanOperationStatus status = titanDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null);
1185             if (status != TitanOperationStatus.OK) {
1186                 log.debug( "Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
1187                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1188             }
1189         }
1190         if (result == null) {
1191             serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name());
1192             long lastUpdateDate = System.currentTimeMillis();
1193             serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1194             Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(serviceVertex);
1195             if (updateRes.isRight()) {
1196                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1197             }
1198         }
1199         if (result == null) {
1200             result = Either.left(serviceVertex);
1201         }
1202         return result;
1203     }
1204     /**
1205      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
1206      * @param componentId
1207      * @param instanceId
1208      * @param capabilityName
1209      * @param capabilityType
1210      * @param ownerId
1211      * @return
1212      */
1213     public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
1214
1215         Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null;
1216         Map<String, MapCapabilityProperty> mapPropertiesDataDefinition = null;
1217         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse);
1218         if (componentByLabelAndId.isRight()) {
1219             result = Either.right(componentByLabelAndId.right().value());
1220         }
1221         if(componentByLabelAndId.isLeft()){
1222             Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1223             if (getDataRes.isRight()) {
1224                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getDataRes.right().value()));
1225             } else {
1226                 mapPropertiesDataDefinition = getDataRes.left().value();
1227             }
1228         }
1229         if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){
1230             result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
1231         }
1232         return result;
1233     }
1234
1235     public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) {
1236         return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId);
1237     }
1238
1239
1240     private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> mapPropertiesDataDefinition) {
1241         return  MapUtils.isNotEmpty(mapPropertiesDataDefinition) &&
1242                 mapPropertiesDataDefinition.get(instanceId) != null &&
1243                 MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
1244     }
1245
1246     private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) {
1247         List<ComponentInstanceProperty> capPropsList = null;
1248         for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){
1249             if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) {
1250                 Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition();
1251                 if (capMap != null && !capMap.isEmpty()) {
1252                     capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList());
1253                     break;
1254                 }
1255             }
1256         }
1257         if(capPropsList == null){
1258             capPropsList = new ArrayList<>();
1259         }
1260         return capPropsList;
1261     }
1262
1263     private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) {
1264         if (capProp != null) {
1265             String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM );
1266             if (path.length < 4) {
1267                 log.debug("wrong key format for capabilty, key {}", capProp);
1268                 return false;
1269             }
1270             return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId);
1271         }
1272         return false;
1273     }
1274
1275     public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1276         fillPolicyDefinition(componentV, policyDefinition, counter);
1277         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
1278     }
1279
1280     public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List<PolicyDefinition> policies) {
1281         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, JsonPresentationFields.UNIQUE_ID);
1282     }
1283
1284     public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) {
1285         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
1286     }
1287
1288     public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) {
1289         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID);
1290     }
1291
1292     public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) {
1293         return  deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
1294     }
1295
1296         public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) {
1297                 return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME);
1298         }
1299
1300         private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1301                 String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter);
1302                 policyDefinition.setName(policyName);
1303                 policyDefinition.setInvariantName(policyName);
1304                 policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME));
1305                 policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName));
1306                 policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1307                 policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID());
1308         }
1309         
1310         public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) {
1311         String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName);
1312                 String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length());
1313                 return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter;
1314         }
1315
1316     void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1317         if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){
1318             GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
1319                     .left()
1320                     .on(this::throwStorageException);
1321             if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){
1322                 toscaElement.getComponentInstances().values().forEach(i -> revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId()));
1323             }
1324             if(MapUtils.isNotEmpty(toscaElement.getGroups())){
1325                 toscaElement.getGroups().values().forEach(g -> revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId()));
1326             }
1327             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,  toscaElement.getCalculatedCapabilities());
1328             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,  toscaElement.getCalculatedRequirements());
1329             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,  toscaElement.getCalculatedCapabilitiesProperties());
1330         }
1331     }
1332
1333     public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1334         if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){
1335             GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
1336                     .left()
1337                     .on(this::throwStorageException);
1338             if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){
1339                 toscaElement.getComponentInstances().values().forEach(i -> updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName()));
1340             }
1341             if(MapUtils.isNotEmpty(toscaElement.getGroups())){
1342                 toscaElement.getGroups().values().forEach(g -> updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName()));
1343             }
1344             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,  toscaElement.getCalculatedCapabilities());
1345             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,  toscaElement.getCalculatedRequirements());
1346             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,  toscaElement.getCalculatedCapabilitiesProperties());
1347         }
1348     }
1349
1350     private void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName) {
1351         updateCalculatedCapabilitiesNames(toscaElement, ownerId, ownerName);
1352         updateCalculatedRequirementsNames(toscaElement, ownerId, ownerName);
1353         updateCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId);
1354     }
1355
1356     private void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) {
1357         if(toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().containsKey(ownerId)){
1358             MapCapabilityProperty newProps =  new MapCapabilityProperty();
1359             toscaElement.getCalculatedCapabilitiesProperties().get(ownerId)
1360                     .getMapToscaDataDefinition()
1361                     .forEach((k, v)-> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
1362             if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
1363                 toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps);
1364             }
1365         }
1366     }
1367
1368     private void updateCalculatedRequirementsNames(TopologyTemplate toscaElement, String ownerId, String ownerName) {
1369         if(toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().containsKey(ownerId)){
1370             String prefix = ownerName + ".";
1371             toscaElement.getCalculatedRequirements().get(ownerId)
1372                 .getMapToscaDataDefinition().values().stream()
1373                 .flatMap(l -> l.getListToscaDataDefinition().stream())
1374                 .forEach(r -> {
1375                     if(ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
1376                         if(StringUtils.isNotEmpty(r.getPreviousName())){
1377                             r.setParentName(r.getPreviousName());
1378                         }
1379                         r.setPreviousName(r.getName());
1380                     }
1381                     r.setName(prefix + r.getPreviousName());
1382                 });
1383         }
1384     }
1385
1386     private void updateCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId, String ownerName) {
1387         if(toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().containsKey(ownerId)){
1388             String prefix = ownerName + ".";
1389             toscaElement.getCalculatedCapabilities().get(ownerId)
1390                 .getMapToscaDataDefinition().values().stream()
1391                 .flatMap(l -> l.getListToscaDataDefinition().stream())
1392                 .forEach(c -> {
1393                     if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) {
1394                         if(StringUtils.isNotEmpty(c.getPreviousName())){
1395                             c.setParentName(c.getPreviousName());
1396                         }
1397                         c.setPreviousName(c.getName());
1398                     }
1399                     c.setName(prefix + c.getPreviousName());
1400                 });
1401         }
1402     }
1403
1404     private void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) {
1405         String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM);
1406         String capType = key[key.length - 2];
1407         String capName = key[key.length - 1];
1408         Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType)
1409                 .getListToscaDataDefinition().stream()
1410                 .filter(c -> c.getPreviousName().equals(capName))
1411                 .findFirst();
1412         if(foundCapOpt.isPresent()){
1413             key[key.length - 1] = foundCapOpt.get().getName();
1414             newProps.put(buildCaLCapPropKey(key),properties);
1415         }
1416     }
1417
1418     private void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId) {
1419         revertCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId);
1420         revertCalculatedCapabilitiesNames(toscaElement, ownerId);
1421         revertCalculatedRequirementsNames(toscaElement, ownerId);
1422     }
1423
1424     private void revertCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) {
1425         if(toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().containsKey(ownerId)){
1426             MapCapabilityProperty newProps =  new MapCapabilityProperty();
1427             toscaElement.getCalculatedCapabilitiesProperties().get(ownerId)
1428                     .getMapToscaDataDefinition()
1429                     .forEach((k,v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
1430             if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
1431                 toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps);
1432             }
1433         }
1434     }
1435
1436     private void revertCalculatedRequirementsNames(TopologyTemplate toscaElement, String ownerId) {
1437         if(toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().containsKey(ownerId)){
1438             toscaElement.getCalculatedRequirements().get(ownerId)
1439                     .getMapToscaDataDefinition().values().stream()
1440                     .flatMap(l -> l.getListToscaDataDefinition().stream())
1441                     .forEach(r -> {r.setName(r.getPreviousName());r.setPreviousName(r.getParentName());});
1442         }
1443     }
1444
1445     private void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) {
1446         if(toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().containsKey(ownerId)){
1447             toscaElement.getCalculatedCapabilities().get(ownerId)
1448                     .getMapToscaDataDefinition().values().stream()
1449                     .flatMap(l -> l.getListToscaDataDefinition().stream())
1450                     .forEach(c -> {c.setName(c.getPreviousName());c.setPreviousName(c.getParentName());});
1451         }
1452     }
1453
1454     private void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) {
1455         String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM);
1456         String capType = key[key.length - 2];
1457         String capName = key[key.length - 1];
1458         Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType)
1459                 .getListToscaDataDefinition().stream()
1460                 .filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName()))
1461                 .findFirst();
1462         if(foundCapOpt.isPresent()){
1463             key[key.length - 1] = foundCapOpt.get().getPreviousName();
1464         }
1465         newProps.put(buildCaLCapPropKey(key), properties);
1466     }
1467
1468     private String buildCaLCapPropKey(String[] keyArray) {
1469         StringBuilder key = new StringBuilder();
1470         for(int i = 0; i< keyArray.length; ++i){
1471             key.append(keyArray[i]);
1472             if(i < keyArray.length - 1){
1473                 key.append(ModelConverter.CAP_PROP_DELIM);
1474             }
1475         }
1476         return key.toString();
1477     }
1478
1479     private GraphVertex throwStorageException(TitanOperationStatus status) {
1480         throw new StorageException(status);
1481     }
1482
1483 }