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