fab64988d4c4e655cae1da4f0be2d3bc46a38459
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.model.jsontitan.operations;
22
23 import com.google.gson.reflect.TypeToken;
24 import fj.data.Either;
25 import org.apache.commons.collections.MapUtils;
26 import org.apache.tinkerpop.gremlin.structure.Direction;
27 import org.apache.tinkerpop.gremlin.structure.Edge;
28 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
29 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
30 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
31 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
32 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
33 import org.openecomp.sdc.be.datatypes.elements.*;
34 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
35 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
36 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
37 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
38 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
39 import org.openecomp.sdc.be.model.*;
40 import org.openecomp.sdc.be.model.category.CategoryDefinition;
41 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
42 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
43 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
44 import org.openecomp.sdc.be.model.jsontitan.utils.CapabilityRequirementNameResolver;
45 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
46 import org.openecomp.sdc.be.model.operations.StorageException;
47 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
48 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
49 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
50 import org.openecomp.sdc.common.api.Constants;
51 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
52 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
53 import org.openecomp.sdc.common.log.wrappers.Logger;
54 import org.openecomp.sdc.common.util.ValidationUtils;
55 import org.springframework.beans.factory.annotation.Autowired;
56
57 import java.lang.reflect.Type;
58 import java.util.*;
59 import java.util.Map.Entry;
60 import java.util.stream.Collectors;
61
62 @org.springframework.stereotype.Component("topology-template-operation")
63 public class TopologyTemplateOperation extends ToscaElementOperation {
64
65     private static final Logger log = Logger.getLogger(TopologyTemplateOperation.class);
66     private Set<OriginTypeEnum> nodeTypeSet = new HashSet<>(Arrays.asList(OriginTypeEnum.VFC, OriginTypeEnum.CP, OriginTypeEnum.VL, OriginTypeEnum.Configuration, OriginTypeEnum.VFCMT));
67
68     @Autowired
69     private ArchiveOperation archiveOperation;
70
71     public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) {
72         Either<TopologyTemplate, StorageOperationStatus> result = null;
73
74         topologyTemplate.generateUUID();
75
76         topologyTemplate = getResourceMetaDataFromResource(topologyTemplate);
77         String resourceUniqueId = topologyTemplate.getUniqueId();
78         if (resourceUniqueId == null) {
79             resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
80             topologyTemplate.setUniqueId(resourceUniqueId);
81         }
82
83         GraphVertex topologyTemplateVertex = new GraphVertex();
84         topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll);
85
86         Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(topologyTemplateVertex);
87         if (createdVertex.isRight()) {
88             TitanOperationStatus status = createdVertex.right().value();
89             log.debug("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status);
90             result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
91             return result;
92         }
93
94         topologyTemplateVertex = createdVertex.left().value();
95
96         StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null);
97         if (assosiateCommon != StorageOperationStatus.OK) {
98             result = Either.right(assosiateCommon);
99             return result;
100         }
101
102         StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate);
103         if (associateCategory != StorageOperationStatus.OK) {
104             result = Either.right(associateCategory);
105             return result;
106         }
107
108         StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate);
109         if (associateInputs != StorageOperationStatus.OK) {
110             result = Either.right(associateInputs);
111             return result;
112         }
113         StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate);
114         if (associateGroups != StorageOperationStatus.OK) {
115             result = Either.right(associateGroups);
116             return result;
117         }
118         StorageOperationStatus associatePolicies = associatePoliciesToComponent(topologyTemplateVertex, topologyTemplate);
119         if (associatePolicies != StorageOperationStatus.OK) {
120             result = Either.right(associatePolicies);
121             return result;
122         }
123         StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate);
124         if (associateInstAttr != StorageOperationStatus.OK) {
125             result = Either.right(associateInstAttr);
126             return result;
127         }
128         StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate);
129         if (associateInstProperties != StorageOperationStatus.OK) {
130             result = Either.right(associateInstProperties);
131             return result;
132         }
133         StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate);
134         if (associateInstProperties != StorageOperationStatus.OK) {
135             result = Either.right(associateInstInputs);
136             return result;
137         }
138         StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate);
139         if (associateInstGroups != StorageOperationStatus.OK) {
140             result = Either.right(associateInstInputs);
141             return result;
142         }
143
144         StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate);
145         if (associateRequirements != StorageOperationStatus.OK) {
146             result = Either.right(associateRequirements);
147             return result;
148         }
149
150         StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate);
151         if (associateCapabilities != StorageOperationStatus.OK) {
152             result = Either.right(associateCapabilities);
153             return result;
154         }
155
156         StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate);
157         if (associateArtifacts != StorageOperationStatus.OK) {
158             result = Either.right(associateArtifacts);
159             return result;
160         }
161
162         StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate);
163         if (addAdditionalInformation != StorageOperationStatus.OK) {
164             result = Either.right(addAdditionalInformation);
165             return result;
166         }
167         StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate);
168         if (associateCapProperties != StorageOperationStatus.OK) {
169             result = Either.right(associateCapProperties);
170             return result;
171         }
172         StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate);
173         if (associateCapProperties != StorageOperationStatus.OK) {
174             result = Either.right(associatePathProperties);
175             return result;
176         }
177
178
179         return Either.left(topologyTemplate);
180
181     }
182
183     private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
184         return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies());
185     }
186
187     private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) {
188         if (policies != null && !policies.isEmpty()) {
189             policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
190                 String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
191                 p.setUniqueId(uid);
192             });
193             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies);
194             if (assosiateElementToData.isRight()) {
195                 return assosiateElementToData.right().value();
196             }
197         }
198         return StorageOperationStatus.OK;
199     }
200
201     private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
202         Map<String, ForwardingPathDataDefinition> forwardingPaths = topologyTemplate.getForwardingPaths();
203         return associateForwardingPathToComponent(topologyTemplateVertex, forwardingPaths);
204     }
205
206     private StorageOperationStatus associateNodeFilterToResource(GraphVertex topologyTemplateVertex,
207                                                                  TopologyTemplate topologyTemplate) {
208         Map<String, CINodeFilterDataDefinition> nodeFilters =
209                 topologyTemplate.getNodeFilterComponents();
210         return associateNodeFiltersToComponent(topologyTemplateVertex, nodeFilters);
211     }
212
213     private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
214         Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
215         if (calculatedCapProperties != null && !calculatedCapProperties.isEmpty()) {
216             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties);
217             if (assosiateElementToData.isRight()) {
218                 return assosiateElementToData.right().value();
219             }
220         }
221         return StorageOperationStatus.OK;
222     }
223
224     private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
225         Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = topologyTemplate.getCalculatedCapabilities();
226         if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) {
227             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities);
228             if (assosiateElementToData.isRight()) {
229                 return assosiateElementToData.right().value();
230             }
231         }
232         Map<String, MapListCapabilityDataDefinition> fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities();
233         if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) {
234             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities);
235             if (assosiateElementToData.isRight()) {
236                 return assosiateElementToData.right().value();
237             }
238         }
239         return StorageOperationStatus.OK;
240
241     }
242
243     private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
244         Map<String, MapListRequirementDataDefinition> calculatedRequirements = topologyTemplate.getCalculatedRequirements();
245         if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) {
246             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements);
247             if (assosiateElementToData.isRight()) {
248                 return assosiateElementToData.right().value();
249             }
250         }
251         Map<String, MapListRequirementDataDefinition> fullfilledRequirements = topologyTemplate.getFullfilledRequirements();
252         if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) {
253             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements);
254             if (assosiateElementToData.isRight()) {
255                 return assosiateElementToData.right().value();
256             }
257         }
258         return StorageOperationStatus.OK;
259     }
260
261     private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
262         Map<String, ArtifactDataDefinition> addInformation = topologyTemplate.getServiceApiArtifacts();
263
264         if (addInformation != null && !addInformation.isEmpty()) {
265             addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
266                 String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
267                 a.setUniqueId(uniqueId);
268             });
269             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation);
270             if (assosiateElementToData.isRight()) {
271                 return assosiateElementToData.right().value();
272             }
273         }
274         Map<String, MapArtifactDataDefinition> instArtifacts = topologyTemplate.getInstDeploymentArtifacts();
275
276         if (instArtifacts != null && !instArtifacts.isEmpty()) {
277             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts);
278             if (assosiateElementToData.isRight()) {
279                 return assosiateElementToData.right().value();
280             }
281         }
282         Map<String, MapArtifactDataDefinition> instInfoArtifacts = topologyTemplate.getInstanceArtifacts();
283
284         if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) {
285             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts);
286             if (assosiateElementToData.isRight()) {
287                 return assosiateElementToData.right().value();
288             }
289         }
290         return StorageOperationStatus.OK;
291     }
292
293     private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
294
295         Map<String, AdditionalInfoParameterDataDefinition> addInformation = topologyTemplate.getAdditionalInformation();
296
297         if (addInformation != null && !addInformation.isEmpty()) {
298             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation);
299             if (assosiateElementToData.isRight()) {
300                 return assosiateElementToData.right().value();
301             }
302         }
303         return StorageOperationStatus.OK;
304     }
305
306     public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
307         Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstProperties();
308         return associateInstPropertiesToComponent(nodeTypeVertex, instProps);
309     }
310
311     public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
312         Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstInputs();
313         return associateInstInputsToComponent(nodeTypeVertex, instProps);
314     }
315
316     public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
317         Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups();
318         return associateInstGroupsToComponent(nodeTypeVertex, instGroups);
319     }
320
321
322     public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instProps) {
323         if (instProps != null && !instProps.isEmpty()) {
324             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps);
325             if (assosiateElementToData.isRight()) {
326                 return assosiateElementToData.right().value();
327             }
328         }
329         return StorageOperationStatus.OK;
330     }
331
332     public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
333         if (instInputs != null && !instInputs.isEmpty()) {
334             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs);
335             if (assosiateElementToData.isRight()) {
336                 return assosiateElementToData.right().value();
337             }
338         }
339         return StorageOperationStatus.OK;
340     }
341
342     public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, MapGroupsDataDefinition> instGroups) {
343         if (instGroups != null && !instGroups.isEmpty()) {
344             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups);
345             if (assosiateElementToData.isRight()) {
346                 return assosiateElementToData.right().value();
347             }
348         }
349         return StorageOperationStatus.OK;
350     }
351
352
353     public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
354
355         if (instInputs != null && !instInputs.isEmpty()) {
356             instInputs.entrySet().forEach(i -> {
357                 List<String> uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet());
358                 List<String> pathKeys = new ArrayList<>();
359                 pathKeys.add(i.getKey());
360
361                 StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME);
362                 if (status != StorageOperationStatus.OK) {
363                     return;
364                 }
365             });
366         }
367
368         return StorageOperationStatus.OK;
369     }
370
371     public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
372
373         if (instInputs != null && !instInputs.isEmpty()) {
374             instInputs.entrySet().forEach(i -> {
375                 StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey());
376                 if (status != StorageOperationStatus.OK) {
377                     return;
378                 }
379             });
380         }
381
382         return StorageOperationStatus.OK;
383     }
384
385     public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
386         return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
387     }
388
389     public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
390         return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS);
391     }
392
393     private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) {
394         if (instProps != null && !instProps.isEmpty()) {
395             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps);
396             if (assosiateElementToData.isRight()) {
397                 return assosiateElementToData.right().value();
398             }
399         }
400         return StorageOperationStatus.OK;
401     }
402
403     public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabilityDataDefinition> calcCapabilty, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
404         if (calcRequirements != null && !calcRequirements.isEmpty()) {
405             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements);
406             if (assosiateElementToData.isRight()) {
407                 return assosiateElementToData.right().value();
408             }
409             Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>();
410             assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled);
411             if (assosiateElementToData.isRight()) {
412                 return assosiateElementToData.right().value();
413             }
414         }
415         if (calcCapabilty != null && !calcCapabilty.isEmpty()) {
416             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty);
417             if (assosiateElementToData.isRight()) {
418                 return assosiateElementToData.right().value();
419             }
420             Map<String, MapListCapabilityDataDefinition> fullFilled = new HashMap<>();
421             assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled);
422             if (assosiateElementToData.isRight()) {
423                 return assosiateElementToData.right().value();
424             }
425         }
426         if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) {
427             return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
428                     EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties)
429                     .right()
430                     .on(v -> StorageOperationStatus.OK);
431         }
432         return StorageOperationStatus.OK;
433     }
434
435     private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap) {
436         return titanDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson)
437                 .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap),
438                         status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap));
439     }
440
441     private Either<GraphVertex, StorageOperationStatus> associateElementToDataIfNotFound(TitanOperationStatus status, GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, ? extends ToscaDataDefinition> dataMap) {
442         if (status == TitanOperationStatus.NOT_FOUND) {
443             return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap);
444         }
445         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
446     }
447
448     private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> addElementsToComponent(GraphVertex nodeTypeVertex, GraphVertex dataVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap) {
449         Optional<StorageOperationStatus> error = dataMap.entrySet()
450                 .stream()
451                 .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e))
452                 .filter(s -> s != StorageOperationStatus.OK)
453                 .findFirst();
454         if (error.isPresent()) {
455             return Either.right(error.get());
456         }
457         return Either.left(dataVertex);
458     }
459
460     private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
461         Map<String, MapPropertiesDataDefinition> instAttr = topologyTemplate.getInstAttributes();
462         return associateInstAttributeToComponent(nodeTypeVertex, instAttr);
463     }
464
465     public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map<String, ForwardingPathDataDefinition> forwardingPathMap) {
466         if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) {
467             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap);
468             if (assosiateElementToData.isRight()) {
469                 return assosiateElementToData.right().value();
470             }
471         }
472         return StorageOperationStatus.OK;
473     }
474
475     public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instAttr) {
476         if (instAttr != null && !instAttr.isEmpty()) {
477             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
478             if (assosiateElementToData.isRight()) {
479                 return assosiateElementToData.right().value();
480             }
481         }
482         return StorageOperationStatus.OK;
483     }
484
485     public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) {
486
487         if (groups != null && !groups.isEmpty()) {
488             groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
489                 String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
490                 p.setUniqueId(uid);
491             });
492             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
493             if (assosiateElementToData.isRight()) {
494                 return assosiateElementToData.right().value();
495             }
496         }
497         return StorageOperationStatus.OK;
498     }
499
500     private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
501         return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups());
502     }
503
504     public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
505         Map<String, PropertyDataDefinition> inputs = topologyTemplate.getInputs();
506         return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId());
507     }
508
509     public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) {
510         if (inputs != null && !inputs.isEmpty()) {
511             inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
512
513             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs);
514             if (assosiateElementToData.isRight()) {
515                 return assosiateElementToData.right().value();
516             }
517         }
518         return StorageOperationStatus.OK;
519     }
520
521     private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) {
522         nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
523         fillCommonMetadata(nodeTypeVertex, topologyTemplate);
524         if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) {
525             nodeTypeVertex.setJson(topologyTemplate.getCompositions());
526         }
527         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID));
528         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS));
529
530         return nodeTypeVertex;
531
532     }
533
534     private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
535         if (topologyTemplate.getResourceType() == null) {
536             // service
537             return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate);
538         } else {
539             // VF
540             return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate);
541         }
542     }
543
544     private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
545         String categoryName = topologyTemplate.getCategories().get(0).getName();
546         Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY);
547         if (category.isRight()) {
548             log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId());
549             return StorageOperationStatus.CATEGORY_NOT_FOUND;
550         }
551         GraphVertex categoryV = category.left().value();
552         TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
553         if (createEdge != TitanOperationStatus.OK) {
554             log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId());
555             return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
556         }
557         return StorageOperationStatus.OK;
558     }
559
560     @Override
561     public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
562         JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag();
563
564         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, parseFlag);
565         if (componentByLabelAndId.isRight()) {
566             return Either.right(componentByLabelAndId.right().value());
567         }
568         GraphVertex componentV = componentByLabelAndId.left().value();
569
570         return getToscaElement(componentV, componentParametersView);
571
572     }
573     // -------------------------------------------------------------
574
575     public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) {
576         TopologyTemplate toscaElement;
577
578         toscaElement = convertToTopologyTemplate(componentV);
579         TitanOperationStatus status;
580         if (!componentParametersView.isIgnoreUsers()) {
581             status = setCreatorFromGraph(componentV, toscaElement);
582             if (status != TitanOperationStatus.OK) {
583                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
584             }
585
586             status = setLastModifierFromGraph(componentV, toscaElement);
587             if (status != TitanOperationStatus.OK) {
588                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
589             }
590         }
591         if (!componentParametersView.isIgnoreCategories()) {
592             status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement);
593             if (status != TitanOperationStatus.OK) {
594                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
595
596             }
597         }
598         if (!componentParametersView.isIgnoreArtifacts()) {
599             TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement);
600             if (storageStatus != TitanOperationStatus.OK) {
601                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus));
602             }
603         }
604         if (!componentParametersView.isIgnoreComponentInstancesProperties()) {
605             status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement);
606             if (status != TitanOperationStatus.OK) {
607                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
608             }
609         }
610         if (!componentParametersView.isIgnoreCapabilities()) {
611             status = setCapabilitiesFromGraph(componentV, toscaElement);
612             if (status != TitanOperationStatus.OK) {
613                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
614             }
615         }
616         if (!componentParametersView.isIgnoreRequirements()) {
617             status = setRequirementsFromGraph(componentV, toscaElement);
618             if (status != TitanOperationStatus.OK) {
619                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
620             }
621         }
622         if (!componentParametersView.isIgnoreAllVersions()) {
623             status = setAllVersions(componentV, toscaElement);
624             if (status != TitanOperationStatus.OK) {
625                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
626             }
627         }
628         if (!componentParametersView.isIgnoreAdditionalInformation()) {
629             status = setAdditionalInformationFromGraph(componentV, toscaElement);
630             if (status != TitanOperationStatus.OK) {
631                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
632             }
633         }
634
635         if (!componentParametersView.isIgnoreGroups()) {
636             status = setGroupsFromGraph(componentV, toscaElement);
637             if (status != TitanOperationStatus.OK) {
638                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
639             }
640
641         }
642         if (!componentParametersView.isIgnorePolicies()) {
643             status = setPoliciesFromGraph(componentV, toscaElement);
644             if (status != TitanOperationStatus.OK) {
645                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
646             }
647
648         }
649         if (!componentParametersView.isIgnoreComponentInstances()) {
650             status = setInstGroupsFromGraph(componentV, toscaElement);
651
652             //Mark all CIs that has archived origins
653             archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV);
654
655             if (status != TitanOperationStatus.OK) {
656                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
657             }
658
659         }
660         if (!componentParametersView.isIgnoreInputs()) {
661             status = setInputsFromGraph(componentV, toscaElement);
662             if (status != TitanOperationStatus.OK) {
663                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
664             }
665
666         }
667         if (!componentParametersView.isIgnoreProperties()) {
668             status = setPropertiesFromGraph(componentV, toscaElement);
669             if (status != TitanOperationStatus.OK) {
670                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
671             }
672
673         }
674
675         if (!componentParametersView.isIgnoreComponentInstancesInputs()) {
676             status = setComponentInstancesInputsFromGraph(componentV, toscaElement);
677             if (status != TitanOperationStatus.OK) {
678                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
679
680             }
681         }
682
683         if (!componentParametersView.isIgnoreCapabiltyProperties()) {
684             status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement);
685             if (status != TitanOperationStatus.OK) {
686                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
687
688             }
689         }
690
691         if (!componentParametersView.isIgnoreForwardingPath()) {
692             status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement);
693             if (status != TitanOperationStatus.OK) {
694                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
695
696             }
697         }
698
699         if (!componentParametersView.isIgnoreNodeFilter()) {
700             status = setNodeFilterComponentFromGraph(componentV, toscaElement);
701             if (status != TitanOperationStatus.OK) {
702                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
703
704             }
705         }
706
707         return Either.left(toscaElement);
708     }
709
710     private TitanOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
711         Either<Map<String, PolicyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES);
712         if (result.isLeft()) {
713             toscaElement.setPolicies(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     public StorageOperationStatus associateNodeFiltersToComponent(GraphVertex nodeTypeVertex,
723                                                                   Map<String, CINodeFilterDataDefinition> filterMaps) {
724         if (filterMaps != null && !filterMaps.isEmpty()) {
725             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData
726                     (nodeTypeVertex, VertexTypeEnum.NODE_FILTER_TEMPLATE,
727                             EdgeLabelEnum.NODE_FILTER_TEMPLATE, filterMaps);
728             if (assosiateElementToData.isRight()) {
729                 return assosiateElementToData.right().value();
730             }
731         }
732         return StorageOperationStatus.OK;
733     }
734
735     private TitanOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
736         Either<Map<String, ForwardingPathDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH);
737         if (result.isLeft()) {
738             topologyTemplate.setForwardingPaths(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
748     private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
749         Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
750         if (result.isLeft()) {
751             topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value());
752         } else {
753             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
754                 return result.right().value();
755             }
756         }
757         return TitanOperationStatus.OK;
758     }
759
760     private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
761         Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES);
762         if (result.isLeft()) {
763             toscaElement.setProperties(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 setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
773         Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS);
774         if (result.isLeft()) {
775             topologyTemplate.setInstGroups(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 setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
785         Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES);
786         if (result.isLeft()) {
787             topologyTemplate.setInstProperties(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 setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
797         Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS);
798         if (result.isLeft()) {
799             topologyTemplate.setInstInputs(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 setNodeFilterComponentFromGraph(GraphVertex componentV,
809                                                                  TopologyTemplate topologyTemplate) {
810         Either<Map<String, CINodeFilterDataDefinition>, TitanOperationStatus> result =
811                 getDataFromGraph(componentV,
812                         EdgeLabelEnum.NODE_FILTER_TEMPLATE);
813         if (result.isLeft()) {
814             topologyTemplate.setNodeFilterComponents(result.left().value());
815         } else {
816             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
817                 return result.right().value();
818             }
819         }
820         return TitanOperationStatus.OK;
821     }
822
823     @Override
824     protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
825         Either<Map<String, MapListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
826         if (result.isLeft()) {
827             ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value());
828         } else {
829             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
830                 return result.right().value();
831             }
832         }
833         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
834         if (result.isLeft()) {
835             ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value());
836         } else {
837             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
838                 return result.right().value();
839             }
840         }
841         return TitanOperationStatus.OK;
842
843     }
844
845     protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
846         Either<Map<String, MapListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
847         if (result.isLeft()) {
848             ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value());
849         } else {
850             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
851                 return result.right().value();
852             }
853         }
854         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
855         if (result.isLeft()) {
856             ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value());
857         } else {
858             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
859                 return result.right().value();
860             }
861         }
862         return TitanOperationStatus.OK;
863     }
864
865     private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
866         TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement);
867         if (storageStatus != TitanOperationStatus.OK) {
868             return storageStatus;
869         }
870         Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
871         if (result.isLeft()) {
872             toscaElement.setServiceApiArtifacts(result.left().value());
873         } else {
874             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
875                 return result.right().value();
876             }
877         }
878         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
879         if (resultInstArt.isLeft()) {
880             toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value());
881         } else {
882             if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) {
883                 return resultInstArt.right().value();
884             }
885         }
886         Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS);
887         if (instanceArt.isLeft()) {
888             toscaElement.setInstanceArtifacts(instanceArt.left().value());
889         } else {
890             if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) {
891                 return instanceArt.right().value();
892             }
893         }
894         return TitanOperationStatus.OK;
895     }
896
897     private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
898         Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS);
899         if (result.isLeft()) {
900             toscaElement.setInputs(result.left().value());
901         } else {
902             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
903                 return result.right().value();
904             }
905         }
906         return TitanOperationStatus.OK;
907     }
908
909     private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
910         Either<Map<String, GroupDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS);
911         if (result.isLeft()) {
912             toscaElement.setGroups(result.left().value());
913         } else {
914             if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
915                 return result.right().value();
916             }
917         }
918         return TitanOperationStatus.OK;
919     }
920
921     private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
922         List<CategoryDefinition> categories = new ArrayList<>();
923
924         switch (componentV.getType()) {
925             case RESOURCE:
926                 return setResourceCategoryFromGraph(componentV, toscaElement);
927             case SERVICE:
928                 return setServiceCategoryFromGraph(componentV, toscaElement, categories);
929
930             default:
931                 log.debug("Not supported component type {} ", componentV.getType());
932                 break;
933         }
934         return TitanOperationStatus.OK;
935     }
936
937     private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) {
938         Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
939         if (childVertex.isRight()) {
940             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
941             return childVertex.right().value();
942         }
943         GraphVertex categoryV = childVertex.left().value();
944         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
945         CategoryDefinition category = new CategoryDefinition();
946         category.setUniqueId(categoryV.getUniqueId());
947         category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
948         category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
949
950         Type listTypeCat = new TypeToken<List<String>>() {
951         }.getType();
952         List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
953         category.setIcons(iconsfromJsonCat);
954         categories.add(category);
955         toscaElement.setCategories(categories);
956
957         return TitanOperationStatus.OK;
958     }
959
960     @SuppressWarnings("unchecked")
961     private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
962
963         TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
964
965         Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson();
966         topologyTemplate.setCompositions(json);
967
968         return topologyTemplate;
969     }
970
971     @Override
972     public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
973         Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView());
974         if (nodeType.isRight()) {
975             log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value());
976             return nodeType;
977         }
978         TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex);
979         if (status != TitanOperationStatus.OK) {
980             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
981         }
982         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES);
983         if (status != TitanOperationStatus.OK) {
984             log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
985             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
986         }
987         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES);
988         if (status != TitanOperationStatus.OK) {
989             log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status);
990             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
991         }
992
993         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
994         if (status != TitanOperationStatus.OK) {
995             log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
996             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
997         }
998
999         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS);
1000         if (status != TitanOperationStatus.OK) {
1001             log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1002             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1003         }
1004         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.POLICIES);
1005         if (status != TitanOperationStatus.OK) {
1006             log.debug("Failed to disassociate policies for {} error {}", toscaElementVertex.getUniqueId(), status);
1007             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1008         }
1009         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS);
1010         if (status != TitanOperationStatus.OK) {
1011             log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1012             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1013         }
1014         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS);
1015         if (status != TitanOperationStatus.OK) {
1016             log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1017             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1018         }
1019         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1020         if (status != TitanOperationStatus.OK) {
1021             log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1022             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1023         }
1024         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES);
1025         if (status != TitanOperationStatus.OK) {
1026             log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status);
1027             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1028         }
1029         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
1030         if (status != TitanOperationStatus.OK) {
1031             log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
1032             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1033         }
1034         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1035         if (status != TitanOperationStatus.OK) {
1036             log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1037             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1038         }
1039         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
1040         if (status != TitanOperationStatus.OK) {
1041             log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1042             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1043         }
1044         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
1045         if (status != TitanOperationStatus.OK) {
1046             log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1047             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1048         }
1049         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
1050         if (status != TitanOperationStatus.OK) {
1051             log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1052             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1053         }
1054         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
1055         if (status != TitanOperationStatus.OK) {
1056             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1057             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1058         }
1059         status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
1060         if (status != TitanOperationStatus.OK) {
1061             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1062             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1063         }
1064
1065         titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS);
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     /**
1188      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
1189      *
1190      * @param componentId
1191      * @param instanceId
1192      * @param capabilityName
1193      * @param capabilityType
1194      * @param ownerId
1195      * @return
1196      */
1197     public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
1198
1199         Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null;
1200         Map<String, MapCapabilityProperty> mapPropertiesDataDefinition = null;
1201         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse);
1202         if (componentByLabelAndId.isRight()) {
1203             result = Either.right(componentByLabelAndId.right().value());
1204         }
1205         if (componentByLabelAndId.isLeft()) {
1206             Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1207             if (getDataRes.isRight()) {
1208                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getDataRes.right().value()));
1209             } else {
1210                 mapPropertiesDataDefinition = getDataRes.left().value();
1211             }
1212         }
1213         if (isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)) {
1214             result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
1215         }
1216         return result;
1217     }
1218
1219     public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) {
1220         return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId);
1221     }
1222
1223
1224     private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> mapPropertiesDataDefinition) {
1225         return MapUtils.isNotEmpty(mapPropertiesDataDefinition) &&
1226                 mapPropertiesDataDefinition.get(instanceId) != null &&
1227                 MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
1228     }
1229
1230     private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) {
1231         List<ComponentInstanceProperty> capPropsList = null;
1232         for (Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()) {
1233             if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) {
1234                 Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition();
1235                 if (capMap != null && !capMap.isEmpty()) {
1236                     capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList());
1237                     break;
1238                 }
1239             }
1240         }
1241         if (capPropsList == null) {
1242             capPropsList = new ArrayList<>();
1243         }
1244         return capPropsList;
1245     }
1246
1247     private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) {
1248         if (capProp != null) {
1249             String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM);
1250             if (path.length < 4) {
1251                 log.debug("wrong key format for capabilty, key {}", capProp);
1252                 return false;
1253             }
1254             return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId);
1255         }
1256         return false;
1257     }
1258
1259     public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1260         fillPolicyDefinition(componentV, policyDefinition, counter);
1261         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
1262     }
1263
1264     public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List<PolicyDefinition> policies) {
1265         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, JsonPresentationFields.UNIQUE_ID);
1266     }
1267
1268     public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) {
1269         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
1270     }
1271
1272     public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) {
1273         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID);
1274     }
1275
1276     public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) {
1277         return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
1278     }
1279
1280     public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) {
1281         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME);
1282     }
1283
1284     private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1285         String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter);
1286         policyDefinition.setName(policyName);
1287         policyDefinition.setInvariantName(policyName);
1288         policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME));
1289         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName));
1290         policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1291         policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID());
1292     }
1293
1294     public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) {
1295         String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName);
1296         String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length());
1297         return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter;
1298     }
1299
1300     void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1301         if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) {
1302             GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
1303                     .left()
1304                     .on(this::throwStorageException);
1305             if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) {
1306                 toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement));
1307             }
1308             if (MapUtils.isNotEmpty(toscaElement.getGroups())) {
1309                 toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement));
1310             }
1311             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities());
1312             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements());
1313             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties());
1314         }
1315     }
1316
1317     public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1318         if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) {
1319             GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
1320                     .left()
1321                     .on(this::throwStorageException);
1322             if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) {
1323                 toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(), this::getOriginToscaElement));
1324             }
1325             if (MapUtils.isNotEmpty(toscaElement.getGroups())) {
1326                 toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement));
1327             }
1328             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities());
1329             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements());
1330             topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties());
1331         }
1332     }
1333
1334     private GraphVertex throwStorageException(TitanOperationStatus status) {
1335         throw new StorageException(status);
1336     }
1337
1338     private ToscaElement getOriginToscaElement(ComponentInstanceDataDefinition instance) {
1339         log.debug("#getOriginToscaElement - origin name: {}", instance.getComponentName());
1340         ToscaElementTypeEnum elementType = detectToscaType(instance.getOriginType());
1341         Either<ToscaElement, StorageOperationStatus> getOriginRes;
1342         if (elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) {
1343             getOriginRes = this.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter());
1344
1345         } else {
1346             getOriginRes = nodeTypeOperation.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter());
1347         }
1348         if (getOriginRes.isRight()) {
1349             log.debug("Failed to get an origin component with uniqueId {}", CapabilityRequirementNameResolver.getActualComponentUid(instance));
1350             throw new StorageException(getOriginRes.right().value());
1351         }
1352         return getOriginRes.left().value();
1353     }
1354
1355     private ToscaElementTypeEnum detectToscaType(OriginTypeEnum originType) {
1356         log.debug("#detectToscaType - type: {}", originType);
1357         if (nodeTypeSet.contains(originType)){
1358             return ToscaElementTypeEnum.NODE_TYPE;
1359         } else {
1360             return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE;
1361         }
1362     }
1363
1364     private ComponentParametersView getFilter() {
1365         ComponentParametersView filter = new ComponentParametersView();
1366         filter.setIgnoreCapabilities(false);
1367         filter.setIgnoreCapabiltyProperties(false);
1368         filter.setIgnoreRequirements(false);
1369         return filter;
1370     }
1371
1372 }