Revert "Interface operation feature enhancements"
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / ToscaExportHandler.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
21 package org.openecomp.sdc.be.tosca;
22
23 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
24 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
25
26 import fj.data.Either;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.apache.commons.lang3.tuple.ImmutableTriple;
30 import org.apache.commons.lang3.tuple.Triple;
31 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
34 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
35 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
36 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
37 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
38 import org.openecomp.sdc.be.model.ArtifactDefinition;
39 import org.openecomp.sdc.be.model.CapabilityDefinition;
40 import org.openecomp.sdc.be.model.Component;
41 import org.openecomp.sdc.be.model.ComponentInstance;
42 import org.openecomp.sdc.be.model.ComponentInstanceInput;
43 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
44 import org.openecomp.sdc.be.model.ComponentParametersView;
45 import org.openecomp.sdc.be.model.DataTypeDefinition;
46 import org.openecomp.sdc.be.model.GroupInstance;
47 import org.openecomp.sdc.be.model.InputDefinition;
48 import org.openecomp.sdc.be.model.PropertyDefinition;
49 import org.openecomp.sdc.be.model.RelationshipInfo;
50 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
51 import org.openecomp.sdc.be.model.RequirementDefinition;
52 import org.openecomp.sdc.be.model.Resource;
53 import org.openecomp.sdc.be.model.Service;
54 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
55 import org.openecomp.sdc.be.model.category.CategoryDefinition;
56 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
57 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
58 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
59 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
60 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
61 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
62 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
63 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
64 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
65 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
66 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
67 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
68 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
69 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
70 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
71 import org.openecomp.sdc.be.tosca.utils.InputConverter;
72 import org.openecomp.sdc.common.log.wrappers.Logger;
73 import org.springframework.beans.factory.annotation.Autowired;
74 import org.yaml.snakeyaml.DumperOptions;
75 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
76 import org.yaml.snakeyaml.Yaml;
77 import org.yaml.snakeyaml.introspector.BeanAccess;
78 import org.yaml.snakeyaml.introspector.Property;
79 import org.yaml.snakeyaml.introspector.PropertyUtils;
80 import org.yaml.snakeyaml.nodes.MappingNode;
81 import org.yaml.snakeyaml.nodes.Node;
82 import org.yaml.snakeyaml.nodes.NodeTuple;
83 import org.yaml.snakeyaml.nodes.Tag;
84 import org.yaml.snakeyaml.representer.Represent;
85 import org.yaml.snakeyaml.representer.Representer;
86
87 import java.beans.IntrospectionException;
88 import java.util.ArrayList;
89 import java.util.Collection;
90 import java.util.HashMap;
91 import java.util.LinkedHashSet;
92 import java.util.List;
93 import java.util.Map;
94 import java.util.Map.Entry;
95 import java.util.Optional;
96 import java.util.Set;
97 import java.util.function.Supplier;
98 import java.util.stream.Collectors;
99
100 import static org.apache.commons.collections.CollectionUtils.isEmpty;
101 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
102 import static org.apache.commons.collections.MapUtils.isNotEmpty;
103 import static org.apache.commons.lang.StringUtils.isNotEmpty;
104
105 @org.springframework.stereotype.Component("tosca-export-handler")
106 public class ToscaExportHandler {
107
108     private ApplicationDataTypeCache dataTypeCache;
109     private ToscaOperationFacade toscaOperationFacade;  
110     private CapabilityRequirementConverter capabilityRequirementConverter;
111     private PolicyExportParser policyExportParser;
112     private GroupExportParser groupExportParser;
113     private PropertyConvertor propertyConvertor;
114     private InputConverter inputConverter;
115
116     @Autowired 
117     public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
118                               CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
119                               GroupExportParser groupExportParser, InputConverter inputConverter) {
120             this.dataTypeCache = dataTypeCache;
121             this.toscaOperationFacade = toscaOperationFacade;
122             this.capabilityRequirementConverter = capabilityRequirementConverter;
123             this.policyExportParser = policyExportParser;
124             this.groupExportParser = groupExportParser;
125             this.propertyConvertor = PropertyConvertor.getInstance();
126             this.inputConverter =  inputConverter;
127       }
128
129
130     private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
131
132     public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
133     private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
134     private static final String IMPORTS_FILE_KEY = "file";
135     private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
136     public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
137     private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
138     private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
139     private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
140             .getConfigurationManager().getConfiguration().getDefaultImports();
141
142     public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
143
144         Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
145         if (toscaTemplateRes.isRight()) {
146             return Either.right(toscaTemplateRes.right().value());
147         }
148
149         ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
150         ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
151         return Either.left(toscaRepresentation);
152     }
153
154     public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
155                                                                             boolean isAssociatedResourceComponent) {
156         if (null == DEFAULT_IMPORTS) {
157             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
158             return Either.right(ToscaError.GENERAL_ERROR);
159         }
160
161         ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
162         toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
163         Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
164         Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
165                 toscaTemplate, nodeTypes, isAssociatedResourceComponent);
166         if (toscaTemplateRes.isRight()) {
167             return Either.right(toscaTemplateRes.right().value());
168         }
169
170         toscaTemplate = toscaTemplateRes.left().value();
171         ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
172         return Either.left(toscaRepresentation);
173     }
174
175     public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
176         CustomRepresenter representer = new CustomRepresenter();
177         DumperOptions options = new DumperOptions();
178         options.setAllowReadOnlyProperties(false);
179         options.setPrettyFlow(true);
180
181         options.setDefaultFlowStyle(FlowStyle.FLOW);
182         options.setCanonical(false);
183
184         representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
185
186         representer.setPropertyUtils(new UnsortedPropertyUtils());
187         Yaml yaml = new Yaml(representer, options);
188
189         String yamlAsString = yaml.dumpAsMap(toscaTemplate);
190
191         StringBuilder sb = new StringBuilder();
192         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
193         sb.append(yamlAsString);
194         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
195
196         ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
197         toscaRepresentation.setMainYaml(sb.toString());
198         toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
199
200         return toscaRepresentation;
201     }
202
203     public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
204         ToscaTemplate toscaTemplate = new ToscaTemplate(null);
205         Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
206                 toscaTemplate);
207         if (fillImports.isRight()) {
208             return Either.right(fillImports.right().value());
209         }
210         return Either.left(fillImports.left().value().left);
211     }
212
213     private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
214         if (null == DEFAULT_IMPORTS) {
215             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
216             return Either.right(ToscaError.GENERAL_ERROR);
217         }
218
219         log.trace("start tosca export for {}", component.getUniqueId());
220         ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
221
222         toscaTemplate.setMetadata(convertMetadata(component));
223         toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
224         Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
225         if (ModelConverter.isAtomicComponent(component)) {
226             log.trace("convert component as node type");
227             return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
228         } else {
229             log.trace("convert component as topology template");
230             return convertToscaTemplate(component, toscaTemplate);
231         }
232
233     }
234
235     private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
236
237         Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
238                 toscaNode);
239         if (importsRes.isRight()) {
240             return Either.right(importsRes.right().value());
241         }
242         toscaNode = importsRes.left().value().left;
243         Map<String, Component> componentCache = importsRes.left().value().right;
244         Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
245         if (nodeTypesMapEither.isRight()) {
246             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
247                     nodeTypesMapEither.right().value());
248             return Either.right(nodeTypesMapEither.right().value());
249         }
250         Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
251         if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
252             toscaNode.setNode_types(nodeTypesMap);
253         }
254
255
256         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
257         if (dataTypesEither.isRight()) {
258             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
259             return Either.right(ToscaError.GENERAL_ERROR);
260         }
261         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
262         ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
263         List<InputDefinition> inputDef = component.getInputs();
264         Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
265
266         if (!inputs.isEmpty()) {
267             topologyTemplate.setInputs(inputs);
268         }
269
270         List<ComponentInstance> componentInstances = component.getComponentInstances();
271         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
272                 .getComponentInstancesProperties();
273         if (componentInstances != null && !componentInstances.isEmpty()) {
274
275             Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
276                     componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
277             if (nodeTemplates.isRight()) {
278                 return Either.right(nodeTemplates.right().value());
279             }
280             log.debug("node templates converted");
281
282             topologyTemplate.setNode_templates(nodeTemplates.left().value());
283         }
284         
285         
286         addGroupsToTopologyTemplate(component, topologyTemplate);
287             
288         try {
289              addPoliciesToTopologyTemplate(component, topologyTemplate);
290             } catch (SdcResourceNotFoundException e) {
291                   log.debug("Fail to add policies to topology template:",e);
292                   Either.right(ToscaError.GENERAL_ERROR);
293             }
294             
295             
296         SubstitutionMapping substitutionMapping = new SubstitutionMapping();
297         String toscaResourceName;
298         switch (component.getComponentType()) {
299         case RESOURCE:
300             toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
301                     .getMetadataDataDefinition()).getToscaResourceName();
302             break;
303         case SERVICE:
304             toscaResourceName = SERVICE_NODE_TYPE_PREFIX
305                     + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
306             break;
307         default:
308             log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
309             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
310         }
311         substitutionMapping.setNode_type(toscaResourceName);
312
313         Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
314         if (capabilities.isRight()) {
315             return Either.right(capabilities.right().value());
316         }
317         substitutionMapping = capabilities.left().value();
318
319         Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
320                 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
321         if (requirements.isRight()) {
322             return Either.right(requirements.right().value());
323         }
324         substitutionMapping = requirements.left().value();
325
326         topologyTemplate.setSubstitution_mappings(substitutionMapping);
327
328         toscaNode.setTopology_template(topologyTemplate);
329         return Either.left(toscaNode);
330     }
331
332       private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
333             
334             
335             Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
336             if(groups!= null) {
337                   topologyTemplate.addGroups(groups);
338             }
339       }
340
341       private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
342                   throws SdcResourceNotFoundException {
343             Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
344             if(policies!= null) {
345                   topologyTemplate.addPolicies(policies);
346             }
347       }
348
349     private ToscaMetadata convertMetadata(Component component) {
350         return convertMetadata(component, false, null);
351     }
352
353     private ToscaMetadata convertMetadata(Component component, boolean isInstance,
354             ComponentInstance componentInstance) {
355         ToscaMetadata toscaMetadata = new ToscaMetadata();
356         toscaMetadata.setInvariantUUID(component.getInvariantUUID());
357         toscaMetadata.setUUID(component.getUUID());
358         toscaMetadata.setDescription(component.getDescription());
359         toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
360
361         List<CategoryDefinition> categories = component.getCategories();
362         CategoryDefinition categoryDefinition = categories.get(0);
363         toscaMetadata.setCategory(categoryDefinition.getName());
364
365         if (isInstance) {
366             toscaMetadata.setVersion(component.getVersion());
367             toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
368             if (componentInstance.getSourceModelInvariant() != null
369                     && !componentInstance.getSourceModelInvariant().isEmpty()) {
370                 toscaMetadata.setVersion(componentInstance.getComponentVersion());
371                 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
372                 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
373                 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
374                 toscaMetadata.setName(
375                         componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
376                 toscaMetadata.setDescription(componentInstance.getDescription());
377             }
378
379         }
380         switch (component.getComponentType()) {
381         case RESOURCE:
382             Resource resource = (Resource) component;
383
384             if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
385                 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
386             } else {
387                 toscaMetadata.setType(resource.getResourceType().name());
388             }
389             toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
390             toscaMetadata.setResourceVendor(resource.getVendorName());
391             toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
392             toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
393             break;
394         case SERVICE:
395             Service service = (Service) component;
396             toscaMetadata.setType(component.getComponentType().getValue());
397             toscaMetadata.setServiceType(service.getServiceType());
398             toscaMetadata.setServiceRole(service.getServiceRole());
399             toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
400             resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
401             if (!isInstance) {
402                 // DE268546
403                 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
404                 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
405                 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
406             }
407             break;
408         default:
409             log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
410         }
411         return toscaMetadata;
412     }
413
414       private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
415             if (service.getInstantiationType() != null) {
416                         toscaMetadata.setInstantiationType(service.getInstantiationType());
417             }
418             else {
419                         toscaMetadata.setInstantiationType(StringUtils.EMPTY);
420             }
421       }
422
423     private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
424             ToscaTemplate toscaTemplate) {
425
426         if (null == DEFAULT_IMPORTS) {
427             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
428             return Either.right(ToscaError.GENERAL_ERROR);
429         }
430         Map<String, Component> componentCache = new HashMap<>();
431
432         if (!ModelConverter.isAtomicComponent(component)) {
433             List<ComponentInstance> componentInstances = component.getComponentInstances();
434             if (componentInstances != null && !componentInstances.isEmpty()) {
435
436                 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
437                         ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
438
439                 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
440
441                 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
442                 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
443
444                 Map<String, Map<String, String>> importsListMember = new HashMap<>();
445                 Map<String, String> interfaceFiles = new HashMap<>();
446                 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
447                 StringBuilder keyNameBuilder = new StringBuilder();
448                 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
449                 keyNameBuilder.append("-");
450                 keyNameBuilder.append(component.getName());
451                 keyNameBuilder.append("-interface");
452                 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
453                 additionalImports.add(importsListMember);
454
455                 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
456                 toscaTemplate.setDependencies(dependecies);
457                 toscaTemplate.setImports(additionalImports);
458             }
459         } else {
460             log.debug("currently imports supported for VF and service only");
461         }
462         return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
463     }
464
465     private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
466             List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
467         Map<String, String> files = new HashMap<>();
468         Map<String, Map<String, String>> importsListMember = new HashMap<>();
469         StringBuilder keyNameBuilder;
470
471         Component componentRI = componentCache.get(ci.getComponentUid());
472         if (componentRI == null) {
473             // all resource must be only once!
474             Either<Component, StorageOperationStatus> resource = toscaOperationFacade
475                     .getToscaFullElement(ci.getComponentUid());
476             if ((resource.isRight()) && (log.isDebugEnabled())) {
477                 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
478                 return ;
479             }
480
481             Component fetchedComponent = resource.left().value();
482             componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
483
484             if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
485                 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
486                         .getToscaFullElement(ci.getSourceModelUid());
487                 if (sourceService.isRight() && (log.isDebugEnabled())) {
488                     log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
489                 }
490                 Component fetchedSource = sourceService.left().value();
491                 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
492             }
493
494             componentRI = fetchedComponent;
495
496             Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
497             ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
498             if (artifactDefinition != null) {
499                 String artifactName = artifactDefinition.getArtifactName();
500                 files.put(IMPORTS_FILE_KEY, artifactName);
501                 keyNameBuilder = new StringBuilder();
502                 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
503                 keyNameBuilder.append("-");
504                 keyNameBuilder.append(ci.getComponentName());
505                 importsListMember.put(keyNameBuilder.toString(), files);
506                 imports.add(importsListMember);
507                 dependecies.add(new ImmutableTriple<>(artifactName,
508                         artifactDefinition.getEsId(), fetchedComponent));
509
510                 if (!ModelConverter.isAtomicComponent(componentRI)) {
511                     importsListMember = new HashMap<>();
512                     Map<String, String> interfaceFiles = new HashMap<>();
513                     interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
514                     keyNameBuilder.append("-interface");
515                     importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
516                     imports.add(importsListMember);
517                 }
518             }
519         }
520     }
521
522     public static String getInterfaceFilename(String artifactName) {
523         return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
524     }
525
526     private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
527             Map<String, ToscaNodeType> nodeTypes) {
528         log.debug("start convert node type for {}", component.getUniqueId());
529         ToscaNodeType toscaNodeType = createNodeType(component);
530
531         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
532         if (dataTypesEither.isRight()) {
533             log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
534             return Either.right(ToscaError.GENERAL_ERROR);
535         }
536
537         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
538         Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
539                 dataTypes);
540         if (properties.isRight()) {
541             return Either.right(properties.right().value());
542         }
543         toscaNodeType = properties.left().value();
544         log.debug("Properties converted for {}", component.getUniqueId());
545
546         // Extracted to method for code reuse
547         return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
548     }
549
550     private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
551                                                                        Component component, ToscaTemplate toscaNode,
552                                                                        Map<String, ToscaNodeType> nodeTypes,
553                                                                        boolean isAssociatedResourceComponent) {
554         log.debug("start convert node type for {}", component.getUniqueId());
555         ToscaNodeType toscaNodeType = createNodeType(component);
556         toscaNode.setInterface_types(addInterfaceTypeElement(component));
557         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
558         if (dataTypesEither.isRight()) {
559             log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
560             return Either.right(ToscaError.GENERAL_ERROR);
561         }
562
563         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
564
565         List<InputDefinition> inputDef = component.getInputs();
566         Map<String, ToscaProperty> inputs = new HashMap<>();
567         addInterfaceDefinitionElement(component, toscaNodeType, isAssociatedResourceComponent);
568         if (inputDef != null) {
569             inputDef.forEach(i -> {
570                 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
571                 inputs.put(i.getName(), property);
572             });
573             if (!inputs.isEmpty()) {
574                 toscaNodeType.setProperties(inputs);
575             }
576         }
577         return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
578     }
579
580     private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
581             Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
582             Map<String, DataTypeDefinition> dataTypes) {
583         Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
584         if (capabilities.isRight()) {
585             return Either.right(capabilities.right().value());
586         }
587         toscaNodeType = capabilities.left().value();
588         log.debug("Capabilities converted for {}", component.getUniqueId());
589
590         Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
591                 toscaNodeType);
592         if (requirements.isRight()) {
593             return Either.right(requirements.right().value());
594         }
595         toscaNodeType = requirements.left().value();
596         log.debug("Requirements converted for {}", component.getUniqueId());
597
598         String toscaResourceName;
599         switch (component.getComponentType()) {
600         case RESOURCE:
601             toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
602                     .getMetadataDataDefinition()).getToscaResourceName();
603             break;
604         case SERVICE:
605             toscaResourceName = SERVICE_NODE_TYPE_PREFIX
606                     + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
607             break;
608         default:
609             log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
610             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
611         }
612
613         nodeTypes.put(toscaResourceName, toscaNodeType);
614         toscaNode.setNode_types(nodeTypes);
615         log.debug("finish convert node type for {}", component.getUniqueId());
616         return Either.left(toscaNode);
617     }
618
619     private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
620             List<ComponentInstance> componentInstances,
621             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
622             Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
623             ToscaTopolgyTemplate topologyTemplate) {
624
625         Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
626         log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
627                 component.getComponentType());
628         Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
629         Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
630
631         Map<String, ToscaGroupTemplate> groupsMap = null;
632         for (ComponentInstance componentInstance : componentInstances) {
633             ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
634             nodeTemplate.setType(componentInstance.getToscaComponentName());
635
636             Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
637                     .getOriginComponent(componentCache, componentInstance);
638             if (originComponentRes.isRight()) {
639                 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
640                 break;
641             }
642             Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
643                     componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
644                     originComponentRes.left().value(), componentCache);
645             if (requirements.isRight()) {
646                 convertNodeTemplatesRes = Either.right(requirements.right().value());
647                 break;
648             }
649             String instanceUniqueId = componentInstance.getUniqueId();
650             log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
651
652             nodeTemplate = requirements.left().value();
653
654             Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
655
656             if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
657                 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
658                 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
659             } else {
660                 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
661             }
662
663             Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
664                     .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
665             if (capabilities.isRight()) {
666                 convertNodeTemplatesRes = Either.right(capabilities.right().value());
667                 break;
668             }
669             log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
670
671             nodeTemplate = capabilities.left().value();
672             Map<String, Object> props = new HashMap<>();
673
674             if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
675                 // Adds the properties of parent component to map
676                 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
677             }
678
679             if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
680                 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
681                         instanceUniqueId, props);
682             }
683
684             if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
685                 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
686                         props);
687             }
688             if (!props.isEmpty()) {
689                 nodeTemplate.setProperties(props);
690             }
691
692             List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
693             if (groupInstances != null) {
694                 if (groupsMap == null) {
695                     groupsMap = new HashMap<>();
696                 }
697                 for (GroupInstance groupInst : groupInstances) {
698                     boolean addToTosca = true;
699
700                     List<String> artifacts = groupInst.getArtifacts();
701                     if (artifacts == null || artifacts.isEmpty()) {
702                         addToTosca = false;
703                     }
704
705                     if (addToTosca) {
706                         ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
707                         groupsMap.put(groupInst.getName(), toscaGroup);
708                     }
709                 }
710             }
711
712             nodeTemplates.put(componentInstance.getName(), nodeTemplate);
713         }
714         if (groupsMap != null) {
715             log.debug("instance groups added");
716             topologyTemplate.addGroups(groupsMap);
717         }
718         if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
719             log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
720                     component.getName());
721             ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
722             log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
723                     component.getName());
724         }
725         if (convertNodeTemplatesRes == null) {
726             convertNodeTemplatesRes = Either.left(nodeTemplates);
727         }
728         log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
729                 component.getComponentType());
730         return convertNodeTemplatesRes;
731     }
732
733     private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
734                                             Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
735                                             String instanceUniqueId, Map<String, Object> props) {
736
737         List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
738         if (instanceInputsList != null) {
739             instanceInputsList.forEach(input -> {
740
741                 Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
742                         ? input.getValue() : input.getDefaultValue();
743                         propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
744             });
745         }
746     }
747
748     private void addPropertiesOfComponentInstance(
749             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
750             Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
751             Map<String, Object> props) {
752
753         if (isNotEmpty(componentInstancesProperties)) {
754             componentInstancesProperties.get(instanceUniqueId)
755                     // Converts and adds each value to property map
756                     .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
757                             prop::getValue));
758         }
759     }
760
761     private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
762                                                 Component componentOfInstance, Map<String, Object> props) {
763
764         List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
765         if (isNotEmpty(componentProperties)) {
766             componentProperties.stream()
767                     // Filters out properties with empty default values
768                     .filter(prop -> isNotEmpty(prop.getDefaultValue()))
769                     // Converts and adds each value to property map
770                     .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
771                             prop::getDefaultValue));
772         }
773     }
774
775     private ToscaNodeType createNodeType(Component component) {
776         ToscaNodeType toscaNodeType = new ToscaNodeType();
777         if (ModelConverter.isAtomicComponent(component)) {
778             if (((Resource) component).getDerivedFrom() != null) {
779                 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
780             }
781             toscaNodeType.setDescription(component.getDescription());
782         } else {
783             String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
784                     : "tosca.nodes.Root";
785             toscaNodeType.setDerived_from(derivedFrom);
786         }
787         return toscaNodeType;
788     }
789
790     private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container  ) {
791
792         Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
793         Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
794
795         List<ComponentInstance> componentInstances = container.getComponentInstances();
796
797         if (componentInstances == null || componentInstances.isEmpty()) {
798             return res;
799         }
800         Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
801         List<ComponentInstance> proxyInst = componentInstances.stream()
802                 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
803                 .collect(Collectors.toList());
804         if (proxyInst != null && !proxyInst.isEmpty()) {
805             for (ComponentInstance inst : proxyInst) {
806                 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
807             }
808         }
809
810         if (serviceProxyInstanceList.isEmpty()) {
811             return res;
812         }
813         ComponentParametersView filter = new ComponentParametersView(true);
814         filter.setIgnoreCapabilities(false);
815         filter.setIgnoreComponentInstances(false);
816         Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
817                 .getLatestByName("serviceProxy");
818         if (serviceProxyOrigin.isRight()) {
819             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
820                     serviceProxyOrigin.right().value());
821             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
822         }
823         Component origComponent = serviceProxyOrigin.left().value();
824
825         for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
826             Component serviceComponent = null;
827             ComponentParametersView componentParametersView = new ComponentParametersView();
828             componentParametersView.disableAll();
829             componentParametersView.setIgnoreCategories(false);
830             Either<Component, StorageOperationStatus> service = toscaOperationFacade
831                     .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
832             if (service.isRight()) {
833                 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(),  entryProxy.getValue().getName());
834             } else {
835                 serviceComponent = service.left().value();
836             }
837
838             ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
839             nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
840         }
841
842         return Either.left(nodeTypesMap);
843     }
844
845     private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
846             ComponentInstance instance) {
847         ToscaNodeType toscaNodeType = new ToscaNodeType();
848         String derivedFrom = ((Resource) origComponent).getToscaResourceName();
849
850         toscaNodeType.setDerived_from(derivedFrom);
851         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
852         if (dataTypesEither.isRight()) {
853             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
854         }
855         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
856         Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
857                 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
858
859         toscaNodeType.setCapabilities(capabilities);
860
861         return toscaNodeType;
862     }
863
864     private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
865             ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
866             ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
867
868         List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
869         if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
870             log.debug("Failed to convert component instance requirements for the component instance {}. ",
871                     componentInstance.getName());
872             return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
873         }
874         if (!toscaRequirements.isEmpty()) {
875             nodeTypeTemplate.setRequirements(toscaRequirements);
876         }
877         log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
878         return Either.left(nodeTypeTemplate);
879     }
880
881     private boolean addRequirements(Component component, ComponentInstance componentInstance,
882             List<RequirementCapabilityRelDef> relations, Component originComponent,
883             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
884         List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
885                 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
886         return isEmpty(filteredRelations) ||
887                 filteredRelations.stream()
888                         .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
889     }
890
891     private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
892             List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
893             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
894
895         boolean result = true;
896         Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
897         RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
898         Either<Component, StorageOperationStatus> getOriginRes = null;
899         Optional<RequirementDefinition> reqOpt = Optional.empty();
900         Component toOriginComponent = null;
901         Optional<CapabilityDefinition> capOpt = Optional.empty();
902
903         ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
904                 .findFirst().orElse(null);
905         if (toInstance == null) {
906             log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
907                     rel.getToNode());
908             result = false;
909         }
910         if (result) {
911             reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
912             if (!reqOpt.isPresent()) {
913                 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
914                         reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
915                 result = false;
916             }
917         }
918         if (result) {
919             ComponentParametersView filter = new ComponentParametersView(true);
920             filter.setIgnoreComponentInstances(false);
921             filter.setIgnoreCapabilities(false);
922             filter.setIgnoreGroups(false);
923             getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
924             if (getOriginRes.isRight()) {
925                 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
926                         reqOpt.get().getName(), toInstance.getActualComponentUid());
927                 result = false;
928             }
929         }
930         if (result) {
931             toOriginComponent = getOriginRes.left().value();
932             capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
933                     .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
934             if (!capOpt.isPresent()) {
935                 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
936                 if(!capOpt.isPresent()){
937                 result = false;
938                 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
939                         reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
940                 }
941             }
942         }
943         if (result) {
944             result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
945                     reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
946         }
947         return result;
948     }
949
950     private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
951         return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
952     }
953
954     private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
955         Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
956         if (!cap.isPresent()) {
957             log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
958         }
959         return cap;
960     }
961
962     private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
963         List<String> reducedPath = capability.getPath();
964         if(capability.getOwnerId() !=null){
965             reducedPath =   capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
966         }
967         Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
968                 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
969         if (buildCapNameRes.isRight()) {
970             log.debug(
971                     "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
972                     reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
973             return false;
974         }
975         Either<String, Boolean> buildReqNameRes  = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
976                 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
977         if (buildReqNameRes.isRight()) {
978             log.debug(
979                     "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
980                     reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
981             return false;
982         }
983         ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
984         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
985         toscaRequirement.setNode(toInstance.getName());
986         toscaRequirement.setCapability(buildCapNameRes.left().value());
987         toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
988         toscaRequirements.add(toscaReqMap);
989         return true;
990     }
991
992     private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair,  String fromInstanceId) {
993         for(List<RequirementDefinition> reqList: reqMap.values()){
994             Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
995             if(reqOpt.isPresent()){
996                 return reqOpt;
997             }
998         }
999         return Optional.empty();
1000     }
1001
1002     /**
1003      * Allows detecting the requirement belonging to the received relationship
1004      * The detection logic is: A requirement belongs to a relationship IF 1.The
1005      * name of the requirement equals to the "requirement" field of the
1006      * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1007      * requirement equals to requirementOwnerId of the relation OR uniqueId of
1008      * toInstance equals to capabilityOwnerId of the relation
1009      */
1010     private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1011         if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1012             log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}",
1013                     requirement.getName(), reqAndRelationshipPair.getRequirement());
1014             return false;
1015         }
1016         return ModelConverter.isAtomicComponent(originComponent) ||
1017                 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1018     }
1019
1020     private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1021         return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1022     }
1023
1024     private boolean isCvfc(Component component) {
1025         return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1026                 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1027     }
1028
1029     private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1030             SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1031
1032         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1033         Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1034                 .convertSubstitutionMappingCapabilities(componentCache, component);
1035         if (toscaCapabilitiesRes.isRight()) {
1036             result = Either.right(toscaCapabilitiesRes.right().value());
1037             log.debug("Failed convert capabilities for the component {}. ", component.getName());
1038         } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1039             substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1040             log.debug("Finish convert capabilities for the component {}. ", component.getName());
1041         }
1042         log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1043         return result;
1044     }
1045
1046     private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1047             Map<String, DataTypeDefinition> dataTypes) {
1048         Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1049                 dataTypes);
1050         if (!toscaCapabilities.isEmpty()) {
1051             nodeType.setCapabilities(toscaCapabilities);
1052         }
1053         log.debug("Finish convert Capabilities for node type");
1054
1055         return Either.left(nodeType);
1056     }
1057
1058     private static class CustomRepresenter extends Representer {
1059         public CustomRepresenter() {
1060             super();
1061             // null representer is exceptional and it is stored as an instance
1062             // variable.
1063             this.nullRepresenter = new RepresentNull();
1064
1065         }
1066
1067         @Override
1068         protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1069                 Tag customTag) {
1070             if (propertyValue == null) {
1071                 return null;
1072             } else {
1073                 // skip not relevant for Tosca property
1074                 if ("dependencies".equals(property.getName())) {
1075                     return null;
1076                 }
1077                 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1078
1079                 return "_defaultp_".equals(property.getName())
1080                         ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1081             }
1082         }
1083
1084         @Override
1085         protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1086             // remove the bean type from the output yaml (!! ...)
1087             if (!classTags.containsKey(javaBean.getClass())) {
1088                 addClassTag(javaBean.getClass(), Tag.MAP);
1089             }
1090
1091             return super.representJavaBean(properties, javaBean);
1092         }
1093
1094         private class RepresentNull implements Represent {
1095             @Override
1096             public Node representData(Object data) {
1097                 // possible values are here http://yaml.org/type/null.html
1098                 return representScalar(Tag.NULL, "");
1099             }
1100         }
1101     }
1102
1103     private static class UnsortedPropertyUtils extends PropertyUtils {
1104         @Override
1105         protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1106                 throws IntrospectionException {
1107             Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1108             return new LinkedHashSet<>(fields);
1109         }
1110     }
1111
1112 }
1113