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