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