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