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