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