2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.tosca;
23 import java.beans.IntrospectionException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.LinkedHashSet;
28 import java.util.List;
30 import java.util.Optional;
32 import java.util.function.Supplier;
33 import java.util.stream.Collectors;
35 import org.apache.commons.collections.CollectionUtils;
36 import org.apache.commons.collections.MapUtils;
37 import org.apache.commons.lang.StringUtils;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.apache.commons.lang3.tuple.ImmutableTriple;
40 import org.apache.commons.lang3.tuple.Triple;
41 import org.openecomp.sdc.be.config.ConfigurationManager;
42 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
43 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.model.*;
46 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
47 import org.openecomp.sdc.be.model.category.CategoryDefinition;
48 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
49 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
50 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
51 import org.openecomp.sdc.be.tosca.model.IToscaMetadata;
52 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
53 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
54 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
55 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
56 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
57 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
58 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
59 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
60 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
61 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
62 import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.yaml.snakeyaml.DumperOptions;
68 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
69 import org.yaml.snakeyaml.Yaml;
70 import org.yaml.snakeyaml.introspector.BeanAccess;
71 import org.yaml.snakeyaml.introspector.Property;
72 import org.yaml.snakeyaml.introspector.PropertyUtils;
73 import org.yaml.snakeyaml.nodes.MappingNode;
74 import org.yaml.snakeyaml.nodes.Node;
75 import org.yaml.snakeyaml.nodes.NodeTuple;
76 import org.yaml.snakeyaml.nodes.Tag;
77 import org.yaml.snakeyaml.representer.Represent;
78 import org.yaml.snakeyaml.representer.Representer;
80 import fj.data.Either;
82 @org.springframework.stereotype.Component("tosca-export-handler")
83 public class ToscaExportHandler {
86 private ApplicationDataTypeCache dataTypeCache;
89 private ToscaOperationFacade toscaOperationFacade;
91 private CapabiltyRequirementConvertor capabiltyRequirementConvertor = CapabiltyRequirementConvertor.getInstance();
92 private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
95 private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
97 public static final String TOSCA_VERSION = "tosca_simple_yaml_1_0";
98 public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
99 public static final String IMPORTS_FILE_KEY = "file";
100 public static final String TOSCA_TEMPLATE_NAME = "-template.yml";
101 public static final String TOSCA_INTERFACE_NAME = "-interface.yml";
102 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
103 public static final String VF_MODULE_TYPE_KEY = "vf_module_type";
104 public static final String VF_MODULE_DESC_KEY = "vf_module_description";
105 public static final String VOLUME_GROUP_KEY = "volume_group";
106 public static final String VF_MODULE_TYPE_BASE = "Base";
107 public static final String VF_MODULE_TYPE_EXPANSION = "Expansion";
108 public static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports();
112 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
114 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
115 if (toscaTemplateRes.isRight()) {
116 return Either.right(toscaTemplateRes.right().value());
119 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
120 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
121 return Either.left(toscaRepresentation);
124 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) {
125 if(null == DEFAULT_IMPORTS) {
126 log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
127 return Either.right(ToscaError.GENERAL_ERROR);
130 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
131 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
132 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
133 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, nodeTypes);
134 if (toscaTemplateRes.isRight()) {
135 return Either.right(toscaTemplateRes.right().value());
138 toscaTemplate = toscaTemplateRes.left().value();
139 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
140 return Either.left(toscaRepresentation);
143 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
144 CustomRepresenter representer = new CustomRepresenter();
145 DumperOptions options = new DumperOptions();
146 options.setAllowReadOnlyProperties(false);
147 options.setPrettyFlow(true);
149 options.setDefaultFlowStyle(FlowStyle.FLOW);
150 options.setCanonical(false);
152 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
154 representer.setPropertyUtils(new UnsortedPropertyUtils());
155 Yaml yaml = new Yaml(representer, options);
157 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
159 StringBuilder sb = new StringBuilder();
160 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
161 sb.append(yamlAsString);
162 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
164 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
165 toscaRepresentation.setMainYaml(sb.toString());
166 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
168 return toscaRepresentation;
171 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
172 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
173 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
175 if (fillImports.isRight()) {
176 return Either.right(fillImports.right().value());
178 return Either.left(fillImports.left().value().left);
181 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
182 if(null == DEFAULT_IMPORTS) {
183 log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
184 return Either.right(ToscaError.GENERAL_ERROR);
187 log.trace("start tosca export for {}", component.getUniqueId());
188 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
190 toscaTemplate.setMetadata(convertMetadata(component));
191 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
192 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
193 if (ToscaUtils.isAtomicType(component)) {
194 log.trace("convert component as node type");
195 return convertNodeType(component, toscaTemplate, nodeTypes);
197 log.trace("convert component as topology template");
198 return convertToscaTemplate(component, toscaTemplate);
203 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
205 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
207 if (importsRes.isRight()) {
208 return Either.right(importsRes.right().value());
210 toscaNode = importsRes.left().value().left;
212 Map<String, Component> componentCache = importsRes.left().value().right;
213 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
214 if (dataTypesEither.isRight()) {
215 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
216 return Either.right(ToscaError.GENERAL_ERROR);
218 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
220 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
222 Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
223 if (inputs.isRight()) {
224 return Either.right(inputs.right().value());
226 topologyTemplate = inputs.left().value();
228 List<ComponentInstance> componentInstances = component.getComponentInstances();
229 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
230 .getComponentInstancesProperties();
231 List<GroupDefinition> groups = component.getGroups();
232 if (componentInstances != null && !componentInstances.isEmpty()) {
234 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
235 componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
236 if (nodeTemplates.isRight()) {
237 return Either.right(nodeTemplates.right().value());
239 log.debug("node templates converted");
241 topologyTemplate.setNode_templates(nodeTemplates.left().value());
243 Map<String, ToscaGroupTemplate> groupsMap = null;
244 if (groups != null && !groups.isEmpty()) {
245 groupsMap = new HashMap<String, ToscaGroupTemplate>();
246 for (GroupDefinition group : groups) {
247 ToscaGroupTemplate toscaGroup = convertGroup(group);
248 groupsMap.put(group.getName(), toscaGroup);
251 log.debug("groups converted");
252 topologyTemplate.addGroups(groupsMap);
254 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
255 String toscaResourceName = null;
256 switch (component.getComponentType()) {
258 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
259 .getMetadataDataDefinition()).getToscaResourceName();
262 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
263 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
266 log.debug("Not supported component type {}", component.getComponentType());
267 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
269 substitutionMapping.setNode_type(toscaResourceName);
271 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
273 if (capabilities.isRight()) {
274 return Either.right(capabilities.right().value());
276 substitutionMapping = capabilities.left().value();
278 Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping);
279 if (requirements.isRight()) {
280 return Either.right(requirements.right().value());
282 substitutionMapping = requirements.left().value();
284 topologyTemplate.setSubstitution_mappings(substitutionMapping);
286 toscaNode.setTopology_template(topologyTemplate);
287 return Either.left(toscaNode);
290 private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
291 ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
292 if (log.isDebugEnabled())
293 log.debug("fillInputs for component {}", component.getUniqueId());
294 List<InputDefinition> inputDef = component.getInputs();
295 Map<String, ToscaProperty> inputs = new HashMap<>();
297 if (inputDef != null) {
298 inputDef.forEach(i -> {
299 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
300 inputs.put(i.getName(), property);
302 if (!inputs.isEmpty()) {
303 topologyTemplate.setInputs(inputs);
306 return Either.left(topologyTemplate);
309 private ToscaMetadata convertMetadata(Component component) {
310 return convertMetadata(component, false, null);
313 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
314 ComponentInstance componentInstance) {
315 ToscaMetadata toscaMetadata = new ToscaMetadata();
316 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
317 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
318 toscaMetadata.setUUID(component.getUUID());
319 toscaMetadata.setDescription(component.getDescription());
321 List<CategoryDefinition> categories = component.getCategories();
322 CategoryDefinition categoryDefinition = categories.get(0);
323 toscaMetadata.setCategory(categoryDefinition.getName());
326 toscaMetadata.setVersion(component.getVersion());
327 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
329 switch (component.getComponentType()) {
331 Resource resource = (Resource) component;
332 toscaMetadata.setType(resource.getResourceType().name());
333 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
334 toscaMetadata.setResourceVendor(resource.getVendorName());
335 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
336 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
339 Service service = (Service) component;
340 toscaMetadata.setType(component.getComponentType().getValue());
341 toscaMetadata.setServiceType(service.getServiceType());
342 toscaMetadata.setServiceRole(service.getServiceRole());
345 toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
346 toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming());
347 toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy());
351 log.debug("Not supported component type {}", component.getComponentType());
353 return toscaMetadata;
356 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
357 ToscaTemplate toscaTemplate) {
359 if(null == DEFAULT_IMPORTS) {
360 log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
361 return Either.right(ToscaError.GENERAL_ERROR);
364 Map<String, Component> componentCache = new HashMap<>();
366 if (!ToscaUtils.isAtomicType(component)) {
367 List<ComponentInstance> componentInstances = component.getComponentInstances();
368 if (componentInstances != null && !componentInstances.isEmpty()) {
370 List<Map<String, Map<String, String>>> additionalImports =
371 toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
373 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
375 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
376 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
378 Map<String, Map<String, String>> importsListMember = new HashMap<>();
379 Map<String, String> interfaceFiles = new HashMap<>();
380 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
381 StringBuilder keyNameBuilder = new StringBuilder();
382 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
383 keyNameBuilder.append("-");
384 keyNameBuilder.append(component.getName());
385 keyNameBuilder.append("-interface");
386 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
387 additionalImports.add(importsListMember);
389 componentInstances.forEach(ci -> {
390 createDependency(componentCache, additionalImports, dependecies, ci);
392 toscaTemplate.setDependencies(dependecies);
393 toscaTemplate.setImports(additionalImports);
396 log.debug("currently imports supported for VF and service only");
398 return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
401 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
402 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
403 Map<String, String> files = new HashMap<>();
404 Map<String, Map<String, String>> importsListMember = new HashMap<>();
405 StringBuilder keyNameBuilder;
407 Component componentRI = componentCache.get(ci.getComponentUid());
408 if (componentRI == null) {
409 // all resource must be only once!
410 Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
411 if (resource.isRight()) {
412 log.debug("Failed to fetch resource with id {} for instance {}");
414 Component fetchedComponent = resource.left().value();
415 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
416 componentRI = fetchedComponent;
418 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
419 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
420 if (artifactDefinition != null) {
421 String artifactName = artifactDefinition.getArtifactName();
422 files.put(IMPORTS_FILE_KEY, artifactName);
423 keyNameBuilder = new StringBuilder();
424 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
425 keyNameBuilder.append("-");
426 keyNameBuilder.append(ci.getComponentName());
427 importsListMember.put(keyNameBuilder.toString(), files);
428 imports.add(importsListMember);
429 dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
430 artifactDefinition.getEsId(), fetchedComponent));
432 if(!ToscaUtils.isAtomicType(componentRI)) {
433 importsListMember = new HashMap<>();
434 Map<String, String> interfaceFiles = new HashMap<>();
435 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
436 keyNameBuilder.append("-interface");
437 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
438 imports.add(importsListMember);
444 public static String getInterfaceFilename(String artifactName) {
445 String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
446 return interfaceFileName;
449 private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
450 Map<String, ToscaNodeType> nodeTypes) {
451 log.debug("start convert node type for {}", component.getUniqueId());
452 ToscaNodeType toscaNodeType = createNodeType(component);
454 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
455 if (dataTypesEither.isRight()) {
456 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
457 return Either.right(ToscaError.GENERAL_ERROR);
460 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
461 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
463 if (properties.isRight()) {
464 return Either.right(properties.right().value());
466 toscaNodeType = properties.left().value();
467 log.debug("Properties converted for {}", component.getUniqueId());
469 //Extracted to method for code reuse
470 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
473 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
474 Map<String, ToscaNodeType> nodeTypes) {
475 log.debug("start convert node type for {}", component.getUniqueId());
476 ToscaNodeType toscaNodeType = createNodeType(component);
478 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
479 if (dataTypesEither.isRight()) {
480 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
481 return Either.right(ToscaError.GENERAL_ERROR);
484 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
486 List<InputDefinition> inputDef = component.getInputs();
487 Map<String, ToscaProperty> inputs = new HashMap<>();
489 if (inputDef != null) {
490 inputDef.forEach(i -> {
491 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
492 inputs.put(i.getName(), property);
494 if (!inputs.isEmpty()) {
495 toscaNodeType.setProperties(inputs);
499 //Extracted to method for code reuse
500 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
503 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
504 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
505 Map<String, DataTypeDefinition> dataTypes) {
506 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
507 if (capabilities.isRight()) {
508 return Either.right(capabilities.right().value());
510 toscaNodeType = capabilities.left().value();
511 log.debug("Capabilities converted for {}", component.getUniqueId());
513 Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
515 if (requirements.isRight()) {
516 return Either.right(requirements.right().value());
518 toscaNodeType = requirements.left().value();
519 log.debug("Requirements converted for {}", component.getUniqueId());
522 String toscaResourceName;
523 switch (component.getComponentType()) {
525 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
526 .getMetadataDataDefinition()).getToscaResourceName();
529 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
530 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
533 log.debug("Not supported component type {}", component.getComponentType());
534 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
537 nodeTypes.put(toscaResourceName, toscaNodeType);
538 toscaNode.setNode_types(nodeTypes);
539 log.debug("finish convert node type for {}", component.getUniqueId());
540 return Either.left(toscaNode);
543 private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
544 List<ComponentInstance> componentInstances,
545 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
546 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
547 ToscaTopolgyTemplate topologyTemplate) {
549 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
550 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
551 component.getComponentType());
552 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
553 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
555 Map<String, ToscaGroupTemplate> groupsMap = null;
556 for (ComponentInstance componentInstance : componentInstances) {
557 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
558 nodeTemplate.setType(componentInstance.getToscaComponentName());
560 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
561 componentInstance, component.getComponentInstancesRelations(), nodeTemplate, componentCache.get(componentInstance.getComponentUid()));
562 if (requirements.isRight()) {
563 convertNodeTemplatesRes = Either.right(requirements.right().value());
566 String instanceUniqueId = componentInstance.getUniqueId();
567 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
569 nodeTemplate = requirements.left().value();
571 Component componentOfInstance = componentCache.get(componentInstance.getComponentUid());
572 nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
574 Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor
575 .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
576 if (capabilities.isRight()) {
577 convertNodeTemplatesRes = Either.right(requirements.right().value());
580 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
582 nodeTemplate = capabilities.left().value();
583 Map<String, Object> props = new HashMap<>();
585 if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) {
586 // Adds the properties of parent component to map
587 addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props);
590 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
591 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
592 instanceUniqueId, props);
595 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
596 addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
599 if (props != null && !props.isEmpty()) {
600 nodeTemplate.setProperties(props);
603 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
604 if (groupInstances != null) {
605 if (groupsMap == null) {
606 groupsMap = new HashMap<>();
608 for (GroupInstance groupInst : groupInstances) {
609 ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
611 groupsMap.put(groupInst.getName(), toscaGroup);
615 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
617 if (groupsMap != null) {
618 log.debug("instance groups added");
619 topologyTemplate.addGroups(groupsMap);
622 if (convertNodeTemplatesRes == null) {
623 convertNodeTemplatesRes = Either.left(nodeTemplates);
625 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
626 component.getComponentType());
627 return convertNodeTemplatesRes;
630 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
631 Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
632 String instanceUniqueId, Map<String, Object> props) {
634 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
635 if (instanceInputsList != null) {
636 instanceInputsList.forEach(input -> {
637 Supplier<String> supplier = () -> input.getValue();
638 convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
643 private void addPropertiesOfComponentInstance(
644 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
645 Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
646 Map<String, Object> props) {
648 if (!MapUtils.isEmpty(componentInstancesProperties)) {
649 componentInstancesProperties.get(instanceUniqueId).stream()
650 // Collects filtered properties to List
651 .collect(Collectors.toList()).stream()
652 // Converts and adds each value to property map
653 .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
654 () -> prop.getValue()));
658 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
659 ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
661 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
662 if (!CollectionUtils.isEmpty(componentProperties)) {
663 componentProperties.stream()
664 // Filters out properties with empty default values
665 .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
666 // Collects filtered properties to List
667 .collect(Collectors.toList()).stream()
668 // Converts and adds each value to property map
669 .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
670 () -> prop.getDefaultValue()));
676 * @param componentInstance
681 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
682 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
683 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
684 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
685 props.put(prop.getName(), convertedValue);
689 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
690 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
691 log.debug("Convert property or input value {} for instance {}", input.getName(),
692 componentInstance.getUniqueId());
693 String propertyType = input.getType();
694 String innerType = null;
695 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
696 innerType = input.getSchema().getProperty().getType();
698 return propertyConvertor.convertToToscaObject(propertyType, input.getName(), supplier.get(), innerType, dataTypes);
701 private ToscaGroupTemplate convertGroup(GroupDefinition group) {
702 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
703 Map<String, String> members = group.getMembers();
705 toscaGroup.setMembers(new ArrayList<String>(members.keySet()));
707 Supplier<String> supplGroupType = () -> group.getType();
708 Supplier<String> supplDescription = () -> group.getDescription();
709 Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
710 Supplier<String> supplgroupName = () -> group.getName();
711 Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
712 Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
713 Supplier<String> supplVersion = () -> group.getVersion();
715 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
716 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
717 toscaGroup.setMetadata(toscaMetadata);
721 private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
722 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
724 Supplier<String> supplGroupType = () -> groupInstance.getType();
725 Supplier<String> supplDescription = () -> groupInstance.getDescription();
726 Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance.convertToGroupInstancesProperties();
727 Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
728 Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
729 Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
730 Supplier<String> supplVersion = () -> groupInstance.getVersion();
732 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
733 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
735 toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
736 toscaGroup.setMetadata(toscaMetadata);
740 private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
741 Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
742 Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
743 boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
744 toscaGroup.setType(groupType.get());
746 IToscaMetadata toscaMetadata;
748 toscaMetadata = new ToscaMetadata();
750 toscaMetadata = new VfModuleToscaMetadata();
752 Map<String, Object> properties = fillGroupProperties(props.get());
753 if(!properties.containsKey(VF_MODULE_DESC_KEY) || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))){
754 properties.put(VF_MODULE_DESC_KEY, description.get());
756 toscaGroup.setProperties(properties);
758 toscaMetadata.setName(groupName.get());
759 toscaMetadata.setInvariantUUID(invariantUUID.get());
760 toscaMetadata.setUUID(groupUUID.get());
761 toscaMetadata.setVersion(version.get());
762 return toscaMetadata;
765 private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
766 Map<String, Object> properties = new HashMap<>();
767 if(groupProps != null){
768 for (GroupProperty gp : groupProps) {
769 if (gp.getName().equals(Constants.IS_BASE)) {
770 Boolean isBase = Boolean.parseBoolean(gp.getValue());
771 String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
772 properties.put(VF_MODULE_TYPE_KEY, type);
775 String type = gp.getType();
779 if (gp.getValue() != null) {
780 value = Integer.valueOf(gp.getValue());
784 if (gp.getValue() != null) {
785 value = Boolean.valueOf(gp.getValue());
790 value = gp.getValue();
793 properties.put(gp.getName(), value);
800 private ToscaNodeType createNodeType(Component component) {
801 ToscaNodeType toscaNodeType = new ToscaNodeType();
802 if (ToscaUtils.isAtomicType(component)){
803 if (((Resource) component).getDerivedFrom() != null){
804 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
806 toscaNodeType.setDescription(component.getDescription()); // or name??
808 String derivedFrom = null != component.getDerivedFromGenericType()? component.getDerivedFromGenericType() : "tosca.nodes.Root";
809 toscaNodeType.setDerived_from(derivedFrom);
811 return toscaNodeType;
814 //TODO save the capability(type or name) info on relation data
815 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
816 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
817 ToscaNodeTemplate nodeTypeTemplate, Component originComponent) {
819 List<ComponentInstance> instancesList = component.getComponentInstances();
820 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
821 Map<String, List<RequirementDefinition>> reqMap = originComponent.getRequirements();
823 relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(rel -> {
824 ComponentInstance toComponentInstance = instancesList.stream()
825 .filter(i -> rel.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
826 if (toComponentInstance == null) {
827 log.debug("Failed to find relation between node {} to node {}", componentInstance.getName(),
831 RequirementAndRelationshipPair reqAndRelationshipPair = rel.getRelationships().get(0);
832 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
833 toscaRequirement.setNode(toComponentInstance.getName());
834 Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream())
835 .filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny();
836 if (findAny.isPresent()) {
837 RequirementDefinition reqDefinition = findAny.get();
838 toscaRequirement.setCapability(reqDefinition.getCapability());
839 toscaRequirement.setRelationship(reqDefinition.getRelationship());
841 // reqMap represents calculated requirements! if not found there, export data directly from the relation definition
842 log.debug("Failed to find requirement {} definition for node {}", reqAndRelationshipPair.getRequirement(), componentInstance.getName());
845 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
846 toscaReqMap.put(reqAndRelationshipPair.getRequirement(), toscaRequirement);
847 toscaRequirements.add(toscaReqMap);
851 if (!toscaRequirements.isEmpty()) {
852 nodeTypeTemplate.setRequirements(toscaRequirements);
854 log.debug("Finish convert Requirements for node type");
855 return Either.left(nodeTypeTemplate);
859 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map<String, DataTypeDefinition> dataTypes) {
860 Map<String, String[]> toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes);
862 if (!toscaCapabilities.isEmpty()) {
863 substitutionMapping.setCapabilities(toscaCapabilities);
865 log.debug("Finish convert Capabilities for node type");
867 return Either.left(substitutionMapping);
870 private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
871 Map<String, DataTypeDefinition> dataTypes) {
872 Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
874 if (!toscaCapabilities.isEmpty()) {
875 nodeType.setCapabilities(toscaCapabilities);
877 log.debug("Finish convert Capabilities for node type");
879 return Either.left(nodeType);
882 private static class CustomRepresenter extends Representer {
883 public CustomRepresenter() {
885 // null representer is exceptional and it is stored as an instance
887 this.nullRepresenter = new RepresentNull();
892 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
894 if (propertyValue == null) {
897 // skip not relevant for Tosca property
898 if (property.getName().equals("dependencies")) {
901 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
903 return property.getName().equals("_defaultp_")
904 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
909 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
910 // remove the bean type from the output yaml (!! ...)
911 if (!classTags.containsKey(javaBean.getClass()))
912 addClassTag(javaBean.getClass(), Tag.MAP);
914 return super.representJavaBean(properties, javaBean);
917 private class RepresentNull implements Represent {
918 public Node representData(Object data) {
919 // possible values are here http://yaml.org/type/null.html
920 return representScalar(Tag.NULL, "");
925 private static class UnsortedPropertyUtils extends PropertyUtils {
927 protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
928 throws IntrospectionException {
929 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
930 return new LinkedHashSet<Property>(fields);