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