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.ArtifactDefinition;
46 import org.openecomp.sdc.be.model.Component;
47 import org.openecomp.sdc.be.model.ComponentInstance;
48 import org.openecomp.sdc.be.model.ComponentInstanceInput;
49 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
50 import org.openecomp.sdc.be.model.DataTypeDefinition;
51 import org.openecomp.sdc.be.model.GroupDefinition;
52 import org.openecomp.sdc.be.model.GroupInstance;
53 import org.openecomp.sdc.be.model.GroupProperty;
54 import org.openecomp.sdc.be.model.InputDefinition;
55 import org.openecomp.sdc.be.model.PropertyDefinition;
56 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
57 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
58 import org.openecomp.sdc.be.model.RequirementDefinition;
59 import org.openecomp.sdc.be.model.Resource;
60 import org.openecomp.sdc.be.model.Service;
61 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
62 import org.openecomp.sdc.be.model.category.CategoryDefinition;
63 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
64 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
65 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
66 import org.openecomp.sdc.be.tosca.model.IToscaMetadata;
67 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
68 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
69 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
70 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
71 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
72 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
73 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
74 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
75 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
76 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
77 import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
78 import org.openecomp.sdc.common.api.Constants;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.yaml.snakeyaml.DumperOptions;
83 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
84 import org.yaml.snakeyaml.Yaml;
85 import org.yaml.snakeyaml.introspector.BeanAccess;
86 import org.yaml.snakeyaml.introspector.Property;
87 import org.yaml.snakeyaml.introspector.PropertyUtils;
88 import org.yaml.snakeyaml.nodes.MappingNode;
89 import org.yaml.snakeyaml.nodes.Node;
90 import org.yaml.snakeyaml.nodes.NodeTuple;
91 import org.yaml.snakeyaml.nodes.Tag;
92 import org.yaml.snakeyaml.representer.Represent;
93 import org.yaml.snakeyaml.representer.Representer;
95 import fj.data.Either;
97 @org.springframework.stereotype.Component("tosca-export-handler")
98 public class ToscaExportHandler {
101 private ApplicationDataTypeCache dataTypeCache;
104 private ToscaOperationFacade toscaOperationFacade;
106 private CapabiltyRequirementConvertor capabiltyRequirementConvertor = CapabiltyRequirementConvertor.getInstance();
107 private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
110 private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
112 public static final String TOSCA_VERSION = "tosca_simple_yaml_1_0";
113 public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
114 public static final String IMPORTS_FILE_KEY = "file";
115 public static final String TOSCA_TEMPLATE_NAME = "-template.yml";
116 public static final String TOSCA_INTERFACE_NAME = "-interface.yml";
117 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
118 public static final String VF_MODULE_TYPE_KEY = "vf_module_type";
119 public static final String VF_MODULE_DESC_KEY = "vf_module_description";
120 public static final String VOLUME_GROUP_KEY = "volume_group";
121 public static final String VF_MODULE_TYPE_BASE = "Base";
122 public static final String VF_MODULE_TYPE_EXPANSION = "Expansion";
123 public static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports();
127 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
129 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
130 if (toscaTemplateRes.isRight()) {
131 return Either.right(toscaTemplateRes.right().value());
134 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
135 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
136 return Either.left(toscaRepresentation);
139 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) {
140 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
141 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
142 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
143 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, nodeTypes);
144 if (toscaTemplateRes.isRight()) {
145 return Either.right(toscaTemplateRes.right().value());
148 toscaTemplate = toscaTemplateRes.left().value();
149 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
150 return Either.left(toscaRepresentation);
153 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
154 CustomRepresenter representer = new CustomRepresenter();
155 DumperOptions options = new DumperOptions();
156 options.setAllowReadOnlyProperties(false);
157 options.setPrettyFlow(true);
159 options.setDefaultFlowStyle(FlowStyle.FLOW);
160 options.setCanonical(false);
162 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
164 representer.setPropertyUtils(new UnsortedPropertyUtils());
165 Yaml yaml = new Yaml(representer, options);
167 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
169 StringBuilder sb = new StringBuilder();
170 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
171 sb.append(yamlAsString);
172 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
174 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
175 toscaRepresentation.setMainYaml(sb.toString());
176 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
178 return toscaRepresentation;
181 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
182 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
183 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
185 if (fillImports.isRight()) {
186 return Either.right(fillImports.right().value());
188 return Either.left(fillImports.left().value().left);
191 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
192 log.trace("start tosca export for {}", component.getUniqueId());
193 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
195 toscaTemplate.setMetadata(convertMetadata(component));
196 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
197 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
198 if (ToscaUtils.isAtomicType(component)) {
199 log.trace("convert component as node type");
200 return convertNodeType(component, toscaTemplate, nodeTypes);
202 log.trace("convert component as topology template");
203 return convertToscaTemplate(component, toscaTemplate);
208 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
210 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
212 if (importsRes.isRight()) {
213 return Either.right(importsRes.right().value());
215 toscaNode = importsRes.left().value().left;
217 Map<String, Component> componentCache = importsRes.left().value().right;
218 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
219 if (dataTypesEither.isRight()) {
220 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
221 return Either.right(ToscaError.GENERAL_ERROR);
223 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
225 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
227 Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
228 if (inputs.isRight()) {
229 return Either.right(inputs.right().value());
231 topologyTemplate = inputs.left().value();
233 List<ComponentInstance> componentInstances = component.getComponentInstances();
234 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
235 .getComponentInstancesProperties();
236 List<GroupDefinition> groups = component.getGroups();
237 if (componentInstances != null && !componentInstances.isEmpty()) {
239 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
240 componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
241 if (nodeTemplates.isRight()) {
242 return Either.right(nodeTemplates.right().value());
244 log.debug("node templates converted");
246 topologyTemplate.setNode_templates(nodeTemplates.left().value());
248 Map<String, ToscaGroupTemplate> groupsMap = null;
249 if (groups != null && !groups.isEmpty()) {
250 groupsMap = new HashMap<String, ToscaGroupTemplate>();
251 for (GroupDefinition group : groups) {
252 ToscaGroupTemplate toscaGroup = convertGroup(group);
253 groupsMap.put(group.getName(), toscaGroup);
256 log.debug("groups converted");
257 topologyTemplate.addGroups(groupsMap);
259 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
260 String toscaResourceName = null;
261 switch (component.getComponentType()) {
263 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
264 .getMetadataDataDefinition()).getToscaResourceName();
267 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
268 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
271 log.debug("Not supported component type {}", component.getComponentType());
272 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
274 substitutionMapping.setNode_type(toscaResourceName);
276 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
278 if (capabilities.isRight()) {
279 return Either.right(capabilities.right().value());
281 substitutionMapping = capabilities.left().value();
283 Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping);
284 if (requirements.isRight()) {
285 return Either.right(requirements.right().value());
287 substitutionMapping = requirements.left().value();
289 topologyTemplate.setSubstitution_mappings(substitutionMapping);
291 toscaNode.setTopology_template(topologyTemplate);
292 return Either.left(toscaNode);
295 private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
296 ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
297 if (log.isDebugEnabled())
298 log.debug("fillInputs for component {}", component.getUniqueId());
299 List<InputDefinition> inputDef = component.getInputs();
300 Map<String, ToscaProperty> inputs = new HashMap<>();
302 if (inputDef != null) {
303 inputDef.forEach(i -> {
304 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
305 inputs.put(i.getName(), property);
307 if (!inputs.isEmpty()) {
308 topologyTemplate.setInputs(inputs);
311 return Either.left(topologyTemplate);
314 private ToscaMetadata convertMetadata(Component component) {
315 return convertMetadata(component, false, null);
318 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
319 ComponentInstance componentInstance) {
320 ToscaMetadata toscaMetadata = new ToscaMetadata();
321 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
322 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
323 toscaMetadata.setUUID(component.getUUID());
324 toscaMetadata.setDescription(component.getDescription());
326 List<CategoryDefinition> categories = component.getCategories();
327 CategoryDefinition categoryDefinition = categories.get(0);
328 toscaMetadata.setCategory(categoryDefinition.getName());
331 toscaMetadata.setVersion(component.getVersion());
332 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
334 switch (component.getComponentType()) {
336 Resource resource = (Resource) component;
337 toscaMetadata.setType(resource.getResourceType().name());
338 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
339 toscaMetadata.setResourceVendor(resource.getVendorName());
340 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
344 toscaMetadata.setType(component.getComponentType().getValue());
347 toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
348 toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming());
349 toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy());
353 log.debug("Not supported component type {}", component.getComponentType());
355 return toscaMetadata;
358 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
359 ToscaTemplate toscaTemplate) {
360 Map<String, Component> componentCache = new HashMap<>();
362 if (!ToscaUtils.isAtomicType(component)) {
363 List<ComponentInstance> componentInstances = component.getComponentInstances();
364 if (componentInstances != null && !componentInstances.isEmpty()) {
366 List<Map<String, Map<String, String>>> additionalImports =
367 toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
369 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
371 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
372 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
374 Map<String, Map<String, String>> importsListMember = new HashMap<>();
375 Map<String, String> interfaceFiles = new HashMap<>();
376 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
377 StringBuilder keyNameBuilder = new StringBuilder();
378 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
379 keyNameBuilder.append("-");
380 keyNameBuilder.append(component.getName());
381 keyNameBuilder.append("-interface");
382 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
383 additionalImports.add(importsListMember);
385 componentInstances.forEach(ci -> {
386 createDependency(componentCache, additionalImports, dependecies, ci);
388 toscaTemplate.setDependencies(dependecies);
389 toscaTemplate.setImports(additionalImports);
392 log.debug("currently imports supported for VF and service only");
394 return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
397 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
398 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
399 Map<String, String> files = new HashMap<>();
400 Map<String, Map<String, String>> importsListMember = new HashMap<>();
401 StringBuilder keyNameBuilder;
403 Component componentRI = componentCache.get(ci.getComponentUid());
404 if (componentRI == null) {
405 // all resource must be only once!
406 Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
407 if (resource.isRight()) {
408 log.debug("Failed to fetch resource with id {} for instance {}");
410 Component fetchedComponent = resource.left().value();
411 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
412 componentRI = fetchedComponent;
414 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
415 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
416 if (artifactDefinition != null) {
417 String artifactName = artifactDefinition.getArtifactName();
418 files.put(IMPORTS_FILE_KEY, artifactName);
419 keyNameBuilder = new StringBuilder();
420 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
421 keyNameBuilder.append("-");
422 keyNameBuilder.append(ci.getComponentName());
423 importsListMember.put(keyNameBuilder.toString(), files);
424 imports.add(importsListMember);
425 dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
426 artifactDefinition.getEsId(), fetchedComponent));
428 if(!ToscaUtils.isAtomicType(componentRI)) {
429 importsListMember = new HashMap<>();
430 Map<String, String> interfaceFiles = new HashMap<>();
431 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
432 keyNameBuilder.append("-interface");
433 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
434 imports.add(importsListMember);
440 public static String getInterfaceFilename(String artifactName) {
441 String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
442 return interfaceFileName;
445 private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
446 Map<String, ToscaNodeType> nodeTypes) {
447 log.debug("start convert node type for {}", component.getUniqueId());
448 ToscaNodeType toscaNodeType = createNodeType(component);
450 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
451 if (dataTypesEither.isRight()) {
452 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
453 return Either.right(ToscaError.GENERAL_ERROR);
456 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
457 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
459 if (properties.isRight()) {
460 return Either.right(properties.right().value());
462 toscaNodeType = properties.left().value();
463 log.debug("Properties converted for {}", component.getUniqueId());
465 //Extracted to method for code reuse
466 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
469 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
470 Map<String, ToscaNodeType> nodeTypes) {
471 log.debug("start convert node type for {}", component.getUniqueId());
472 ToscaNodeType toscaNodeType = createNodeType(component);
474 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
475 if (dataTypesEither.isRight()) {
476 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
477 return Either.right(ToscaError.GENERAL_ERROR);
480 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
482 List<InputDefinition> inputDef = component.getInputs();
483 Map<String, ToscaProperty> inputs = new HashMap<>();
485 if (inputDef != null) {
486 inputDef.forEach(i -> {
487 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
488 inputs.put(i.getName(), property);
490 if (!inputs.isEmpty()) {
491 toscaNodeType.setProperties(inputs);
495 //Extracted to method for code reuse
496 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
499 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
500 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
501 Map<String, DataTypeDefinition> dataTypes) {
502 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
503 if (capabilities.isRight()) {
504 return Either.right(capabilities.right().value());
506 toscaNodeType = capabilities.left().value();
507 log.debug("Capabilities converted for {}", component.getUniqueId());
509 Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
511 if (requirements.isRight()) {
512 return Either.right(requirements.right().value());
514 toscaNodeType = requirements.left().value();
515 log.debug("Requirements converted for {}", component.getUniqueId());
518 String toscaResourceName;
519 switch (component.getComponentType()) {
521 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
522 .getMetadataDataDefinition()).getToscaResourceName();
525 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
526 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
529 log.debug("Not supported component type {}", component.getComponentType());
530 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
533 nodeTypes.put(toscaResourceName, toscaNodeType);
534 toscaNode.setNode_types(nodeTypes);
535 log.debug("finish convert node type for {}", component.getUniqueId());
536 return Either.left(toscaNode);
539 private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
540 List<ComponentInstance> componentInstances,
541 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
542 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
543 ToscaTopolgyTemplate topologyTemplate) {
545 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
546 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
547 component.getComponentType());
548 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
549 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
551 Map<String, ToscaGroupTemplate> groupsMap = null;
552 for (ComponentInstance componentInstance : componentInstances) {
553 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
554 nodeTemplate.setType(componentInstance.getToscaComponentName());
556 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
557 componentInstance, component.getComponentInstancesRelations(), nodeTemplate);
558 if (requirements.isRight()) {
559 convertNodeTemplatesRes = Either.right(requirements.right().value());
562 String instanceUniqueId = componentInstance.getUniqueId();
563 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
565 nodeTemplate = requirements.left().value();
567 Component componentOfInstance = componentCache.get(componentInstance.getComponentUid());
568 nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
570 Either<ToscaNodeTemplate, ToscaError> capabilties = capabiltyRequirementConvertor
571 .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
572 if (capabilties.isRight()) {
573 convertNodeTemplatesRes = Either.right(requirements.right().value());
576 log.debug("Component instance Capabilties converted for instance {}", instanceUniqueId);
578 nodeTemplate = capabilties.left().value();
579 Map<String, Object> props = new HashMap<>();
581 if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) {
582 // Adds the properties of parent component to map
583 addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props);
586 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
587 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
588 instanceUniqueId, props);
591 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
592 addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
595 if (props != null && !props.isEmpty()) {
596 nodeTemplate.setProperties(props);
599 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
600 if (groupInstances != null) {
601 if (groupsMap == null) {
602 groupsMap = new HashMap<>();
604 for (GroupInstance groupInst : groupInstances) {
605 ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
606 String keyName = groupInst.getGroupName();
608 groupsMap.put(keyName, toscaGroup);
612 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
614 if (groupsMap != null) {
615 log.debug("instance groups added");
616 topologyTemplate.addGroups(groupsMap);
619 if (convertNodeTemplatesRes == null) {
620 convertNodeTemplatesRes = Either.left(nodeTemplates);
622 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
623 component.getComponentType());
624 return convertNodeTemplatesRes;
627 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
628 Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
629 String instanceUniqueId, Map<String, Object> props) {
631 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
632 if (instanceInputsList != null) {
633 instanceInputsList.forEach(input -> {
634 Supplier<String> supplier = () -> input.getValue();
635 convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
640 private void addPropertiesOfComponentInstance(
641 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
642 Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
643 Map<String, Object> props) {
645 if (!MapUtils.isEmpty(componentInstancesProperties)) {
646 componentInstancesProperties.get(instanceUniqueId).stream()
647 // Filters out properties with empty ValueUniqueUid
648 .filter(e -> e.getValue() != null && !e.getValue().isEmpty() )
649 // Collects filtered properties to List
650 .collect(Collectors.toList()).stream()
651 // Converts and adds each value to property map
652 .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
653 () -> prop.getValue()));
657 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
658 ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
660 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
661 if (!CollectionUtils.isEmpty(componentProperties)) {
662 componentProperties.stream()
663 // Filters out properties with empty default values
664 .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
665 // Collects filtered properties to List
666 .collect(Collectors.toList()).stream()
667 // Converts and adds each value to property map
668 .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
669 () -> prop.getDefaultValue()));
675 * @param componentInstance
680 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
681 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
682 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
683 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
684 props.put(prop.getName(), convertedValue);
688 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
689 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
690 log.debug("Convert property or input value {} for instance {}", input.getName(),
691 componentInstance.getUniqueId());
692 String propertyType = input.getType();
693 String innerType = null;
694 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
695 innerType = input.getSchema().getProperty().getType();
697 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
700 private ToscaGroupTemplate convertGroup(GroupDefinition group) {
701 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
702 Map<String, String> members = group.getMembers();
704 toscaGroup.setMembers(new ArrayList(members.keySet()));
706 Supplier<String> supplGroupType = () -> group.getType();
707 Supplier<String> supplDescription = () -> group.getDescription();
708 Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
709 Supplier<String> supplgroupName = () -> group.getName();
710 Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
711 Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
712 Supplier<String> supplVersion = () -> group.getVersion();
714 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
715 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
716 toscaGroup.setMetadata(toscaMetadata);
720 private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
721 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
723 Supplier<String> supplGroupType = () -> groupInstance.getType();
724 Supplier<String> supplDescription = () -> groupInstance.getDescription();
725 Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance.convertToGroupInstancesProperties();
726 Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
727 Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
728 Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
729 Supplier<String> supplVersion = () -> groupInstance.getVersion();
731 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
732 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
734 toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
735 toscaGroup.setMetadata(toscaMetadata);
739 private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
740 Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
741 Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
742 boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
743 toscaGroup.setType(groupType.get());
745 IToscaMetadata toscaMetadata;
747 toscaMetadata = new ToscaMetadata();
749 toscaMetadata = new VfModuleToscaMetadata();
751 Map<String, Object> properties = fillGroupProperties(props.get());
753 properties.put(VF_MODULE_DESC_KEY, description.get());
754 toscaGroup.setProperties(properties);
756 toscaMetadata.setName(groupName.get());
757 toscaMetadata.setInvariantUUID(invariantUUID.get());
758 toscaMetadata.setUUID(groupUUID.get());
759 toscaMetadata.setVersion(version.get());
760 return toscaMetadata;
763 private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
764 Map<String, Object> properties = new HashMap<>();
765 if(groupProps != null){
766 for (GroupProperty gp : groupProps) {
767 if (gp.getName().equals(Constants.IS_BASE)) {
768 Boolean isBase = Boolean.parseBoolean(gp.getValue());
769 String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
770 properties.put(VF_MODULE_TYPE_KEY, type);
773 String type = gp.getType();
777 if (gp.getValue() != null) {
778 value = Integer.valueOf(gp.getValue());
782 if (gp.getValue() != null) {
783 value = Boolean.valueOf(gp.getValue());
788 value = gp.getValue();
791 properties.put(gp.getName(), value);
798 private ToscaNodeType createNodeType(Component component) {
799 ToscaNodeType toscaNodeType = new ToscaNodeType();
800 if (ToscaUtils.isAtomicType(component)){
801 if (((Resource) component).getDerivedFrom() != null){
802 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
804 toscaNodeType.setDescription(component.getDescription()); // or name??
806 String derivedFrom = null != component.getDerivedFromGenericType()? component.getDerivedFromGenericType() : "tosca.nodes.Root";
807 toscaNodeType.setDerived_from(derivedFrom);
809 return toscaNodeType;
812 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
813 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
814 ToscaNodeTemplate nodeTypeTemplate) {
816 List<ComponentInstance> instancesList = component.getComponentInstances();
817 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
818 Map<String, List<RequirementDefinition>> reqMap = componentInstance.getRequirements();
820 relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(req -> {
821 ComponentInstance toComponentInstance = instancesList.stream()
822 .filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
823 if (toComponentInstance == null) {
824 log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(),
829 RequirementAndRelationshipPair reqAndRelationshopPair = req.getRelationships().get(0);
830 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
831 toscaRequirement.setRelationship(reqAndRelationshopPair.getRelationship().getType());
832 toscaRequirement.setNode(toComponentInstance.getName());
833 Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream())
834 .filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny();
835 if (findAny.isPresent()) {
836 RequirementDefinition regDefinition = findAny.get();
837 toscaRequirement.setCapability(regDefinition.getCapability());
839 log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(),
843 Map<String, ToscaTemplateRequirement> reqmap = new HashMap<String, ToscaTemplateRequirement>();
844 reqmap.put(reqAndRelationshopPair.getRequirement(), toscaRequirement);
845 toscaRequirements.add(reqmap);
849 if (!toscaRequirements.isEmpty()) {
850 nodeTypeTemplate.setRequirements(toscaRequirements);
852 log.debug("Finish convert Requirements for node type");
853 return Either.left(nodeTypeTemplate);
856 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map<String, DataTypeDefinition> dataTypes) {
857 Map<String, String[]> toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes);
859 if (!toscaCapabilities.isEmpty()) {
860 substitutionMapping.setCapabilities(toscaCapabilities);
862 log.debug("Finish convert Capabilities for node type");
864 return Either.left(substitutionMapping);
867 private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
868 Map<String, DataTypeDefinition> dataTypes) {
869 Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
871 if (!toscaCapabilities.isEmpty()) {
872 nodeType.setCapabilities(toscaCapabilities);
874 log.debug("Finish convert Capabilities for node type");
876 return Either.left(nodeType);
879 private static class CustomRepresenter extends Representer {
880 public CustomRepresenter() {
882 // null representer is exceptional and it is stored as an instance
884 this.nullRepresenter = new RepresentNull();
889 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
891 if (propertyValue == null) {
894 // skip not relevant for Tosca property
895 if (property.getName().equals("dependencies")) {
898 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
900 return property.getName().equals("_defaultp_")
901 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
906 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
907 // remove the bean type from the output yaml (!! ...)
908 if (!classTags.containsKey(javaBean.getClass()))
909 addClassTag(javaBean.getClass(), Tag.MAP);
911 return super.representJavaBean(properties, javaBean);
914 private class RepresentNull implements Represent {
915 public Node representData(Object data) {
916 // possible values are here http://yaml.org/type/null.html
917 return representScalar(Tag.NULL, "");
922 private static class UnsortedPropertyUtils extends PropertyUtils {
924 protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
925 throws IntrospectionException {
926 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
927 return new LinkedHashSet<Property>(fields);