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