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 com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
25 import fj.data.Either;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.apache.commons.lang3.tuple.ImmutableTriple;
31 import org.apache.commons.lang3.tuple.Triple;
32 import org.onap.sdc.tosca.services.YamlUtil;
33 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
34 import org.openecomp.sdc.be.config.ConfigurationManager;
35 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
36 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
37 import org.openecomp.sdc.be.datatypes.elements.*;
38 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
39 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
40 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
41 import org.openecomp.sdc.be.model.*;
42 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
43 import org.openecomp.sdc.be.model.category.CategoryDefinition;
44 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
45 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
46 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
47 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
48 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
49 import org.openecomp.sdc.be.tosca.model.*;
50 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
51 import org.openecomp.sdc.be.tosca.utils.InputConverter;
52 import org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil;
53 import org.openecomp.sdc.common.log.wrappers.Logger;
54 import org.openecomp.sdc.externalupload.utils.ServiceUtils;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.yaml.snakeyaml.DumperOptions;
57 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
58 import org.yaml.snakeyaml.Yaml;
59 import org.yaml.snakeyaml.introspector.BeanAccess;
60 import org.yaml.snakeyaml.introspector.Property;
61 import org.yaml.snakeyaml.introspector.PropertyUtils;
62 import org.yaml.snakeyaml.nodes.MappingNode;
63 import org.yaml.snakeyaml.nodes.Node;
64 import org.yaml.snakeyaml.nodes.NodeTuple;
65 import org.yaml.snakeyaml.nodes.Tag;
66 import org.yaml.snakeyaml.representer.Represent;
67 import org.yaml.snakeyaml.representer.Representer;
69 import java.beans.IntrospectionException;
71 import java.util.Map.Entry;
72 import java.util.function.Supplier;
73 import java.util.stream.Collectors;
75 import static org.apache.commons.collections.CollectionUtils.isEmpty;
76 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
77 import static org.apache.commons.collections.MapUtils.isNotEmpty;
78 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
79 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
80 import static org.openecomp.sdc.be.tosca.utils.ToscaExportUtils.addInputsToProperties;
81 import static org.openecomp.sdc.be.tosca.utils.ToscaExportUtils.getProxyNodeTypeInterfaces;
82 import static org.openecomp.sdc.be.tosca.utils.ToscaExportUtils.getProxyNodeTypeProperties;
83 import static org.openecomp.sdc.be.tosca.utils.ToscaExportUtils.resolvePropertyDefaultValueFromInput;
85 @org.springframework.stereotype.Component("tosca-export-handler")
86 public class ToscaExportHandler {
88 private ApplicationDataTypeCache dataTypeCache;
89 private ToscaOperationFacade toscaOperationFacade;
90 private CapabilityRequirementConverter capabilityRequirementConverter;
91 private PolicyExportParser policyExportParser;
92 private GroupExportParser groupExportParser;
93 private PropertyConvertor propertyConvertor;
94 private InputConverter inputConverter;
95 private InterfaceLifecycleOperation interfaceLifecycleOperation;
98 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
99 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
100 GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
101 this.dataTypeCache = dataTypeCache;
102 this.toscaOperationFacade = toscaOperationFacade;
103 this.capabilityRequirementConverter = capabilityRequirementConverter;
104 this.policyExportParser = policyExportParser;
105 this.groupExportParser = groupExportParser;
106 this.propertyConvertor = PropertyConvertor.getInstance();
107 this.inputConverter = inputConverter;
108 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
112 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
114 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
115 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
116 private static final String IMPORTS_FILE_KEY = "file";
117 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
118 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
119 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
120 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
121 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
122 .getConfigurationManager().getConfiguration().getDefaultImports();
123 private static YamlUtil yamlUtil = new YamlUtil();
125 public ToscaExportHandler(){}
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 boolean isAssociatedComponent) {
141 if (null == DEFAULT_IMPORTS) {
142 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
143 return Either.right(ToscaError.GENERAL_ERROR);
146 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
147 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
148 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
149 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
150 toscaTemplate, nodeTypes, isAssociatedComponent);
151 if (toscaTemplateRes.isRight()) {
152 return Either.right(toscaTemplateRes.right().value());
155 toscaTemplate = toscaTemplateRes.left().value();
156 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
157 return Either.left(toscaRepresentation);
160 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
161 CustomRepresenter representer = new CustomRepresenter();
162 DumperOptions options = new DumperOptions();
163 options.setAllowReadOnlyProperties(false);
164 options.setPrettyFlow(true);
166 options.setDefaultFlowStyle(FlowStyle.FLOW);
167 options.setCanonical(false);
169 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
171 representer.setPropertyUtils(new UnsortedPropertyUtils());
172 Yaml yaml = new Yaml(representer, options);
174 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
176 StringBuilder sb = new StringBuilder();
177 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
178 sb.append(yamlAsString);
179 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
181 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
182 toscaRepresentation.setMainYaml(sb.toString());
183 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
185 return toscaRepresentation;
188 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
189 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
190 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
192 if (fillImports.isRight()) {
193 return Either.right(fillImports.right().value());
195 return Either.left(fillImports.left().value().left);
198 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
199 if (null == DEFAULT_IMPORTS) {
200 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
201 return Either.right(ToscaError.GENERAL_ERROR);
204 log.trace("start tosca export for {}", component.getUniqueId());
205 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
207 toscaTemplate.setMetadata(convertMetadata(component));
208 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
209 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
210 if (ModelConverter.isAtomicComponent(component)) {
211 log.trace("convert component as node type");
212 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
214 log.trace("convert component as topology template");
215 return convertToscaTemplate(component, toscaTemplate);
220 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
222 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
224 if (importsRes.isRight()) {
225 return Either.right(importsRes.right().value());
227 toscaNode = importsRes.left().value().left;
228 Map<String, Component> componentCache = importsRes.left().value().right;
229 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache,
231 if (nodeTypesMapEither.isRight()) {
232 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
233 nodeTypesMapEither.right().value());
234 return Either.right(nodeTypesMapEither.right().value());
236 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
237 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
238 toscaNode.setNode_types(nodeTypesMap);
241 Either<Map<String, Object>, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component);
242 if (proxyInterfaceTypesEither.isRight()) {
243 log.debug("Failed to populate service proxy local interface types in tosca, error {}",
244 nodeTypesMapEither.right().value());
245 return Either.right(proxyInterfaceTypesEither.right().value());
247 Map<String, Object> proxyInterfaceTypes = proxyInterfaceTypesEither.left().value();
248 if (MapUtils.isNotEmpty(proxyInterfaceTypes)) {
249 toscaNode.setInterface_types(proxyInterfaceTypes);
252 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
253 if (dataTypesEither.isRight()) {
254 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
255 return Either.right(ToscaError.GENERAL_ERROR);
257 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
258 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
259 List<InputDefinition> inputDef = component.getInputs();
260 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
262 if (!inputs.isEmpty()) {
263 topologyTemplate.setInputs(inputs);
266 List<ComponentInstance> componentInstances = component.getComponentInstances();
267 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
268 component.getComponentInstancesProperties();
269 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
270 component.getComponentInstancesInterfaces();
271 if (componentInstances != null && !componentInstances.isEmpty()) {
273 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
274 convertNodeTemplates(component, componentInstances,
275 componentInstancesProperties, componentInstanceInterfaces,
276 componentCache, dataTypes, topologyTemplate);
277 if (nodeTemplates.isRight()) {
278 return Either.right(nodeTemplates.right().value());
280 log.debug("node templates converted");
282 topologyTemplate.setNode_templates(nodeTemplates.left().value());
286 addGroupsToTopologyTemplate(component, topologyTemplate);
289 addPoliciesToTopologyTemplate(component, topologyTemplate);
290 } catch (SdcResourceNotFoundException e) {
291 log.debug("Fail to add policies to topology template:",e);
292 return Either.right(ToscaError.GENERAL_ERROR);
296 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
297 String toscaResourceName;
298 switch (component.getComponentType()) {
300 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
301 .getMetadataDataDefinition()).getToscaResourceName();
304 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
305 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
308 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
309 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
311 substitutionMapping.setNode_type(toscaResourceName);
313 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
314 if (capabilities.isRight()) {
315 return Either.right(capabilities.right().value());
317 substitutionMapping = capabilities.left().value();
319 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
320 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
321 if (requirements.isRight()) {
322 return Either.right(requirements.right().value());
324 substitutionMapping = requirements.left().value();
326 topologyTemplate.setSubstitution_mappings(substitutionMapping);
328 toscaNode.setTopology_template(topologyTemplate);
329 return Either.left(toscaNode);
332 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
335 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
337 topologyTemplate.addGroups(groups);
341 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
342 throws SdcResourceNotFoundException {
343 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
344 if(policies!= null) {
345 topologyTemplate.addPolicies(policies);
349 private ToscaMetadata convertMetadata(Component component) {
350 return convertMetadata(component, false, null);
353 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
354 ComponentInstance componentInstance) {
355 ToscaMetadata toscaMetadata = new ToscaMetadata();
356 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
357 toscaMetadata.setUUID(component.getUUID());
358 toscaMetadata.setDescription(component.getDescription());
359 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
361 List<CategoryDefinition> categories = component.getCategories();
362 CategoryDefinition categoryDefinition = categories.get(0);
363 toscaMetadata.setCategory(categoryDefinition.getName());
366 toscaMetadata.setVersion(component.getVersion());
367 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
368 if (componentInstance.getSourceModelInvariant() != null
369 && !componentInstance.getSourceModelInvariant().isEmpty()) {
370 toscaMetadata.setVersion(componentInstance.getComponentVersion());
371 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
372 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
373 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
374 toscaMetadata.setName(
375 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
376 toscaMetadata.setDescription(componentInstance.getDescription());
380 switch (component.getComponentType()) {
382 Resource resource = (Resource) component;
384 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
385 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
387 toscaMetadata.setType(resource.getResourceType().name());
389 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
390 toscaMetadata.setResourceVendor(resource.getVendorName());
391 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
392 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
395 Service service = (Service) component;
396 toscaMetadata.setType(component.getComponentType().getValue());
397 toscaMetadata.setServiceType(service.getServiceType());
398 toscaMetadata.setServiceRole(service.getServiceRole());
399 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
400 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
403 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
404 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
405 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
409 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
411 return toscaMetadata;
414 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
415 if (service.getInstantiationType() != null) {
416 toscaMetadata.setInstantiationType(service.getInstantiationType());
419 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
423 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
424 ToscaTemplate toscaTemplate) {
426 if (null == DEFAULT_IMPORTS) {
427 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
428 return Either.right(ToscaError.GENERAL_ERROR);
430 Map<String, Component> componentCache = new HashMap<>();
432 if (!ModelConverter.isAtomicComponent(component)) {
433 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
434 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
436 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
438 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
439 if (isNotEmpty(toscaArtifacts)) {
440 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
441 if(artifactDefinition != null) {
442 Map<String, Map<String, String>> importsListMember = new HashMap<>();
443 Map<String, String> interfaceFiles = new HashMap<>();
444 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
445 StringBuilder keyNameBuilder = new StringBuilder();
446 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
447 .append(component.getName()).append("-interface");
448 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
449 additionalImports.add(importsListMember);
452 List<ComponentInstance> componentInstances = component.getComponentInstances();
453 if (componentInstances != null && !componentInstances.isEmpty()) {
454 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
456 toscaTemplate.setDependencies(dependecies);
457 toscaTemplate.setImports(additionalImports);
459 log.debug("currently imports supported for VF and service only");
461 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
464 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
465 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
466 Map<String, String> files = new HashMap<>();
467 Map<String, Map<String, String>> importsListMember = new HashMap<>();
468 StringBuilder keyNameBuilder;
470 Component componentRI = componentCache.get(ci.getComponentUid());
471 if (componentRI == null) {
472 // all resource must be only once!
473 Either<Component, StorageOperationStatus> resource = toscaOperationFacade
474 .getToscaFullElement(ci.getComponentUid());
475 if ((resource.isRight()) && (log.isDebugEnabled())) {
476 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
480 Component fetchedComponent = resource.left().value();
481 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
483 if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
484 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
485 .getToscaFullElement(ci.getSourceModelUid());
486 if (sourceService.isRight() && (log.isDebugEnabled())) {
487 log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
489 Component fetchedSource = sourceService.left().value();
490 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
493 componentRI = fetchedComponent;
495 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
496 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
497 if (artifactDefinition != null) {
498 String artifactName = artifactDefinition.getArtifactName();
499 files.put(IMPORTS_FILE_KEY, artifactName);
500 keyNameBuilder = new StringBuilder();
501 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
502 keyNameBuilder.append("-");
503 keyNameBuilder.append(ci.getComponentName());
504 importsListMember.put(keyNameBuilder.toString(), files);
505 imports.add(importsListMember);
506 dependecies.add(new ImmutableTriple<>(artifactName,
507 artifactDefinition.getEsId(), fetchedComponent));
509 if (!ModelConverter.isAtomicComponent(componentRI)) {
510 importsListMember = new HashMap<>();
511 Map<String, String> interfaceFiles = new HashMap<>();
512 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
513 keyNameBuilder.append("-interface");
514 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
515 imports.add(importsListMember);
521 public static String getInterfaceFilename(String artifactName) {
522 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
525 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
526 Map<String, ToscaNodeType> nodeTypes) {
527 return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
530 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
531 Component component, ToscaTemplate toscaNode,
532 Map<String, ToscaNodeType> nodeTypes,
533 boolean isAssociatedComponent) {
534 log.debug("start convert node type for {}", component.getUniqueId());
535 ToscaNodeType toscaNodeType = createNodeType(component);
537 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
538 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
539 if(lifecycleTypeEither.isRight()){
540 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
541 return Either.right(ToscaError.GENERAL_ERROR);
543 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
546 .map(InterfaceDataDefinition::getType)
547 .collect(Collectors.toList());
548 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
550 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
551 if (dataTypesEither.isRight()) {
552 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
553 return Either.right(ToscaError.GENERAL_ERROR);
556 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
558 List<InputDefinition> inputDef = component.getInputs();
559 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
560 addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
561 addInputsToProperties(dataTypes, inputDef, mergedProperties);
563 if(CollectionUtils.isNotEmpty(component.getProperties())) {
564 List<PropertyDefinition> properties = component.getProperties();
565 Map<String, ToscaProperty> convertedProperties = properties.stream().collect(Collectors.toMap(
566 PropertyDataDefinition::getName,
567 property -> propertyConvertor.convertProperty(dataTypes, property,
568 PropertyConvertor.PropertyType.PROPERTY)));
569 // merge component properties and inputs properties
570 mergedProperties.putAll(convertedProperties);
572 if (MapUtils.isNotEmpty(mergedProperties)) {
573 resolvePropertyDefaultValueFromInput(inputDef, mergedProperties, dataTypes);
574 toscaNodeType.setProperties(mergedProperties);
576 // Extracted to method for code reuse
577 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
580 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
581 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
582 Map<String, DataTypeDefinition> dataTypes) {
583 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
584 if (capabilities.isRight()) {
585 return Either.right(capabilities.right().value());
587 toscaNodeType = capabilities.left().value();
588 log.debug("Capabilities converted for {}", component.getUniqueId());
590 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
592 if (requirements.isRight()) {
593 return Either.right(requirements.right().value());
595 toscaNodeType = requirements.left().value();
596 log.debug("Requirements converted for {}", component.getUniqueId());
598 String toscaResourceName;
599 switch (component.getComponentType()) {
601 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
602 .getMetadataDataDefinition()).getToscaResourceName();
605 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
606 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
609 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
610 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
613 nodeTypes.put(toscaResourceName, toscaNodeType);
614 toscaNode.setNode_types(nodeTypes);
615 log.debug("finish convert node type for {}", component.getUniqueId());
616 return Either.left(toscaNode);
619 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
621 List<ComponentInstance> componentInstances,
622 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
623 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
624 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
625 ToscaTopolgyTemplate topologyTemplate) {
627 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
628 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
629 component.getComponentType());
630 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
631 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
633 Map<String, ToscaGroupTemplate> groupsMap = null;
634 for (ComponentInstance componentInstance : componentInstances) {
635 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
636 nodeTemplate.setType(componentInstance.getToscaComponentName());
637 nodeTemplate.setDirectives(componentInstance.getDirectives());
638 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
640 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
641 .getOriginComponent(componentCache, componentInstance);
642 if (originComponentRes.isRight()) {
643 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
646 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
647 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
648 originComponentRes.left().value(), componentCache);
649 if (requirements.isRight()) {
650 convertNodeTemplatesRes = Either.right(requirements.right().value());
653 String instanceUniqueId = componentInstance.getUniqueId();
654 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
656 nodeTemplate = requirements.left().value();
658 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
660 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
661 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
662 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
664 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
667 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
668 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
669 if (capabilities.isRight()) {
670 convertNodeTemplatesRes = Either.right(capabilities.right().value());
673 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
675 nodeTemplate = capabilities.left().value();
676 Map<String, Object> props = new HashMap<>();
678 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
679 // Adds the properties of parent component to map
680 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
683 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)
684 && !isComponentOfTypeServiceProxy(componentInstance)) {
685 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
686 instanceUniqueId, props);
689 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
690 && !isComponentOfTypeServiceProxy(componentInstance)) {
691 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
694 //M3[00001] - NODE TEMPLATE INTERFACES - START
695 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
696 instanceUniqueId, component);
697 //M3[00001] - NODE TEMPLATE INTERFACES - END
698 if (props != null && !props.isEmpty()) {
699 nodeTemplate.setProperties(props);
702 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
703 if (groupInstances != null) {
704 if (groupsMap == null) {
705 groupsMap = new HashMap<>();
707 for (GroupInstance groupInst : groupInstances) {
708 boolean addToTosca = true;
710 List<String> artifacts = groupInst.getArtifacts();
711 if (artifacts == null || artifacts.isEmpty()) {
716 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
717 groupsMap.put(groupInst.getName(), toscaGroup);
722 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
724 if (groupsMap != null) {
725 log.debug("instance groups added");
726 topologyTemplate.addGroups(groupsMap);
728 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
729 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
730 component.getName());
731 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
732 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
733 component.getName());
735 if (convertNodeTemplatesRes == null) {
736 convertNodeTemplatesRes = Either.left(nodeTemplates);
738 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
739 component.getComponentType());
740 return convertNodeTemplatesRes;
743 private void handleInstanceInterfaces(
744 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
745 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
746 String instanceUniqueId,
747 Component parentComponent) {
749 Map<String, Object> interfaces;
751 // we need to handle service proxy interfaces
752 if(isComponentOfTypeServiceProxy(componentInstance)) {
753 if(MapUtils.isEmpty(componentInstanceInterfaces)
754 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
757 List<ComponentInstanceInterface> currServiceInterfaces =
758 componentInstanceInterfaces.get(instanceUniqueId);
760 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
761 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
762 .getUniqueId(), instInterface));
764 interfaces = InterfacesOperationsToscaUtil
765 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
769 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
770 componentInstance, instanceUniqueId);
772 nodeTemplate.setInterfaces(interfaces);
775 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
776 return Objects.nonNull(componentInstance.getOriginType())
777 && componentInstance.getOriginType().getValue().equals("Service Proxy");
780 //M3[00001] - NODE TEMPLATE INTERFACES - START
781 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
782 ComponentInstance componentInstance,
783 String instanceUniqueId) {
784 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
788 List<ComponentInstanceInterface> componentInstanceInterfaces =
789 componentInstancesInterfaces.get(instanceUniqueId);
791 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
795 Map<String, Object> interfaces = new HashMap<>();
796 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
797 interfaces.put(componentInstanceInterface.getInterfaceId(),
798 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
801 componentInstance.setInterfaces(interfaces);
806 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
807 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
808 String instanceUniqueId, Map<String, Object> props) {
810 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
811 if (instanceInputsList != null) {
812 instanceInputsList.forEach(input -> {
814 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
815 ? input.getValue() : input.getDefaultValue();
816 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
821 private void addPropertiesOfComponentInstance(
822 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
823 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
824 Map<String, Object> props) {
826 if (isNotEmpty(componentInstancesProperties)) {
827 componentInstancesProperties.get(instanceUniqueId)
828 // Converts and adds each value to property map
829 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
834 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
835 Component componentOfInstance, Map<String, Object> props) {
837 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
838 if (isNotEmpty(componentProperties)) {
839 componentProperties.stream()
840 // Filters out properties with empty default values
841 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
842 // Converts and adds each value to property map
843 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
844 prop::getDefaultValue));
850 * @param componentInstance
855 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
856 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
857 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
858 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
859 props.put(prop.getName(), convertedValue);
863 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
864 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
865 log.debug("Convert property or input value {} for instance {}", input.getName(),
866 componentInstance.getUniqueId());
867 String propertyType = input.getType();
868 String innerType = null;
869 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
870 innerType = input.getSchema().getProperty().getType();
872 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
876 private ToscaNodeType createNodeType(Component component) {
877 ToscaNodeType toscaNodeType = new ToscaNodeType();
878 if (ModelConverter.isAtomicComponent(component)) {
879 if (((Resource) component).getDerivedFrom() != null) {
880 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
882 toscaNodeType.setDescription(component.getDescription());
884 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
885 : "tosca.nodes.Root";
886 toscaNodeType.setDerived_from(derivedFrom);
888 return toscaNodeType;
891 private Either<Map<String, Object>, ToscaError> createProxyInterfaceTypes(Component container) {
893 Map<String, Object> proxyInterfaceTypes = new HashMap<>();
894 Either<Map<String, Object>, ToscaError> res = Either.left(proxyInterfaceTypes);
895 List<ComponentInstance> componentInstances = container.getComponentInstances();
896 if (CollectionUtils.isEmpty(componentInstances)) {
899 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
900 componentInstances.stream()
901 .filter(this::isComponentOfTypeServiceProxy)
902 .forEach(inst -> serviceProxyInstanceList.put(inst.getToscaComponentName(), inst));
903 if (MapUtils.isEmpty(serviceProxyInstanceList)) {
906 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
907 Component serviceComponent;
908 ComponentParametersView componentParametersView = new ComponentParametersView();
909 componentParametersView.disableAll();
910 componentParametersView.setIgnoreInterfaces(false);
911 Either<Component, StorageOperationStatus> service = toscaOperationFacade
912 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
913 if (service.isRight()) {
914 log.debug("Failed to fetch original service component with id {} for instance {}",
915 entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
916 return Either.right(ToscaError.GENERAL_ERROR);
918 serviceComponent = service.left().value();
921 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
922 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
923 if(lifecycleTypeEither.isRight()){
924 log.debug("Failed to retrieve global interface types :", lifecycleTypeEither.right().value());
925 return Either.right(ToscaError.GENERAL_ERROR);
928 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream()
929 .map(InterfaceDataDefinition::getType)
930 .collect(Collectors.toList());
931 //Add interface types for local interfaces in the original service component for proxy
932 Map<String, Object> localInterfaceTypes = addInterfaceTypeElement(serviceComponent,
933 allGlobalInterfaceTypes);
934 if (MapUtils.isNotEmpty(localInterfaceTypes)) {
935 proxyInterfaceTypes.putAll(localInterfaceTypes);
939 return Either.left(proxyInterfaceTypes);
942 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache,
943 Component container) {
945 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
946 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
948 List<ComponentInstance> componentInstances = container.getComponentInstances();
950 if (componentInstances == null || componentInstances.isEmpty()) {
953 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
954 List<ComponentInstance> proxyInst = componentInstances.stream()
955 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
956 .collect(Collectors.toList());
957 if (proxyInst != null && !proxyInst.isEmpty()) {
958 for (ComponentInstance inst : proxyInst) {
959 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
963 if (serviceProxyInstanceList.isEmpty()) {
966 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
967 .getLatestByName("serviceProxy");
968 if (serviceProxyOrigin.isRight()) {
969 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
970 serviceProxyOrigin.right().value());
971 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
973 Component origComponent = serviceProxyOrigin.left().value();
975 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
976 Component serviceComponent = null;
977 ComponentParametersView componentParametersView = new ComponentParametersView();
978 componentParametersView.disableAll();
979 componentParametersView.setIgnoreCategories(false);
980 componentParametersView.setIgnoreProperties(false);
981 componentParametersView.setIgnoreInputs(false);
982 componentParametersView.setIgnoreInterfaces(false);
983 componentParametersView.setIgnoreRequirements(false);
984 Either<Component, StorageOperationStatus> service = toscaOperationFacade
985 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
986 if (service.isRight()) {
987 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
989 serviceComponent = service.left().value();
992 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache, origComponent, serviceComponent,
993 entryProxy.getValue());
994 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
997 return Either.left(nodeTypesMap);
1000 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent,
1001 Component proxyComponent, ComponentInstance instance) {
1002 ToscaNodeType toscaNodeType = new ToscaNodeType();
1003 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1005 toscaNodeType.setDerived_from(derivedFrom);
1006 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
1007 if (dataTypesEither.isRight()) {
1008 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1010 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1011 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1012 .convertProxyCapabilities(componentCache, instance, dataTypes);
1014 if (MapUtils.isNotEmpty(capabilities)) {
1015 toscaNodeType.setCapabilities(capabilities);
1017 List<Map<String, ToscaRequirement>> proxyNodeTypeRequirements = this.capabilityRequirementConverter
1018 .convertProxyRequirements(componentCache, instance);
1019 if (CollectionUtils.isNotEmpty(proxyNodeTypeRequirements)) {
1020 toscaNodeType.setRequirements(proxyNodeTypeRequirements);
1022 Optional<Map<String, ToscaProperty>> proxyProperties = getProxyNodeTypeProperties(proxyComponent, dataTypes);
1023 proxyProperties.ifPresent(toscaNodeType::setProperties);
1025 Optional<Map<String, Object>> proxyInterfaces = getProxyNodeTypeInterfaces(proxyComponent, dataTypes);
1026 proxyInterfaces.ifPresent(toscaNodeType::setInterfaces);
1028 return toscaNodeType;
1031 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1032 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
1033 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
1035 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1036 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
1037 log.debug("Failed to convert component instance requirements for the component instance {}. ",
1038 componentInstance.getName());
1039 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1041 if (!toscaRequirements.isEmpty()) {
1042 nodeTypeTemplate.setRequirements(toscaRequirements);
1044 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1045 return Either.left(nodeTypeTemplate);
1048 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1049 List<RequirementCapabilityRelDef> relations, Component originComponent,
1050 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1051 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1052 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1053 return isEmpty(filteredRelations) ||
1054 filteredRelations.stream()
1055 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1058 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1059 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1060 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1062 boolean result = true;
1063 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1064 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1065 Either<Component, StorageOperationStatus> getOriginRes = null;
1066 Optional<RequirementDefinition> reqOpt = Optional.empty();
1067 Component toOriginComponent = null;
1068 Optional<CapabilityDefinition> capOpt = Optional.empty();
1070 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1071 .findFirst().orElse(null);
1072 if (toInstance == null) {
1073 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1078 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1079 if (!reqOpt.isPresent()) {
1080 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1081 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1086 ComponentParametersView filter = new ComponentParametersView(true);
1087 filter.setIgnoreComponentInstances(false);
1088 filter.setIgnoreCapabilities(false);
1089 filter.setIgnoreGroups(false);
1090 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1091 if (getOriginRes.isRight()) {
1092 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1093 reqOpt.get().getName(), toInstance.getActualComponentUid());
1098 toOriginComponent = getOriginRes.left().value();
1099 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1100 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1101 if (!capOpt.isPresent()) {
1102 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1103 if(!capOpt.isPresent()){
1105 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1106 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1111 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1112 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1117 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1118 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1121 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1122 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1123 if (!cap.isPresent()) {
1124 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1129 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1130 List<String> reducedPath = capability.getPath();
1131 if(capability.getOwnerId() !=null){
1132 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1134 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1135 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1136 if (buildCapNameRes.isRight()) {
1138 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1139 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1142 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1143 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1144 if (buildReqNameRes.isRight()) {
1146 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1147 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1150 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1151 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1152 toscaRequirement.setNode(toInstance.getName());
1153 toscaRequirement.setCapability(buildCapNameRes.left().value());
1154 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1155 toscaRequirements.add(toscaReqMap);
1159 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1160 for(List<RequirementDefinition> reqList: reqMap.values()){
1161 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1162 if(reqOpt.isPresent()){
1166 return Optional.empty();
1170 * Allows detecting the requirement belonging to the received relationship
1171 * The detection logic is: A requirement belongs to a relationship IF 1.The
1172 * name of the requirement equals to the "requirement" field of the
1173 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1174 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1175 * toInstance equals to capabilityOwnerId of the relation
1177 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1178 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1179 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1180 requirement.getName(), reqAndRelationshipPair.getRequirement());
1183 return ModelConverter.isAtomicComponent(originComponent) ||
1184 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1187 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1188 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId())
1189 || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())
1190 || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId()));
1193 private boolean isCvfc(Component component) {
1194 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1195 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1198 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1199 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1201 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1202 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1203 .convertSubstitutionMappingCapabilities(componentCache, component);
1204 if (toscaCapabilitiesRes.isRight()) {
1205 result = Either.right(toscaCapabilitiesRes.right().value());
1206 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1207 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1208 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1209 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1211 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1215 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1216 Map<String, DataTypeDefinition> dataTypes) {
1217 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1219 if (!toscaCapabilities.isEmpty()) {
1220 nodeType.setCapabilities(toscaCapabilities);
1222 log.debug("Finish convert Capabilities for node type");
1224 return Either.left(nodeType);
1228 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1229 if (inNodeFilter == null){
1232 NodeFilter nodeFilter = new NodeFilter();
1234 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1235 inNodeFilter.getCapabilities();
1237 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1239 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1240 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1242 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1243 copyNodeFilterProperties(origProperties, propertiesCopy);
1245 if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1246 nodeFilter.setCapabilities(capabilitiesCopy);
1249 if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1250 nodeFilter.setProperties(propertiesCopy);
1253 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1256 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1261 private Object cloneToscaId(Object toscaId) {
1262 return Objects.isNull(toscaId) ? null
1263 : cloneObjectFromYml(toscaId, toscaId.getClass());
1267 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1268 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1269 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1271 private void copyNodeFilterCapabilitiesTemplate(
1272 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1273 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1274 if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1275 origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1278 for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1279 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1280 CapabilityFilter capabilityFilter = new CapabilityFilter();
1281 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1282 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1283 capabilityFilter.setProperties(propertiesCopy);
1284 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1285 capabilitiesCopy.add(capabilityFilterCopyMap);
1289 private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1290 String listAsString = yamlUtil.objectToYaml(propertyList);
1291 return yamlUtil.yamlToObject(listAsString, List.class);
1295 private void copyNodeFilterProperties(
1296 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1297 List<Map<String, List<Object>>> propertiesCopy) {
1298 if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1299 origProperties.isEmpty()) {
1302 for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1303 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1304 for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1305 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1306 if (propertyMapCopy.containsKey(propertyDataDefinition.getName())){
1307 propertyMapCopy.get(propertyDataDefinition.getName()).add(propertyValObj);
1309 if (propertyDataDefinition.getName() != null) {
1310 List propsList =new ArrayList();
1311 propsList.add(propertyValObj);
1312 propertyMapCopy.put(propertyDataDefinition.getName(), propsList);
1314 propertyMapCopy.putAll(propertyValObj);
1318 propertiesCopy.add(propertyMapCopy);
1323 private static class CustomRepresenter extends Representer {
1324 public CustomRepresenter() {
1326 // null representer is exceptional and it is stored as an instance
1328 this.nullRepresenter = new RepresentNull();
1333 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1335 if (propertyValue == null) {
1338 // skip not relevant for Tosca property
1339 if ("dependencies".equals(property.getName())) {
1342 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1344 return "_defaultp_".equals(property.getName())
1345 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1350 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1351 // remove the bean type from the output yaml (!! ...)
1352 if (!classTags.containsKey(javaBean.getClass())) {
1353 addClassTag(javaBean.getClass(), Tag.MAP);
1356 return super.representJavaBean(properties, javaBean);
1359 private class RepresentNull implements Represent {
1361 public Node representData(Object data) {
1362 // possible values are here http://yaml.org/type/null.html
1363 return representScalar(Tag.NULL, "");
1368 private static class UnsortedPropertyUtils extends PropertyUtils {
1370 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1371 throws IntrospectionException {
1372 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1373 return new LinkedHashSet<>(fields);
1377 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1378 ObjectMapper objectMapper = new ObjectMapper();
1379 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1381 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1382 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1383 interfaceAsMap.remove("empty");
1385 if(MapUtils.isNotEmpty(operations)) {
1386 interfaceAsMap.putAll(operations);
1389 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1391 return interfaceObject;