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