[SDC] rebase 1710 code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / ToscaExportHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.tosca;
22
23 import 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.Optional;
31 import java.util.Set;
32 import java.util.function.Supplier;
33 import java.util.stream.Collectors;
34
35 import org.apache.commons.collections.CollectionUtils;
36 import org.apache.commons.collections.MapUtils;
37 import org.apache.commons.lang.StringUtils;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.apache.commons.lang3.tuple.ImmutableTriple;
40 import org.apache.commons.lang3.tuple.Triple;
41 import org.openecomp.sdc.be.config.ConfigurationManager;
42 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
43 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.model.*;
46 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
47 import org.openecomp.sdc.be.model.category.CategoryDefinition;
48 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
49 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
50 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
51 import org.openecomp.sdc.be.tosca.model.IToscaMetadata;
52 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
53 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
54 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
55 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
56 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
57 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
58 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
59 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
60 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
61 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
62 import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.yaml.snakeyaml.DumperOptions;
68 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
69 import org.yaml.snakeyaml.Yaml;
70 import org.yaml.snakeyaml.introspector.BeanAccess;
71 import org.yaml.snakeyaml.introspector.Property;
72 import org.yaml.snakeyaml.introspector.PropertyUtils;
73 import org.yaml.snakeyaml.nodes.MappingNode;
74 import org.yaml.snakeyaml.nodes.Node;
75 import org.yaml.snakeyaml.nodes.NodeTuple;
76 import org.yaml.snakeyaml.nodes.Tag;
77 import org.yaml.snakeyaml.representer.Represent;
78 import org.yaml.snakeyaml.representer.Representer;
79
80 import fj.data.Either;
81
82 @org.springframework.stereotype.Component("tosca-export-handler")
83 public class ToscaExportHandler {
84
85         @Autowired
86         private ApplicationDataTypeCache dataTypeCache;
87
88         @Autowired
89         private ToscaOperationFacade toscaOperationFacade;
90
91         private CapabiltyRequirementConvertor capabiltyRequirementConvertor = CapabiltyRequirementConvertor.getInstance();
92         private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
93
94
95         private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
96
97         public static final String TOSCA_VERSION = "tosca_simple_yaml_1_0";
98         public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
99         public static final String IMPORTS_FILE_KEY = "file";
100         public static final String TOSCA_TEMPLATE_NAME = "-template.yml";
101         public static final String TOSCA_INTERFACE_NAME = "-interface.yml";
102         public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
103         public static final String VF_MODULE_TYPE_KEY = "vf_module_type";
104         public static final String VF_MODULE_DESC_KEY = "vf_module_description";
105         public static final String VOLUME_GROUP_KEY = "volume_group";
106         public static final String VF_MODULE_TYPE_BASE = "Base";
107         public static final String VF_MODULE_TYPE_EXPANSION = "Expansion";
108         public static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports();
109
110
111
112         public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
113
114                 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
115                 if (toscaTemplateRes.isRight()) {
116                         return Either.right(toscaTemplateRes.right().value());
117                 }
118
119                 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
120                 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
121                 return Either.left(toscaRepresentation);
122         }
123
124         public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) {
125                 if(null == DEFAULT_IMPORTS) {
126                         log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
127                         return Either.right(ToscaError.GENERAL_ERROR);
128                 }
129
130                 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
131                 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
132                 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
133                 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, nodeTypes);
134                 if (toscaTemplateRes.isRight()) {
135                         return Either.right(toscaTemplateRes.right().value());
136                 }
137
138                 toscaTemplate = toscaTemplateRes.left().value();
139                 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
140                 return Either.left(toscaRepresentation);
141         }
142
143         public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
144                 CustomRepresenter representer = new CustomRepresenter();
145                 DumperOptions options = new DumperOptions();
146                 options.setAllowReadOnlyProperties(false);
147                 options.setPrettyFlow(true);
148
149                 options.setDefaultFlowStyle(FlowStyle.FLOW);
150                 options.setCanonical(false);
151
152                 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
153
154                 representer.setPropertyUtils(new UnsortedPropertyUtils());
155                 Yaml yaml = new Yaml(representer, options);
156
157                 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
158
159                 StringBuilder sb = new StringBuilder();
160                 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
161                 sb.append(yamlAsString);
162                 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
163
164                 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
165                 toscaRepresentation.setMainYaml(sb.toString());
166                 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
167
168                 return toscaRepresentation;
169         }
170
171         public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
172                 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
173                 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
174                                 toscaTemplate);
175                 if (fillImports.isRight()) {
176                         return Either.right(fillImports.right().value());
177                 }
178                 return Either.left(fillImports.left().value().left);
179         }
180
181         private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
182                 if(null == DEFAULT_IMPORTS) {
183                         log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
184                         return Either.right(ToscaError.GENERAL_ERROR);
185                 }
186
187                 log.trace("start tosca export for {}", component.getUniqueId());
188                 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
189
190                 toscaTemplate.setMetadata(convertMetadata(component));
191                 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
192                 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
193                 if (ToscaUtils.isAtomicType(component)) {
194                         log.trace("convert component as node type");
195                         return convertNodeType(component, toscaTemplate, nodeTypes);
196                 } else {
197                         log.trace("convert component as topology template");
198                         return convertToscaTemplate(component, toscaTemplate);
199                 }
200
201         }
202
203         private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
204
205                 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
206                                 toscaNode);
207                 if (importsRes.isRight()) {
208                         return Either.right(importsRes.right().value());
209                 }
210                 toscaNode = importsRes.left().value().left;
211
212                 Map<String, Component> componentCache = importsRes.left().value().right;
213                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
214                 if (dataTypesEither.isRight()) {
215                         log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
216                         return Either.right(ToscaError.GENERAL_ERROR);
217                 }
218                 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
219
220                 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
221
222                 Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
223                 if (inputs.isRight()) {
224                         return Either.right(inputs.right().value());
225                 }
226                 topologyTemplate = inputs.left().value();
227
228                 List<ComponentInstance> componentInstances = component.getComponentInstances();
229                 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
230                                 .getComponentInstancesProperties();
231                 List<GroupDefinition> groups = component.getGroups();
232                 if (componentInstances != null && !componentInstances.isEmpty()) {
233
234                         Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
235                                         componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
236                         if (nodeTemplates.isRight()) {
237                                 return Either.right(nodeTemplates.right().value());
238                         }
239                         log.debug("node templates converted");
240
241                         topologyTemplate.setNode_templates(nodeTemplates.left().value());
242                 }
243                 Map<String, ToscaGroupTemplate> groupsMap = null;
244                 if (groups != null && !groups.isEmpty()) {
245                         groupsMap = new HashMap<String, ToscaGroupTemplate>();
246                         for (GroupDefinition group : groups) {
247                                 ToscaGroupTemplate toscaGroup = convertGroup(group);
248                                 groupsMap.put(group.getName(), toscaGroup);
249
250                         }
251                         log.debug("groups converted");
252                         topologyTemplate.addGroups(groupsMap);
253                 }
254                 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
255                 String toscaResourceName = null;
256                 switch (component.getComponentType()) {
257                 case RESOURCE:
258                         toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
259                                         .getMetadataDataDefinition()).getToscaResourceName();
260                         break;
261                 case SERVICE:
262                         toscaResourceName = SERVICE_NODE_TYPE_PREFIX
263                                         + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
264                         break;
265                 default:
266                         log.debug("Not supported component type {}", component.getComponentType());
267                         return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
268                 }
269                 substitutionMapping.setNode_type(toscaResourceName);
270
271                 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
272                                 dataTypes);
273                 if (capabilities.isRight()) {
274                         return Either.right(capabilities.right().value());
275                 }
276                 substitutionMapping = capabilities.left().value();
277
278                 Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping);
279                 if (requirements.isRight()) {
280                         return Either.right(requirements.right().value());
281                 }
282                 substitutionMapping = requirements.left().value();
283
284                 topologyTemplate.setSubstitution_mappings(substitutionMapping);
285
286                 toscaNode.setTopology_template(topologyTemplate);
287                 return Either.left(toscaNode);
288         }
289
290         private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
291                         ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
292                 if (log.isDebugEnabled())
293                         log.debug("fillInputs for component {}", component.getUniqueId());
294                 List<InputDefinition> inputDef = component.getInputs();
295                 Map<String, ToscaProperty> inputs = new HashMap<>();
296
297                 if (inputDef != null) {
298                         inputDef.forEach(i -> {
299                                 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
300                                 inputs.put(i.getName(), property);
301                         });
302                         if (!inputs.isEmpty()) {
303                                 topologyTemplate.setInputs(inputs);
304                         }
305                 }
306                 return Either.left(topologyTemplate);
307         }
308
309         private ToscaMetadata convertMetadata(Component component) {
310                 return convertMetadata(component, false, null);
311         }
312
313         private ToscaMetadata convertMetadata(Component component, boolean isInstance,
314                         ComponentInstance componentInstance) {
315                 ToscaMetadata toscaMetadata = new ToscaMetadata();
316                 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
317                 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
318                 toscaMetadata.setUUID(component.getUUID());
319                 toscaMetadata.setDescription(component.getDescription());
320
321                 List<CategoryDefinition> categories = component.getCategories();
322                 CategoryDefinition categoryDefinition = categories.get(0);
323                 toscaMetadata.setCategory(categoryDefinition.getName());
324
325                 if (isInstance) {
326                         toscaMetadata.setVersion(component.getVersion());
327                         toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
328                 }
329                 switch (component.getComponentType()) {
330                 case RESOURCE:
331                         Resource resource = (Resource) component;
332                         toscaMetadata.setType(resource.getResourceType().name());
333                         toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
334                         toscaMetadata.setResourceVendor(resource.getVendorName());
335                         toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
336                         toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
337                         break;
338                 case SERVICE:
339                         Service service = (Service) component;
340                         toscaMetadata.setType(component.getComponentType().getValue());
341                         toscaMetadata.setServiceType(service.getServiceType());
342                         toscaMetadata.setServiceRole(service.getServiceRole());
343                         if (!isInstance) {
344                                 // DE268546
345                                 toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
346                                 toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming());
347                                 toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy());
348                         }
349                         break;
350                 default:
351                         log.debug("Not supported component type {}", component.getComponentType());
352                 }
353                 return toscaMetadata;
354         }
355
356         private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
357                         ToscaTemplate toscaTemplate) {
358
359                 if(null == DEFAULT_IMPORTS) {
360                         log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
361                         return Either.right(ToscaError.GENERAL_ERROR);
362                 }
363
364                 Map<String, Component> componentCache = new HashMap<>();
365
366                 if (!ToscaUtils.isAtomicType(component)) {
367                         List<ComponentInstance> componentInstances = component.getComponentInstances();
368                         if (componentInstances != null && !componentInstances.isEmpty()) {
369
370                                 List<Map<String, Map<String, String>>> additionalImports =
371                                                 toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
372
373                                 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
374
375                                 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
376                                 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
377
378                                 Map<String, Map<String, String>> importsListMember = new HashMap<>();
379                                 Map<String, String> interfaceFiles = new HashMap<>();
380                                 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
381                                 StringBuilder keyNameBuilder = new StringBuilder();
382                                 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
383                                 keyNameBuilder.append("-");
384                                 keyNameBuilder.append(component.getName());
385                                 keyNameBuilder.append("-interface");
386                                 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
387                                 additionalImports.add(importsListMember);
388
389                                 componentInstances.forEach(ci -> {
390                                         createDependency(componentCache, additionalImports, dependecies, ci);
391                                 });
392                                 toscaTemplate.setDependencies(dependecies);
393                                 toscaTemplate.setImports(additionalImports);
394                         }
395                 } else {
396                         log.debug("currently imports supported for VF and service only");
397                 }
398                 return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
399         }
400
401         private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
402                         List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
403                 Map<String, String> files = new HashMap<>();
404                 Map<String, Map<String, String>> importsListMember = new HashMap<>();
405                 StringBuilder keyNameBuilder;
406
407                 Component componentRI = componentCache.get(ci.getComponentUid());
408                 if (componentRI == null) {
409                         // all resource must be only once!
410                         Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
411                         if (resource.isRight()) {
412                                 log.debug("Failed to fetch resource with id {} for instance {}");
413                         }
414                         Component fetchedComponent = resource.left().value();
415                         componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
416                         componentRI = fetchedComponent;
417
418                         Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
419                         ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
420                         if (artifactDefinition != null) {
421                                 String artifactName = artifactDefinition.getArtifactName();
422                                 files.put(IMPORTS_FILE_KEY, artifactName);
423                                 keyNameBuilder = new StringBuilder();
424                                 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
425                                 keyNameBuilder.append("-");
426                                 keyNameBuilder.append(ci.getComponentName());
427                                 importsListMember.put(keyNameBuilder.toString(), files);
428                                 imports.add(importsListMember);
429                                 dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
430                                                 artifactDefinition.getEsId(), fetchedComponent));
431
432                                 if(!ToscaUtils.isAtomicType(componentRI)) {
433                                         importsListMember = new HashMap<>();
434                                         Map<String, String> interfaceFiles = new HashMap<>();
435                                         interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
436                                         keyNameBuilder.append("-interface");
437                                         importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
438                                         imports.add(importsListMember);
439                                 }
440                         }
441                 }
442         }
443
444         public static String getInterfaceFilename(String artifactName) {
445                 String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
446                 return interfaceFileName;
447         }
448
449         private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
450                         Map<String, ToscaNodeType> nodeTypes) {
451                 log.debug("start convert node type for {}", component.getUniqueId());
452                 ToscaNodeType toscaNodeType = createNodeType(component);
453
454                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
455                 if (dataTypesEither.isRight()) {
456                         log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
457                         return Either.right(ToscaError.GENERAL_ERROR);
458                 }
459
460                 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
461                 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
462                                 dataTypes);
463                 if (properties.isRight()) {
464                         return Either.right(properties.right().value());
465                 }
466                 toscaNodeType = properties.left().value();
467                 log.debug("Properties converted for {}", component.getUniqueId());
468
469                 //Extracted to method for code reuse
470                 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
471         }
472
473         private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
474                         Map<String, ToscaNodeType> nodeTypes) {
475                 log.debug("start convert node type for {}", component.getUniqueId());
476                 ToscaNodeType toscaNodeType = createNodeType(component);
477
478                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
479                 if (dataTypesEither.isRight()) {
480                         log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
481                         return Either.right(ToscaError.GENERAL_ERROR);
482                 }
483
484                 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
485
486                 List<InputDefinition> inputDef = component.getInputs();
487                 Map<String, ToscaProperty> inputs = new HashMap<>();
488
489                 if (inputDef != null) {
490                         inputDef.forEach(i -> {
491                                 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
492                                 inputs.put(i.getName(), property);
493                         });
494                         if (!inputs.isEmpty()) {
495                                 toscaNodeType.setProperties(inputs);
496                         }
497                 }
498
499                 //Extracted to method for code reuse
500                 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
501         }
502
503         private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
504                         Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
505                         Map<String, DataTypeDefinition> dataTypes) {
506                 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
507                 if (capabilities.isRight()) {
508                         return Either.right(capabilities.right().value());
509                 }
510                 toscaNodeType = capabilities.left().value();
511                 log.debug("Capabilities converted for {}", component.getUniqueId());
512
513                 Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
514                                 toscaNodeType);
515                 if (requirements.isRight()) {
516                         return Either.right(requirements.right().value());
517                 }
518                 toscaNodeType = requirements.left().value();
519                 log.debug("Requirements converted for {}", component.getUniqueId());
520
521
522                 String toscaResourceName;
523                 switch (component.getComponentType()) {
524                 case RESOURCE:
525                         toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
526                                         .getMetadataDataDefinition()).getToscaResourceName();
527                         break;
528                 case SERVICE:
529                         toscaResourceName = SERVICE_NODE_TYPE_PREFIX
530                                         + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
531                         break;
532                 default:
533                         log.debug("Not supported component type {}", component.getComponentType());
534                         return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
535                 }
536
537                 nodeTypes.put(toscaResourceName, toscaNodeType);
538                 toscaNode.setNode_types(nodeTypes);
539                 log.debug("finish convert node type for {}", component.getUniqueId());
540                 return Either.left(toscaNode);
541         }
542
543         private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
544                         List<ComponentInstance> componentInstances,
545                         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
546                         Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
547                         ToscaTopolgyTemplate topologyTemplate) {
548
549                 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
550                 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
551                                 component.getComponentType());
552                 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
553                 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
554
555                 Map<String, ToscaGroupTemplate> groupsMap = null;
556                 for (ComponentInstance componentInstance : componentInstances) {
557                         ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
558                         nodeTemplate.setType(componentInstance.getToscaComponentName());
559
560                         Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
561                                         componentInstance, component.getComponentInstancesRelations(), nodeTemplate, componentCache.get(componentInstance.getComponentUid()));
562                         if (requirements.isRight()) {
563                                 convertNodeTemplatesRes = Either.right(requirements.right().value());
564                                 break;
565                         }
566                         String instanceUniqueId = componentInstance.getUniqueId();
567                         log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
568
569                         nodeTemplate = requirements.left().value();
570
571                         Component componentOfInstance = componentCache.get(componentInstance.getComponentUid());
572                         nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
573
574                         Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor
575                                         .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
576                         if (capabilities.isRight()) {
577                                 convertNodeTemplatesRes = Either.right(requirements.right().value());
578                                 break;
579                         }
580                         log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
581
582                         nodeTemplate = capabilities.left().value();
583                         Map<String, Object> props = new HashMap<>();
584
585                         if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) {
586                                 // Adds the properties of parent component to map
587                                 addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props);
588                         }
589
590                         if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
591                                 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
592                                                 instanceUniqueId, props);
593                         }
594
595                         if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
596                                 addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
597                                                 props);
598                         }
599                         if (props != null && !props.isEmpty()) {
600                                 nodeTemplate.setProperties(props);
601                         }
602
603                         List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
604                         if (groupInstances != null) {
605                                 if (groupsMap == null) {
606                                         groupsMap = new HashMap<>();
607                                 }
608                                 for (GroupInstance groupInst : groupInstances) {
609                                         ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
610
611                                         groupsMap.put(groupInst.getName(), toscaGroup);
612                                 }
613                         }
614
615                         nodeTemplates.put(componentInstance.getName(), nodeTemplate);
616                 }
617                 if (groupsMap != null) {
618                         log.debug("instance groups added");
619                         topologyTemplate.addGroups(groupsMap);
620                 }
621
622                 if (convertNodeTemplatesRes == null) {
623                         convertNodeTemplatesRes = Either.left(nodeTemplates);
624                 }
625                 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
626                                 component.getComponentType());
627                 return convertNodeTemplatesRes;
628         }
629
630         private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
631                         Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
632                         String instanceUniqueId, Map<String, Object> props) {
633
634                 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
635                 if (instanceInputsList != null) {
636                         instanceInputsList.forEach(input -> {
637                                 Supplier<String> supplier = () -> input.getValue();
638                                 convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
639                         });
640                 }
641         }
642
643         private void addPropertiesOfComponentInstance(
644                         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
645                         Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
646                         Map<String, Object> props) {
647
648                 if (!MapUtils.isEmpty(componentInstancesProperties)) {
649                         componentInstancesProperties.get(instanceUniqueId).stream()
650                                         // Collects filtered properties to List
651                                         .collect(Collectors.toList()).stream()
652                                         // Converts and adds each value to property map
653                                         .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
654                                                         () -> prop.getValue()));
655                 }
656         }
657
658         private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
659                         ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
660
661                 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
662                 if (!CollectionUtils.isEmpty(componentProperties)) {
663                         componentProperties.stream()
664                                         // Filters out properties with empty default values
665                                         .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
666                                         // Collects filtered properties to List
667                                         .collect(Collectors.toList()).stream()
668                                         // Converts and adds each value to property map
669                                         .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
670                                                         () -> prop.getDefaultValue()));
671                 }
672         }
673
674         /**
675          * @param dataTypes
676          * @param componentInstance
677          * @param props
678          * @param prop
679          * @param supplier
680          */
681         private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
682                         Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
683                 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
684                 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
685                         props.put(prop.getName(), convertedValue);
686                 }
687         }
688
689         private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
690                         ComponentInstance componentInstance, T input, Supplier<String> supplier) {
691                 log.debug("Convert property or input value {} for instance {}", input.getName(),
692                                 componentInstance.getUniqueId());
693                 String propertyType = input.getType();
694                 String innerType = null;
695                 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
696                         innerType = input.getSchema().getProperty().getType();
697                 }
698                 return propertyConvertor.convertToToscaObject(propertyType, input.getName(), supplier.get(), innerType, dataTypes);
699         }
700
701         private ToscaGroupTemplate convertGroup(GroupDefinition group) {
702                 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
703                 Map<String, String> members = group.getMembers();
704                 if (members != null)
705                         toscaGroup.setMembers(new ArrayList<String>(members.keySet()));
706
707                 Supplier<String> supplGroupType = () -> group.getType();
708                 Supplier<String> supplDescription = () -> group.getDescription();
709                 Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
710                 Supplier<String> supplgroupName = () -> group.getName();
711                 Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
712                 Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
713                 Supplier<String> supplVersion = () -> group.getVersion();
714
715                 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
716                                 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
717                 toscaGroup.setMetadata(toscaMetadata);
718                 return toscaGroup;
719         }
720
721         private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
722                 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
723
724                 Supplier<String> supplGroupType = () -> groupInstance.getType();
725                 Supplier<String> supplDescription = () -> groupInstance.getDescription();
726                 Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance.convertToGroupInstancesProperties();
727                 Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
728                 Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
729                 Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
730                 Supplier<String> supplVersion = () -> groupInstance.getVersion();
731
732                 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
733                                 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
734
735                 toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
736                 toscaGroup.setMetadata(toscaMetadata);
737                 return toscaGroup;
738         }
739
740         private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
741                         Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
742                         Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
743                 boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
744                 toscaGroup.setType(groupType.get());
745
746                 IToscaMetadata toscaMetadata;
747                 if (!isVfModule) {
748                         toscaMetadata = new ToscaMetadata();
749                 } else {
750                         toscaMetadata = new VfModuleToscaMetadata();
751
752                         Map<String, Object> properties = fillGroupProperties(props.get());
753                         if(!properties.containsKey(VF_MODULE_DESC_KEY) || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))){
754                                 properties.put(VF_MODULE_DESC_KEY, description.get());
755                         }
756                         toscaGroup.setProperties(properties);
757                 }
758                 toscaMetadata.setName(groupName.get());
759                 toscaMetadata.setInvariantUUID(invariantUUID.get());
760                 toscaMetadata.setUUID(groupUUID.get());
761                 toscaMetadata.setVersion(version.get());
762                 return toscaMetadata;
763         }
764
765         private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
766                 Map<String, Object> properties = new HashMap<>();
767                 if(groupProps != null){
768                         for (GroupProperty gp : groupProps) {
769                                 if (gp.getName().equals(Constants.IS_BASE)) {
770                                         Boolean isBase = Boolean.parseBoolean(gp.getValue());
771                                         String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
772                                         properties.put(VF_MODULE_TYPE_KEY, type);
773                                 } else {
774                                         Object value = null;
775                                         String type = gp.getType();
776
777                                         switch (type) {
778                                         case "integer":
779                                                 if (gp.getValue() != null) {
780                                                         value = Integer.valueOf(gp.getValue());
781                                                 }
782                                                 break;
783                                         case "boolean":
784                                                 if (gp.getValue() != null) {
785                                                         value = Boolean.valueOf(gp.getValue());
786                                                 }
787                                                 break;
788
789                                         default:
790                                                 value = gp.getValue();
791                                                 break;
792                                         }
793                                         properties.put(gp.getName(), value);
794                                 }
795                         }
796                 }
797                 return properties;
798         }
799
800         private ToscaNodeType createNodeType(Component component) {
801                 ToscaNodeType toscaNodeType = new ToscaNodeType();
802                 if (ToscaUtils.isAtomicType(component)){
803                         if (((Resource) component).getDerivedFrom() != null){
804                                 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
805                         }
806                         toscaNodeType.setDescription(component.getDescription()); // or name??
807                 } else {
808                         String derivedFrom = null != component.getDerivedFromGenericType()? component.getDerivedFromGenericType() : "tosca.nodes.Root";
809                         toscaNodeType.setDerived_from(derivedFrom);
810                 }
811                 return toscaNodeType;
812         }
813
814         //TODO save the capability(type or name) info on relation data
815         private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
816                                                                                                                                                                            ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
817                                                                                                                                                                            ToscaNodeTemplate nodeTypeTemplate, Component originComponent) {
818
819                 List<ComponentInstance> instancesList = component.getComponentInstances();
820                 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
821                 Map<String, List<RequirementDefinition>> reqMap = originComponent.getRequirements();
822
823                 relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(rel -> {
824                         ComponentInstance toComponentInstance = instancesList.stream()
825                                         .filter(i -> rel.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
826                         if (toComponentInstance == null) {
827                                 log.debug("Failed to find relation between node {} to node {}", componentInstance.getName(),
828                                                 rel.getToNode());
829                                 return;
830                         }
831                         RequirementAndRelationshipPair reqAndRelationshipPair = rel.getRelationships().get(0);
832                         ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
833                         toscaRequirement.setNode(toComponentInstance.getName());
834                         Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream())
835                                         .filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny();
836                         if (findAny.isPresent()) {
837                                 RequirementDefinition reqDefinition = findAny.get();
838                                 toscaRequirement.setCapability(reqDefinition.getCapability());
839                                 toscaRequirement.setRelationship(reqDefinition.getRelationship());
840                         } else {
841                                 // reqMap represents calculated requirements! if not found there, export data directly from the relation definition
842                                 log.debug("Failed to find requirement {} definition for node {}", reqAndRelationshipPair.getRequirement(), componentInstance.getName());
843                                 return;
844                         }
845                         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
846                         toscaReqMap.put(reqAndRelationshipPair.getRequirement(), toscaRequirement);
847                         toscaRequirements.add(toscaReqMap);
848
849                 });
850
851                 if (!toscaRequirements.isEmpty()) {
852                         nodeTypeTemplate.setRequirements(toscaRequirements);
853                 }
854                 log.debug("Finish convert Requirements for node type");
855                 return Either.left(nodeTypeTemplate);
856         }
857
858
859         private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map<String, DataTypeDefinition> dataTypes) {
860                 Map<String, String[]> toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes);
861
862                 if (!toscaCapabilities.isEmpty()) {
863                         substitutionMapping.setCapabilities(toscaCapabilities);
864                 }
865                 log.debug("Finish convert Capabilities for node type");
866
867                 return Either.left(substitutionMapping);
868         }
869
870         private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
871                         Map<String, DataTypeDefinition> dataTypes) {
872                 Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
873                                 dataTypes);
874                 if (!toscaCapabilities.isEmpty()) {
875                         nodeType.setCapabilities(toscaCapabilities);
876                 }
877                 log.debug("Finish convert Capabilities for node type");
878
879                 return Either.left(nodeType);
880         }
881
882         private static class CustomRepresenter extends Representer {
883                 public CustomRepresenter() {
884                         super();
885                         // null representer is exceptional and it is stored as an instance
886                         // variable.
887                         this.nullRepresenter = new RepresentNull();
888
889                 }
890
891                 @Override
892                 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
893                                 Tag customTag) {
894                         if (propertyValue == null) {
895                                 return null;
896                         } else {
897                                 // skip not relevant for Tosca property
898                                 if (property.getName().equals("dependencies")) {
899                                         return null;
900                                 }
901                                 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
902
903                                 return property.getName().equals("_defaultp_")
904                                                 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
905                         }
906                 }
907
908                 @Override
909                 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
910                         // remove the bean type from the output yaml (!! ...)
911                         if (!classTags.containsKey(javaBean.getClass()))
912                                 addClassTag(javaBean.getClass(), Tag.MAP);
913
914                         return super.representJavaBean(properties, javaBean);
915                 }
916
917                 private class RepresentNull implements Represent {
918                         public Node representData(Object data) {
919                                 // possible values are here http://yaml.org/type/null.html
920                                 return representScalar(Tag.NULL, "");
921                         }
922                 }
923         }
924
925         private static class UnsortedPropertyUtils extends PropertyUtils {
926                 @Override
927                 protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
928                                 throws IntrospectionException {
929                         Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
930                         return new LinkedHashSet<Property>(fields);
931                 }
932         }
933
934 }