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