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