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