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