Add support for substitution_filter business logic
[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 static org.apache.commons.collections.CollectionUtils.isEmpty;
24 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
25 import static org.apache.commons.collections.MapUtils.isNotEmpty;
26 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.resolvePropertyValueFromInput;
27 import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.addInterfaceTypeElement;
28
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.fasterxml.jackson.databind.SerializationFeature;
31 import fj.data.Either;
32 import java.beans.IntrospectionException;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.LinkedHashSet;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Objects;
42 import java.util.Optional;
43 import java.util.Set;
44 import java.util.function.Supplier;
45 import java.util.stream.Collectors;
46 import org.apache.commons.collections.CollectionUtils;
47 import org.apache.commons.collections.MapUtils;
48 import org.apache.commons.lang.StringUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.apache.commons.lang3.tuple.ImmutableTriple;
51 import org.apache.commons.lang3.tuple.Triple;
52 import org.onap.sdc.tosca.services.YamlUtil;
53 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
54 import org.openecomp.sdc.be.config.ConfigurationManager;
55 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
56 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
61 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition;
62 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition;
63 import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition;
64 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition;
65 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
66 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
67 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
68 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
69 import org.openecomp.sdc.be.model.ArtifactDefinition;
70 import org.openecomp.sdc.be.model.CapabilityDefinition;
71 import org.openecomp.sdc.be.model.Component;
72 import org.openecomp.sdc.be.model.ComponentInstance;
73 import org.openecomp.sdc.be.model.ComponentInstanceInput;
74 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
75 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
76 import org.openecomp.sdc.be.model.ComponentParametersView;
77 import org.openecomp.sdc.be.model.DataTypeDefinition;
78 import org.openecomp.sdc.be.model.GroupInstance;
79 import org.openecomp.sdc.be.model.InputDefinition;
80 import org.openecomp.sdc.be.model.InterfaceDefinition;
81 import org.openecomp.sdc.be.model.PropertyDefinition;
82 import org.openecomp.sdc.be.model.RelationshipInfo;
83 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
84 import org.openecomp.sdc.be.model.RequirementDefinition;
85 import org.openecomp.sdc.be.model.Resource;
86 import org.openecomp.sdc.be.model.Service;
87 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
88 import org.openecomp.sdc.be.model.category.CategoryDefinition;
89 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
90 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
91 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
92 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
93 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
94 import org.openecomp.sdc.be.tosca.model.CapabilityFilter;
95 import org.openecomp.sdc.be.tosca.model.NodeFilter;
96 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
97 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
98 import org.openecomp.sdc.be.tosca.model.ToscaDataType;
99 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
100 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
101 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
102 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
103 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
104 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
105 import org.openecomp.sdc.be.tosca.model.ToscaRequirement;
106 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
107 import org.openecomp.sdc.be.tosca.model.ToscaTemplateArtifact;
108 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
109 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
110 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
111 import org.openecomp.sdc.be.tosca.utils.InputConverter;
112 import org.openecomp.sdc.common.log.wrappers.Logger;
113 import org.openecomp.sdc.externalupload.utils.ServiceUtils;
114 import org.springframework.beans.factory.annotation.Autowired;
115 import org.yaml.snakeyaml.DumperOptions;
116 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
117 import org.yaml.snakeyaml.Yaml;
118 import org.yaml.snakeyaml.introspector.BeanAccess;
119 import org.yaml.snakeyaml.introspector.Property;
120 import org.yaml.snakeyaml.introspector.PropertyUtils;
121 import org.yaml.snakeyaml.nodes.MappingNode;
122 import org.yaml.snakeyaml.nodes.Node;
123 import org.yaml.snakeyaml.nodes.NodeTuple;
124 import org.yaml.snakeyaml.nodes.Tag;
125 import org.yaml.snakeyaml.representer.Represent;
126 import org.yaml.snakeyaml.representer.Representer;
127
128 @org.springframework.stereotype.Component("tosca-export-handler")
129 public class ToscaExportHandler {
130
131     private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
132
133     private ApplicationDataTypeCache dataTypeCache;
134     private ToscaOperationFacade toscaOperationFacade;
135     private CapabilityRequirementConverter capabilityRequirementConverter;
136     private PolicyExportParser policyExportParser;
137     private GroupExportParser groupExportParser;
138     private PropertyConvertor propertyConvertor;
139     private InputConverter inputConverter;
140     private InterfaceLifecycleOperation interfaceLifecycleOperation;
141     private InterfacesOperationsConverter interfacesOperationsConverter;
142
143     @Autowired
144     public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
145                               CapabilityRequirementConverter capabilityRequirementConverter,
146                               PolicyExportParser policyExportParser,
147                               GroupExportParser groupExportParser, PropertyConvertor propertyConvertor,
148                               InputConverter inputConverter,
149                               InterfaceLifecycleOperation interfaceLifecycleOperation,
150                               InterfacesOperationsConverter interfacesOperationsConverter) {
151         this.dataTypeCache = dataTypeCache;
152         this.toscaOperationFacade = toscaOperationFacade;
153         this.capabilityRequirementConverter = capabilityRequirementConverter;
154         this.policyExportParser = policyExportParser;
155         this.groupExportParser = groupExportParser;
156         this.propertyConvertor = propertyConvertor;
157         this.inputConverter = inputConverter;
158         this.interfaceLifecycleOperation = interfaceLifecycleOperation;
159         this.interfacesOperationsConverter = interfacesOperationsConverter;
160     }
161
162     private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
163     private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
164     private static final String IMPORTS_FILE_KEY = "file";
165     private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
166     public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
167     private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
168     private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
169     private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
170         .getConfigurationManager().getConfiguration().getDefaultImports();
171     private static final String NATIVE_ROOT = "tosca.nodes.Root";
172     private static YamlUtil yamlUtil = new YamlUtil();
173
174     public ToscaExportHandler() {
175     }
176
177     public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
178         return convertToToscaTemplate(component).left().map(this::createToscaRepresentation);
179     }
180
181     public Either<ToscaRepresentation, ToscaError> exportComponentInterface(final Component component,
182                                                                             final boolean isAssociatedComponent) {
183         if (null == DEFAULT_IMPORTS) {
184             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
185             return Either.right(ToscaError.GENERAL_ERROR);
186         }
187
188         String toscaVersion = null;
189         if (component instanceof Resource) {
190             toscaVersion = ((Resource) component).getToscaVersion();
191         }
192         ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
193         toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
194         final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
195         final Either<ToscaTemplate, ToscaError> toscaTemplateRes =
196             convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes, isAssociatedComponent);
197         if (toscaTemplateRes.isRight()) {
198             return Either.right(toscaTemplateRes.right().value());
199         }
200
201         toscaTemplate = toscaTemplateRes.left().value();
202         ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
203         return Either.left(toscaRepresentation);
204     }
205
206     public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
207         CustomRepresenter representer = new CustomRepresenter();
208         DumperOptions options = new DumperOptions();
209         options.setAllowReadOnlyProperties(false);
210         options.setPrettyFlow(true);
211
212         options.setDefaultFlowStyle(FlowStyle.FLOW);
213         options.setCanonical(false);
214
215         representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
216
217         representer.setPropertyUtils(new UnsortedPropertyUtils());
218         Yaml yaml = new Yaml(representer, options);
219
220         String yamlAsString = yaml.dumpAsMap(toscaTemplate);
221
222         StringBuilder sb = new StringBuilder();
223         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
224         sb.append(yamlAsString);
225         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
226
227         return ToscaRepresentation.make(sb.toString().getBytes(), toscaTemplate);
228     }
229
230     public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
231         ToscaTemplate toscaTemplate = new ToscaTemplate(null);
232         Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
233             toscaTemplate);
234         if (fillImports.isRight()) {
235             return Either.right(fillImports.right().value());
236         }
237         return Either.left(fillImports.left().value().left);
238     }
239
240     public Either<ToscaTemplate, ToscaError> convertToToscaTemplate(final Component component) {
241         if (null == DEFAULT_IMPORTS) {
242             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
243             return Either.right(ToscaError.GENERAL_ERROR);
244         }
245         log.trace("start tosca export for {}", component.getUniqueId());
246         String toscaVersion = null;
247         if (component instanceof Resource) {
248             toscaVersion = ((Resource) component).getToscaVersion();
249         }
250         final ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
251         toscaTemplate.setMetadata(convertMetadata(component));
252         toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
253         final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
254         if (ModelConverter.isAtomicComponent(component)) {
255             log.trace("convert component as node type");
256             return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
257         } else {
258             log.trace("convert component as topology template");
259             return convertToscaTemplate(component, toscaTemplate);
260         }
261
262     }
263
264     private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
265
266         Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
267             toscaNode);
268         if (importsRes.isRight()) {
269             return Either.right(importsRes.right().value());
270         }
271         toscaNode = importsRes.left().value().left;
272         Map<String, Component> componentCache = importsRes.left().value().right;
273         Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache,
274             component);
275         if (nodeTypesMapEither.isRight()) {
276             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
277                 nodeTypesMapEither.right().value());
278             return Either.right(nodeTypesMapEither.right().value());
279         }
280         Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
281         if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
282             toscaNode.setNode_types(nodeTypesMap);
283         }
284
285         Either<Map<String, Object>, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component);
286         if (proxyInterfaceTypesEither.isRight()) {
287             log.debug("Failed to populate service proxy local interface types in tosca, error {}",
288                 nodeTypesMapEither.right().value());
289             return Either.right(proxyInterfaceTypesEither.right().value());
290         }
291         Map<String, Object> proxyInterfaceTypes = proxyInterfaceTypesEither.left().value();
292         if (MapUtils.isNotEmpty(proxyInterfaceTypes)) {
293             toscaNode.setInterface_types(proxyInterfaceTypes);
294         }
295
296         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
297         if (dataTypesEither.isRight()) {
298             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
299             return Either.right(ToscaError.GENERAL_ERROR);
300         }
301         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
302         ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
303         List<InputDefinition> inputDef = component.getInputs();
304         Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
305
306         if (!inputs.isEmpty()) {
307             topologyTemplate.setInputs(inputs);
308         }
309
310         final List<ComponentInstance> componentInstances = component.getComponentInstances();
311         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
312             component.getComponentInstancesProperties();
313         Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
314             component.getComponentInstancesInterfaces();
315         SubstitutionMapping substitutionMapping = new SubstitutionMapping();
316         if (CollectionUtils.isNotEmpty(componentInstances)) {
317             final Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
318                 convertNodeTemplates(component, componentInstances,
319                     componentInstancesProperties, componentInstanceInterfaces,
320                     componentCache, dataTypes, topologyTemplate);
321             if (nodeTemplates.isRight()) {
322                 return Either.right(nodeTemplates.right().value());
323             }
324             log.debug("node templates converted");
325             topologyTemplate.setNode_templates(nodeTemplates.left().value());
326
327             convertSubstitutionMappingFilter(componentInstances, substitutionMapping);
328         }
329
330         addGroupsToTopologyTemplate(component, topologyTemplate);
331
332         try {
333             addPoliciesToTopologyTemplate(component, topologyTemplate);
334         } catch (SdcResourceNotFoundException e) {
335             log.debug("Fail to add policies to topology template:", e);
336             return Either.right(ToscaError.GENERAL_ERROR);
337         }
338
339         String toscaResourceName;
340         switch (component.getComponentType()) {
341             case RESOURCE:
342                 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
343                     .getMetadataDataDefinition()).getToscaResourceName();
344                 break;
345             case SERVICE:
346                 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
347                     + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
348                 break;
349             default:
350                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
351                 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
352         }
353         substitutionMapping.setNode_type(toscaResourceName);
354         Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
355             componentCache);
356         if (capabilities.isRight()) {
357             return Either.right(capabilities.right().value());
358         }
359         substitutionMapping = capabilities.left().value();
360
361         Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
362             .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
363         if (requirements.isRight()) {
364             return Either.right(requirements.right().value());
365         }
366         substitutionMapping = requirements.left().value();
367
368         topologyTemplate.setSubstitution_mappings(substitutionMapping);
369
370         toscaNode.setTopology_template(topologyTemplate);
371
372         return Either.left(toscaNode);
373     }
374
375     private void convertSubstitutionMappingFilter(final List<ComponentInstance> componentInstances,
376                                                   final SubstitutionMapping substitutionMapping) {
377         componentInstances.stream()
378             .filter(componentInstance -> hasSubstitutionFilterDataDefinition(componentInstance.getSubstitutionFilter()))
379             .forEach(componentInstance -> substitutionMapping
380                 .setSubstitution_filter(convertToSubstitutionFilterComponent(componentInstance.getSubstitutionFilter())));
381     }
382
383     private boolean hasSubstitutionFilterDataDefinition(
384         final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
385
386         return substitutionFilterDataDefinition != null && substitutionFilterDataDefinition.getProperties() != null
387             && CollectionUtils.isNotEmpty(substitutionFilterDataDefinition.getProperties().getListToscaDataDefinition());
388     }
389
390     private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
391         Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
392         if (groups != null) {
393             topologyTemplate.addGroups(groups);
394         }
395     }
396
397     private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
398         throws SdcResourceNotFoundException {
399         Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
400         if (policies != null) {
401             topologyTemplate.addPolicies(policies);
402         }
403     }
404
405     private ToscaMetadata convertMetadata(Component component) {
406         return convertMetadata(component, false, null);
407     }
408
409     private ToscaMetadata convertMetadata(Component component, boolean isInstance,
410                                           ComponentInstance componentInstance) {
411         ToscaMetadata toscaMetadata = new ToscaMetadata();
412         toscaMetadata.setInvariantUUID(component.getInvariantUUID());
413         toscaMetadata.setUUID(component.getUUID());
414         toscaMetadata.setDescription(component.getDescription());
415         toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
416
417         List<CategoryDefinition> categories = component.getCategories();
418         CategoryDefinition categoryDefinition = categories.get(0);
419         toscaMetadata.setCategory(categoryDefinition.getName());
420
421         if (isInstance) {
422             toscaMetadata.setVersion(component.getVersion());
423             toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
424             if (componentInstance.getSourceModelInvariant() != null
425                 && !componentInstance.getSourceModelInvariant().isEmpty()) {
426                 toscaMetadata.setVersion(componentInstance.getComponentVersion());
427                 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
428                 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
429                 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
430                 toscaMetadata.setName(
431                     componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
432                 toscaMetadata.setDescription(componentInstance.getDescription());
433             }
434
435         }
436         switch (component.getComponentType()) {
437             case RESOURCE:
438                 Resource resource = (Resource) component;
439
440                 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
441                     toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
442                 } else {
443                     toscaMetadata.setType(resource.getResourceType().name());
444                 }
445                 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
446                 toscaMetadata.setResourceVendor(resource.getVendorName());
447                 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
448                 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
449                 break;
450             case SERVICE:
451                 Service service = (Service) component;
452                 toscaMetadata.setType(component.getComponentType().getValue());
453                 toscaMetadata.setServiceType(service.getServiceType());
454                 toscaMetadata.setServiceRole(service.getServiceRole());
455                 toscaMetadata.setServiceFunction(service.getServiceFunction());
456                 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
457                 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
458                 if (!isInstance) {
459                     // DE268546
460                     toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
461                     toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
462                     toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
463                 }
464                 break;
465             default:
466                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
467         }
468         return toscaMetadata;
469     }
470
471     private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
472         if (service.getInstantiationType() != null) {
473             toscaMetadata.setInstantiationType(service.getInstantiationType());
474         } else {
475             toscaMetadata.setInstantiationType(StringUtils.EMPTY);
476         }
477     }
478
479     private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
480                                                                                                  ToscaTemplate toscaTemplate) {
481
482         if (null == DEFAULT_IMPORTS) {
483             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
484             return Either.right(ToscaError.GENERAL_ERROR);
485         }
486         Map<String, Component> componentCache = new HashMap<>();
487
488         if (!ModelConverter.isAtomicComponent(component)) {
489             List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
490                 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
491
492             List<Triple<String, String, Component>> dependecies = new ArrayList<>();
493
494             Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
495             if (isNotEmpty(toscaArtifacts)) {
496                 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
497                 if (artifactDefinition != null) {
498                     Map<String, Map<String, String>> importsListMember = new HashMap<>();
499                     Map<String, String> interfaceFiles = new HashMap<>();
500                     interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
501                     StringBuilder keyNameBuilder = new StringBuilder();
502                     keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
503                         .append(component.getName()).append("-interface");
504                     importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
505                     additionalImports.add(importsListMember);
506                 }
507             }
508             List<ComponentInstance> componentInstances = component.getComponentInstances();
509             if (componentInstances != null && !componentInstances.isEmpty()) {
510                 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
511             }
512             toscaTemplate.setDependencies(dependecies);
513             toscaTemplate.setImports(additionalImports);
514         } else {
515             log.debug("currently imports supported for VF and service only");
516         }
517         return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
518     }
519
520     private void createDependency(final Map<String, Component> componentCache,
521                                   final List<Map<String, Map<String, String>>> imports,
522                                   final List<Triple<String, String, Component>> dependencies,
523                                   final ComponentInstance componentInstance) {
524         log.debug("createDependency componentCache {}", componentCache);
525         final Component componentRI = componentCache.get(componentInstance.getComponentUid());
526         if (componentRI == null) {
527             // all resource must be only once!
528             final Either<Component, StorageOperationStatus> resource = toscaOperationFacade
529                 .getToscaFullElement(componentInstance.getComponentUid());
530             if ((resource.isRight()) && (log.isDebugEnabled())) {
531                 log.debug("Failed to fetch resource with id {} for instance {}", componentInstance.getComponentUid(),
532                     componentInstance.getUniqueId());
533                 return;
534             }
535             final Component fetchedComponent = resource.left().value();
536             setComponentCache(componentCache, componentInstance, fetchedComponent);
537             addDependencies(imports, dependencies, fetchedComponent);
538         }
539     }
540
541     /**
542      * Sets a componentCache from the given component/resource.
543      */
544     private void setComponentCache(final Map<String, Component> componentCache,
545                                    final ComponentInstance componentInstance,
546                                    final Component fetchedComponent) {
547         componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
548         if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
549             final Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
550                 .getToscaFullElement(componentInstance.getSourceModelUid());
551             if (sourceService.isRight() && (log.isDebugEnabled())) {
552                 log.debug("Failed to fetch source service with id {} for proxy {}",
553                     componentInstance.getSourceModelUid(), componentInstance.getUniqueId());
554             }
555             final Component fetchedSource = sourceService.left().value();
556             componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
557         }
558     }
559
560     /**
561      * Retrieves all derived_from nodes and stores it in a predictable order.
562      */
563     private void addDependencies(final List<Map<String, Map<String, String>>> imports,
564                                  final List<Triple<String, String, Component>> dependencies,
565                                  final Component fetchedComponent) {
566         final Set<Component> componentsList = new LinkedHashSet<>();
567         if (fetchedComponent instanceof Resource) {
568             log.debug("fetchedComponent is a resource {}", fetchedComponent);
569
570             final Optional<Map<String, String>> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent,
571                 componentsList);
572             if (derivedFromMapOfIdToName.isPresent()) {
573                 derivedFromMapOfIdToName.get().entrySet().forEach(entry -> {
574                     log.debug("Started entry.getValue() : {}", entry.getValue());
575                     if (!NATIVE_ROOT.equals(entry.getValue())) {
576                         Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
577                             .getToscaElement(entry.getKey());
578                         if (resourcefetched != null && resourcefetched.isLeft()) {
579                             componentsList.add(resourcefetched.left().value());
580                         }
581                     }
582                 });
583             }
584             setImports(imports, dependencies, componentsList);
585         }
586     }
587
588     /**
589      * Returns all derived_from nodes found.
590      */
591     private Optional<Map<String, String>> getDerivedFromMapOfIdToName(final Component fetchedComponent,
592                                                                       final Set<Component> componentsList) {
593         final Resource parentResource = (Resource) fetchedComponent;
594         Map<String, String> derivedFromMapOfIdToName = new HashMap<>();
595         if (CollectionUtils.isNotEmpty(parentResource.getComponentInstances())) {
596             componentsList.add(fetchedComponent);
597             for (final ComponentInstance componentInstance : parentResource.getComponentInstances()) {
598                 final Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
599                     .getToscaElement(componentInstance.getComponentUid());
600                 if (resourcefetched != null && resourcefetched.isLeft()) {
601                     final Map<String, String> derivedWithId = resourcefetched.left().value()
602                         .getDerivedFromMapOfIdToName();
603                     if (MapUtils.isNotEmpty(derivedWithId)) {
604                         derivedFromMapOfIdToName.putAll(derivedWithId);
605                     }
606                 }
607             }
608         } else {
609             derivedFromMapOfIdToName = parentResource.getDerivedFromMapOfIdToName();
610         }
611         log.debug("Started derivedFromMapOfIdToName: {}", derivedFromMapOfIdToName);
612         return Optional.ofNullable(derivedFromMapOfIdToName);
613     }
614
615     /**
616      * Creates a resource map and adds it to the import list.
617      */
618     private void setImports(final List<Map<String, Map<String, String>>> imports,
619                             final List<Triple<String, String, Component>> dependencies,
620                             final Set<Component> componentsList) {
621         componentsList.forEach(component -> {
622             final Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
623             final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
624             if (artifactDefinition != null) {
625                 final Map<String, String> files = new HashMap<>();
626                 final String artifactName = artifactDefinition.getArtifactName();
627                 files.put(IMPORTS_FILE_KEY, artifactName);
628                 final StringBuilder keyNameBuilder = new StringBuilder();
629                 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
630                 keyNameBuilder.append("-");
631                 keyNameBuilder.append(component.getName());
632                 addImports(imports, keyNameBuilder, files);
633                 dependencies
634                     .add(new ImmutableTriple<String, String, Component>(artifactName, artifactDefinition.getEsId(),
635                         component));
636
637                 if (!ModelConverter.isAtomicComponent(component)) {
638                     final Map<String, String> interfaceFiles = new HashMap<>();
639                     interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
640                     keyNameBuilder.append("-interface");
641                     addImports(imports, keyNameBuilder, interfaceFiles);
642                 }
643             }
644         });
645     }
646
647     /**
648      * Adds the found resource to the import definition list.
649      */
650     private void addImports(final List<Map<String, Map<String, String>>> imports,
651                             final StringBuilder keyNameBuilder,
652                             final Map<String, String> files) {
653         final String mapKey = keyNameBuilder.toString();
654         if (imports.stream().allMatch(stringMapMap -> stringMapMap.get(mapKey) == null)) {
655             final Map<String, Map<String, String>> importsListMember = new HashMap<>();
656             importsListMember.put(keyNameBuilder.toString(), files);
657             imports.add(importsListMember);
658         }
659     }
660
661     public static String getInterfaceFilename(String artifactName) {
662         return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
663     }
664
665     private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache,
666                                                               Component component, ToscaTemplate toscaNode,
667                                                               Map<String, ToscaNodeType> nodeTypes) {
668         return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
669     }
670
671     public Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
672                                                                       Component component, ToscaTemplate toscaNode,
673                                                                       Map<String, ToscaNodeType> nodeTypes,
674                                                                       boolean isAssociatedComponent) {
675         log.debug("start convert node type for {}", component.getUniqueId());
676         ToscaNodeType toscaNodeType = createNodeType(component);
677
678         Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
679             interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
680         if (lifecycleTypeEither.isRight()) {
681             log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
682             return Either.right(ToscaError.GENERAL_ERROR);
683         }
684         List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
685             .values()
686             .stream()
687             .map(InterfaceDataDefinition::getType)
688             .collect(Collectors.toList());
689         toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
690
691         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
692         if (dataTypesEither.isRight()) {
693             log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
694             return Either.right(ToscaError.GENERAL_ERROR);
695         }
696
697         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
698
699         List<InputDefinition> inputDef = component.getInputs();
700         Map<String, ToscaProperty> mergedProperties = new HashMap<>();
701         interfacesOperationsConverter
702             .addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
703         addInputsToProperties(dataTypes, inputDef, mergedProperties);
704
705         if (CollectionUtils.isNotEmpty(component.getProperties())) {
706             List<PropertyDefinition> properties = component.getProperties();
707             Map<String, ToscaProperty> convertedProperties = properties.stream()
708                 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs()))
709                 .collect(Collectors.toMap(PropertyDataDefinition::getName,
710                     property -> propertyConvertor.convertProperty(dataTypes, property,
711                         PropertyConvertor.PropertyType.PROPERTY)));
712             // merge component properties and inputs properties
713             mergedProperties.putAll(convertedProperties);
714         }
715         if (MapUtils.isNotEmpty(mergedProperties)) {
716             toscaNodeType.setProperties(mergedProperties);
717         }
718
719         /* convert private data_types */
720         List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
721         if (CollectionUtils.isNotEmpty(privateDataTypes)) {
722             Map<String, ToscaDataType> toscaDataTypeMap = new HashMap<>();
723             for (DataTypeDefinition dataType : privateDataTypes) {
724                 log.debug("Emitting private data type: component.name={} dataType.name={}",
725                     component.getNormalizedName(), dataType.getName());
726                 ToscaDataType toscaDataType = new ToscaDataType();
727                 toscaDataType.setDerived_from(dataType.getDerivedFromName());
728                 toscaDataType.setDescription(dataType.getDescription());
729                 toscaDataType.setVersion(dataType.getVersion());
730                 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
731                     toscaDataType.setProperties(dataType.getProperties().stream()
732                         .collect(Collectors.toMap(
733                             s -> s.getName(),
734                             s -> propertyConvertor
735                                 .convertProperty(dataTypes, s, PropertyConvertor.PropertyType.PROPERTY)
736                         )));
737                 }
738                 toscaDataTypeMap.put(dataType.getName(), toscaDataType);
739             }
740             toscaNode.setData_types(toscaDataTypeMap);
741         }
742
743         // Extracted to method for code reuse
744         return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
745     }
746
747     private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache,
748                                                                        Component component, ToscaTemplate toscaNode,
749                                                                        Map<String, ToscaNodeType> nodeTypes,
750                                                                        ToscaNodeType toscaNodeType,
751                                                                        Map<String, DataTypeDefinition> dataTypes) {
752         Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType,
753             dataTypes);
754         if (capabilities.isRight()) {
755             return Either.right(capabilities.right().value());
756         }
757         toscaNodeType = capabilities.left().value();
758         log.debug("Capabilities converted for {}", component.getUniqueId());
759
760         Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter
761             .convertRequirements(componentsCache, component,
762                 toscaNodeType);
763         if (requirements.isRight()) {
764             return Either.right(requirements.right().value());
765         }
766         toscaNodeType = requirements.left().value();
767         log.debug("Requirements converted for {}", component.getUniqueId());
768
769         String toscaResourceName;
770         switch (component.getComponentType()) {
771             case RESOURCE:
772                 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
773                     .getMetadataDataDefinition()).getToscaResourceName();
774                 break;
775             case SERVICE:
776                 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
777                     + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
778                 break;
779             default:
780                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
781                 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
782         }
783
784         nodeTypes.put(toscaResourceName, toscaNodeType);
785         toscaNode.setNode_types(nodeTypes);
786         log.debug("finish convert node type for {}", component.getUniqueId());
787         return Either.left(toscaNode);
788     }
789
790     protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
791         Component component,
792         List<ComponentInstance> componentInstances,
793         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
794         Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
795         Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
796         ToscaTopolgyTemplate topologyTemplate) {
797
798         Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
799         log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
800             component.getComponentType());
801         Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
802         Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
803
804         Map<String, ToscaGroupTemplate> groupsMap = null;
805         for (ComponentInstance componentInstance : componentInstances) {
806             ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
807             if (MapUtils.isNotEmpty(componentInstance.getToscaArtifacts())) {
808                 nodeTemplate.setArtifacts(convertToNodeTemplateArtifacts(componentInstance.getToscaArtifacts()));
809             }
810             nodeTemplate.setType(componentInstance.getToscaComponentName());
811             nodeTemplate.setDirectives(componentInstance.getDirectives());
812             nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
813
814             Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
815                 .getOriginComponent(componentCache, componentInstance);
816             if (originComponentRes.isRight()) {
817                 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
818                 break;
819             }
820             Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
821                 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
822                 originComponentRes.left().value(), componentCache);
823             if (requirements.isRight()) {
824                 convertNodeTemplatesRes = Either.right(requirements.right().value());
825                 break;
826             }
827             String instanceUniqueId = componentInstance.getUniqueId();
828             log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
829
830             nodeTemplate = requirements.left().value();
831
832             Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
833
834             if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
835                 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
836                 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
837             } else {
838                 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
839             }
840
841             Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
842                 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
843             if (capabilities.isRight()) {
844                 convertNodeTemplatesRes = Either.right(capabilities.right().value());
845                 break;
846             }
847             log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
848
849             nodeTemplate = capabilities.left().value();
850             Map<String, Object> props = new HashMap<>();
851
852             if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
853                 // Adds the properties of parent component to map
854                 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
855             }
856
857             if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
858                 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, instanceUniqueId,
859                     props);
860             }
861
862             if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
863                 && !isComponentOfTypeServiceProxy(componentInstance)) {
864                 //For service proxy the inputs are already handled under instance properties above
865                 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
866                     props);
867             }
868             //M3[00001] - NODE TEMPLATE INTERFACES  - START
869             handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
870                 instanceUniqueId, component);
871             //M3[00001] - NODE TEMPLATE INTERFACES  - END
872             if (props != null && !props.isEmpty()) {
873                 nodeTemplate.setProperties(props);
874             }
875
876             List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
877             if (groupInstances != null) {
878                 if (groupsMap == null) {
879                     groupsMap = new HashMap<>();
880                 }
881                 for (GroupInstance groupInst : groupInstances) {
882                     boolean addToTosca = true;
883
884                     List<String> artifacts = groupInst.getArtifacts();
885                     if (artifacts == null || artifacts.isEmpty()) {
886                         addToTosca = false;
887                     }
888
889                     if (addToTosca) {
890                         ToscaGroupTemplate toscaGroup = groupExportParser
891                             .getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
892                         groupsMap.put(groupInst.getName(), toscaGroup);
893                     }
894                 }
895             }
896
897             nodeTemplates.put(componentInstance.getName(), nodeTemplate);
898         }
899         if (groupsMap != null) {
900             log.debug("instance groups added");
901             topologyTemplate.addGroups(groupsMap);
902         }
903         if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(
904             ((Service) component).getForwardingPaths())) {
905             log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
906                 component.getName());
907             ForwardingPathToscaUtil
908                 .addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache,
909                     toscaOperationFacade);
910             log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
911                 component.getName());
912         }
913         if (convertNodeTemplatesRes == null) {
914             convertNodeTemplatesRes = Either.left(nodeTemplates);
915         }
916         log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
917             component.getComponentType());
918         return convertNodeTemplatesRes;
919     }
920
921     private void handleInstanceInterfaces(
922         Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
923         ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
924         String instanceUniqueId,
925         Component parentComponent) {
926
927         Map<String, Object> interfaces;
928
929         // we need to handle service proxy interfaces
930         if (isComponentOfTypeServiceProxy(componentInstance)) {
931             if (MapUtils.isEmpty(componentInstanceInterfaces)
932                 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
933                 interfaces = null;
934             } else {
935                 List<ComponentInstanceInterface> currServiceInterfaces =
936                     componentInstanceInterfaces.get(instanceUniqueId);
937
938                 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
939                 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
940                     .getUniqueId(), instInterface));
941
942                 interfaces = interfacesOperationsConverter
943                     .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
944             }
945         } else {
946             interfaces =
947                 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
948                     componentInstance, instanceUniqueId);
949         }
950         nodeTemplate.setInterfaces(interfaces);
951     }
952
953     private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
954         return Objects.nonNull(componentInstance.getOriginType())
955             && componentInstance.getOriginType().getValue().equals("Service Proxy");
956     }
957
958     //M3[00001] - NODE TEMPLATE INTERFACES  - START
959     private Map<String, Object> getComponentInstanceInterfaceInstances(
960         Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
961         ComponentInstance componentInstance,
962         String instanceUniqueId) {
963         if (MapUtils.isEmpty(componentInstancesInterfaces)) {
964             return null;
965         }
966
967         List<ComponentInstanceInterface> componentInstanceInterfaces =
968             componentInstancesInterfaces.get(instanceUniqueId);
969
970         if (CollectionUtils.isEmpty(componentInstanceInterfaces)) {
971             return null;
972         }
973
974         Map<String, Object> interfaces = new HashMap<>();
975         for (ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
976             interfaces.put(componentInstanceInterface.getInterfaceId(),
977                 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
978         }
979
980         componentInstance.setInterfaces(interfaces);
981
982         return interfaces;
983     }
984
985     private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
986                                             Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
987                                             String instanceUniqueId, Map<String, Object> props) {
988
989         List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
990         if (instanceInputsList != null) {
991             instanceInputsList.forEach(input -> {
992
993                 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
994                     ? input.getValue() : input.getDefaultValue();
995                 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
996             });
997         }
998     }
999
1000     private void addPropertiesOfComponentInstance(
1001         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
1002         Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
1003         Map<String, Object> props) {
1004
1005         if (isNotEmpty(componentInstancesProperties)) {
1006             componentInstancesProperties.get(instanceUniqueId)
1007                 // Converts and adds each value to property map
1008                 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
1009                     prop::getValue));
1010         }
1011     }
1012
1013     private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
1014                                                 Component componentOfInstance, Map<String, Object> props) {
1015
1016         List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
1017         if (isNotEmpty(componentProperties)) {
1018             componentProperties.stream()
1019                 // Filters out properties with empty default values
1020                 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
1021                 // Converts and adds each value to property map
1022                 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
1023                     prop::getDefaultValue));
1024         }
1025     }
1026
1027     /**
1028      *
1029      */
1030     private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
1031                                     Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
1032         Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
1033         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
1034             props.put(prop.getName(), convertedValue);
1035         }
1036     }
1037
1038     private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
1039                                                                ComponentInstance componentInstance, T input,
1040                                                                Supplier<String> supplier) {
1041         log.debug("Convert property or input value {} for instance {}", input.getName(),
1042             componentInstance.getUniqueId());
1043         String propertyType = input.getType();
1044         String innerType = null;
1045         if (input.getSchema() != null && input.getSchema().getProperty() != null) {
1046             innerType = input.getSchema().getProperty().getType();
1047         }
1048         return propertyConvertor.convertToToscaObject(input, supplier.get(), dataTypes, true);
1049     }
1050
1051     private ToscaNodeType createNodeType(Component component) {
1052         ToscaNodeType toscaNodeType = new ToscaNodeType();
1053         if (ModelConverter.isAtomicComponent(component)) {
1054             if (((Resource) component).getDerivedFrom() != null) {
1055                 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
1056             }
1057             toscaNodeType.setDescription(component.getDescription());
1058         } else {
1059             String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
1060                 : NATIVE_ROOT;
1061             toscaNodeType.setDerived_from(derivedFrom);
1062         }
1063         return toscaNodeType;
1064     }
1065
1066     private Either<Map<String, Object>, ToscaError> createProxyInterfaceTypes(Component container) {
1067
1068         Map<String, Object> proxyInterfaceTypes = new HashMap<>();
1069         Either<Map<String, Object>, ToscaError> res = Either.left(proxyInterfaceTypes);
1070         List<ComponentInstance> componentInstances = container.getComponentInstances();
1071         if (CollectionUtils.isEmpty(componentInstances)) {
1072             return res;
1073         }
1074         Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1075         componentInstances.stream()
1076             .filter(this::isComponentOfTypeServiceProxy)
1077             .forEach(inst -> serviceProxyInstanceList.put(inst.getToscaComponentName(), inst));
1078         if (MapUtils.isEmpty(serviceProxyInstanceList)) {
1079             return res;
1080         }
1081         for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1082             Component serviceComponent;
1083             ComponentParametersView componentParametersView = new ComponentParametersView();
1084             componentParametersView.disableAll();
1085             componentParametersView.setIgnoreInterfaces(false);
1086             Either<Component, StorageOperationStatus> service = toscaOperationFacade
1087                 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1088             if (service.isRight()) {
1089                 log.debug("Failed to fetch original service component with id {} for instance {}",
1090                     entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1091                 return Either.right(ToscaError.GENERAL_ERROR);
1092             } else {
1093                 serviceComponent = service.left().value();
1094             }
1095
1096             Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
1097                 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
1098             if (lifecycleTypeEither.isRight()) {
1099                 log.debug("Failed to retrieve global interface types :", lifecycleTypeEither.right().value());
1100                 return Either.right(ToscaError.GENERAL_ERROR);
1101             }
1102
1103             List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream()
1104                 .map(InterfaceDataDefinition::getType)
1105                 .collect(Collectors.toList());
1106             //Add interface types for local interfaces in the original service component for proxy
1107             Map<String, Object> localInterfaceTypes = addInterfaceTypeElement(serviceComponent,
1108                 allGlobalInterfaceTypes);
1109             if (MapUtils.isNotEmpty(localInterfaceTypes)) {
1110                 proxyInterfaceTypes.putAll(localInterfaceTypes);
1111             }
1112
1113         }
1114         return Either.left(proxyInterfaceTypes);
1115     }
1116
1117     private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache,
1118                                                                                 Component container) {
1119
1120         Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
1121         Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
1122
1123         List<ComponentInstance> componentInstances = container.getComponentInstances();
1124
1125         if (componentInstances == null || componentInstances.isEmpty()) {
1126             return res;
1127         }
1128         Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1129         List<ComponentInstance> proxyInst = componentInstances.stream()
1130             .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
1131             .collect(Collectors.toList());
1132         if (proxyInst != null && !proxyInst.isEmpty()) {
1133             for (ComponentInstance inst : proxyInst) {
1134                 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
1135             }
1136         }
1137
1138         if (serviceProxyInstanceList.isEmpty()) {
1139             return res;
1140         }
1141         Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
1142             .getLatestByName("serviceProxy");
1143         if (serviceProxyOrigin.isRight()) {
1144             log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
1145                 serviceProxyOrigin.right().value());
1146             return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
1147         }
1148         Component origComponent = serviceProxyOrigin.left().value();
1149
1150         for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1151             Component serviceComponent = null;
1152             ComponentParametersView componentParametersView = new ComponentParametersView();
1153             componentParametersView.disableAll();
1154             componentParametersView.setIgnoreCategories(false);
1155             componentParametersView.setIgnoreProperties(false);
1156             componentParametersView.setIgnoreInputs(false);
1157             componentParametersView.setIgnoreInterfaces(false);
1158             componentParametersView.setIgnoreRequirements(false);
1159             Either<Component, StorageOperationStatus> service = toscaOperationFacade
1160                 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1161             if (service.isRight()) {
1162                 log.debug("Failed to fetch resource with id {} for instance {}",
1163                     entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1164             } else {
1165                 serviceComponent = service.left().value();
1166             }
1167
1168             ToscaNodeType toscaNodeType = createProxyNodeType(componentCache, origComponent, serviceComponent,
1169                 entryProxy.getValue());
1170             nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
1171         }
1172
1173         return Either.left(nodeTypesMap);
1174     }
1175
1176     private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache, Component origComponent,
1177                                               Component proxyComponent, ComponentInstance instance) {
1178         ToscaNodeType toscaNodeType = new ToscaNodeType();
1179         String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1180
1181         toscaNodeType.setDerived_from(derivedFrom);
1182         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
1183         if (dataTypesEither.isRight()) {
1184             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1185         }
1186         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1187         Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1188             .convertProxyCapabilities(componentCache, instance, dataTypes);
1189
1190         if (MapUtils.isNotEmpty(capabilities)) {
1191             toscaNodeType.setCapabilities(capabilities);
1192         }
1193         List<Map<String, ToscaRequirement>> proxyNodeTypeRequirements = this.capabilityRequirementConverter
1194             .convertProxyRequirements(componentCache, instance);
1195         if (CollectionUtils.isNotEmpty(proxyNodeTypeRequirements)) {
1196             toscaNodeType.setRequirements(proxyNodeTypeRequirements);
1197         }
1198         Optional<Map<String, ToscaProperty>> proxyProperties = getProxyNodeTypeProperties(proxyComponent, dataTypes);
1199         proxyProperties.ifPresent(toscaNodeType::setProperties);
1200
1201         Optional<Map<String, Object>> proxyInterfaces = getProxyNodeTypeInterfaces(proxyComponent, dataTypes);
1202         proxyInterfaces.ifPresent(toscaNodeType::setInterfaces);
1203
1204         return toscaNodeType;
1205     }
1206
1207     private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1208                                                                                        ComponentInstance componentInstance,
1209                                                                                        List<RequirementCapabilityRelDef> relations,
1210                                                                                        ToscaNodeTemplate nodeTypeTemplate,
1211                                                                                        Component originComponent,
1212                                                                                        Map<String, Component> componentCache) {
1213
1214         List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1215         if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements,
1216             componentCache)) {
1217             log.debug("Failed to convert component instance requirements for the component instance {}. ",
1218                 componentInstance.getName());
1219             return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1220         }
1221         if (!toscaRequirements.isEmpty()) {
1222             nodeTypeTemplate.setRequirements(toscaRequirements);
1223         }
1224         log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1225         return Either.left(nodeTypeTemplate);
1226     }
1227
1228     private boolean addRequirements(Component component, ComponentInstance componentInstance,
1229                                     List<RequirementCapabilityRelDef> relations, Component originComponent,
1230                                     List<Map<String, ToscaTemplateRequirement>> toscaRequirements,
1231                                     Map<String, Component> componentCache) {
1232         List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1233             .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1234         return isEmpty(filteredRelations) ||
1235             filteredRelations.stream()
1236                 .allMatch(
1237                     rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel,
1238                         toscaRequirements, componentCache));
1239     }
1240
1241     private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1242                                    List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1243                                    List<Map<String, ToscaTemplateRequirement>> toscaRequirements,
1244                                    Map<String, Component> componentCache) {
1245
1246         boolean result = true;
1247         Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1248         RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1249         Either<Component, StorageOperationStatus> getOriginRes = null;
1250         Optional<RequirementDefinition> reqOpt = Optional.empty();
1251         Component toOriginComponent = null;
1252         Optional<CapabilityDefinition> capOpt = Optional.empty();
1253
1254         ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1255             .findFirst().orElse(null);
1256         if (toInstance == null) {
1257             log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1258                 rel.getToNode());
1259             result = false;
1260         }
1261         if (result) {
1262             reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1263             if (!reqOpt.isPresent()) {
1264                 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1265                     reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1266                 result = false;
1267             }
1268         }
1269         if (result) {
1270             ComponentParametersView filter = new ComponentParametersView(true);
1271             filter.setIgnoreComponentInstances(false);
1272             filter.setIgnoreCapabilities(false);
1273             filter.setIgnoreGroups(false);
1274             getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1275             if (getOriginRes.isRight()) {
1276                 log.debug(
1277                     "Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1278                     reqOpt.get().getName(), toInstance.getActualComponentUid());
1279                 result = false;
1280             }
1281         }
1282         if (result) {
1283             toOriginComponent = getOriginRes.left().value();
1284             capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1285                 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1286             if (!capOpt.isPresent()) {
1287                 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1288                 if (!capOpt.isPresent()) {
1289                     result = false;
1290                     log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1291                         reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1292                 }
1293             }
1294         }
1295         if (result) {
1296             result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1297                 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1298         }
1299         return result;
1300     }
1301
1302     private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair,
1303                                                  CapabilityDefinition capability) {
1304         return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() != null
1305             && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1306     }
1307
1308     private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair,
1309                                                           Component toOriginComponent, Component fromOriginComponent,
1310                                                           RequirementDefinition requirement) {
1311         Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability())
1312             .stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1313         if (!cap.isPresent()) {
1314             log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1315                 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1316         }
1317         return cap;
1318     }
1319
1320     private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements,
1321                                            Component fromOriginComponent, Component toOriginComponent,
1322                                            CapabilityDefinition capability, RequirementDefinition requirement,
1323                                            RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance,
1324                                            Map<String, Component> componentCache) {
1325         List<String> reducedPath = capability.getPath();
1326         if (capability.getOwnerId() != null) {
1327             reducedPath = capabilityRequirementConverter
1328                 .getReducedPathByOwner(capability.getPath(), capability.getOwnerId());
1329         }
1330         Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1331             toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1332         if (buildCapNameRes.isRight()) {
1333             log.debug(
1334                 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1335                 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1336             return false;
1337         }
1338         Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter
1339             .buildSubstitutedName(componentCache, fromOriginComponent,
1340                 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1341         if (buildReqNameRes.isRight()) {
1342             log.debug(
1343                 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1344                 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1345             return false;
1346         }
1347         ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1348         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1349         toscaRequirement.setNode(toInstance.getName());
1350         toscaRequirement.setCapability(buildCapNameRes.left().value());
1351         toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1352         toscaRequirements.add(toscaReqMap);
1353         return true;
1354     }
1355
1356     private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent,
1357                                                             Map<String, List<RequirementDefinition>> reqMap,
1358                                                             RelationshipInfo reqAndRelationshipPair,
1359                                                             String fromInstanceId) {
1360         for (List<RequirementDefinition> reqList : reqMap.values()) {
1361             Optional<RequirementDefinition> reqOpt = reqList.stream().filter(
1362                 r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId))
1363                 .findFirst();
1364             if (reqOpt.isPresent()) {
1365                 return reqOpt;
1366             }
1367         }
1368         return Optional.empty();
1369     }
1370
1371     /**
1372      * Allows detecting the requirement belonging to the received relationship The detection logic is: A requirement
1373      * belongs to a relationship IF 1.The name of the requirement equals to the "requirement" field of the relation; AND
1374      * 2. In case of a non-atomic resource, OwnerId of the requirement equals to requirementOwnerId of the relation OR
1375      * uniqueId of toInstance equals to capabilityOwnerId of the relation
1376      */
1377     private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair,
1378                                                   RequirementDefinition requirement, String fromInstanceId) {
1379         if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1380             log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}",
1381                 requirement.getName(), reqAndRelationshipPair.getRequirement());
1382             return false;
1383         }
1384         return ModelConverter.isAtomicComponent(originComponent) ||
1385             isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1386     }
1387
1388     private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair,
1389                                                RequirementDefinition requirement, String fromInstanceId,
1390                                                Component originComponent) {
1391         return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId())
1392             || (isCvfc(originComponent) && StringUtils
1393             .equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())
1394             || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId()));
1395     }
1396
1397     private boolean isCvfc(Component component) {
1398         return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1399             ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1400     }
1401
1402     private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1403                                                                         SubstitutionMapping substitutionMappings,
1404                                                                         Map<String, Component> componentCache) {
1405
1406         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1407         Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1408             .convertSubstitutionMappingCapabilities(componentCache, component);
1409         if (toscaCapabilitiesRes.isRight()) {
1410             result = Either.right(toscaCapabilitiesRes.right().value());
1411             log.debug("Failed convert capabilities for the component {}. ", component.getName());
1412         } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1413             substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1414             log.debug("Finish convert capabilities for the component {}. ", component.getName());
1415         }
1416         log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1417         return result;
1418     }
1419
1420     private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache,
1421                                                                   Component component, ToscaNodeType nodeType,
1422                                                                   Map<String, DataTypeDefinition> dataTypes) {
1423         Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter
1424             .convertCapabilities(componentsCache, component,
1425                 dataTypes);
1426         if (!toscaCapabilities.isEmpty()) {
1427             nodeType.setCapabilities(toscaCapabilities);
1428         }
1429         log.debug("Finish convert Capabilities for node type");
1430
1431         return Either.left(nodeType);
1432     }
1433
1434     private Map<String, ToscaTemplateArtifact> convertToNodeTemplateArtifacts(
1435         Map<String, ToscaArtifactDataDefinition> artifacts) {
1436         if (artifacts == null) {
1437             return null;
1438         }
1439         Map<String, ToscaTemplateArtifact> arts = new HashMap<>();
1440         for (Map.Entry<String, ToscaArtifactDataDefinition> entry : artifacts.entrySet()) {
1441             ToscaTemplateArtifact artifact = new ToscaTemplateArtifact();
1442             artifact.setFile(entry.getValue().getFile());
1443             artifact.setType(entry.getValue().getType());
1444             arts.put(entry.getKey(), artifact);
1445         }
1446         return arts;
1447     }
1448
1449     protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1450         if (inNodeFilter == null) {
1451             return null;
1452         }
1453         NodeFilter nodeFilter = new NodeFilter();
1454
1455         ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1456             inNodeFilter.getCapabilities();
1457
1458         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1459
1460         List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1461         List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1462
1463         copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1464         copyNodeFilterProperties(origProperties, propertiesCopy);
1465
1466         if (CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1467             nodeFilter.setCapabilities(capabilitiesCopy);
1468         }
1469
1470         if (CollectionUtils.isNotEmpty(propertiesCopy)) {
1471             nodeFilter.setProperties(propertiesCopy);
1472         }
1473
1474         nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1475
1476         nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1477
1478         return nodeFilter;
1479     }
1480
1481     private NodeFilter convertToSubstitutionFilterComponent(
1482         final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
1483
1484         NodeFilter nodeFilter = new NodeFilter();
1485
1486         final List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1487         copySubstitutionFilterProperties(substitutionFilterDataDefinition.getProperties(), propertiesCopy);
1488
1489         if (CollectionUtils.isNotEmpty(propertiesCopy)) {
1490             nodeFilter.setProperties(propertiesCopy);
1491         }
1492         nodeFilter.setTosca_id(cloneToscaId(substitutionFilterDataDefinition.getTosca_id()));
1493         nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1494
1495         return nodeFilter;
1496     }
1497
1498     private Object cloneToscaId(Object toscaId) {
1499         return Objects.isNull(toscaId) ? null
1500             : cloneObjectFromYml(toscaId, toscaId.getClass());
1501     }
1502
1503     private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1504         String objectAsYml = yamlUtil.objectToYaml(objToClone);
1505         return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1506     }
1507
1508     private void copyNodeFilterCapabilitiesTemplate(
1509         ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1510         List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1511         if (origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1512             origCapabilities.getListToscaDataDefinition().isEmpty()) {
1513             return;
1514         }
1515         for (RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1516             Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1517             CapabilityFilter capabilityFilter = new CapabilityFilter();
1518             List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1519             copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1520             capabilityFilter.setProperties(propertiesCopy);
1521             capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1522             capabilitiesCopy.add(capabilityFilterCopyMap);
1523         }
1524     }
1525
1526     private void copyNodeFilterProperties(
1527         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1528         List<Map<String, List<Object>>> propertiesCopy) {
1529         if (origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1530             origProperties.isEmpty()) {
1531             return;
1532         }
1533         Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1534         for (RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties
1535             .getListToscaDataDefinition()) {
1536             for (String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1537                 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1538                 String propertyName = propertyDataDefinition.getName();
1539                 if (propertyMapCopy.containsKey(propertyName)) {
1540                     addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
1541                 } else {
1542                     if (propertyName != null) {
1543                         List propsList = new ArrayList();
1544                         addPropertyConstraintValueToList(propertyName, propertyValObj, propsList);
1545                         propertyMapCopy.put(propertyName, propsList);
1546                     } else {
1547                         propertyMapCopy.putAll(propertyValObj);
1548                     }
1549                 }
1550             }
1551         }
1552         propertyMapCopy.entrySet().stream().forEach(entry ->
1553             addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
1554     }
1555
1556     private void copySubstitutionFilterProperties(
1557         final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> origProperties,
1558         final List<Map<String, List<Object>>> propertiesCopy) {
1559         if (origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1560             origProperties.isEmpty()) {
1561             return;
1562         }
1563         final Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1564         for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties
1565             .getListToscaDataDefinition()) {
1566             for (final String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1567                 final Map<String, List<Object>> propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1568                 final String propertyName = propertyDataDefinition.getName();
1569                 if (propertyMapCopy.containsKey(propertyName)) {
1570                     addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
1571                 } else {
1572                     if (propertyName != null) {
1573                         final List<Object> propsList = new ArrayList();
1574                         addPropertyConstraintValueToList(propertyName, propertyValObj, propsList);
1575                         propertyMapCopy.put(propertyName, propsList);
1576                     } else {
1577                         propertyMapCopy.putAll(propertyValObj);
1578                     }
1579                 }
1580             }
1581         }
1582         propertyMapCopy.entrySet().forEach(entry ->
1583             addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
1584     }
1585
1586     private void addPropertyConstraintValueToList(String propertyName, Map propertyValObj, List propsList) {
1587         if (propertyValObj.containsKey(propertyName)) {
1588             propsList.add(propertyValObj.get(propertyName));
1589         } else {
1590             propsList.add(propertyValObj);
1591         }
1592     }
1593
1594     private void addCalculatedConstraintsIntoPropertiesList(List<Map<String, List<Object>>> propertiesCopy,
1595                                                             Entry<String, List<Object>> entry) {
1596         Map<String, List<Object>> tempMap = new HashMap<>();
1597         tempMap.put(entry.getKey(), entry.getValue());
1598         propertiesCopy.add(tempMap);
1599     }
1600
1601     private static class CustomRepresenter extends Representer {
1602
1603         CustomRepresenter() {
1604             super();
1605             // null representer is exceptional and it is stored as an instance
1606             // variable.
1607             this.nullRepresenter = new RepresentNull();
1608
1609         }
1610
1611         @Override
1612         protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1613                                                       Tag customTag) {
1614             if (propertyValue == null) {
1615                 return null;
1616             }
1617             // skip not relevant for Tosca property
1618             if ("dependencies".equals(property.getName())) {
1619                 return null;
1620             }
1621             removeDefaultP(propertyValue);
1622             NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1623
1624             return "_defaultp_".equals(property.getName())
1625                 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1626         }
1627
1628         private void removeDefaultP(final Object propertyValue) {
1629             if (propertyValue instanceof Map) {
1630                 final Map mapPropertyValue = ((Map) propertyValue);
1631
1632                 final Iterator<Entry> iter = mapPropertyValue.entrySet().iterator();
1633                 Object defaultValue = null;
1634                 while (iter.hasNext()) {
1635                     final Map.Entry entry = iter.next();
1636
1637                     if ("_defaultp_".equals(entry.getKey())) {
1638                         defaultValue = entry.getValue();
1639                         iter.remove();
1640                     } else if (entry.getValue() instanceof Map) {
1641                         removeDefaultP(entry.getValue());
1642                     }
1643                 }
1644                 if (defaultValue != null) {
1645                     mapPropertyValue.putIfAbsent("default", defaultValue);
1646                 }
1647             }
1648         }
1649
1650         @Override
1651         protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1652             // remove the bean type from the output yaml (!! ...)
1653             if (!classTags.containsKey(javaBean.getClass())) {
1654                 addClassTag(javaBean.getClass(), Tag.MAP);
1655             }
1656
1657             return super.representJavaBean(properties, javaBean);
1658         }
1659
1660         private class RepresentNull implements Represent {
1661
1662             @Override
1663             public Node representData(Object data) {
1664                 // possible values are here http://yaml.org/type/null.html
1665                 return representScalar(Tag.NULL, "");
1666             }
1667         }
1668     }
1669
1670     private static class UnsortedPropertyUtils extends PropertyUtils {
1671
1672         @Override
1673         protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1674             throws IntrospectionException {
1675             Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1676             return new LinkedHashSet<>(fields);
1677         }
1678     }
1679
1680     private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1681         ObjectMapper objectMapper = new ObjectMapper();
1682         objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1683
1684         Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1685         Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1686         interfaceAsMap.remove("empty");
1687
1688         if (MapUtils.isNotEmpty(operations)) {
1689             interfaceAsMap.putAll(operations);
1690         }
1691
1692         Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1693
1694         return interfaceObject;
1695
1696     }
1697
1698     Optional<Map<String, ToscaProperty>> getProxyNodeTypeProperties(Component proxyComponent,
1699                                                                     Map<String, DataTypeDefinition>
1700                                                                         dataTypes) {
1701         if (Objects.isNull(proxyComponent)) {
1702             return Optional.empty();
1703         }
1704         Map<String, ToscaProperty> proxyProperties = new HashMap<>();
1705         addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties);
1706         if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) {
1707             proxyProperties.putAll(proxyComponent.getProperties().stream()
1708                 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition,
1709                     proxyComponent.getInputs()))
1710                 .collect(Collectors.toMap(PropertyDataDefinition::getName,
1711                     property -> propertyConvertor.convertProperty(dataTypes, property,
1712                         PropertyConvertor.PropertyType.PROPERTY))));
1713         }
1714         return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty();
1715     }
1716
1717     void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
1718                                List<InputDefinition> componentInputs,
1719                                Map<String, ToscaProperty> mergedProperties) {
1720         if (CollectionUtils.isEmpty(componentInputs)) {
1721             return;
1722         }
1723         for (InputDefinition input : componentInputs) {
1724             ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input,
1725                 PropertyConvertor.PropertyType.INPUT);
1726             mergedProperties.put(input.getName(), property);
1727         }
1728     }
1729
1730     Optional<Map<String, Object>> getProxyNodeTypeInterfaces(Component proxyComponent,
1731                                                              Map<String, DataTypeDefinition> dataTypes) {
1732         if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) {
1733             return Optional.empty();
1734         }
1735         Map<String, InterfaceDefinition> proxyComponentInterfaces = proxyComponent.getInterfaces();
1736         //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is
1737         // always available in the proxy node template
1738         removeOperationImplementationForProxyNodeType(proxyComponentInterfaces);
1739         return Optional.ofNullable(interfacesOperationsConverter
1740             .getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes,
1741                 false, false));
1742     }
1743
1744     private static void removeOperationImplementationForProxyNodeType(
1745         Map<String, InterfaceDefinition> proxyComponentInterfaces) {
1746         if (MapUtils.isEmpty(proxyComponentInterfaces)) {
1747             return;
1748         }
1749         proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations)
1750             .filter(MapUtils::isNotEmpty)
1751             .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null)));
1752     }
1753 }