Fixed properties merge logic not to lose properties from inputs
[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.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
80 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
81
82 @org.springframework.stereotype.Component("tosca-export-handler")
83 public class ToscaExportHandler {
84
85     private ApplicationDataTypeCache dataTypeCache;
86     private ToscaOperationFacade toscaOperationFacade;
87     private CapabilityRequirementConverter capabilityRequirementConverter;
88     private PolicyExportParser policyExportParser;
89     private GroupExportParser groupExportParser;
90     private PropertyConvertor propertyConvertor;
91     private InputConverter inputConverter;
92     private InterfaceLifecycleOperation interfaceLifecycleOperation;
93
94     @Autowired
95     public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
96             CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
97             GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
98         this.dataTypeCache = dataTypeCache;
99         this.toscaOperationFacade = toscaOperationFacade;
100         this.capabilityRequirementConverter = capabilityRequirementConverter;
101         this.policyExportParser = policyExportParser;
102         this.groupExportParser = groupExportParser;
103         this.propertyConvertor = PropertyConvertor.getInstance();
104         this.inputConverter =  inputConverter;
105         this.interfaceLifecycleOperation = interfaceLifecycleOperation;
106     }
107
108
109     private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
110
111     private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
112     private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
113     private static final String IMPORTS_FILE_KEY = "file";
114     private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
115     public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
116     private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
117     private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
118     private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
119                                                                                           .getConfigurationManager().getConfiguration().getDefaultImports();
120     private static YamlUtil yamlUtil = new YamlUtil();
121
122     public ToscaExportHandler(){}
123
124     public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
125
126         Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
127         if (toscaTemplateRes.isRight()) {
128             return Either.right(toscaTemplateRes.right().value());
129         }
130
131         ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
132         ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
133         return Either.left(toscaRepresentation);
134     }
135
136     public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
137             boolean isAssociatedComponent) {
138         if (null == DEFAULT_IMPORTS) {
139             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
140             return Either.right(ToscaError.GENERAL_ERROR);
141         }
142
143         ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
144         toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
145         Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
146         Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
147                 toscaTemplate, nodeTypes, isAssociatedComponent);
148         if (toscaTemplateRes.isRight()) {
149             return Either.right(toscaTemplateRes.right().value());
150         }
151
152         toscaTemplate = toscaTemplateRes.left().value();
153         ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
154         return Either.left(toscaRepresentation);
155     }
156
157     public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
158         CustomRepresenter representer = new CustomRepresenter();
159         DumperOptions options = new DumperOptions();
160         options.setAllowReadOnlyProperties(false);
161         options.setPrettyFlow(true);
162
163         options.setDefaultFlowStyle(FlowStyle.FLOW);
164         options.setCanonical(false);
165
166         representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
167
168         representer.setPropertyUtils(new UnsortedPropertyUtils());
169         Yaml yaml = new Yaml(representer, options);
170
171         String yamlAsString = yaml.dumpAsMap(toscaTemplate);
172
173         StringBuilder sb = new StringBuilder();
174         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
175         sb.append(yamlAsString);
176         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
177
178         ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
179         toscaRepresentation.setMainYaml(sb.toString());
180         toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
181
182         return toscaRepresentation;
183     }
184
185     public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
186         ToscaTemplate toscaTemplate = new ToscaTemplate(null);
187         Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
188                 toscaTemplate);
189         if (fillImports.isRight()) {
190             return Either.right(fillImports.right().value());
191         }
192         return Either.left(fillImports.left().value().left);
193     }
194
195     private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
196         if (null == DEFAULT_IMPORTS) {
197             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
198             return Either.right(ToscaError.GENERAL_ERROR);
199         }
200
201         log.trace("start tosca export for {}", component.getUniqueId());
202         ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
203
204         toscaTemplate.setMetadata(convertMetadata(component));
205         toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
206         Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
207         if (ModelConverter.isAtomicComponent(component)) {
208             log.trace("convert component as node type");
209             return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
210         } else {
211             log.trace("convert component as topology template");
212             return convertToscaTemplate(component, toscaTemplate);
213         }
214
215     }
216
217     private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
218
219         Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
220                 toscaNode);
221         if (importsRes.isRight()) {
222             return Either.right(importsRes.right().value());
223         }
224         toscaNode = importsRes.left().value().left;
225         Map<String, Component> componentCache = importsRes.left().value().right;
226         Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
227         if (nodeTypesMapEither.isRight()) {
228             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
229                     nodeTypesMapEither.right().value());
230             return Either.right(nodeTypesMapEither.right().value());
231         }
232         Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
233         if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
234             toscaNode.setNode_types(nodeTypesMap);
235         }
236
237
238         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
239         if (dataTypesEither.isRight()) {
240             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
241             return Either.right(ToscaError.GENERAL_ERROR);
242         }
243         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
244         ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
245         List<InputDefinition> inputDef = component.getInputs();
246         Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
247
248         if (!inputs.isEmpty()) {
249             topologyTemplate.setInputs(inputs);
250         }
251
252         List<ComponentInstance> componentInstances = component.getComponentInstances();
253         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
254                 component.getComponentInstancesProperties();
255         Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
256             component.getComponentInstancesInterfaces();
257         if (componentInstances != null && !componentInstances.isEmpty()) {
258
259             Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
260                     convertNodeTemplates(component, componentInstances,
261                         componentInstancesProperties, componentInstanceInterfaces,
262                         componentCache, dataTypes, topologyTemplate);
263             if (nodeTemplates.isRight()) {
264                 return Either.right(nodeTemplates.right().value());
265             }
266             log.debug("node templates converted");
267
268             topologyTemplate.setNode_templates(nodeTemplates.left().value());
269         }
270
271
272         addGroupsToTopologyTemplate(component, topologyTemplate);
273
274         try {
275             addPoliciesToTopologyTemplate(component, topologyTemplate);
276         } catch (SdcResourceNotFoundException e) {
277             log.debug("Fail to add policies to topology template:",e);
278             return Either.right(ToscaError.GENERAL_ERROR);
279         }
280
281
282         SubstitutionMapping substitutionMapping = new SubstitutionMapping();
283         String toscaResourceName;
284         switch (component.getComponentType()) {
285             case RESOURCE:
286                 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
287                                                                                .getMetadataDataDefinition()).getToscaResourceName();
288                 break;
289             case SERVICE:
290                 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
291                                             + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
292                 break;
293             default:
294                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
295                 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
296         }
297         substitutionMapping.setNode_type(toscaResourceName);
298
299         Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
300         if (capabilities.isRight()) {
301             return Either.right(capabilities.right().value());
302         }
303         substitutionMapping = capabilities.left().value();
304
305         Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
306                                                                        .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
307         if (requirements.isRight()) {
308             return Either.right(requirements.right().value());
309         }
310         substitutionMapping = requirements.left().value();
311
312         topologyTemplate.setSubstitution_mappings(substitutionMapping);
313
314         toscaNode.setTopology_template(topologyTemplate);
315
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             Map<String, ToscaProperty> convertedProperties;
555             convertedProperties = properties.stream().collect(Collectors.toMap(
556                     PropertyDataDefinition::getName,
557                     property -> propertyConvertor.convertProperty(dataTypes, property,
558                             PropertyConvertor.PropertyType.PROPERTY)));
559             // merge component properties and inputs properties
560             mergedProperties.putAll(convertedProperties);
561         }
562         if (MapUtils.isNotEmpty(mergedProperties) && Objects.nonNull(inputDef)) {
563             resolveDefaultPropertyValue(inputDef, mergedProperties, dataTypes);
564             toscaNodeType.setProperties(mergedProperties);
565         }
566
567         /* convert private data_types */
568         List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
569         if (CollectionUtils.isNotEmpty(privateDataTypes) ) {
570             Map<String, ToscaDataType> toscaDataTypeMap = new HashMap<>();
571             for (DataTypeDefinition dataType: privateDataTypes) {
572                 log.debug("Emitting private data type: component.name={} dataType.name={}",
573                         component.getNormalizedName(), dataType.getName());
574                 ToscaDataType toscaDataType = new ToscaDataType();
575                 toscaDataType.setDerived_from(dataType.getDerivedFromName());
576                 toscaDataType.setDescription(dataType.getDescription());
577                 toscaDataType.setVersion(dataType.getVersion());
578                 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
579                     toscaDataType.setProperties(dataType.getProperties().stream()
580                             .collect(Collectors.toMap(
581                                     s -> s.getName(),
582                                     s -> propertyConvertor.convertProperty(dataTypes, s, PropertyConvertor.PropertyType.PROPERTY)
583                             )));
584                 }
585                 toscaDataTypeMap.put(dataType.getName(), toscaDataType);
586             }
587             toscaNode.setData_types(toscaDataTypeMap);
588         }
589
590         // Extracted to method for code reuse
591         return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
592     }
593
594     private void resolveDefaultPropertyValue(List<InputDefinition> inputDef,
595                                              Map<String, ToscaProperty> mergedProperties,
596                                              Map<String, DataTypeDefinition> dataTypes) {
597         for (Map.Entry<String, ToscaProperty> mergedPropertyEntry : mergedProperties.entrySet()) {
598             ToscaProperty value = mergedPropertyEntry.getValue();
599             if (Objects.nonNull(value) && value.getDefaultp() instanceof Map) {
600                 Map<String, Object> valueAsMap = (Map<String, Object>) value.getDefaultp();
601                 Object getInputValue = valueAsMap.get(ToscaFunctions.GET_INPUT.getFunctionName());
602                 if (getInputValue instanceof String) {
603                     String inputName = (String)getInputValue;
604                     Optional<InputDefinition> matchedInputDefinition = inputDef.stream()
605                             .filter(componentInput -> componentInput.getName().equals(inputName))
606                             .findFirst();
607                     if (matchedInputDefinition.isPresent()) {
608                         InputDefinition matchedInput = matchedInputDefinition.get();
609                         Object resolvedDefaultValue = new PropertyConvertor().convertToToscaObject(matchedInput.getType(),
610                                 matchedInput.getDefaultValue(), matchedInput.getSchemaType(), dataTypes, false);
611                         value.setDefaultp(resolvedDefaultValue);
612                         mergedProperties.put(mergedPropertyEntry.getKey(), value);
613                     }
614                 } else if (getInputValue instanceof List) {
615                     // new get_input syntax to refer to sub-element (introduced from TOSCA v1.3)
616                     // e.g. get_input: [input_name, INDEX, inner_property]
617                     // currently resolving default value for the syntax is not supported
618                     log.debug("#resolveDefaultPropertyValue: ignore get_input list syntax. propname={}, val={}",
619                         mergedPropertyEntry.getKey(), getInputValue);
620                 } else {
621                     // Ignore unknown get_input syntax
622                     log.debug("#resolveDefaultPropertyValue: ignore unknown get_input syntax. propname={}, val={}",
623                         mergedPropertyEntry.getKey(), getInputValue);
624                 }
625             }
626         }
627     }
628
629   private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
630                                      List<InputDefinition> inputDef,
631                                      Map<String, ToscaProperty> mergedProperties) {
632     for(InputDefinition input : inputDef) {
633       ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
634       mergedProperties.put(input.getName(), property);
635     }
636   }
637
638     private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
639             Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
640             Map<String, DataTypeDefinition> dataTypes) {
641         Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
642         if (capabilities.isRight()) {
643             return Either.right(capabilities.right().value());
644         }
645         toscaNodeType = capabilities.left().value();
646         log.debug("Capabilities converted for {}", component.getUniqueId());
647
648         Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
649                 toscaNodeType);
650         if (requirements.isRight()) {
651             return Either.right(requirements.right().value());
652         }
653         toscaNodeType = requirements.left().value();
654         log.debug("Requirements converted for {}", component.getUniqueId());
655
656         String toscaResourceName;
657         switch (component.getComponentType()) {
658             case RESOURCE:
659                 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
660                                                                                .getMetadataDataDefinition()).getToscaResourceName();
661                 break;
662             case SERVICE:
663                 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
664                                             + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
665                 break;
666             default:
667                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
668                 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
669         }
670
671         nodeTypes.put(toscaResourceName, toscaNodeType);
672         toscaNode.setNode_types(nodeTypes);
673         log.debug("finish convert node type for {}", component.getUniqueId());
674         return Either.left(toscaNode);
675     }
676
677     protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
678             Component component,
679             List<ComponentInstance> componentInstances,
680             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
681             Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
682             Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
683             ToscaTopolgyTemplate topologyTemplate) {
684
685         Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
686         log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
687                 component.getComponentType());
688         Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
689         Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
690
691         Map<String, ToscaGroupTemplate> groupsMap = null;
692         for (ComponentInstance componentInstance : componentInstances) {
693             ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
694             nodeTemplate.setType(componentInstance.getToscaComponentName());
695             nodeTemplate.setDirectives(componentInstance.getDirectives());
696             nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
697
698             Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
699                                                                     .getOriginComponent(componentCache, componentInstance);
700             if (originComponentRes.isRight()) {
701                 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
702                 break;
703             }
704             Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
705                     componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
706                     originComponentRes.left().value(), componentCache);
707             if (requirements.isRight()) {
708                 convertNodeTemplatesRes = Either.right(requirements.right().value());
709                 break;
710             }
711             String instanceUniqueId = componentInstance.getUniqueId();
712             log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
713
714             nodeTemplate = requirements.left().value();
715
716             Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
717
718             if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
719                 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
720                 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
721             } else {
722                 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
723             }
724
725             Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
726                                                                          .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
727             if (capabilities.isRight()) {
728                 convertNodeTemplatesRes = Either.right(capabilities.right().value());
729                 break;
730             }
731             log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
732
733             nodeTemplate = capabilities.left().value();
734             Map<String, Object> props = new HashMap<>();
735
736             if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
737                 // Adds the properties of parent component to map
738                 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
739             }
740
741             if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)
742                     && !isComponentOfTypeServiceProxy(componentInstance)) {
743                 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
744                         instanceUniqueId, props);
745             }
746
747             if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
748                     && !isComponentOfTypeServiceProxy(componentInstance)) {
749                 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
750                         props);
751             }
752             //M3[00001] - NODE TEMPLATE INTERFACES  - START
753             handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
754                     instanceUniqueId, component);
755             //M3[00001] - NODE TEMPLATE INTERFACES  - END
756             if (props != null && !props.isEmpty()) {
757                 nodeTemplate.setProperties(props);
758             }
759
760             List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
761             if (groupInstances != null) {
762                 if (groupsMap == null) {
763                     groupsMap = new HashMap<>();
764                 }
765                 for (GroupInstance groupInst : groupInstances) {
766                     boolean addToTosca = true;
767
768                     List<String> artifacts = groupInst.getArtifacts();
769                     if (artifacts == null || artifacts.isEmpty()) {
770                         addToTosca = false;
771                     }
772
773                     if (addToTosca) {
774                         ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
775                         groupsMap.put(groupInst.getName(), toscaGroup);
776                     }
777                 }
778             }
779
780             nodeTemplates.put(componentInstance.getName(), nodeTemplate);
781         }
782         if (groupsMap != null) {
783             log.debug("instance groups added");
784             topologyTemplate.addGroups(groupsMap);
785         }
786         if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
787             log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
788                     component.getName());
789             ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
790             log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
791                     component.getName());
792         }
793         if (convertNodeTemplatesRes == null) {
794             convertNodeTemplatesRes = Either.left(nodeTemplates);
795         }
796         log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
797                 component.getComponentType());
798         return convertNodeTemplatesRes;
799     }
800
801     private void handleInstanceInterfaces(
802             Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
803             ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
804             String instanceUniqueId,
805             Component parentComponent) {
806
807         Map<String, Object> interfaces;
808
809         // we need to handle service proxy interfaces
810         if(isComponentOfTypeServiceProxy(componentInstance)) {
811             if(MapUtils.isEmpty(componentInstanceInterfaces)
812                 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
813                 interfaces = null;
814             } else {
815                 List<ComponentInstanceInterface> currServiceInterfaces =
816                     componentInstanceInterfaces.get(instanceUniqueId);
817
818                 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
819                 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
820                     .getUniqueId(), instInterface));
821
822                 interfaces = InterfacesOperationsToscaUtil
823                                      .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
824             }
825         } else {
826             interfaces =
827                 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
828                     componentInstance, instanceUniqueId);
829         }
830         nodeTemplate.setInterfaces(interfaces);
831     }
832
833     private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
834         return Objects.nonNull(componentInstance.getOriginType())
835             && componentInstance.getOriginType().getValue().equals("Service Proxy");
836     }
837
838     //M3[00001] - NODE TEMPLATE INTERFACES  - START
839     private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
840                                                                         ComponentInstance componentInstance,
841                                                                        String instanceUniqueId) {
842         if(MapUtils.isEmpty(componentInstancesInterfaces)) {
843             return null;
844         }
845
846         List<ComponentInstanceInterface> componentInstanceInterfaces =
847             componentInstancesInterfaces.get(instanceUniqueId);
848
849         if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
850           return null;
851         }
852
853         Map<String, Object> interfaces = new HashMap<>();
854         for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
855             interfaces.put(componentInstanceInterface.getInterfaceId(),
856                 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
857         }
858
859         componentInstance.setInterfaces(interfaces);
860
861         return interfaces;
862     }
863
864     private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
865             Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
866             String instanceUniqueId, Map<String, Object> props) {
867
868         List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
869         if (instanceInputsList != null) {
870             instanceInputsList.forEach(input -> {
871
872                 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
873                         ? input.getValue() : input.getDefaultValue();
874                 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
875             });
876         }
877     }
878
879     private void addPropertiesOfComponentInstance(
880             Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
881             Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
882             Map<String, Object> props) {
883
884         if (isNotEmpty(componentInstancesProperties)) {
885             componentInstancesProperties.get(instanceUniqueId)
886                                         // Converts and adds each value to property map
887                                         .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
888                                                 prop::getValue));
889         }
890     }
891
892     private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
893             Component componentOfInstance, Map<String, Object> props) {
894
895         List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
896         if (isNotEmpty(componentProperties)) {
897             componentProperties.stream()
898                     // Filters out properties with empty default values
899                                .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
900                     // Converts and adds each value to property map
901                     .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
902                                        prop::getDefaultValue));
903         }
904     }
905
906     /**
907      * @param dataTypes
908      * @param componentInstance
909      * @param props
910      * @param prop
911      * @param supplier
912      */
913     private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
914             Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
915         Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
916         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
917             props.put(prop.getName(), convertedValue);
918         }
919     }
920
921     private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
922             ComponentInstance componentInstance, T input, Supplier<String> supplier) {
923         log.debug("Convert property or input value {} for instance {}", input.getName(),
924                 componentInstance.getUniqueId());
925         String propertyType = input.getType();
926         String innerType = null;
927         if (input.getSchema() != null && input.getSchema().getProperty() != null) {
928             innerType = input.getSchema().getProperty().getType();
929         }
930         return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
931             dataTypes, true);
932     }
933
934     private ToscaNodeType createNodeType(Component component) {
935         ToscaNodeType toscaNodeType = new ToscaNodeType();
936         if (ModelConverter.isAtomicComponent(component)) {
937             if (((Resource) component).getDerivedFrom() != null) {
938                 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
939             }
940             toscaNodeType.setDescription(component.getDescription());
941         } else {
942             String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
943                                          : "tosca.nodes.Root";
944             toscaNodeType.setDerived_from(derivedFrom);
945         }
946         return toscaNodeType;
947     }
948
949     private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container  ) {
950
951         Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
952         Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
953
954         List<ComponentInstance> componentInstances = container.getComponentInstances();
955
956         if (componentInstances == null || componentInstances.isEmpty()) {
957             return res;
958         }
959         Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
960         List<ComponentInstance> proxyInst = componentInstances.stream()
961                                                               .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
962                                                               .collect(Collectors.toList());
963         if (proxyInst != null && !proxyInst.isEmpty()) {
964             for (ComponentInstance inst : proxyInst) {
965                 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
966             }
967         }
968
969         if (serviceProxyInstanceList.isEmpty()) {
970             return res;
971         }
972         ComponentParametersView filter = new ComponentParametersView(true);
973         filter.setIgnoreCapabilities(false);
974         filter.setIgnoreComponentInstances(false);
975         Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
976                                                                               .getLatestByName("serviceProxy");
977         if (serviceProxyOrigin.isRight()) {
978             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
979                     serviceProxyOrigin.right().value());
980             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
981         }
982         Component origComponent = serviceProxyOrigin.left().value();
983
984         for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
985             Component serviceComponent = null;
986             ComponentParametersView componentParametersView = new ComponentParametersView();
987             componentParametersView.disableAll();
988             componentParametersView.setIgnoreCategories(false);
989             Either<Component, StorageOperationStatus> service = toscaOperationFacade
990                                                                         .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
991             if (service.isRight()) {
992                 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(),  entryProxy.getValue().getName());
993             } else {
994                 serviceComponent = service.left().value();
995             }
996
997             ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
998             nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
999         }
1000
1001         return Either.left(nodeTypesMap);
1002     }
1003
1004     private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
1005             ComponentInstance instance) {
1006         ToscaNodeType toscaNodeType = new ToscaNodeType();
1007         String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1008
1009         toscaNodeType.setDerived_from(derivedFrom);
1010         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
1011         if (dataTypesEither.isRight()) {
1012             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1013         }
1014         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1015         Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1016                                                             .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
1017
1018         toscaNodeType.setCapabilities(capabilities);
1019
1020         return toscaNodeType;
1021     }
1022
1023     private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1024             ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
1025             ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
1026
1027         List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1028         if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
1029             log.debug("Failed to convert component instance requirements for the component instance {}. ",
1030                     componentInstance.getName());
1031             return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1032         }
1033         if (!toscaRequirements.isEmpty()) {
1034             nodeTypeTemplate.setRequirements(toscaRequirements);
1035         }
1036         log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1037         return Either.left(nodeTypeTemplate);
1038     }
1039
1040     private boolean addRequirements(Component component, ComponentInstance componentInstance,
1041             List<RequirementCapabilityRelDef> relations, Component originComponent,
1042             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1043         List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1044                                                                        .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1045         return isEmpty(filteredRelations) ||
1046                        filteredRelations.stream()
1047                                         .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1048     }
1049
1050     private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1051             List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1052             List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1053
1054         boolean result = true;
1055         Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1056         RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1057         Either<Component, StorageOperationStatus> getOriginRes = null;
1058         Optional<RequirementDefinition> reqOpt = Optional.empty();
1059         Component toOriginComponent = null;
1060         Optional<CapabilityDefinition> capOpt = Optional.empty();
1061
1062         ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1063                                                     .findFirst().orElse(null);
1064         if (toInstance == null) {
1065             log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1066                     rel.getToNode());
1067             result = false;
1068         }
1069         if (result) {
1070             reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1071             if (!reqOpt.isPresent()) {
1072                 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1073                         reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1074                 result = false;
1075             }
1076         }
1077         if (result) {
1078             ComponentParametersView filter = new ComponentParametersView(true);
1079             filter.setIgnoreComponentInstances(false);
1080             filter.setIgnoreCapabilities(false);
1081             filter.setIgnoreGroups(false);
1082             getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1083             if (getOriginRes.isRight()) {
1084                 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1085                         reqOpt.get().getName(), toInstance.getActualComponentUid());
1086                 result = false;
1087             }
1088         }
1089         if (result) {
1090             toOriginComponent = getOriginRes.left().value();
1091             capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1092                                       .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1093             if (!capOpt.isPresent()) {
1094                 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1095                 if(!capOpt.isPresent()){
1096                     result = false;
1097                     log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1098                             reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1099                 }
1100             }
1101         }
1102         if (result) {
1103             result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1104                     reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1105         }
1106         return result;
1107     }
1108
1109     private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1110         return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1111     }
1112
1113     private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1114         Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1115         if (!cap.isPresent()) {
1116             log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1117         }
1118         return cap;
1119     }
1120
1121     private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1122         List<String> reducedPath = capability.getPath();
1123         if(capability.getOwnerId() !=null){
1124             reducedPath =   capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1125         }
1126         Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1127                 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1128         if (buildCapNameRes.isRight()) {
1129             log.debug(
1130                     "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1131                     reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1132             return false;
1133         }
1134         Either<String, Boolean> buildReqNameRes  = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1135                 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1136         if (buildReqNameRes.isRight()) {
1137             log.debug(
1138                     "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1139                     reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1140             return false;
1141         }
1142         ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1143         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1144         toscaRequirement.setNode(toInstance.getName());
1145         toscaRequirement.setCapability(buildCapNameRes.left().value());
1146         toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1147         toscaRequirements.add(toscaReqMap);
1148         return true;
1149     }
1150
1151     private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair,  String fromInstanceId) {
1152         for(List<RequirementDefinition> reqList: reqMap.values()){
1153             Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1154             if(reqOpt.isPresent()){
1155                 return reqOpt;
1156             }
1157         }
1158         return Optional.empty();
1159     }
1160
1161     /**
1162      * Allows detecting the requirement belonging to the received relationship
1163      * The detection logic is: A requirement belongs to a relationship IF 1.The
1164      * name of the requirement equals to the "requirement" field of the
1165      * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1166      * requirement equals to requirementOwnerId of the relation OR uniqueId of
1167      * toInstance equals to capabilityOwnerId of the relation
1168      */
1169     private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1170         if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1171             log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}",
1172                     requirement.getName(), reqAndRelationshipPair.getRequirement());
1173             return false;
1174         }
1175         return ModelConverter.isAtomicComponent(originComponent) ||
1176                        isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1177     }
1178
1179     private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1180         return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1181     }
1182
1183     private boolean isCvfc(Component component) {
1184         return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1185                        ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1186     }
1187
1188     private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1189             SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1190
1191         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1192         Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1193                                                                                  .convertSubstitutionMappingCapabilities(componentCache, component);
1194         if (toscaCapabilitiesRes.isRight()) {
1195             result = Either.right(toscaCapabilitiesRes.right().value());
1196             log.debug("Failed convert capabilities for the component {}. ", component.getName());
1197         } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1198             substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1199             log.debug("Finish convert capabilities for the component {}. ", component.getName());
1200         }
1201         log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1202         return result;
1203     }
1204
1205     private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1206             Map<String, DataTypeDefinition> dataTypes) {
1207         Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1208                 dataTypes);
1209         if (!toscaCapabilities.isEmpty()) {
1210             nodeType.setCapabilities(toscaCapabilities);
1211         }
1212         log.debug("Finish convert Capabilities for node type");
1213
1214         return Either.left(nodeType);
1215     }
1216
1217
1218     protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1219         if (inNodeFilter == null){
1220             return null;
1221         }
1222         NodeFilter nodeFilter = new NodeFilter();
1223
1224         ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1225                 inNodeFilter.getCapabilities();
1226
1227         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1228
1229         List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1230         List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1231
1232         copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1233         copyNodeFilterProperties(origProperties, propertiesCopy);
1234
1235         if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1236             nodeFilter.setCapabilities(capabilitiesCopy);
1237         }
1238
1239         if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1240             nodeFilter.setProperties(propertiesCopy);
1241         }
1242
1243         nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1244
1245
1246         nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1247
1248         return nodeFilter;
1249     }
1250
1251     private Object cloneToscaId(Object toscaId) {
1252         return Objects.isNull(toscaId) ? null
1253                        : cloneObjectFromYml(toscaId, toscaId.getClass());
1254     }
1255
1256
1257     private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1258         String objectAsYml = yamlUtil.objectToYaml(objToClone);
1259         return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1260     }
1261     private void copyNodeFilterCapabilitiesTemplate(
1262             ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1263             List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1264         if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1265                    origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1266             return;
1267         }
1268         for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1269             Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1270             CapabilityFilter capabilityFilter = new CapabilityFilter();
1271             List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1272             copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1273             capabilityFilter.setProperties(propertiesCopy);
1274             capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1275             capabilitiesCopy.add(capabilityFilterCopyMap);
1276         }
1277     }
1278
1279     private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1280         String listAsString = yamlUtil.objectToYaml(propertyList);
1281         return yamlUtil.yamlToObject(listAsString, List.class);
1282     }
1283
1284
1285     private void copyNodeFilterProperties(
1286             ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1287             List<Map<String, List<Object>>> propertiesCopy) {
1288         if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1289                    origProperties.isEmpty()) {
1290             return;
1291         }
1292         for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1293             Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1294             for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1295                 Map propertyValObj =  new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1296                 if (propertyMapCopy.containsKey(propertyDataDefinition.getName())){
1297                     propertyMapCopy.get(propertyDataDefinition.getName()).add(propertyValObj);
1298                 } else {
1299                     if (propertyDataDefinition.getName() != null) {
1300                         List propsList =new ArrayList();
1301                         propsList.add(propertyValObj);
1302                         propertyMapCopy.put(propertyDataDefinition.getName(), propsList);
1303                     } else {
1304                         propertyMapCopy.putAll(propertyValObj);
1305                     }
1306                 }
1307             }
1308             propertiesCopy.add(propertyMapCopy);
1309         }
1310
1311     }
1312
1313     private static class CustomRepresenter extends Representer {
1314         public CustomRepresenter() {
1315             super();
1316             // null representer is exceptional and it is stored as an instance
1317             // variable.
1318             this.nullRepresenter = new RepresentNull();
1319
1320         }
1321
1322         @Override
1323         protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1324                 Tag customTag) {
1325             if (propertyValue == null) {
1326                 return null;
1327             } else {
1328                 // skip not relevant for Tosca property
1329                 if ("dependencies".equals(property.getName())) {
1330                     return null;
1331                 }
1332                 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1333
1334                 return "_defaultp_".equals(property.getName())
1335                                ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1336             }
1337         }
1338
1339         @Override
1340         protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1341             // remove the bean type from the output yaml (!! ...)
1342             if (!classTags.containsKey(javaBean.getClass())) {
1343                 addClassTag(javaBean.getClass(), Tag.MAP);
1344             }
1345
1346             return super.representJavaBean(properties, javaBean);
1347         }
1348
1349         private class RepresentNull implements Represent {
1350             @Override
1351             public Node representData(Object data) {
1352                 // possible values are here http://yaml.org/type/null.html
1353                 return representScalar(Tag.NULL, "");
1354             }
1355         }
1356     }
1357
1358     private static class UnsortedPropertyUtils extends PropertyUtils {
1359         @Override
1360         protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1361                 throws IntrospectionException {
1362             Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1363             return new LinkedHashSet<>(fields);
1364         }
1365     }
1366
1367     private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1368         ObjectMapper objectMapper = new ObjectMapper();
1369         objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1370
1371             Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1372             Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1373             interfaceAsMap.remove("empty");
1374
1375             if(MapUtils.isNotEmpty(operations)) {
1376                 interfaceAsMap.putAll(operations);
1377             }
1378
1379             Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1380
1381             return interfaceObject;
1382
1383     }
1384 }
1385