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 if(null == DEFAULT_IMPORTS) {
141 log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
142 return Either.right(ToscaError.GENERAL_ERROR);
145 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
146 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
147 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
148 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, nodeTypes);
149 if (toscaTemplateRes.isRight()) {
150 return Either.right(toscaTemplateRes.right().value());
153 toscaTemplate = toscaTemplateRes.left().value();
154 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
155 return Either.left(toscaRepresentation);
158 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
159 CustomRepresenter representer = new CustomRepresenter();
160 DumperOptions options = new DumperOptions();
161 options.setAllowReadOnlyProperties(false);
162 options.setPrettyFlow(true);
164 options.setDefaultFlowStyle(FlowStyle.FLOW);
165 options.setCanonical(false);
167 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
169 representer.setPropertyUtils(new UnsortedPropertyUtils());
170 Yaml yaml = new Yaml(representer, options);
172 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
174 StringBuilder sb = new StringBuilder();
175 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
176 sb.append(yamlAsString);
177 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
179 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
180 toscaRepresentation.setMainYaml(sb.toString());
181 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
183 return toscaRepresentation;
186 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
187 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
188 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
190 if (fillImports.isRight()) {
191 return Either.right(fillImports.right().value());
193 return Either.left(fillImports.left().value().left);
196 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
197 if(null == DEFAULT_IMPORTS) {
198 log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
199 return Either.right(ToscaError.GENERAL_ERROR);
202 log.trace("start tosca export for {}", component.getUniqueId());
203 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
205 toscaTemplate.setMetadata(convertMetadata(component));
206 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
207 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
208 if (ToscaUtils.isAtomicType(component)) {
209 log.trace("convert component as node type");
210 return convertNodeType(component, toscaTemplate, nodeTypes);
212 log.trace("convert component as topology template");
213 return convertToscaTemplate(component, toscaTemplate);
218 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
220 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
222 if (importsRes.isRight()) {
223 return Either.right(importsRes.right().value());
225 toscaNode = importsRes.left().value().left;
227 Map<String, Component> componentCache = importsRes.left().value().right;
228 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
229 if (dataTypesEither.isRight()) {
230 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
231 return Either.right(ToscaError.GENERAL_ERROR);
233 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
235 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
237 Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
238 if (inputs.isRight()) {
239 return Either.right(inputs.right().value());
241 topologyTemplate = inputs.left().value();
243 List<ComponentInstance> componentInstances = component.getComponentInstances();
244 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
245 .getComponentInstancesProperties();
246 List<GroupDefinition> groups = component.getGroups();
247 if (componentInstances != null && !componentInstances.isEmpty()) {
249 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
250 componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
251 if (nodeTemplates.isRight()) {
252 return Either.right(nodeTemplates.right().value());
254 log.debug("node templates converted");
256 topologyTemplate.setNode_templates(nodeTemplates.left().value());
258 Map<String, ToscaGroupTemplate> groupsMap = null;
259 if (groups != null && !groups.isEmpty()) {
260 groupsMap = new HashMap<String, ToscaGroupTemplate>();
261 for (GroupDefinition group : groups) {
262 ToscaGroupTemplate toscaGroup = convertGroup(group);
263 groupsMap.put(group.getName(), toscaGroup);
266 log.debug("groups converted");
267 topologyTemplate.addGroups(groupsMap);
269 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
270 String toscaResourceName = null;
271 switch (component.getComponentType()) {
273 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
274 .getMetadataDataDefinition()).getToscaResourceName();
277 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
278 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
281 log.debug("Not supported component type {}", component.getComponentType());
282 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
284 substitutionMapping.setNode_type(toscaResourceName);
286 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
288 if (capabilities.isRight()) {
289 return Either.right(capabilities.right().value());
291 substitutionMapping = capabilities.left().value();
293 Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping);
294 if (requirements.isRight()) {
295 return Either.right(requirements.right().value());
297 substitutionMapping = requirements.left().value();
299 topologyTemplate.setSubstitution_mappings(substitutionMapping);
301 toscaNode.setTopology_template(topologyTemplate);
302 return Either.left(toscaNode);
305 private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
306 ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
307 if (log.isDebugEnabled())
308 log.debug("fillInputs for component {}", component.getUniqueId());
309 List<InputDefinition> inputDef = component.getInputs();
310 Map<String, ToscaProperty> inputs = new HashMap<>();
312 if (inputDef != null) {
313 inputDef.forEach(i -> {
314 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
315 inputs.put(i.getName(), property);
317 if (!inputs.isEmpty()) {
318 topologyTemplate.setInputs(inputs);
321 return Either.left(topologyTemplate);
324 private ToscaMetadata convertMetadata(Component component) {
325 return convertMetadata(component, false, null);
328 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
329 ComponentInstance componentInstance) {
330 ToscaMetadata toscaMetadata = new ToscaMetadata();
331 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
332 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
333 toscaMetadata.setUUID(component.getUUID());
334 toscaMetadata.setDescription(component.getDescription());
336 List<CategoryDefinition> categories = component.getCategories();
337 CategoryDefinition categoryDefinition = categories.get(0);
338 toscaMetadata.setCategory(categoryDefinition.getName());
341 toscaMetadata.setVersion(component.getVersion());
342 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
344 switch (component.getComponentType()) {
346 Resource resource = (Resource) component;
347 toscaMetadata.setType(resource.getResourceType().name());
348 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
349 toscaMetadata.setResourceVendor(resource.getVendorName());
350 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
354 toscaMetadata.setType(component.getComponentType().getValue());
357 toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
358 toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming());
359 toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy());
363 log.debug("Not supported component type {}", component.getComponentType());
365 return toscaMetadata;
368 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
369 ToscaTemplate toscaTemplate) {
371 if(null == DEFAULT_IMPORTS) {
372 log.debug("convertToToscaTemplate - failed to get Default Imports section from configuration");
373 return Either.right(ToscaError.GENERAL_ERROR);
376 Map<String, Component> componentCache = new HashMap<>();
378 if (!ToscaUtils.isAtomicType(component)) {
379 List<ComponentInstance> componentInstances = component.getComponentInstances();
380 if (componentInstances != null && !componentInstances.isEmpty()) {
382 List<Map<String, Map<String, String>>> additionalImports =
383 toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
385 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
387 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
388 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
390 Map<String, Map<String, String>> importsListMember = new HashMap<>();
391 Map<String, String> interfaceFiles = new HashMap<>();
392 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
393 StringBuilder keyNameBuilder = new StringBuilder();
394 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
395 keyNameBuilder.append("-");
396 keyNameBuilder.append(component.getName());
397 keyNameBuilder.append("-interface");
398 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
399 additionalImports.add(importsListMember);
401 componentInstances.forEach(ci -> {
402 createDependency(componentCache, additionalImports, dependecies, ci);
404 toscaTemplate.setDependencies(dependecies);
405 toscaTemplate.setImports(additionalImports);
408 log.debug("currently imports supported for VF and service only");
410 return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
413 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
414 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
415 Map<String, String> files = new HashMap<>();
416 Map<String, Map<String, String>> importsListMember = new HashMap<>();
417 StringBuilder keyNameBuilder;
419 Component componentRI = componentCache.get(ci.getComponentUid());
420 if (componentRI == null) {
421 // all resource must be only once!
422 Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
423 if (resource.isRight()) {
424 log.debug("Failed to fetch resource with id {} for instance {}");
426 Component fetchedComponent = resource.left().value();
427 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
428 componentRI = fetchedComponent;
430 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
431 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
432 if (artifactDefinition != null) {
433 String artifactName = artifactDefinition.getArtifactName();
434 files.put(IMPORTS_FILE_KEY, artifactName);
435 keyNameBuilder = new StringBuilder();
436 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
437 keyNameBuilder.append("-");
438 keyNameBuilder.append(ci.getComponentName());
439 importsListMember.put(keyNameBuilder.toString(), files);
440 imports.add(importsListMember);
441 dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
442 artifactDefinition.getEsId(), fetchedComponent));
444 if(!ToscaUtils.isAtomicType(componentRI)) {
445 importsListMember = new HashMap<>();
446 Map<String, String> interfaceFiles = new HashMap<>();
447 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
448 keyNameBuilder.append("-interface");
449 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
450 imports.add(importsListMember);
456 public static String getInterfaceFilename(String artifactName) {
457 String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
458 return interfaceFileName;
461 private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
462 Map<String, ToscaNodeType> nodeTypes) {
463 log.debug("start convert node type for {}", component.getUniqueId());
464 ToscaNodeType toscaNodeType = createNodeType(component);
466 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
467 if (dataTypesEither.isRight()) {
468 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
469 return Either.right(ToscaError.GENERAL_ERROR);
472 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
473 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
475 if (properties.isRight()) {
476 return Either.right(properties.right().value());
478 toscaNodeType = properties.left().value();
479 log.debug("Properties converted for {}", component.getUniqueId());
481 //Extracted to method for code reuse
482 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
485 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
486 Map<String, ToscaNodeType> nodeTypes) {
487 log.debug("start convert node type for {}", component.getUniqueId());
488 ToscaNodeType toscaNodeType = createNodeType(component);
490 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
491 if (dataTypesEither.isRight()) {
492 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
493 return Either.right(ToscaError.GENERAL_ERROR);
496 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
498 List<InputDefinition> inputDef = component.getInputs();
499 Map<String, ToscaProperty> inputs = new HashMap<>();
501 if (inputDef != null) {
502 inputDef.forEach(i -> {
503 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
504 inputs.put(i.getName(), property);
506 if (!inputs.isEmpty()) {
507 toscaNodeType.setProperties(inputs);
511 //Extracted to method for code reuse
512 return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
515 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
516 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
517 Map<String, DataTypeDefinition> dataTypes) {
518 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
519 if (capabilities.isRight()) {
520 return Either.right(capabilities.right().value());
522 toscaNodeType = capabilities.left().value();
523 log.debug("Capabilities converted for {}", component.getUniqueId());
525 Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
527 if (requirements.isRight()) {
528 return Either.right(requirements.right().value());
530 toscaNodeType = requirements.left().value();
531 log.debug("Requirements converted for {}", component.getUniqueId());
534 String toscaResourceName;
535 switch (component.getComponentType()) {
537 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
538 .getMetadataDataDefinition()).getToscaResourceName();
541 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
542 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
545 log.debug("Not supported component type {}", component.getComponentType());
546 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
549 nodeTypes.put(toscaResourceName, toscaNodeType);
550 toscaNode.setNode_types(nodeTypes);
551 log.debug("finish convert node type for {}", component.getUniqueId());
552 return Either.left(toscaNode);
555 private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
556 List<ComponentInstance> componentInstances,
557 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
558 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
559 ToscaTopolgyTemplate topologyTemplate) {
561 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
562 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
563 component.getComponentType());
564 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
565 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
567 Map<String, ToscaGroupTemplate> groupsMap = null;
568 for (ComponentInstance componentInstance : componentInstances) {
569 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
570 nodeTemplate.setType(componentInstance.getToscaComponentName());
572 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
573 componentInstance, component.getComponentInstancesRelations(), nodeTemplate);
574 if (requirements.isRight()) {
575 convertNodeTemplatesRes = Either.right(requirements.right().value());
578 String instanceUniqueId = componentInstance.getUniqueId();
579 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
581 nodeTemplate = requirements.left().value();
583 Component componentOfInstance = componentCache.get(componentInstance.getComponentUid());
584 nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
586 Either<ToscaNodeTemplate, ToscaError> capabilties = capabiltyRequirementConvertor
587 .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
588 if (capabilties.isRight()) {
589 convertNodeTemplatesRes = Either.right(requirements.right().value());
592 log.debug("Component instance Capabilties converted for instance {}", instanceUniqueId);
594 nodeTemplate = capabilties.left().value();
595 Map<String, Object> props = new HashMap<>();
597 if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) {
598 // Adds the properties of parent component to map
599 addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props);
602 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
603 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
604 instanceUniqueId, props);
607 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
608 addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
611 if (props != null && !props.isEmpty()) {
612 nodeTemplate.setProperties(props);
615 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
616 if (groupInstances != null) {
617 if (groupsMap == null) {
618 groupsMap = new HashMap<>();
620 for (GroupInstance groupInst : groupInstances) {
621 ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
623 groupsMap.put(groupInst.getName(), toscaGroup);
627 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
629 if (groupsMap != null) {
630 log.debug("instance groups added");
631 topologyTemplate.addGroups(groupsMap);
634 if (convertNodeTemplatesRes == null) {
635 convertNodeTemplatesRes = Either.left(nodeTemplates);
637 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
638 component.getComponentType());
639 return convertNodeTemplatesRes;
642 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
643 Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
644 String instanceUniqueId, Map<String, Object> props) {
646 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
647 if (instanceInputsList != null) {
648 instanceInputsList.forEach(input -> {
649 Supplier<String> supplier = () -> input.getValue();
650 convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
655 private void addPropertiesOfComponentInstance(
656 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
657 Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
658 Map<String, Object> props) {
660 if (!MapUtils.isEmpty(componentInstancesProperties)) {
661 componentInstancesProperties.get(instanceUniqueId).stream()
662 // Filters out properties with empty ValueUniqueUid
663 .filter(e -> e.getValue() != null && !e.getValue().isEmpty() )
664 // Collects filtered properties to List
665 .collect(Collectors.toList()).stream()
666 // Converts and adds each value to property map
667 .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
668 () -> prop.getValue()));
672 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
673 ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
675 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
676 if (!CollectionUtils.isEmpty(componentProperties)) {
677 componentProperties.stream()
678 // Filters out properties with empty default values
679 .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
680 // Collects filtered properties to List
681 .collect(Collectors.toList()).stream()
682 // Converts and adds each value to property map
683 .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
684 () -> prop.getDefaultValue()));
690 * @param componentInstance
695 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
696 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
697 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
698 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
699 props.put(prop.getName(), convertedValue);
703 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
704 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
705 log.debug("Convert property or input value {} for instance {}", input.getName(),
706 componentInstance.getUniqueId());
707 String propertyType = input.getType();
708 String innerType = null;
709 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
710 innerType = input.getSchema().getProperty().getType();
712 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
715 private ToscaGroupTemplate convertGroup(GroupDefinition group) {
716 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
717 Map<String, String> members = group.getMembers();
719 toscaGroup.setMembers(new ArrayList<String>(members.keySet()));
721 Supplier<String> supplGroupType = () -> group.getType();
722 Supplier<String> supplDescription = () -> group.getDescription();
723 Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
724 Supplier<String> supplgroupName = () -> group.getName();
725 Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
726 Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
727 Supplier<String> supplVersion = () -> group.getVersion();
729 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
730 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
731 toscaGroup.setMetadata(toscaMetadata);
735 private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
736 ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
738 Supplier<String> supplGroupType = () -> groupInstance.getType();
739 Supplier<String> supplDescription = () -> groupInstance.getDescription();
740 Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance.convertToGroupInstancesProperties();
741 Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
742 Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
743 Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
744 Supplier<String> supplVersion = () -> groupInstance.getVersion();
746 IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
747 supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
749 toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
750 toscaGroup.setMetadata(toscaMetadata);
754 private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
755 Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
756 Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
757 boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
758 toscaGroup.setType(groupType.get());
760 IToscaMetadata toscaMetadata;
762 toscaMetadata = new ToscaMetadata();
764 toscaMetadata = new VfModuleToscaMetadata();
766 Map<String, Object> properties = fillGroupProperties(props.get());
768 properties.put(VF_MODULE_DESC_KEY, description.get());
769 toscaGroup.setProperties(properties);
771 toscaMetadata.setName(groupName.get());
772 toscaMetadata.setInvariantUUID(invariantUUID.get());
773 toscaMetadata.setUUID(groupUUID.get());
774 toscaMetadata.setVersion(version.get());
775 return toscaMetadata;
778 private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
779 Map<String, Object> properties = new HashMap<>();
780 if(groupProps != null){
781 for (GroupProperty gp : groupProps) {
782 if (gp.getName().equals(Constants.IS_BASE)) {
783 Boolean isBase = Boolean.parseBoolean(gp.getValue());
784 String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
785 properties.put(VF_MODULE_TYPE_KEY, type);
788 String type = gp.getType();
792 if (gp.getValue() != null) {
793 value = Integer.valueOf(gp.getValue());
797 if (gp.getValue() != null) {
798 value = Boolean.valueOf(gp.getValue());
803 value = gp.getValue();
806 properties.put(gp.getName(), value);
813 private ToscaNodeType createNodeType(Component component) {
814 ToscaNodeType toscaNodeType = new ToscaNodeType();
815 if (ToscaUtils.isAtomicType(component)){
816 if (((Resource) component).getDerivedFrom() != null){
817 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
819 toscaNodeType.setDescription(component.getDescription()); // or name??
821 String derivedFrom = null != component.getDerivedFromGenericType()? component.getDerivedFromGenericType() : "tosca.nodes.Root";
822 toscaNodeType.setDerived_from(derivedFrom);
824 return toscaNodeType;
827 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
828 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
829 ToscaNodeTemplate nodeTypeTemplate) {
831 List<ComponentInstance> instancesList = component.getComponentInstances();
832 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
833 Map<String, List<RequirementDefinition>> reqMap = componentInstance.getRequirements();
835 relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(req -> {
836 ComponentInstance toComponentInstance = instancesList.stream()
837 .filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
838 if (toComponentInstance == null) {
839 log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(),
844 RequirementAndRelationshipPair reqAndRelationshopPair = req.getRelationships().get(0);
845 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
846 toscaRequirement.setRelationship(reqAndRelationshopPair.getRelationship().getType());
847 toscaRequirement.setNode(toComponentInstance.getName());
848 Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream())
849 .filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny();
850 if (findAny.isPresent()) {
851 RequirementDefinition regDefinition = findAny.get();
852 toscaRequirement.setCapability(regDefinition.getCapability());
854 log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(),
858 Map<String, ToscaTemplateRequirement> reqmap = new HashMap<String, ToscaTemplateRequirement>();
859 reqmap.put(reqAndRelationshopPair.getRequirement(), toscaRequirement);
860 toscaRequirements.add(reqmap);
864 if (!toscaRequirements.isEmpty()) {
865 nodeTypeTemplate.setRequirements(toscaRequirements);
867 log.debug("Finish convert Requirements for node type");
868 return Either.left(nodeTypeTemplate);
871 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map<String, DataTypeDefinition> dataTypes) {
872 Map<String, String[]> toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes);
874 if (!toscaCapabilities.isEmpty()) {
875 substitutionMapping.setCapabilities(toscaCapabilities);
877 log.debug("Finish convert Capabilities for node type");
879 return Either.left(substitutionMapping);
882 private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
883 Map<String, DataTypeDefinition> dataTypes) {
884 Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
886 if (!toscaCapabilities.isEmpty()) {
887 nodeType.setCapabilities(toscaCapabilities);
889 log.debug("Finish convert Capabilities for node type");
891 return Either.left(nodeType);
894 private static class CustomRepresenter extends Representer {
895 public CustomRepresenter() {
897 // null representer is exceptional and it is stored as an instance
899 this.nullRepresenter = new RepresentNull();
904 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
906 if (propertyValue == null) {
909 // skip not relevant for Tosca property
910 if (property.getName().equals("dependencies")) {
913 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
915 return property.getName().equals("_defaultp_")
916 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
921 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
922 // remove the bean type from the output yaml (!! ...)
923 if (!classTags.containsKey(javaBean.getClass()))
924 addClassTag(javaBean.getClass(), Tag.MAP);
926 return super.representJavaBean(properties, javaBean);
929 private class RepresentNull implements Represent {
930 public Node representData(Object data) {
931 // possible values are here http://yaml.org/type/null.html
932 return representScalar(Tag.NULL, "");
937 private static class UnsortedPropertyUtils extends PropertyUtils {
939 protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
940 throws IntrospectionException {
941 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
942 return new LinkedHashSet<Property>(fields);