Support Inputs during Import Service
[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 (associateInstInputs != 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 (associatePathProperties != 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 associateInstInterfacesToComponent(
389         GraphVertex nodeTypeVertex,
390         Map<String, MapInterfaceDataDefinition> instInterfaces
391     ) {
392         if (instInterfaces != null && !instInterfaces.isEmpty()) {
393             Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData(
394                 nodeTypeVertex,
395                 VertexTypeEnum.INST_INTERFACES,
396                 EdgeLabelEnum.INST_INTERFACES,
397                 instInterfaces);
398             if (associateElementToData.isRight()) {
399                 return associateElementToData.right().value();
400             }
401         }
402         return StorageOperationStatus.OK;
403     }
404
405     public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, MapGroupsDataDefinition> instGroups) {
406         if (instGroups != null && !instGroups.isEmpty()) {
407             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS,
408                 EdgeLabelEnum.INST_GROUPS, instGroups);
409             if (assosiateElementToData.isRight()) {
410                 return assosiateElementToData.right().value();
411             }
412         }
413         return StorageOperationStatus.OK;
414     }
415
416     public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
417         if (instInputs != null && !instInputs.isEmpty()) {
418             instInputs.entrySet().forEach(i -> {
419                 List<String> uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet());
420                 List<String> pathKeys = new ArrayList<>();
421                 pathKeys.add(i.getKey());
422                 StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
423                     uniqueKeys, pathKeys, JsonPresentationFields.NAME);
424                 if (status != StorageOperationStatus.OK) {
425                     return;
426                 }
427             });
428         }
429         return StorageOperationStatus.OK;
430     }
431
432     public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
433         if (instInputs != null && !instInputs.isEmpty()) {
434             instInputs.entrySet().forEach(i -> {
435                 StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES,
436                     VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey());
437                 if (status != StorageOperationStatus.OK) {
438                     return;
439                 }
440             });
441         }
442         return StorageOperationStatus.OK;
443     }
444
445     public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex,
446                                                                               Map<String, MapArtifactDataDefinition> instArtifacts) {
447         return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS,
448             EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
449     }
450
451     public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex,
452                                                                     Map<String, MapArtifactDataDefinition> instArtifacts) {
453         return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS,
454             EdgeLabelEnum.INSTANCE_ARTIFACTS);
455     }
456
457     private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps,
458                                                                          VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) {
459         if (instProps != null && !instProps.isEmpty()) {
460             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel,
461                 instProps);
462             if (assosiateElementToData.isRight()) {
463                 return assosiateElementToData.right().value();
464             }
465         }
466         return StorageOperationStatus.OK;
467     }
468
469     public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex,
470                                                                       Map<String, MapListRequirementDataDefinition> calcRequirements,
471                                                                       Map<String, MapListCapabilityDataDefinition> calcCapabilty,
472                                                                       Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
473         if (!MapUtils.isEmpty(calcRequirements)) {
474             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex,
475                 VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements);
476             if (assosiateElementToData.isRight()) {
477                 return assosiateElementToData.right().value();
478             }
479             Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>();
480             assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS,
481                 EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled);
482             if (assosiateElementToData.isRight()) {
483                 return assosiateElementToData.right().value();
484             }
485         }
486         if (!MapUtils.isEmpty(calcCapabilty)) {
487             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex,
488                 VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty);
489             if (assosiateElementToData.isRight()) {
490                 return assosiateElementToData.right().value();
491             }
492             Map<String, MapListCapabilityDataDefinition> fullFilled = new HashMap<>();
493             assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES,
494                 EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled);
495             if (assosiateElementToData.isRight()) {
496                 return assosiateElementToData.right().value();
497             }
498         }
499         if (!MapUtils.isEmpty(calculatedCapabilitiesProperties)) {
500             return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
501                 calculatedCapabilitiesProperties).right().on(v -> StorageOperationStatus.OK);
502         }
503         return StorageOperationStatus.OK;
504     }
505
506     private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex,
507                                                                                                                   VertexTypeEnum vertexTypeEnum,
508                                                                                                                   EdgeLabelEnum edgeLabelEnum,
509                                                                                                                   Map<String, T> dataMap) {
510         return janusGraphDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson)
511             .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap),
512                 status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap));
513     }
514
515     private Either<GraphVertex, StorageOperationStatus> associateElementToDataIfNotFound(JanusGraphOperationStatus status, GraphVertex nodeTypeVertex,
516                                                                                          VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum,
517                                                                                          Map<String, ? extends ToscaDataDefinition> dataMap) {
518         if (status == JanusGraphOperationStatus.NOT_FOUND) {
519             return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap);
520         }
521         return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
522     }
523
524     private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> addElementsToComponent(GraphVertex nodeTypeVertex,
525                                                                                                              GraphVertex dataVertex,
526                                                                                                              VertexTypeEnum vertexTypeEnum,
527                                                                                                              EdgeLabelEnum edgeLabelEnum,
528                                                                                                              Map<String, T> dataMap) {
529         Optional<StorageOperationStatus> error = dataMap.entrySet().stream()
530             .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e))
531             .filter(s -> s != StorageOperationStatus.OK).findFirst();
532         if (error.isPresent()) {
533             return Either.right(error.get());
534         }
535         return Either.left(dataVertex);
536     }
537
538     private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
539         Map<String, MapAttributesDataDefinition> instAttr = topologyTemplate.getInstAttributes();
540         return associateInstAttributeToComponent(nodeTypeVertex, instAttr);
541     }
542
543     public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex,
544                                                                      Map<String, ForwardingPathDataDefinition> forwardingPathMap) {
545         if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) {
546             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
547                 VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap);
548             if (assosiateElementToData.isRight()) {
549                 return assosiateElementToData.right().value();
550             }
551         }
552         return StorageOperationStatus.OK;
553     }
554
555     public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapAttributesDataDefinition> instAttr) {
556         if (instAttr != null && !instAttr.isEmpty()) {
557             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
558                 VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
559             if (assosiateElementToData.isRight()) {
560                 return assosiateElementToData.right().value();
561             }
562         }
563         return StorageOperationStatus.OK;
564     }
565
566     public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) {
567         if (groups != null && !groups.isEmpty()) {
568             groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
569                 String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
570                 p.setUniqueId(uid);
571             });
572             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS,
573                 EdgeLabelEnum.GROUPS, groups);
574             if (assosiateElementToData.isRight()) {
575                 return assosiateElementToData.right().value();
576             }
577         }
578         return StorageOperationStatus.OK;
579     }
580
581     private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
582         return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups());
583     }
584
585     public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
586         Map<String, PropertyDataDefinition> inputs = topologyTemplate.getInputs();
587         return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId());
588     }
589
590     public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) {
591         if (inputs != null && !inputs.isEmpty()) {
592             inputs.values().stream().filter(e -> e.getUniqueId() == null)
593                 .forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
594             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS,
595                 EdgeLabelEnum.INPUTS, inputs);
596             if (assosiateElementToData.isRight()) {
597                 return assosiateElementToData.right().value();
598             }
599         }
600         return StorageOperationStatus.OK;
601     }
602
603     public StorageOperationStatus associateOutputsToComponent(final GraphVertex nodeTypeVertex,
604                                                               final Map<String, ? extends AttributeDataDefinition> outputs,
605                                                               final String id) {
606         if (MapUtils.isNotEmpty(outputs)) {
607             outputs.values().stream().filter(e -> e.getUniqueId() == null)
608                 .forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
609             final Either<GraphVertex, StorageOperationStatus> associateElementToData
610                 = associateElementToData(nodeTypeVertex, VertexTypeEnum.OUTPUTS, EdgeLabelEnum.OUTPUTS, outputs);
611             if (associateElementToData.isRight()) {
612                 return associateElementToData.right().value();
613             }
614         }
615         return StorageOperationStatus.OK;
616     }
617
618     private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) {
619         nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
620         fillCommonMetadata(nodeTypeVertex, topologyTemplate);
621         if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) {
622             nodeTypeVertex.setJson(topologyTemplate.getCompositions());
623         }
624         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID));
625         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_VERSION_UUID,
626             topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION_ID));
627         nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS,
628             topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS));
629         return nodeTypeVertex;
630     }
631
632     private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
633         if (topologyTemplate.getResourceType() == null) {
634             // service
635             return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate);
636         } else {
637             // VF
638             return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate);
639         }
640     }
641
642     private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
643         String categoryName = topologyTemplate.getCategories().get(0).getName();
644         Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName,
645             VertexTypeEnum.SERVICE_CATEGORY);
646         if (category.isRight()) {
647             log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId());
648             return StorageOperationStatus.CATEGORY_NOT_FOUND;
649         }
650         GraphVertex categoryV = category.left().value();
651         JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
652         if (createEdge != JanusGraphOperationStatus.OK) {
653             log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName,
654                 categoryV.getUniqueId());
655             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
656         }
657         return StorageOperationStatus.OK;
658     }
659
660     @Override
661     public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
662         JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag();
663         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE,
664             parseFlag);
665         if (componentByLabelAndId.isRight()) {
666             return Either.right(componentByLabelAndId.right().value());
667         }
668         GraphVertex componentV = componentByLabelAndId.left().value();
669         return getToscaElement(componentV, componentParametersView);
670     }
671
672     // -------------------------------------------------------------
673     public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) {
674         TopologyTemplate toscaElement;
675         toscaElement = convertToTopologyTemplate(componentV);
676         JanusGraphOperationStatus status;
677         if (!componentParametersView.isIgnoreUsers()) {
678             status = setCreatorFromGraph(componentV, toscaElement);
679             if (status != JanusGraphOperationStatus.OK) {
680                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
681             }
682             status = setLastModifierFromGraph(componentV, toscaElement);
683             if (status != JanusGraphOperationStatus.OK) {
684                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
685             }
686         }
687         if (!componentParametersView.isIgnoreCategories()) {
688             status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement);
689             if (status != JanusGraphOperationStatus.OK) {
690                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
691             }
692         }
693         if (!componentParametersView.isIgnoreArtifacts()) {
694             JanusGraphOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement);
695             if (storageStatus != JanusGraphOperationStatus.OK) {
696                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
697             }
698         }
699         if (!componentParametersView.isIgnoreComponentInstancesProperties()) {
700             status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement);
701             if (status != JanusGraphOperationStatus.OK) {
702                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
703             }
704         }
705         if (!componentParametersView.isIgnoreComponentInstancesAttributes()) {
706             status = setComponentInstancesAttributesFromGraph(componentV, toscaElement);
707             if (status != JanusGraphOperationStatus.OK) {
708                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
709             }
710         }
711         if (!componentParametersView.isIgnoreCapabilities()) {
712             status = setCapabilitiesFromGraph(componentV, toscaElement);
713             if (status != JanusGraphOperationStatus.OK) {
714                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
715             }
716         }
717         if (!componentParametersView.isIgnoreRequirements()) {
718             status = setRequirementsFromGraph(componentV, toscaElement);
719             if (status != JanusGraphOperationStatus.OK) {
720                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
721             }
722         }
723         if (!componentParametersView.isIgnoreAllVersions()) {
724             status = setAllVersions(componentV, toscaElement);
725             if (status != JanusGraphOperationStatus.OK) {
726                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
727             }
728         }
729         if (!componentParametersView.isIgnoreAdditionalInformation()) {
730             status = setAdditionalInformationFromGraph(componentV, toscaElement);
731             if (status != JanusGraphOperationStatus.OK) {
732                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
733             }
734         }
735         if (!componentParametersView.isIgnoreGroups()) {
736             status = setGroupsFromGraph(componentV, toscaElement);
737             if (status != JanusGraphOperationStatus.OK) {
738                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
739             }
740         }
741         if (!componentParametersView.isIgnorePolicies()) {
742             status = setPoliciesFromGraph(componentV, toscaElement);
743             if (status != JanusGraphOperationStatus.OK) {
744                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
745             }
746         }
747         if (!componentParametersView.isIgnoreComponentInstances()) {
748             status = setInstGroupsFromGraph(componentV, toscaElement);
749             //Mark all CIs that has archived origins
750             archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV);
751             if (status != JanusGraphOperationStatus.OK) {
752                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
753             }
754         }
755         if (!componentParametersView.isIgnoreInputs()) {
756             status = setInputsFromGraph(componentV, toscaElement);
757             if (status != JanusGraphOperationStatus.OK) {
758                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
759             }
760         }
761         if (!componentParametersView.isIgnoreOutputs()) {
762             final JanusGraphOperationStatus storageStatus = setOutputsFromGraph(componentV, toscaElement);
763             if (storageStatus != JanusGraphOperationStatus.OK) {
764                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
765             }
766         }
767         if (!componentParametersView.isIgnoreProperties()) {
768             status = setPropertiesFromGraph(componentV, toscaElement);
769             if (status != JanusGraphOperationStatus.OK) {
770                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
771             }
772         }
773         if (!componentParametersView.isIgnoreComponentInstancesInputs()) {
774             status = setComponentInstancesInputsFromGraph(componentV, toscaElement);
775             if (status != JanusGraphOperationStatus.OK) {
776                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
777             }
778         }
779         if (!componentParametersView.isIgnoreCapabiltyProperties()) {
780             status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement);
781             if (status != JanusGraphOperationStatus.OK) {
782                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
783             }
784         }
785         if (!componentParametersView.isIgnoreServicePath()) {
786             status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement);
787             if (status != JanusGraphOperationStatus.OK) {
788                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
789             }
790         }
791         if (!componentParametersView.isIgnoreNodeFilter()) {
792             status = setNodeFilterComponentFromGraph(componentV, toscaElement);
793             if (status != JanusGraphOperationStatus.OK) {
794                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
795             }
796         }
797         if (!componentParametersView.isIgnoreSubstitutionFilter()) {
798             status = setSubstitutionFilterComponentFromGraph(componentV, toscaElement);
799             if (status != JanusGraphOperationStatus.OK) {
800                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
801             }
802         }
803         if (!componentParametersView.isIgnoreInterfaces()) {
804             JanusGraphOperationStatus storageStatus = setInterfacesFromGraph(componentV, toscaElement);
805             if (storageStatus != JanusGraphOperationStatus.OK) {
806                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
807             }
808         }
809         if (!componentParametersView.isIgnoreComponentInstancesInterfaces()) {
810             JanusGraphOperationStatus storageStatus = setComponentInstancesInterfacesFromGraph(componentV, toscaElement);
811             if (storageStatus != JanusGraphOperationStatus.OK) {
812                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
813             }
814         }
815         if (!componentParametersView.isIgnoreDataType()) {
816             JanusGraphOperationStatus storageStatus = setDataTypesFromGraph(componentV, toscaElement);
817             if (storageStatus != JanusGraphOperationStatus.OK) {
818                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
819             }
820         }
821         return Either.left(toscaElement);
822     }
823
824     private JanusGraphOperationStatus setDataTypesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
825         Either<Map<String, DataTypeDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.DATA_TYPES);
826         if (result.isLeft()) {
827             toscaElement.setDataTypes(result.left().value());
828         } else {
829             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
830                 return result.right().value();
831             }
832         }
833         return JanusGraphOperationStatus.OK;
834     }
835
836     private JanusGraphOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
837         Either<Map<String, PolicyDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES);
838         if (result.isLeft()) {
839             toscaElement.setPolicies(result.left().value());
840         } else {
841             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
842                 return result.right().value();
843             }
844         }
845         return JanusGraphOperationStatus.OK;
846     }
847
848     private JanusGraphOperationStatus setInterfacesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
849         Either<Map<String, InterfaceDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE);
850         if (result.isLeft()) {
851             topologyTemplate.setInterfaces(result.left().value());
852         } else {
853             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
854                 return result.right().value();
855             }
856         }
857         return JanusGraphOperationStatus.OK;
858     }
859
860     private JanusGraphOperationStatus setComponentInstancesInterfacesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
861         Either<Map<String, MapInterfaceDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
862             EdgeLabelEnum.INST_INTERFACES);
863         if (result.isLeft()) {
864             result.left().value().entrySet().forEach(entry -> topologyTemplate.addComponentInstanceInterfaceMap(entry.getKey(), entry.getValue()));
865         } else {
866             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
867                 return result.right().value();
868             }
869         }
870         return JanusGraphOperationStatus.OK;
871     }
872
873     private StorageOperationStatus associateInterfacesToComponent(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
874         Map<String, InterfaceDataDefinition> interfaceMap = topologyTemplate.getInterfaces();
875         if (interfaceMap != null && !interfaceMap.isEmpty()) {
876             Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex,
877                 VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap);
878             if (assosiateElementToData.isRight()) {
879                 return assosiateElementToData.right().value();
880             }
881         }
882         return StorageOperationStatus.OK;
883     }
884
885     private JanusGraphOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
886         Either<Map<String, ForwardingPathDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
887             EdgeLabelEnum.FORWARDING_PATH);
888         if (result.isLeft()) {
889             topologyTemplate.setForwardingPaths(result.left().value());
890         } else {
891             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
892                 return result.right().value();
893             }
894         }
895         return JanusGraphOperationStatus.OK;
896     }
897
898     private JanusGraphOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
899         Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
900             EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
901         if (result.isLeft()) {
902             topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value());
903         } else {
904             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
905                 return result.right().value();
906             }
907         }
908         Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> capPropResult = getDataFromGraph(componentV,
909             EdgeLabelEnum.CAPABILITIES_PROPERTIES);
910         if (capPropResult.isLeft()) {
911             topologyTemplate.setCapabilitiesProperties(capPropResult.left().value());
912         } else {
913             if (capPropResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
914                 return capPropResult.right().value();
915             }
916         }
917         return JanusGraphOperationStatus.OK;
918     }
919
920     private JanusGraphOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
921         Either<Map<String, PropertyDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES);
922         if (result.isLeft()) {
923             toscaElement.setProperties(result.left().value());
924         } else {
925             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
926                 return result.right().value();
927             }
928         }
929         return JanusGraphOperationStatus.OK;
930     }
931
932     private JanusGraphOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
933         Either<Map<String, MapGroupsDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS);
934         if (result.isLeft()) {
935             topologyTemplate.setInstGroups(result.left().value());
936         } else {
937             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
938                 return result.right().value();
939             }
940         }
941         return JanusGraphOperationStatus.OK;
942     }
943
944     private JanusGraphOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
945         Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
946             EdgeLabelEnum.INST_PROPERTIES);
947         if (result.isLeft()) {
948             topologyTemplate.setInstProperties(result.left().value());
949         } else {
950             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
951                 return result.right().value();
952             }
953         }
954         return JanusGraphOperationStatus.OK;
955     }
956
957     private JanusGraphOperationStatus setComponentInstancesAttributesFromGraph(final GraphVertex componentV,
958                                                                                final TopologyTemplate topologyTemplate) {
959         final Either<Map<String, MapAttributesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
960             EdgeLabelEnum.INST_ATTRIBUTES);
961         if (result.isLeft()) {
962             topologyTemplate.setInstAttributes(result.left().value());
963         } else if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
964             return result.right().value();
965         }
966         return JanusGraphOperationStatus.OK;
967     }
968
969     private JanusGraphOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
970         Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS);
971         if (result.isLeft()) {
972             topologyTemplate.setInstInputs(result.left().value());
973         } else {
974             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
975                 return result.right().value();
976             }
977         }
978         return JanusGraphOperationStatus.OK;
979     }
980
981     private JanusGraphOperationStatus setNodeFilterComponentFromGraph(final GraphVertex componentV, final TopologyTemplate topologyTemplate) {
982         final Either<Map<String, CINodeFilterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
983             EdgeLabelEnum.NODE_FILTER_TEMPLATE);
984         if (result.isLeft()) {
985             topologyTemplate.setNodeFilterComponents(result.left().value());
986         } else {
987             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
988                 return result.right().value();
989             }
990         }
991         return JanusGraphOperationStatus.OK;
992     }
993
994     private JanusGraphOperationStatus setSubstitutionFilterComponentFromGraph(final GraphVertex componentV, final TopologyTemplate topologyTemplate) {
995         final Either<Map<String, SubstitutionFilterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
996             EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE);
997         if (result.isLeft()) {
998             final Map<String, SubstitutionFilterDataDefinition> filters = result.left().value();
999             if (MapUtils.isEmpty(filters)) {
1000                 return JanusGraphOperationStatus.OK;
1001             }
1002             if (filters.values().size() > 1) {
1003                 log.error(EcompLoggerErrorCode.DATA_ERROR, TopologyTemplateOperation.class.getName(),
1004                     (ErrorLogOptionalData) null, "Only a single substitution filter is expected, but got '{}'", filters.values().size());
1005                 return JanusGraphOperationStatus.GENERAL_ERROR;
1006             }
1007             topologyTemplate.setSubstitutionFilters(new SubstitutionFilterDataDefinition(filters.values().iterator().next()));
1008         } else {
1009             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1010                 return result.right().value();
1011             }
1012         }
1013         return JanusGraphOperationStatus.OK;
1014     }
1015
1016     @Override
1017     protected <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
1018         Either<Map<String, MapListRequirementDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
1019             EdgeLabelEnum.CALCULATED_REQUIREMENTS);
1020         if (result.isLeft()) {
1021             ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value());
1022         } else {
1023             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1024                 return result.right().value();
1025             }
1026         }
1027         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
1028         if (result.isLeft()) {
1029             ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value());
1030         } else {
1031             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1032                 return result.right().value();
1033             }
1034         }
1035         Either<Map<String, ListRequirementDataDefinition>, JanusGraphOperationStatus> requirementResult = getDataFromGraph(componentV,
1036             EdgeLabelEnum.REQUIREMENTS);
1037         if (requirementResult.isLeft()) {
1038             toscaElement.setRequirements(requirementResult.left().value());
1039         } else {
1040             if (requirementResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1041                 return requirementResult.right().value();
1042             }
1043         }
1044         return JanusGraphOperationStatus.OK;
1045     }
1046
1047     protected <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
1048         Either<Map<String, MapListCapabilityDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
1049             EdgeLabelEnum.CALCULATED_CAPABILITIES);
1050         if (result.isLeft()) {
1051             ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value());
1052         } else {
1053             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1054                 return result.right().value();
1055             }
1056         }
1057         result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
1058         if (result.isLeft()) {
1059             ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value());
1060         } else {
1061             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1062                 return result.right().value();
1063             }
1064         }
1065         Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult = getDataFromGraph(componentV,
1066             EdgeLabelEnum.CAPABILITIES);
1067         if (capabilitiesResult.isLeft()) {
1068             toscaElement.setCapabilities(capabilitiesResult.left().value());
1069         } else {
1070             if (capabilitiesResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1071                 return capabilitiesResult.right().value();
1072             }
1073         }
1074         return JanusGraphOperationStatus.OK;
1075     }
1076
1077     private JanusGraphOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
1078         JanusGraphOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement);
1079         if (storageStatus != JanusGraphOperationStatus.OK) {
1080             return storageStatus;
1081         }
1082         Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
1083             EdgeLabelEnum.SERVICE_API_ARTIFACTS);
1084         if (result.isLeft()) {
1085             toscaElement.setServiceApiArtifacts(result.left().value());
1086         } else {
1087             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1088                 return result.right().value();
1089             }
1090         }
1091         Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> resultInstArt = getDataFromGraph(componentV,
1092             EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
1093         if (resultInstArt.isLeft()) {
1094             toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value());
1095         } else {
1096             if (resultInstArt.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1097                 return resultInstArt.right().value();
1098             }
1099         }
1100         Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> instanceArt = getDataFromGraph(componentV,
1101             EdgeLabelEnum.INSTANCE_ARTIFACTS);
1102         if (instanceArt.isLeft()) {
1103             toscaElement.setInstanceArtifacts(instanceArt.left().value());
1104         } else {
1105             if (instanceArt.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1106                 return instanceArt.right().value();
1107             }
1108         }
1109         return JanusGraphOperationStatus.OK;
1110     }
1111
1112     private JanusGraphOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
1113         Either<Map<String, PropertyDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS);
1114         if (result.isLeft()) {
1115             toscaElement.setInputs(result.left().value());
1116         } else {
1117             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1118                 return result.right().value();
1119             }
1120         }
1121         Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult = getDataFromGraph(componentV,
1122             EdgeLabelEnum.CAPABILITIES);
1123         if (capabilitiesResult.isLeft()) {
1124             toscaElement.setCapabilities(capabilitiesResult.left().value());
1125         } else {
1126             if (capabilitiesResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1127                 return capabilitiesResult.right().value();
1128             }
1129         }
1130         return JanusGraphOperationStatus.OK;
1131     }
1132
1133     private JanusGraphOperationStatus setOutputsFromGraph(final GraphVertex componentV, final TopologyTemplate toscaElement) {
1134         final Either<Map<String, AttributeDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.OUTPUTS);
1135         if (result.isLeft()) {
1136             toscaElement.setOutputs(result.left().value());
1137         } else {
1138             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1139                 return result.right().value();
1140             }
1141         }
1142         return JanusGraphOperationStatus.OK;
1143     }
1144
1145     private JanusGraphOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
1146         Either<Map<String, GroupDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS);
1147         if (result.isLeft()) {
1148             toscaElement.setGroups(result.left().value());
1149         } else {
1150             if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1151                 return result.right().value();
1152             }
1153         }
1154         return JanusGraphOperationStatus.OK;
1155     }
1156
1157     private JanusGraphOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1158         List<CategoryDefinition> categories = new ArrayList<>();
1159         switch (componentV.getType()) {
1160             case RESOURCE:
1161                 return setResourceCategoryFromGraph(componentV, toscaElement);
1162             case SERVICE:
1163                 return setServiceCategoryFromGraph(componentV, toscaElement, categories);
1164             default:
1165                 log.debug("Not supported component type {} ", componentV.getType());
1166                 break;
1167         }
1168         return JanusGraphOperationStatus.OK;
1169     }
1170
1171     private JanusGraphOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement,
1172                                                                   List<CategoryDefinition> categories) {
1173         Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1174             .getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1175         if (childVertex.isRight()) {
1176             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(),
1177                 childVertex.right().value());
1178             return childVertex.right().value();
1179         }
1180         GraphVertex categoryV = childVertex.left().value();
1181         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
1182         CategoryDefinition category = new CategoryDefinition();
1183         category.setUniqueId(categoryV.getUniqueId());
1184         category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1185         category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1186         final Boolean useServiceSubstitutionForNestedServices = (Boolean) metadataProperties
1187             .get(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES);
1188         category.setUseServiceSubstitutionForNestedServices(
1189             useServiceSubstitutionForNestedServices == null ? false : useServiceSubstitutionForNestedServices);
1190         Type listTypeCat = new TypeToken<List<String>>() {
1191         }.getType();
1192         List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
1193         category.setIcons(iconsfromJsonCat);
1194         category.setModels((getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.MODEL.getProperty()), listTypeCat)));
1195         final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1196         }.getType();
1197         final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
1198             .fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
1199         category.setMetadataKeys(metadataKeysfromJsonCat);
1200         categories.add(category);
1201         toscaElement.setCategories(categories);
1202         return JanusGraphOperationStatus.OK;
1203     }
1204
1205     @SuppressWarnings("unchecked")
1206     private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
1207         TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
1208         Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson();
1209         topologyTemplate.setCompositions(json);
1210         return topologyTemplate;
1211     }
1212
1213     @Override
1214     public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
1215         Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView());
1216         if (nodeType.isRight()) {
1217             log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value());
1218             return nodeType;
1219         }
1220         JanusGraphOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex);
1221         if (status != JanusGraphOperationStatus.OK) {
1222             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1223         }
1224         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES);
1225         if (status != JanusGraphOperationStatus.OK) {
1226             log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
1227             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1228         }
1229         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES);
1230         if (status != JanusGraphOperationStatus.OK) {
1231             log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1232             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1233         }
1234         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1235         if (status != JanusGraphOperationStatus.OK) {
1236             log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1237             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1238         }
1239         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS);
1240         if (status != JanusGraphOperationStatus.OK) {
1241             log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1242             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1243         }
1244         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.POLICIES);
1245         if (status != JanusGraphOperationStatus.OK) {
1246             log.debug("Failed to disassociate policies for {} error {}", toscaElementVertex.getUniqueId(), status);
1247             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1248         }
1249         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS);
1250         if (status != JanusGraphOperationStatus.OK) {
1251             log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status);
1252             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1253         }
1254         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS);
1255         if (status != JanusGraphOperationStatus.OK) {
1256             log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1257             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1258         }
1259         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
1260         if (status != JanusGraphOperationStatus.OK) {
1261             log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
1262             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1263         }
1264         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
1265         if (status != JanusGraphOperationStatus.OK) {
1266             log.debug("Failed to disassociate capabilities properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1267             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1268         }
1269         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES);
1270         if (status != JanusGraphOperationStatus.OK) {
1271             log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status);
1272             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1273         }
1274         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
1275         if (status != JanusGraphOperationStatus.OK) {
1276             log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
1277             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1278         }
1279         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1280         if (status != JanusGraphOperationStatus.OK) {
1281             log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status);
1282             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1283         }
1284         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
1285         if (status != JanusGraphOperationStatus.OK) {
1286             log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1287             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1288         }
1289         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
1290         if (status != JanusGraphOperationStatus.OK) {
1291             log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1292             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1293         }
1294         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
1295         if (status != JanusGraphOperationStatus.OK) {
1296             log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1297             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1298         }
1299         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
1300         if (status != JanusGraphOperationStatus.OK) {
1301             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1302             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1303         }
1304         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
1305         if (status != JanusGraphOperationStatus.OK) {
1306             log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
1307             Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1308         }
1309         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE);
1310         if (status != JanusGraphOperationStatus.OK) {
1311             log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status);
1312             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1313         }
1314         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS);
1315         if (status != JanusGraphOperationStatus.OK) {
1316             log.debug("Failed to disassociate instance artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
1317             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1318         }
1319         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
1320         if (status != JanusGraphOperationStatus.OK) {
1321             log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
1322             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1323         }
1324         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
1325         if (status != JanusGraphOperationStatus.OK) {
1326             log.debug("Failed to disassociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
1327             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1328         }
1329         status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INTERFACES);
1330         if (status != JanusGraphOperationStatus.OK) {
1331             log.debug("Failed to disassociate instances interfaces for {} error {}", toscaElementVertex.getUniqueId(), status);
1332             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1333         }
1334         toscaElementVertex.getVertex().remove();
1335         log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
1336         return nodeType;
1337     }
1338
1339     @SuppressWarnings("unchecked")
1340     @Override
1341     public Either<TopologyTemplate, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
1342         return createTopologyTemplate((TopologyTemplate) toscaElement);
1343     }
1344
1345     @Override
1346     protected <T extends ToscaElement> JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
1347         return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement);
1348     }
1349
1350     @Override
1351     protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
1352         // Product isn't supported now!!
1353
1354         // TODO add for Product
1355         if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) {
1356             return validateServiceCategory(toscaElementToUpdate, elementV);
1357         } else {
1358             // Resource
1359             return validateResourceCategory(toscaElementToUpdate, elementV);
1360         }
1361     }
1362
1363     @Override
1364     protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) {
1365         // not relevant now for topology template
1366         return StorageOperationStatus.OK;
1367     }
1368
1369     @Override
1370     public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
1371         fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag);
1372     }
1373
1374     private <T extends ToscaElement> StorageOperationStatus validateServiceCategory(T toscaElementToUpdate, GraphVertex elementV) {
1375         StorageOperationStatus status = StorageOperationStatus.OK;
1376         List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
1377         CategoryDefinition newCategory = newCategoryList.get(0);
1378         Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1379             .getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1380         if (childVertex.isRight()) {
1381             log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(),
1382                 childVertex.right().value());
1383             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1384         }
1385         GraphVertex categoryV = childVertex.left().value();
1386         Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
1387         String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1388         String newCategoryName = newCategory.getName();
1389         if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
1390             // the category was changed
1391             Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation
1392                 .getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY);
1393             if (getCategoryVertex.isRight()) {
1394                 return getCategoryVertex.right().value();
1395             }
1396             GraphVertex newCategoryV = getCategoryVertex.left().value();
1397             status = moveCategoryEdge(elementV, newCategoryV);
1398             log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
1399         }
1400         return status;
1401     }
1402
1403     public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user,
1404                                                                                 DistributionStatusEnum distributionStatus) {
1405         Either<GraphVertex, StorageOperationStatus> result = null;
1406         String userId = user.getUserId();
1407         Either<GraphVertex, JanusGraphOperationStatus> getRes = findUserVertex(userId);
1408         GraphVertex userVertex = null;
1409         GraphVertex serviceVertex = null;
1410         if (getRes.isRight()) {
1411             JanusGraphOperationStatus status = getRes.right().value();
1412             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status);
1413             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1414         }
1415         if (result == null) {
1416             userVertex = getRes.left().value();
1417             getRes = janusGraphDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata);
1418             if (getRes.isRight()) {
1419                 JanusGraphOperationStatus status = getRes.right().value();
1420                 log.debug("Cannot find service {} in the graph. status is {}", uniqueId, status);
1421                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1422             }
1423         }
1424         if (result == null) {
1425             serviceVertex = getRes.left().value();
1426             Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name());
1427             if (edgeIterator.hasNext()) {
1428                 log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId,
1429                     EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
1430                 edgeIterator.next().remove();
1431             }
1432         }
1433         if (result == null) {
1434             JanusGraphOperationStatus status = janusGraphDao
1435                 .createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null);
1436             if (status != JanusGraphOperationStatus.OK) {
1437                 log.debug("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId,
1438                     EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
1439                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1440             }
1441         }
1442         if (result == null) {
1443             serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name());
1444             long lastUpdateDate = System.currentTimeMillis();
1445             serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1446             Either<GraphVertex, JanusGraphOperationStatus> updateRes = janusGraphDao.updateVertex(serviceVertex);
1447             if (updateRes.isRight()) {
1448                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
1449             }
1450         }
1451         if (result == null) {
1452             result = Either.left(serviceVertex);
1453         }
1454         return result;
1455     }
1456
1457     /**
1458      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
1459      *
1460      * @param componentId
1461      * @param instanceId
1462      * @param capabilityName
1463      * @param capabilityType
1464      * @param ownerId
1465      * @return
1466      */
1467     public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId,
1468                                                                                                                     String instanceId,
1469                                                                                                                     String capabilityName,
1470                                                                                                                     String capabilityType,
1471                                                                                                                     String ownerId) {
1472         Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null;
1473         Map<String, MapCapabilityProperty> mapPropertiesDataDefinition = null;
1474         Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId,
1475             ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse);
1476         if (componentByLabelAndId.isRight()) {
1477             result = Either.right(componentByLabelAndId.right().value());
1478         }
1479         if (componentByLabelAndId.isLeft()) {
1480             Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(),
1481                 EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
1482             if (getDataRes.isRight()) {
1483                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getDataRes.right().value()));
1484             } else {
1485                 mapPropertiesDataDefinition = getDataRes.left().value();
1486             }
1487         }
1488         if (isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)) {
1489             result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId,
1490                 mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
1491         }
1492         return result;
1493     }
1494
1495     public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId,
1496                                                                               MapCapabilityProperty instanceProperties) {
1497         return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
1498             instanceProperties, componentInstanceId);
1499     }
1500
1501     public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceId,
1502                                                                     MapInterfaceDataDefinition instanceInterfaces) {
1503         if (MapUtils.isNotEmpty(instanceInterfaces.getMapToscaDataDefinition())) {
1504             return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INTERFACES, instanceInterfaces,
1505                 componentInstanceId);
1506         }
1507         return StorageOperationStatus.OK;
1508     }
1509
1510
1511     public StorageOperationStatus updateComponentInterfaces(final String componentId, final MapInterfaceDataDefinition instanceInterfaces,
1512                                                             final String componentInterfaceUpdatedKey) {
1513         if (MapUtils.isNotEmpty(instanceInterfaces.getMapToscaDataDefinition())) {
1514             return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.INTERFACE_ARTIFACTS, instanceInterfaces,
1515                 componentInterfaceUpdatedKey);
1516         }
1517         return StorageOperationStatus.OK;
1518     }
1519
1520     private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> mapPropertiesDataDefinition) {
1521         return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && instanceId != null && mapPropertiesDataDefinition.get(instanceId) != null
1522             && MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
1523     }
1524
1525     private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType,
1526                                                                                       String ownerId,
1527                                                                                       Map<String, MapPropertiesDataDefinition> propertiesMap) {
1528         List<ComponentInstanceProperty> capPropsList = null;
1529         for (Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()) {
1530             if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) {
1531                 Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition();
1532                 if (capMap != null && !capMap.isEmpty()) {
1533                     capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList());
1534                     break;
1535                 }
1536             }
1537         }
1538         if (capPropsList == null) {
1539             capPropsList = new ArrayList<>();
1540         }
1541         return capPropsList;
1542     }
1543
1544     private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId,
1545                                            Entry<String, MapPropertiesDataDefinition> capProp) {
1546         if (capProp != null) {
1547             String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM);
1548             if (path.length < 4) {
1549                 log.debug("wrong key format for capabilty, key {}", capProp);
1550                 return false;
1551             }
1552             return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0]
1553                 .equals(instanceId);
1554         }
1555         return false;
1556     }
1557
1558     public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1559         fillPolicyDefinition(componentV, policyDefinition, counter);
1560         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition,
1561             JsonPresentationFields.UNIQUE_ID);
1562     }
1563
1564     public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List<PolicyDefinition> policies) {
1565         return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, JsonPresentationFields.UNIQUE_ID);
1566     }
1567
1568     public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) {
1569         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition,
1570             JsonPresentationFields.UNIQUE_ID);
1571     }
1572
1573     public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) {
1574         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions,
1575             JsonPresentationFields.UNIQUE_ID);
1576     }
1577
1578     public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) {
1579         return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
1580     }
1581
1582     public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) {
1583         return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition,
1584             JsonPresentationFields.CI_INVARIANT_NAME);
1585     }
1586
1587     private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
1588         String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME),
1589             policyDefinition.getPolicyTypeName(), counter);
1590         policyDefinition.setName(policyName);
1591         policyDefinition.setInvariantName(policyName);
1592         policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME));
1593         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName));
1594         policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1595         policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID());
1596     }
1597
1598     void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1599         if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) {
1600             GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
1601             if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) {
1602                 toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver
1603                     .revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement));
1604             }
1605             if (MapUtils.isNotEmpty(toscaElement.getGroups())) {
1606                 toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver
1607                     .revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement));
1608             }
1609             topologyTemplateOperation
1610                 .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
1611                     toscaElement.getCalculatedCapabilities());
1612             topologyTemplateOperation
1613                 .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
1614                     toscaElement.getCalculatedRequirements());
1615             topologyTemplateOperation
1616                 .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
1617                     toscaElement.getCalculatedCapabilitiesProperties());
1618         }
1619     }
1620
1621     public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
1622         if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) {
1623             GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
1624             if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) {
1625                 toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver
1626                     .updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(),
1627                         this::getOriginToscaElement));
1628             }
1629             if (MapUtils.isNotEmpty(toscaElement.getGroups())) {
1630                 toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver
1631                     .updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement));
1632             }
1633             topologyTemplateOperation
1634                 .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
1635                     toscaElement.getCalculatedCapabilities());
1636             topologyTemplateOperation
1637                 .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
1638                     toscaElement.getCalculatedRequirements());
1639             topologyTemplateOperation
1640                 .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
1641                     toscaElement.getCalculatedCapabilitiesProperties());
1642         }
1643     }
1644
1645     private ToscaElement getOriginToscaElement(ComponentInstanceDataDefinition instance) {
1646         log.debug("#getOriginToscaElement - origin name: {}", instance.getComponentName());
1647         ToscaElementTypeEnum elementType = detectToscaType(instance.getOriginType());
1648         Either<ToscaElement, StorageOperationStatus> getOriginRes;
1649         if (elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) {
1650             getOriginRes = this.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter());
1651         } else {
1652             getOriginRes = nodeTypeOperation.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter());
1653         }
1654         if (getOriginRes.isRight()) {
1655             log.debug("Failed to get an origin component with uniqueId {}", CapabilityRequirementNameResolver.getActualComponentUid(instance));
1656             throw new StorageException(getOriginRes.right().value());
1657         }
1658         return getOriginRes.left().value();
1659     }
1660
1661     private ToscaElementTypeEnum detectToscaType(OriginTypeEnum originType) {
1662         log.debug("#detectToscaType - type: {}", originType);
1663         if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.CP || originType == OriginTypeEnum.VL
1664             || originType == OriginTypeEnum.Configuration || originType == OriginTypeEnum.VFCMT) {
1665             return ToscaElementTypeEnum.NODE_TYPE;
1666         } else {
1667             return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE;
1668         }
1669     }
1670
1671     private ComponentParametersView getFilter() {
1672         ComponentParametersView filter = new ComponentParametersView();
1673         filter.setIgnoreCapabilities(false);
1674         filter.setIgnoreCapabiltyProperties(false);
1675         filter.setIgnoreRequirements(false);
1676         return filter;
1677     }
1678
1679     public void updateCapReqPropertiesOwnerId(String componentId, TopologyTemplate toscaElement) {
1680         GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
1681         updateCapOwnerId(toscaElement, componentId);
1682         updateReqOwnerId(toscaElement, componentId);
1683         updatePropertiesOwnerId(toscaElement, componentId);
1684         topologyTemplateOperation
1685             .updateFullToscaData(toscaElementV, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILITIES, toscaElement.getCapabilities());
1686         topologyTemplateOperation
1687             .updateFullToscaData(toscaElementV, EdgeLabelEnum.REQUIREMENTS, VertexTypeEnum.REQUIREMENTS, toscaElement.getRequirements());
1688         topologyTemplateOperation
1689             .updateFullToscaData(toscaElementV, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, toscaElement.getProperties());
1690     }
1691
1692     private void updateCapOwnerId(ToscaElement toscaElement, String ownerId) {
1693         if (MapUtils.isNotEmpty(toscaElement.getCapabilities())) {
1694             toscaElement.getCapabilities().values().stream().flatMap(listCapDef -> listCapDef.getListToscaDataDefinition().stream())
1695                 .forEach(capabilityDefinition -> capabilityDefinition.setOwnerId(ownerId));
1696         }
1697     }
1698
1699     private void updateReqOwnerId(ToscaElement toscaElement, String ownerId) {
1700         if (MapUtils.isNotEmpty(toscaElement.getRequirements())) {
1701             toscaElement.getRequirements().values().stream().flatMap(listReqDef -> listReqDef.getListToscaDataDefinition().stream())
1702                 .forEach(requirementDefinition -> requirementDefinition.setOwnerId(ownerId));
1703         }
1704     }
1705
1706     private void updatePropertiesOwnerId(ToscaElement toscaElement, String ownerId) {
1707         Map<String, PropertyDataDefinition> properties = toscaElement.getProperties();
1708         if (MapUtils.isNotEmpty(properties)) {
1709             properties.values().forEach(propertyDataDefinition -> propertyDataDefinition.setParentUniqueId(ownerId));
1710         }
1711     }
1712 }