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