Interface operation support for service - BE
[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         addInterfaceDefinitionElement(component, toscaNodeType);
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             }
573         }
574         return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
575     }
576
577     private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
578             Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
579             Map<String, DataTypeDefinition> dataTypes) {
580         Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
581         if (capabilities.isRight()) {
582             return Either.right(capabilities.right().value());
583         }
584         toscaNodeType = capabilities.left().value();
585         log.debug("Capabilities converted for {}", component.getUniqueId());
586
587         Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
588                 toscaNodeType);
589         if (requirements.isRight()) {
590             return Either.right(requirements.right().value());
591         }
592         toscaNodeType = requirements.left().value();
593         log.debug("Requirements converted for {}", component.getUniqueId());
594
595         String toscaResourceName;
596         switch (component.getComponentType()) {
597         case RESOURCE:
598             toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
599                     .getMetadataDataDefinition()).getToscaResourceName();
600             break;
601         case SERVICE:
602             toscaResourceName = SERVICE_NODE_TYPE_PREFIX
603                     + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
604             break;
605         default:
606             log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
607             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
608         }
609
610         nodeTypes.put(toscaResourceName, toscaNodeType);
611         toscaNode.setNode_types(nodeTypes);
612         log.debug("finish convert node type for {}", component.getUniqueId());
613         return Either.left(toscaNode);
614     }
615
616     private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
617             List<ComponentInstance> componentInstances,
618             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
619             Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
620             ToscaTopolgyTemplate topologyTemplate) {
621
622         Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
623         log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
624                 component.getComponentType());
625         Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
626         Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
627
628         Map<String, ToscaGroupTemplate> groupsMap = null;
629         for (ComponentInstance componentInstance : componentInstances) {
630             ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
631             nodeTemplate.setType(componentInstance.getToscaComponentName());
632
633             Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
634                     .getOriginComponent(componentCache, componentInstance);
635             if (originComponentRes.isRight()) {
636                 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
637                 break;
638             }
639             Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
640                     componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
641                     originComponentRes.left().value(), componentCache);
642             if (requirements.isRight()) {
643                 convertNodeTemplatesRes = Either.right(requirements.right().value());
644                 break;
645             }
646             String instanceUniqueId = componentInstance.getUniqueId();
647             log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
648
649             nodeTemplate = requirements.left().value();
650
651             Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
652
653             if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
654                 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
655                 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
656             } else {
657                 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
658             }
659
660             Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
661                     .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
662             if (capabilities.isRight()) {
663                 convertNodeTemplatesRes = Either.right(capabilities.right().value());
664                 break;
665             }
666             log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
667
668             nodeTemplate = capabilities.left().value();
669             Map<String, Object> props = new HashMap<>();
670
671             if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
672                 // Adds the properties of parent component to map
673                 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
674             }
675
676             if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
677                 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
678                         instanceUniqueId, props);
679             }
680
681             if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
682                 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
683                         props);
684             }
685             if (!props.isEmpty()) {
686                 nodeTemplate.setProperties(props);
687             }
688
689             List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
690             if (groupInstances != null) {
691                 if (groupsMap == null) {
692                     groupsMap = new HashMap<>();
693                 }
694                 for (GroupInstance groupInst : groupInstances) {
695                     boolean addToTosca = true;
696
697                     List<String> artifacts = groupInst.getArtifacts();
698                     if (artifacts == null || artifacts.isEmpty()) {
699                         addToTosca = false;
700                     }
701
702                     if (addToTosca) {
703                         ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
704                         groupsMap.put(groupInst.getName(), toscaGroup);
705                     }
706                 }
707             }
708
709             nodeTemplates.put(componentInstance.getName(), nodeTemplate);
710         }
711         if (groupsMap != null) {
712             log.debug("instance groups added");
713             topologyTemplate.addGroups(groupsMap);
714         }
715         if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
716             log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
717                     component.getName());
718             ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
719             log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
720                     component.getName());
721         }
722         if (convertNodeTemplatesRes == null) {
723             convertNodeTemplatesRes = Either.left(nodeTemplates);
724         }
725         log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
726                 component.getComponentType());
727         return convertNodeTemplatesRes;
728     }
729
730     private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
731                                             Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
732                                             String instanceUniqueId, Map<String, Object> props) {
733
734         List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
735         if (instanceInputsList != null) {
736             instanceInputsList.forEach(input -> {
737
738                 Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
739                         ? input.getValue() : input.getDefaultValue();
740                         propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
741             });
742         }
743     }
744
745     private void addPropertiesOfComponentInstance(
746             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
747             Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
748             Map<String, Object> props) {
749
750         if (isNotEmpty(componentInstancesProperties)) {
751             componentInstancesProperties.get(instanceUniqueId)
752                     // Converts and adds each value to property map
753                     .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
754                             prop::getValue));
755         }
756     }
757
758     private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
759                                                 Component componentOfInstance, Map<String, Object> props) {
760
761         List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
762         if (isNotEmpty(componentProperties)) {
763             componentProperties.stream()
764                     // Filters out properties with empty default values
765                     .filter(prop -> isNotEmpty(prop.getDefaultValue()))
766                     // Converts and adds each value to property map
767                     .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
768                             prop::getDefaultValue));
769         }
770     }
771
772     private ToscaNodeType createNodeType(Component component) {
773         ToscaNodeType toscaNodeType = new ToscaNodeType();
774         if (ModelConverter.isAtomicComponent(component)) {
775             if (((Resource) component).getDerivedFrom() != null) {
776                 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
777             }
778             toscaNodeType.setDescription(component.getDescription());
779         } else {
780             String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
781                     : "tosca.nodes.Root";
782             toscaNodeType.setDerived_from(derivedFrom);
783         }
784         return toscaNodeType;
785     }
786
787     private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container  ) {
788
789         Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
790         Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
791
792         List<ComponentInstance> componentInstances = container.getComponentInstances();
793
794         if (componentInstances == null || componentInstances.isEmpty()) {
795             return res;
796         }
797         Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
798         List<ComponentInstance> proxyInst = componentInstances.stream()
799                 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
800                 .collect(Collectors.toList());
801         if (proxyInst != null && !proxyInst.isEmpty()) {
802             for (ComponentInstance inst : proxyInst) {
803                 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
804             }
805         }
806
807         if (serviceProxyInstanceList.isEmpty()) {
808             return res;
809         }
810         ComponentParametersView filter = new ComponentParametersView(true);
811         filter.setIgnoreCapabilities(false);
812         filter.setIgnoreComponentInstances(false);
813         Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
814                 .getLatestByName("serviceProxy");
815         if (serviceProxyOrigin.isRight()) {
816             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
817                     serviceProxyOrigin.right().value());
818             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
819         }
820         Component origComponent = serviceProxyOrigin.left().value();
821
822         for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
823             Component serviceComponent = null;
824             ComponentParametersView componentParametersView = new ComponentParametersView();
825             componentParametersView.disableAll();
826             componentParametersView.setIgnoreCategories(false);
827             Either<Component, StorageOperationStatus> service = toscaOperationFacade
828                     .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
829             if (service.isRight()) {
830                 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(),  entryProxy.getValue().getName());
831             } else {
832                 serviceComponent = service.left().value();
833             }
834
835             ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
836             nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
837         }
838
839         return Either.left(nodeTypesMap);
840     }
841
842     private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
843             ComponentInstance instance) {
844         ToscaNodeType toscaNodeType = new ToscaNodeType();
845         String derivedFrom = ((Resource) origComponent).getToscaResourceName();
846
847         toscaNodeType.setDerived_from(derivedFrom);
848         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
849         if (dataTypesEither.isRight()) {
850             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
851         }
852         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
853         Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
854                 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
855
856         toscaNodeType.setCapabilities(capabilities);
857
858         return toscaNodeType;
859     }
860
861     private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
862             ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
863             ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
864
865         List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
866         if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
867             log.debug("Failed to convert component instance requirements for the component instance {}. ",
868                     componentInstance.getName());
869             return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
870         }
871         if (!toscaRequirements.isEmpty()) {
872             nodeTypeTemplate.setRequirements(toscaRequirements);
873         }
874         log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
875         return Either.left(nodeTypeTemplate);
876     }
877
878     private boolean addRequirements(Component component, ComponentInstance componentInstance,
879             List<RequirementCapabilityRelDef> relations, Component originComponent,
880             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
881         List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
882                 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
883         return isEmpty(filteredRelations) ||
884                 filteredRelations.stream()
885                         .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
886     }
887
888     private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
889             List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
890             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
891
892         boolean result = true;
893         Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
894         RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
895         Either<Component, StorageOperationStatus> getOriginRes = null;
896         Optional<RequirementDefinition> reqOpt = Optional.empty();
897         Component toOriginComponent = null;
898         Optional<CapabilityDefinition> capOpt = Optional.empty();
899
900         ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
901                 .findFirst().orElse(null);
902         if (toInstance == null) {
903             log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
904                     rel.getToNode());
905             result = false;
906         }
907         if (result) {
908             reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
909             if (!reqOpt.isPresent()) {
910                 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
911                         reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
912                 result = false;
913             }
914         }
915         if (result) {
916             ComponentParametersView filter = new ComponentParametersView(true);
917             filter.setIgnoreComponentInstances(false);
918             filter.setIgnoreCapabilities(false);
919             filter.setIgnoreGroups(false);
920             getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
921             if (getOriginRes.isRight()) {
922                 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
923                         reqOpt.get().getName(), toInstance.getActualComponentUid());
924                 result = false;
925             }
926         }
927         if (result) {
928             toOriginComponent = getOriginRes.left().value();
929             capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
930                     .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
931             if (!capOpt.isPresent()) {
932                 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
933                 if(!capOpt.isPresent()){
934                 result = false;
935                 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
936                         reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
937                 }
938             }
939         }
940         if (result) {
941             result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
942                     reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
943         }
944         return result;
945     }
946
947     private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
948         return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
949     }
950
951     private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
952         Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
953         if (!cap.isPresent()) {
954             log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
955         }
956         return cap;
957     }
958
959     private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
960         List<String> reducedPath = capability.getPath();
961         if(capability.getOwnerId() !=null){
962             reducedPath =   capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
963         }
964         Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
965                 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
966         if (buildCapNameRes.isRight()) {
967             log.debug(
968                     "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
969                     reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
970             return false;
971         }
972         Either<String, Boolean> buildReqNameRes  = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
973                 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
974         if (buildReqNameRes.isRight()) {
975             log.debug(
976                     "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
977                     reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
978             return false;
979         }
980         ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
981         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
982         toscaRequirement.setNode(toInstance.getName());
983         toscaRequirement.setCapability(buildCapNameRes.left().value());
984         toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
985         toscaRequirements.add(toscaReqMap);
986         return true;
987     }
988
989     private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair,  String fromInstanceId) {
990         for(List<RequirementDefinition> reqList: reqMap.values()){
991             Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
992             if(reqOpt.isPresent()){
993                 return reqOpt;
994             }
995         }
996         return Optional.empty();
997     }
998
999     /**
1000      * Allows detecting the requirement belonging to the received relationship
1001      * The detection logic is: A requirement belongs to a relationship IF 1.The
1002      * name of the requirement equals to the "requirement" field of the
1003      * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1004      * requirement equals to requirementOwnerId of the relation OR uniqueId of
1005      * toInstance equals to capabilityOwnerId of the relation
1006      */
1007     private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1008         if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1009             log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}",
1010                     requirement.getName(), reqAndRelationshipPair.getRequirement());
1011             return false;
1012         }
1013         return ModelConverter.isAtomicComponent(originComponent) ||
1014                 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1015     }
1016
1017     private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1018         return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1019     }
1020
1021     private boolean isCvfc(Component component) {
1022         return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1023                 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1024     }
1025
1026     private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1027             SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1028
1029         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1030         Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1031                 .convertSubstitutionMappingCapabilities(componentCache, component);
1032         if (toscaCapabilitiesRes.isRight()) {
1033             result = Either.right(toscaCapabilitiesRes.right().value());
1034             log.debug("Failed convert capabilities for the component {}. ", component.getName());
1035         } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1036             substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1037             log.debug("Finish convert capabilities for the component {}. ", component.getName());
1038         }
1039         log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1040         return result;
1041     }
1042
1043     private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1044             Map<String, DataTypeDefinition> dataTypes) {
1045         Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1046                 dataTypes);
1047         if (!toscaCapabilities.isEmpty()) {
1048             nodeType.setCapabilities(toscaCapabilities);
1049         }
1050         log.debug("Finish convert Capabilities for node type");
1051
1052         return Either.left(nodeType);
1053     }
1054
1055     private static class CustomRepresenter extends Representer {
1056         public CustomRepresenter() {
1057             super();
1058             // null representer is exceptional and it is stored as an instance
1059             // variable.
1060             this.nullRepresenter = new RepresentNull();
1061
1062         }
1063
1064         @Override
1065         protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1066                 Tag customTag) {
1067             if (propertyValue == null) {
1068                 return null;
1069             } else {
1070                 // skip not relevant for Tosca property
1071                 if ("dependencies".equals(property.getName())) {
1072                     return null;
1073                 }
1074                 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1075
1076                 return "_defaultp_".equals(property.getName())
1077                         ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1078             }
1079         }
1080
1081         @Override
1082         protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1083             // remove the bean type from the output yaml (!! ...)
1084             if (!classTags.containsKey(javaBean.getClass())) {
1085                 addClassTag(javaBean.getClass(), Tag.MAP);
1086             }
1087
1088             return super.representJavaBean(properties, javaBean);
1089         }
1090
1091         private class RepresentNull implements Represent {
1092             @Override
1093             public Node representData(Object data) {
1094                 // possible values are here http://yaml.org/type/null.html
1095                 return representScalar(Tag.NULL, "");
1096             }
1097         }
1098     }
1099
1100     private static class UnsortedPropertyUtils extends PropertyUtils {
1101         @Override
1102         protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1103                 throws IntrospectionException {
1104             Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1105             return new LinkedHashSet<>(fields);
1106         }
1107     }
1108
1109 }
1110