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