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