Properties are missing in TOSCA fix
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / ToscaExportHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.tosca;
22
23 import 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)) {
560             if (Objects.nonNull(inputDef)) {
561                 resolveDefaultPropertyValue(inputDef, mergedProperties, dataTypes);
562             }
563             toscaNodeType.setProperties(mergedProperties);
564         }
565         // Extracted to method for code reuse
566         return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
567     }
568
569     private void resolveDefaultPropertyValue(List<InputDefinition> inputDef,
570                                              Map<String, ToscaProperty> mergedProperties,
571                                              Map<String, DataTypeDefinition> dataTypes) {
572         for (Map.Entry<String, ToscaProperty> mergedPropertyEntry : mergedProperties.entrySet()) {
573             ToscaProperty value = mergedPropertyEntry.getValue();
574             if (Objects.nonNull(value) && value.getDefaultp() instanceof Map) {
575                 Map<String, String> valueAsMap = (Map<String, String>) value.getDefaultp();
576                 String inputName = valueAsMap.get(ToscaFunctions.GET_INPUT.getFunctionName());
577                 Optional<InputDefinition> matchedInputDefinition = inputDef.stream()
578                         .filter(componentInput -> componentInput.getName().equals(inputName))
579                         .findFirst();
580                 if (matchedInputDefinition.isPresent()) {
581                     InputDefinition matchedInput = matchedInputDefinition.get();
582                     Object resolvedDefaultValue = new PropertyConvertor().convertToToscaObject(matchedInput.getType(),
583                             matchedInput.getDefaultValue(), matchedInput.getSchemaType(), dataTypes, false);
584                     value.setDefaultp(resolvedDefaultValue);
585                     mergedProperties.put(mergedPropertyEntry.getKey(), value);
586                 }
587             }
588         }
589     }
590
591   private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
592                                      List<InputDefinition> inputDef,
593                                      Map<String, ToscaProperty> mergedProperties) {
594     for(InputDefinition input : inputDef) {
595       ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
596       mergedProperties.put(input.getName(), property);
597     }
598   }
599
600     private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
601             Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
602             Map<String, DataTypeDefinition> dataTypes) {
603         Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
604         if (capabilities.isRight()) {
605             return Either.right(capabilities.right().value());
606         }
607         toscaNodeType = capabilities.left().value();
608         log.debug("Capabilities converted for {}", component.getUniqueId());
609
610         Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
611                 toscaNodeType);
612         if (requirements.isRight()) {
613             return Either.right(requirements.right().value());
614         }
615         toscaNodeType = requirements.left().value();
616         log.debug("Requirements converted for {}", component.getUniqueId());
617
618         String toscaResourceName;
619         switch (component.getComponentType()) {
620             case RESOURCE:
621                 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
622                                                                                .getMetadataDataDefinition()).getToscaResourceName();
623                 break;
624             case SERVICE:
625                 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
626                                             + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
627                 break;
628             default:
629                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
630                 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
631         }
632
633         nodeTypes.put(toscaResourceName, toscaNodeType);
634         toscaNode.setNode_types(nodeTypes);
635         log.debug("finish convert node type for {}", component.getUniqueId());
636         return Either.left(toscaNode);
637     }
638
639     protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
640             Component component,
641             List<ComponentInstance> componentInstances,
642             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
643             Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
644             Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
645             ToscaTopolgyTemplate topologyTemplate) {
646
647         Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
648         log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
649                 component.getComponentType());
650         Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
651         Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
652
653         Map<String, ToscaGroupTemplate> groupsMap = null;
654         for (ComponentInstance componentInstance : componentInstances) {
655             ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
656             nodeTemplate.setType(componentInstance.getToscaComponentName());
657             nodeTemplate.setDirectives(componentInstance.getDirectives());
658             nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
659
660             Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
661                                                                     .getOriginComponent(componentCache, componentInstance);
662             if (originComponentRes.isRight()) {
663                 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
664                 break;
665             }
666             Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
667                     componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
668                     originComponentRes.left().value(), componentCache);
669             if (requirements.isRight()) {
670                 convertNodeTemplatesRes = Either.right(requirements.right().value());
671                 break;
672             }
673             String instanceUniqueId = componentInstance.getUniqueId();
674             log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
675
676             nodeTemplate = requirements.left().value();
677
678             Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
679
680             if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
681                 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
682                 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
683             } else {
684                 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
685             }
686
687             Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
688                                                                          .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
689             if (capabilities.isRight()) {
690                 convertNodeTemplatesRes = Either.right(capabilities.right().value());
691                 break;
692             }
693             log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
694
695             nodeTemplate = capabilities.left().value();
696             Map<String, Object> props = new HashMap<>();
697
698             if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
699                 // Adds the properties of parent component to map
700                 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
701             }
702
703             if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)
704                     && !isComponentOfTypeServiceProxy(componentInstance)) {
705                 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
706                         instanceUniqueId, props);
707             }
708
709             if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
710                     && !isComponentOfTypeServiceProxy(componentInstance)) {
711                 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
712                         props);
713             }
714             //M3[00001] - NODE TEMPLATE INTERFACES  - START
715             handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
716                     instanceUniqueId, component);
717             //M3[00001] - NODE TEMPLATE INTERFACES  - END
718             if (props != null && !props.isEmpty()) {
719                 nodeTemplate.setProperties(props);
720             }
721
722             List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
723             if (groupInstances != null) {
724                 if (groupsMap == null) {
725                     groupsMap = new HashMap<>();
726                 }
727                 for (GroupInstance groupInst : groupInstances) {
728                     boolean addToTosca = true;
729
730                     List<String> artifacts = groupInst.getArtifacts();
731                     if (artifacts == null || artifacts.isEmpty()) {
732                         addToTosca = false;
733                     }
734
735                     if (addToTosca) {
736                         ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
737                         groupsMap.put(groupInst.getName(), toscaGroup);
738                     }
739                 }
740             }
741
742             nodeTemplates.put(componentInstance.getName(), nodeTemplate);
743         }
744         if (groupsMap != null) {
745             log.debug("instance groups added");
746             topologyTemplate.addGroups(groupsMap);
747         }
748         if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
749             log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
750                     component.getName());
751             ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
752             log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
753                     component.getName());
754         }
755         if (convertNodeTemplatesRes == null) {
756             convertNodeTemplatesRes = Either.left(nodeTemplates);
757         }
758         log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
759                 component.getComponentType());
760         return convertNodeTemplatesRes;
761     }
762
763     private void handleInstanceInterfaces(
764             Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
765             ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
766             String instanceUniqueId,
767             Component parentComponent) {
768
769         Map<String, Object> interfaces;
770
771         // we need to handle service proxy interfaces
772         if(isComponentOfTypeServiceProxy(componentInstance)) {
773             if(MapUtils.isEmpty(componentInstanceInterfaces)
774                 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
775                 interfaces = null;
776             } else {
777                 List<ComponentInstanceInterface> currServiceInterfaces =
778                     componentInstanceInterfaces.get(instanceUniqueId);
779
780                 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
781                 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
782                     .getUniqueId(), instInterface));
783
784                 interfaces = InterfacesOperationsToscaUtil
785                                      .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
786             }
787         } else {
788             interfaces =
789                 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
790                     componentInstance, instanceUniqueId);
791         }
792         nodeTemplate.setInterfaces(interfaces);
793     }
794
795     private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
796         return Objects.nonNull(componentInstance.getOriginType())
797             && componentInstance.getOriginType().getValue().equals("Service Proxy");
798     }
799
800     //M3[00001] - NODE TEMPLATE INTERFACES  - START
801     private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
802                                                                         ComponentInstance componentInstance,
803                                                                        String instanceUniqueId) {
804         if(MapUtils.isEmpty(componentInstancesInterfaces)) {
805             return null;
806         }
807
808         List<ComponentInstanceInterface> componentInstanceInterfaces =
809             componentInstancesInterfaces.get(instanceUniqueId);
810
811         if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
812           return null;
813         }
814
815         Map<String, Object> interfaces = new HashMap<>();
816         for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
817             interfaces.put(componentInstanceInterface.getInterfaceId(),
818                 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
819         }
820
821         componentInstance.setInterfaces(interfaces);
822
823         return interfaces;
824     }
825
826     private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
827             Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
828             String instanceUniqueId, Map<String, Object> props) {
829
830         List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
831         if (instanceInputsList != null) {
832             instanceInputsList.forEach(input -> {
833
834                 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
835                         ? input.getValue() : input.getDefaultValue();
836                 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
837             });
838         }
839     }
840
841     private void addPropertiesOfComponentInstance(
842             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
843             Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
844             Map<String, Object> props) {
845
846         if (isNotEmpty(componentInstancesProperties)) {
847             componentInstancesProperties.get(instanceUniqueId)
848                                         // Converts and adds each value to property map
849                                         .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
850                                                 prop::getValue));
851         }
852     }
853
854     private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
855             Component componentOfInstance, Map<String, Object> props) {
856
857         List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
858         if (isNotEmpty(componentProperties)) {
859             componentProperties.stream()
860                     // Filters out properties with empty default values
861                                .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
862                     // Converts and adds each value to property map
863                     .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
864                                        prop::getDefaultValue));
865         }
866     }
867
868     /**
869      * @param dataTypes
870      * @param componentInstance
871      * @param props
872      * @param prop
873      * @param supplier
874      */
875     private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
876             Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
877         Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
878         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
879             props.put(prop.getName(), convertedValue);
880         }
881     }
882
883     private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
884             ComponentInstance componentInstance, T input, Supplier<String> supplier) {
885         log.debug("Convert property or input value {} for instance {}", input.getName(),
886                 componentInstance.getUniqueId());
887         String propertyType = input.getType();
888         String innerType = null;
889         if (input.getSchema() != null && input.getSchema().getProperty() != null) {
890             innerType = input.getSchema().getProperty().getType();
891         }
892         return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
893             dataTypes, true);
894     }
895
896     private ToscaNodeType createNodeType(Component component) {
897         ToscaNodeType toscaNodeType = new ToscaNodeType();
898         if (ModelConverter.isAtomicComponent(component)) {
899             if (((Resource) component).getDerivedFrom() != null) {
900                 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
901             }
902             toscaNodeType.setDescription(component.getDescription());
903         } else {
904             String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
905                                          : "tosca.nodes.Root";
906             toscaNodeType.setDerived_from(derivedFrom);
907         }
908         return toscaNodeType;
909     }
910
911     private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container  ) {
912
913         Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
914         Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
915
916         List<ComponentInstance> componentInstances = container.getComponentInstances();
917
918         if (componentInstances == null || componentInstances.isEmpty()) {
919             return res;
920         }
921         Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
922         List<ComponentInstance> proxyInst = componentInstances.stream()
923                                                               .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
924                                                               .collect(Collectors.toList());
925         if (proxyInst != null && !proxyInst.isEmpty()) {
926             for (ComponentInstance inst : proxyInst) {
927                 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
928             }
929         }
930
931         if (serviceProxyInstanceList.isEmpty()) {
932             return res;
933         }
934         ComponentParametersView filter = new ComponentParametersView(true);
935         filter.setIgnoreCapabilities(false);
936         filter.setIgnoreComponentInstances(false);
937         Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
938                                                                               .getLatestByName("serviceProxy");
939         if (serviceProxyOrigin.isRight()) {
940             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
941                     serviceProxyOrigin.right().value());
942             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
943         }
944         Component origComponent = serviceProxyOrigin.left().value();
945
946         for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
947             Component serviceComponent = null;
948             ComponentParametersView componentParametersView = new ComponentParametersView();
949             componentParametersView.disableAll();
950             componentParametersView.setIgnoreCategories(false);
951             Either<Component, StorageOperationStatus> service = toscaOperationFacade
952                                                                         .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
953             if (service.isRight()) {
954                 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(),  entryProxy.getValue().getName());
955             } else {
956                 serviceComponent = service.left().value();
957             }
958
959             ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
960             nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
961         }
962
963         return Either.left(nodeTypesMap);
964     }
965
966     private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
967             ComponentInstance instance) {
968         ToscaNodeType toscaNodeType = new ToscaNodeType();
969         String derivedFrom = ((Resource) origComponent).getToscaResourceName();
970
971         toscaNodeType.setDerived_from(derivedFrom);
972         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
973         if (dataTypesEither.isRight()) {
974             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
975         }
976         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
977         Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
978                                                             .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
979
980         toscaNodeType.setCapabilities(capabilities);
981
982         return toscaNodeType;
983     }
984
985     private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
986             ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
987             ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
988
989         List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
990         if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
991             log.debug("Failed to convert component instance requirements for the component instance {}. ",
992                     componentInstance.getName());
993             return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
994         }
995         if (!toscaRequirements.isEmpty()) {
996             nodeTypeTemplate.setRequirements(toscaRequirements);
997         }
998         log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
999         return Either.left(nodeTypeTemplate);
1000     }
1001
1002     private boolean addRequirements(Component component, ComponentInstance componentInstance,
1003             List<RequirementCapabilityRelDef> relations, Component originComponent,
1004             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1005         List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1006                                                                        .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1007         return isEmpty(filteredRelations) ||
1008                        filteredRelations.stream()
1009                                         .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1010     }
1011
1012     private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1013             List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1014             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1015
1016         boolean result = true;
1017         Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1018         RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1019         Either<Component, StorageOperationStatus> getOriginRes = null;
1020         Optional<RequirementDefinition> reqOpt = Optional.empty();
1021         Component toOriginComponent = null;
1022         Optional<CapabilityDefinition> capOpt = Optional.empty();
1023
1024         ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1025                                                     .findFirst().orElse(null);
1026         if (toInstance == null) {
1027             log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1028                     rel.getToNode());
1029             result = false;
1030         }
1031         if (result) {
1032             reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1033             if (!reqOpt.isPresent()) {
1034                 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1035                         reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1036                 result = false;
1037             }
1038         }
1039         if (result) {
1040             ComponentParametersView filter = new ComponentParametersView(true);
1041             filter.setIgnoreComponentInstances(false);
1042             filter.setIgnoreCapabilities(false);
1043             filter.setIgnoreGroups(false);
1044             getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1045             if (getOriginRes.isRight()) {
1046                 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1047                         reqOpt.get().getName(), toInstance.getActualComponentUid());
1048                 result = false;
1049             }
1050         }
1051         if (result) {
1052             toOriginComponent = getOriginRes.left().value();
1053             capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1054                                       .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1055             if (!capOpt.isPresent()) {
1056                 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1057                 if(!capOpt.isPresent()){
1058                     result = false;
1059                     log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1060                             reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1061                 }
1062             }
1063         }
1064         if (result) {
1065             result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1066                     reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1067         }
1068         return result;
1069     }
1070
1071     private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1072         return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1073     }
1074
1075     private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1076         Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1077         if (!cap.isPresent()) {
1078             log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1079         }
1080         return cap;
1081     }
1082
1083     private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1084         List<String> reducedPath = capability.getPath();
1085         if(capability.getOwnerId() !=null){
1086             reducedPath =   capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1087         }
1088         Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1089                 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1090         if (buildCapNameRes.isRight()) {
1091             log.debug(
1092                     "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1093                     reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1094             return false;
1095         }
1096         Either<String, Boolean> buildReqNameRes  = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1097                 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1098         if (buildReqNameRes.isRight()) {
1099             log.debug(
1100                     "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1101                     reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1102             return false;
1103         }
1104         ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1105         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1106         toscaRequirement.setNode(toInstance.getName());
1107         toscaRequirement.setCapability(buildCapNameRes.left().value());
1108         toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1109         toscaRequirements.add(toscaReqMap);
1110         return true;
1111     }
1112
1113     private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair,  String fromInstanceId) {
1114         for(List<RequirementDefinition> reqList: reqMap.values()){
1115             Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1116             if(reqOpt.isPresent()){
1117                 return reqOpt;
1118             }
1119         }
1120         return Optional.empty();
1121     }
1122
1123     /**
1124      * Allows detecting the requirement belonging to the received relationship
1125      * The detection logic is: A requirement belongs to a relationship IF 1.The
1126      * name of the requirement equals to the "requirement" field of the
1127      * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1128      * requirement equals to requirementOwnerId of the relation OR uniqueId of
1129      * toInstance equals to capabilityOwnerId of the relation
1130      */
1131     private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1132         if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1133             log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}",
1134                     requirement.getName(), reqAndRelationshipPair.getRequirement());
1135             return false;
1136         }
1137         return ModelConverter.isAtomicComponent(originComponent) ||
1138                        isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1139     }
1140
1141     private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1142         return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1143     }
1144
1145     private boolean isCvfc(Component component) {
1146         return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1147                        ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1148     }
1149
1150     private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1151             SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1152
1153         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1154         Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1155                                                                                  .convertSubstitutionMappingCapabilities(componentCache, component);
1156         if (toscaCapabilitiesRes.isRight()) {
1157             result = Either.right(toscaCapabilitiesRes.right().value());
1158             log.debug("Failed convert capabilities for the component {}. ", component.getName());
1159         } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1160             substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1161             log.debug("Finish convert capabilities for the component {}. ", component.getName());
1162         }
1163         log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1164         return result;
1165     }
1166
1167     private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1168             Map<String, DataTypeDefinition> dataTypes) {
1169         Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1170                 dataTypes);
1171         if (!toscaCapabilities.isEmpty()) {
1172             nodeType.setCapabilities(toscaCapabilities);
1173         }
1174         log.debug("Finish convert Capabilities for node type");
1175
1176         return Either.left(nodeType);
1177     }
1178
1179
1180     protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1181         if (inNodeFilter == null){
1182             return null;
1183         }
1184         NodeFilter nodeFilter = new NodeFilter();
1185
1186         ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1187                 inNodeFilter.getCapabilities();
1188
1189         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1190
1191         List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1192         List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1193
1194         copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1195         copyNodeFilterProperties(origProperties, propertiesCopy);
1196
1197         if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1198             nodeFilter.setCapabilities(capabilitiesCopy);
1199         }
1200
1201         if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1202             nodeFilter.setProperties(propertiesCopy);
1203         }
1204
1205         nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1206
1207
1208         nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1209
1210         return nodeFilter;
1211     }
1212
1213     private Object cloneToscaId(Object toscaId) {
1214         return Objects.isNull(toscaId) ? null
1215                        : cloneObjectFromYml(toscaId, toscaId.getClass());
1216     }
1217
1218
1219     private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1220         String objectAsYml = yamlUtil.objectToYaml(objToClone);
1221         return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1222     }
1223     private void copyNodeFilterCapabilitiesTemplate(
1224             ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1225             List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1226         if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1227                    origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1228             return;
1229         }
1230         for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1231             Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1232             CapabilityFilter capabilityFilter = new CapabilityFilter();
1233             List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1234             copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1235             capabilityFilter.setProperties(propertiesCopy);
1236             capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1237             capabilitiesCopy.add(capabilityFilterCopyMap);
1238         }
1239     }
1240
1241     private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1242         String listAsString = yamlUtil.objectToYaml(propertyList);
1243         return yamlUtil.yamlToObject(listAsString, List.class);
1244     }
1245
1246
1247     private void copyNodeFilterProperties(
1248             ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1249             List<Map<String, List<Object>>> propertiesCopy) {
1250         if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1251                    origProperties.isEmpty()) {
1252             return;
1253         }
1254         for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1255             Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1256             for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1257                 Map propertyValObj =  new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1258                 if (propertyMapCopy.containsKey(propertyDataDefinition.getName())){
1259                     propertyMapCopy.get(propertyDataDefinition.getName()).add(propertyValObj);
1260                 } else {
1261                     if (propertyDataDefinition.getName() != null) {
1262                         List propsList =new ArrayList();
1263                         propsList.add(propertyValObj);
1264                         propertyMapCopy.put(propertyDataDefinition.getName(), propsList);
1265                     } else {
1266                         propertyMapCopy.putAll(propertyValObj);
1267                     }
1268                 }
1269             }
1270             propertiesCopy.add(propertyMapCopy);
1271         }
1272
1273     }
1274
1275     private static class CustomRepresenter extends Representer {
1276         public CustomRepresenter() {
1277             super();
1278             // null representer is exceptional and it is stored as an instance
1279             // variable.
1280             this.nullRepresenter = new RepresentNull();
1281
1282         }
1283
1284         @Override
1285         protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1286                 Tag customTag) {
1287             if (propertyValue == null) {
1288                 return null;
1289             } else {
1290                 // skip not relevant for Tosca property
1291                 if ("dependencies".equals(property.getName())) {
1292                     return null;
1293                 }
1294                 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1295
1296                 return "_defaultp_".equals(property.getName())
1297                                ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1298             }
1299         }
1300
1301         @Override
1302         protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1303             // remove the bean type from the output yaml (!! ...)
1304             if (!classTags.containsKey(javaBean.getClass())) {
1305                 addClassTag(javaBean.getClass(), Tag.MAP);
1306             }
1307
1308             return super.representJavaBean(properties, javaBean);
1309         }
1310
1311         private class RepresentNull implements Represent {
1312             @Override
1313             public Node representData(Object data) {
1314                 // possible values are here http://yaml.org/type/null.html
1315                 return representScalar(Tag.NULL, "");
1316             }
1317         }
1318     }
1319
1320     private static class UnsortedPropertyUtils extends PropertyUtils {
1321         @Override
1322         protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1323                 throws IntrospectionException {
1324             Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1325             return new LinkedHashSet<>(fields);
1326         }
1327     }
1328
1329     private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1330         ObjectMapper objectMapper = new ObjectMapper();
1331         objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1332
1333             Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1334             Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1335             interfaceAsMap.remove("empty");
1336
1337             if(MapUtils.isNotEmpty(operations)) {
1338                 interfaceAsMap.putAll(operations);
1339             }
1340
1341             Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1342
1343             return interfaceObject;
1344
1345     }
1346 }
1347