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