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.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
33 import org.openecomp.sdc.be.config.ConfigurationManager;
34 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
35 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
36 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
37 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
38 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
39 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
40 import org.openecomp.sdc.be.model.*;
41 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
42 import org.openecomp.sdc.be.model.category.CategoryDefinition;
43 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
44 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
47 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
48 import org.openecomp.sdc.be.tosca.model.*;
49 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
50 import org.openecomp.sdc.be.tosca.utils.InputConverter;
51 import org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil;
52 import org.openecomp.sdc.common.log.wrappers.Logger;
53 import org.openecomp.sdc.externalupload.utils.ServiceUtils;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.yaml.snakeyaml.DumperOptions;
56 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
57 import org.yaml.snakeyaml.Yaml;
58 import org.yaml.snakeyaml.introspector.BeanAccess;
59 import org.yaml.snakeyaml.introspector.Property;
60 import org.yaml.snakeyaml.introspector.PropertyUtils;
61 import org.yaml.snakeyaml.nodes.MappingNode;
62 import org.yaml.snakeyaml.nodes.Node;
63 import org.yaml.snakeyaml.nodes.NodeTuple;
64 import org.yaml.snakeyaml.nodes.Tag;
65 import org.yaml.snakeyaml.representer.Represent;
66 import org.yaml.snakeyaml.representer.Representer;
68 import java.beans.IntrospectionException;
70 import java.util.Map.Entry;
71 import java.util.function.Supplier;
72 import java.util.stream.Collectors;
74 import static org.apache.commons.collections.CollectionUtils.isEmpty;
75 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
76 import static org.apache.commons.collections.MapUtils.isNotEmpty;
77 import static org.apache.commons.lang.StringUtils.isNotEmpty;
78 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
79 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
81 @org.springframework.stereotype.Component("tosca-export-handler")
82 public class ToscaExportHandler {
84 private ApplicationDataTypeCache dataTypeCache;
85 private ToscaOperationFacade toscaOperationFacade;
86 private CapabilityRequirementConverter capabilityRequirementConverter;
87 private PolicyExportParser policyExportParser;
88 private GroupExportParser groupExportParser;
89 private PropertyConvertor propertyConvertor;
90 private InputConverter inputConverter;
91 private InterfaceLifecycleOperation interfaceLifecycleOperation;
94 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
95 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
96 GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
97 this.dataTypeCache = dataTypeCache;
98 this.toscaOperationFacade = toscaOperationFacade;
99 this.capabilityRequirementConverter = capabilityRequirementConverter;
100 this.policyExportParser = policyExportParser;
101 this.groupExportParser = groupExportParser;
102 this.propertyConvertor = PropertyConvertor.getInstance();
103 this.inputConverter = inputConverter;
104 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
108 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
110 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
111 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
112 private static final String IMPORTS_FILE_KEY = "file";
113 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
114 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
115 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
116 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
117 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
118 .getConfigurationManager().getConfiguration().getDefaultImports();
120 public ToscaExportHandler(){}
122 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
124 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
125 if (toscaTemplateRes.isRight()) {
126 return Either.right(toscaTemplateRes.right().value());
129 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
130 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
131 return Either.left(toscaRepresentation);
134 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
135 boolean isAssociatedResourceComponent) {
136 if (null == DEFAULT_IMPORTS) {
137 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
138 return Either.right(ToscaError.GENERAL_ERROR);
141 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
142 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
143 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
144 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
145 toscaTemplate, nodeTypes, isAssociatedResourceComponent);
146 if (toscaTemplateRes.isRight()) {
147 return Either.right(toscaTemplateRes.right().value());
150 toscaTemplate = toscaTemplateRes.left().value();
151 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
152 return Either.left(toscaRepresentation);
155 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
156 CustomRepresenter representer = new CustomRepresenter();
157 DumperOptions options = new DumperOptions();
158 options.setAllowReadOnlyProperties(false);
159 options.setPrettyFlow(true);
161 options.setDefaultFlowStyle(FlowStyle.FLOW);
162 options.setCanonical(false);
164 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
166 representer.setPropertyUtils(new UnsortedPropertyUtils());
167 Yaml yaml = new Yaml(representer, options);
169 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
171 StringBuilder sb = new StringBuilder();
172 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
173 sb.append(yamlAsString);
174 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
176 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
177 toscaRepresentation.setMainYaml(sb.toString());
178 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
180 return toscaRepresentation;
183 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
184 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
185 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
187 if (fillImports.isRight()) {
188 return Either.right(fillImports.right().value());
190 return Either.left(fillImports.left().value().left);
193 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
194 if (null == DEFAULT_IMPORTS) {
195 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
196 return Either.right(ToscaError.GENERAL_ERROR);
199 log.trace("start tosca export for {}", component.getUniqueId());
200 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
202 toscaTemplate.setMetadata(convertMetadata(component));
203 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
204 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
205 if (ModelConverter.isAtomicComponent(component)) {
206 log.trace("convert component as node type");
207 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
209 log.trace("convert component as topology template");
210 return convertToscaTemplate(component, toscaTemplate);
215 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
217 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
219 if (importsRes.isRight()) {
220 return Either.right(importsRes.right().value());
222 toscaNode = importsRes.left().value().left;
223 Map<String, Component> componentCache = importsRes.left().value().right;
224 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
225 if (nodeTypesMapEither.isRight()) {
226 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
227 nodeTypesMapEither.right().value());
228 return Either.right(nodeTypesMapEither.right().value());
230 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
231 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
232 toscaNode.setNode_types(nodeTypesMap);
236 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
237 if (dataTypesEither.isRight()) {
238 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
239 return Either.right(ToscaError.GENERAL_ERROR);
241 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
242 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
243 List<InputDefinition> inputDef = component.getInputs();
244 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
246 if (!inputs.isEmpty()) {
247 topologyTemplate.setInputs(inputs);
250 List<ComponentInstance> componentInstances = component.getComponentInstances();
251 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
252 component.getComponentInstancesProperties();
253 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
254 component.getComponentInstancesInterfaces();
255 if (componentInstances != null && !componentInstances.isEmpty()) {
257 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
258 convertNodeTemplates(component, componentInstances,
259 componentInstancesProperties, componentInstanceInterfaces,
260 componentCache, dataTypes, topologyTemplate);
261 if (nodeTemplates.isRight()) {
262 return Either.right(nodeTemplates.right().value());
264 log.debug("node templates converted");
266 topologyTemplate.setNode_templates(nodeTemplates.left().value());
270 addGroupsToTopologyTemplate(component, topologyTemplate);
273 addPoliciesToTopologyTemplate(component, topologyTemplate);
274 } catch (SdcResourceNotFoundException e) {
275 log.debug("Fail to add policies to topology template:",e);
276 return Either.right(ToscaError.GENERAL_ERROR);
280 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
281 String toscaResourceName;
282 switch (component.getComponentType()) {
284 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
285 .getMetadataDataDefinition()).getToscaResourceName();
288 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
289 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
292 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
293 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
295 substitutionMapping.setNode_type(toscaResourceName);
297 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
298 if (capabilities.isRight()) {
299 return Either.right(capabilities.right().value());
301 substitutionMapping = capabilities.left().value();
303 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
304 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
305 if (requirements.isRight()) {
306 return Either.right(requirements.right().value());
308 substitutionMapping = requirements.left().value();
310 topologyTemplate.setSubstitution_mappings(substitutionMapping);
312 toscaNode.setTopology_template(topologyTemplate);
313 return Either.left(toscaNode);
316 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
319 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
321 topologyTemplate.addGroups(groups);
325 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
326 throws SdcResourceNotFoundException {
327 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
328 if(policies!= null) {
329 topologyTemplate.addPolicies(policies);
333 private ToscaMetadata convertMetadata(Component component) {
334 return convertMetadata(component, false, null);
337 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
338 ComponentInstance componentInstance) {
339 ToscaMetadata toscaMetadata = new ToscaMetadata();
340 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
341 toscaMetadata.setUUID(component.getUUID());
342 toscaMetadata.setDescription(component.getDescription());
343 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
345 List<CategoryDefinition> categories = component.getCategories();
346 CategoryDefinition categoryDefinition = categories.get(0);
347 toscaMetadata.setCategory(categoryDefinition.getName());
350 toscaMetadata.setVersion(component.getVersion());
351 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
352 if (componentInstance.getSourceModelInvariant() != null
353 && !componentInstance.getSourceModelInvariant().isEmpty()) {
354 toscaMetadata.setVersion(componentInstance.getComponentVersion());
355 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
356 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
357 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
358 toscaMetadata.setName(
359 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
360 toscaMetadata.setDescription(componentInstance.getDescription());
364 switch (component.getComponentType()) {
366 Resource resource = (Resource) component;
368 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
369 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
371 toscaMetadata.setType(resource.getResourceType().name());
373 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
374 toscaMetadata.setResourceVendor(resource.getVendorName());
375 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
376 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
379 Service service = (Service) component;
380 toscaMetadata.setType(component.getComponentType().getValue());
381 toscaMetadata.setServiceType(service.getServiceType());
382 toscaMetadata.setServiceRole(service.getServiceRole());
383 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
384 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
387 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
388 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
389 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
393 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
395 return toscaMetadata;
398 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
399 if (service.getInstantiationType() != null) {
400 toscaMetadata.setInstantiationType(service.getInstantiationType());
403 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
407 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
408 ToscaTemplate toscaTemplate) {
410 if (null == DEFAULT_IMPORTS) {
411 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
412 return Either.right(ToscaError.GENERAL_ERROR);
414 Map<String, Component> componentCache = new HashMap<>();
416 if (!ModelConverter.isAtomicComponent(component)) {
417 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
418 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
420 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
422 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
423 if (isNotEmpty(toscaArtifacts)) {
424 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
425 if(artifactDefinition != null) {
426 Map<String, Map<String, String>> importsListMember = new HashMap<>();
427 Map<String, String> interfaceFiles = new HashMap<>();
428 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
429 StringBuilder keyNameBuilder = new StringBuilder();
430 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
431 .append(component.getName()).append("-interface");
432 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
433 additionalImports.add(importsListMember);
436 List<ComponentInstance> componentInstances = component.getComponentInstances();
437 if (componentInstances != null && !componentInstances.isEmpty()) {
438 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
440 toscaTemplate.setDependencies(dependecies);
441 toscaTemplate.setImports(additionalImports);
443 log.debug("currently imports supported for VF and service only");
445 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
448 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
449 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
450 Map<String, String> files = new HashMap<>();
451 Map<String, Map<String, String>> importsListMember = new HashMap<>();
452 StringBuilder keyNameBuilder;
454 Component componentRI = componentCache.get(ci.getComponentUid());
455 if (componentRI == null) {
456 // all resource must be only once!
457 Either<Component, StorageOperationStatus> resource = toscaOperationFacade
458 .getToscaFullElement(ci.getComponentUid());
459 if ((resource.isRight()) && (log.isDebugEnabled())) {
460 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
464 Component fetchedComponent = resource.left().value();
465 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
467 if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
468 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
469 .getToscaFullElement(ci.getSourceModelUid());
470 if (sourceService.isRight() && (log.isDebugEnabled())) {
471 log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
473 Component fetchedSource = sourceService.left().value();
474 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
477 componentRI = fetchedComponent;
479 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
480 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
481 if (artifactDefinition != null) {
482 String artifactName = artifactDefinition.getArtifactName();
483 files.put(IMPORTS_FILE_KEY, artifactName);
484 keyNameBuilder = new StringBuilder();
485 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
486 keyNameBuilder.append("-");
487 keyNameBuilder.append(ci.getComponentName());
488 importsListMember.put(keyNameBuilder.toString(), files);
489 imports.add(importsListMember);
490 dependecies.add(new ImmutableTriple<>(artifactName,
491 artifactDefinition.getEsId(), fetchedComponent));
493 if (!ModelConverter.isAtomicComponent(componentRI)) {
494 importsListMember = new HashMap<>();
495 Map<String, String> interfaceFiles = new HashMap<>();
496 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
497 keyNameBuilder.append("-interface");
498 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
499 imports.add(importsListMember);
505 public static String getInterfaceFilename(String artifactName) {
506 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
509 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
510 Map<String, ToscaNodeType> nodeTypes) {
511 log.debug("start convert node type for {}", component.getUniqueId());
512 ToscaNodeType toscaNodeType = createNodeType(component);
514 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
515 if (dataTypesEither.isRight()) {
516 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
517 return Either.right(ToscaError.GENERAL_ERROR);
520 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
521 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
523 if (properties.isRight()) {
524 return Either.right(properties.right().value());
526 toscaNodeType = properties.left().value();
527 log.debug("Properties converted for {}", component.getUniqueId());
529 // Extracted to method for code reuse
530 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
533 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
534 Component component, ToscaTemplate toscaNode,
535 Map<String, ToscaNodeType> nodeTypes,
536 boolean isAssociatedResourceComponent) {
537 log.debug("start convert node type for {}", component.getUniqueId());
538 ToscaNodeType toscaNodeType = createNodeType(component);
540 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
541 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
542 if(lifecycleTypeEither.isRight()){
543 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
544 return Either.right(ToscaError.GENERAL_ERROR);
546 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
549 .map(interfaceDef -> interfaceDef.getType())
550 .collect(Collectors.toList());
551 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
553 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
554 if (dataTypesEither.isRight()) {
555 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
556 return Either.right(ToscaError.GENERAL_ERROR);
559 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
561 List<InputDefinition> inputDef = component.getInputs();
562 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
563 addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedResourceComponent);
564 if (inputDef != null) {
565 addInputsToProperties(dataTypes, inputDef, mergedProperties);
568 if(CollectionUtils.isNotEmpty(component.getProperties())) {
569 List<PropertyDefinition> properties = component.getProperties();
570 mergedProperties = properties.stream().collect(Collectors.toMap(
571 PropertyDataDefinition::getName,
572 property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY)));
574 if (!mergedProperties.isEmpty()) {
575 toscaNodeType.setProperties(mergedProperties);
577 // Extracted to method for code reuse
578 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
581 private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
582 List<InputDefinition> inputDef,
583 Map<String, ToscaProperty> mergedProperties) {
584 for(InputDefinition input : inputDef) {
585 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
586 mergedProperties.put(input.getName(), property);
591 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
592 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
593 Map<String, DataTypeDefinition> dataTypes) {
594 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
595 if (capabilities.isRight()) {
596 return Either.right(capabilities.right().value());
598 toscaNodeType = capabilities.left().value();
599 log.debug("Capabilities converted for {}", component.getUniqueId());
601 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
603 if (requirements.isRight()) {
604 return Either.right(requirements.right().value());
606 toscaNodeType = requirements.left().value();
607 log.debug("Requirements converted for {}", component.getUniqueId());
609 String toscaResourceName;
610 switch (component.getComponentType()) {
612 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
613 .getMetadataDataDefinition()).getToscaResourceName();
616 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
617 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
620 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
621 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
624 nodeTypes.put(toscaResourceName, toscaNodeType);
625 toscaNode.setNode_types(nodeTypes);
626 log.debug("finish convert node type for {}", component.getUniqueId());
627 return Either.left(toscaNode);
630 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
632 List<ComponentInstance> componentInstances,
633 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
634 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
635 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
636 ToscaTopolgyTemplate topologyTemplate) {
638 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
639 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
640 component.getComponentType());
641 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
642 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
644 Map<String, ToscaGroupTemplate> groupsMap = null;
645 for (ComponentInstance componentInstance : componentInstances) {
646 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
647 nodeTemplate.setType(componentInstance.getToscaComponentName());
649 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
650 .getOriginComponent(componentCache, componentInstance);
651 if (originComponentRes.isRight()) {
652 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
655 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
656 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
657 originComponentRes.left().value(), componentCache);
658 if (requirements.isRight()) {
659 convertNodeTemplatesRes = Either.right(requirements.right().value());
662 String instanceUniqueId = componentInstance.getUniqueId();
663 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
665 nodeTemplate = requirements.left().value();
667 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
669 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
670 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
671 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
673 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
676 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
677 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
678 if (capabilities.isRight()) {
679 convertNodeTemplatesRes = Either.right(capabilities.right().value());
682 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
684 nodeTemplate = capabilities.left().value();
685 Map<String, Object> props = new HashMap<>();
687 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
688 // Adds the properties of parent component to map
689 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
692 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
693 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
694 instanceUniqueId, props);
697 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
698 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
701 //M3[00001] - NODE TEMPLATE INTERFACES - START
702 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
703 instanceUniqueId, component);
704 //M3[00001] - NODE TEMPLATE INTERFACES - END
705 if (props != null && !props.isEmpty()) {
706 nodeTemplate.setProperties(props);
709 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
710 if (groupInstances != null) {
711 if (groupsMap == null) {
712 groupsMap = new HashMap<>();
714 for (GroupInstance groupInst : groupInstances) {
715 boolean addToTosca = true;
717 List<String> artifacts = groupInst.getArtifacts();
718 if (artifacts == null || artifacts.isEmpty()) {
723 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
724 groupsMap.put(groupInst.getName(), toscaGroup);
729 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
731 if (groupsMap != null) {
732 log.debug("instance groups added");
733 topologyTemplate.addGroups(groupsMap);
735 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
736 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
737 component.getName());
738 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
739 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
740 component.getName());
742 if (convertNodeTemplatesRes == null) {
743 convertNodeTemplatesRes = Either.left(nodeTemplates);
745 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
746 component.getComponentType());
747 return convertNodeTemplatesRes;
750 private void handleInstanceInterfaces(
751 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
752 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
753 String instanceUniqueId,
754 Component parentComponent) {
756 Map<String, Object> interfaces;
758 // we need to handle service proxy interfaces
759 if(isComponentOfTypeServiceProxy(componentInstance)) {
760 if(MapUtils.isEmpty(componentInstanceInterfaces)
761 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
764 List<ComponentInstanceInterface> currServiceInterfaces =
765 componentInstanceInterfaces.get(instanceUniqueId);
767 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
768 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
769 .getUniqueId(), instInterface));
771 interfaces = InterfacesOperationsToscaUtil
772 .getInterfacesMap(parentComponent, tmpInterfaces, dataTypes, true, true);
776 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
777 componentInstance, instanceUniqueId);
779 nodeTemplate.setInterfaces(interfaces);
782 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
783 return Objects.nonNull(componentInstance.getOriginType())
784 && componentInstance.getOriginType().getValue().equals("Service Proxy");
787 //M3[00001] - NODE TEMPLATE INTERFACES - START
788 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
789 ComponentInstance componentInstance,
790 String instanceUniqueId) {
791 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
795 List<ComponentInstanceInterface> componentInstanceInterfaces =
796 componentInstancesInterfaces.get(instanceUniqueId);
798 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
802 Map<String, Object> interfaces = new HashMap<>();
803 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
804 interfaces.put(componentInstanceInterface.getInterfaceId(),
805 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
808 componentInstance.setInterfaces(interfaces);
812 //M3[00001] - NODE TEMPLATE INTERFACES - END
814 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
815 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
816 String instanceUniqueId, Map<String, Object> props) {
818 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
819 if (instanceInputsList != null) {
820 instanceInputsList.forEach(input -> {
822 Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
823 ? input.getValue() : input.getDefaultValue();
824 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
829 private void addPropertiesOfComponentInstance(
830 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
831 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
832 Map<String, Object> props) {
834 if (isNotEmpty(componentInstancesProperties)) {
835 componentInstancesProperties.get(instanceUniqueId)
836 // Converts and adds each value to property map
837 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
842 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
843 Component componentOfInstance, Map<String, Object> props) {
845 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
846 if (isNotEmpty(componentProperties)) {
847 componentProperties.stream()
848 // Filters out properties with empty default values
849 .filter(prop -> isNotEmpty(prop.getDefaultValue()))
850 // Converts and adds each value to property map
851 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
852 prop::getDefaultValue));
858 * @param componentInstance
863 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
864 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
865 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
866 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
867 props.put(prop.getName(), convertedValue);
871 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
872 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
873 log.debug("Convert property or input value {} for instance {}", input.getName(),
874 componentInstance.getUniqueId());
875 String propertyType = input.getType();
876 String innerType = null;
877 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
878 innerType = input.getSchema().getProperty().getType();
880 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
884 private ToscaNodeType createNodeType(Component component) {
885 ToscaNodeType toscaNodeType = new ToscaNodeType();
886 if (ModelConverter.isAtomicComponent(component)) {
887 if (((Resource) component).getDerivedFrom() != null) {
888 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
890 toscaNodeType.setDescription(component.getDescription());
892 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
893 : "tosca.nodes.Root";
894 toscaNodeType.setDerived_from(derivedFrom);
896 return toscaNodeType;
899 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
901 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
902 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
904 List<ComponentInstance> componentInstances = container.getComponentInstances();
906 if (componentInstances == null || componentInstances.isEmpty()) {
909 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
910 List<ComponentInstance> proxyInst = componentInstances.stream()
911 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
912 .collect(Collectors.toList());
913 if (proxyInst != null && !proxyInst.isEmpty()) {
914 for (ComponentInstance inst : proxyInst) {
915 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
919 if (serviceProxyInstanceList.isEmpty()) {
922 ComponentParametersView filter = new ComponentParametersView(true);
923 filter.setIgnoreCapabilities(false);
924 filter.setIgnoreComponentInstances(false);
925 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
926 .getLatestByName("serviceProxy");
927 if (serviceProxyOrigin.isRight()) {
928 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
929 serviceProxyOrigin.right().value());
930 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
932 Component origComponent = serviceProxyOrigin.left().value();
934 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
935 Component serviceComponent = null;
936 ComponentParametersView componentParametersView = new ComponentParametersView();
937 componentParametersView.disableAll();
938 componentParametersView.setIgnoreCategories(false);
939 Either<Component, StorageOperationStatus> service = toscaOperationFacade
940 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
941 if (service.isRight()) {
942 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
944 serviceComponent = service.left().value();
947 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
948 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
951 return Either.left(nodeTypesMap);
954 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
955 ComponentInstance instance) {
956 ToscaNodeType toscaNodeType = new ToscaNodeType();
957 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
959 toscaNodeType.setDerived_from(derivedFrom);
960 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
961 if (dataTypesEither.isRight()) {
962 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
964 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
965 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
966 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
968 toscaNodeType.setCapabilities(capabilities);
970 return toscaNodeType;
973 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
974 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
975 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
977 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
978 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
979 log.debug("Failed to convert component instance requirements for the component instance {}. ",
980 componentInstance.getName());
981 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
983 if (!toscaRequirements.isEmpty()) {
984 nodeTypeTemplate.setRequirements(toscaRequirements);
986 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
987 return Either.left(nodeTypeTemplate);
990 private boolean addRequirements(Component component, ComponentInstance componentInstance,
991 List<RequirementCapabilityRelDef> relations, Component originComponent,
992 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
993 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
994 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
995 return isEmpty(filteredRelations) ||
996 filteredRelations.stream()
997 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1000 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1001 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1002 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1004 boolean result = true;
1005 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1006 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1007 Either<Component, StorageOperationStatus> getOriginRes = null;
1008 Optional<RequirementDefinition> reqOpt = Optional.empty();
1009 Component toOriginComponent = null;
1010 Optional<CapabilityDefinition> capOpt = Optional.empty();
1012 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1013 .findFirst().orElse(null);
1014 if (toInstance == null) {
1015 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1020 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1021 if (!reqOpt.isPresent()) {
1022 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1023 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1028 ComponentParametersView filter = new ComponentParametersView(true);
1029 filter.setIgnoreComponentInstances(false);
1030 filter.setIgnoreCapabilities(false);
1031 filter.setIgnoreGroups(false);
1032 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1033 if (getOriginRes.isRight()) {
1034 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1035 reqOpt.get().getName(), toInstance.getActualComponentUid());
1040 toOriginComponent = getOriginRes.left().value();
1041 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1042 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1043 if (!capOpt.isPresent()) {
1044 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1045 if(!capOpt.isPresent()){
1047 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1048 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1053 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1054 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1059 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1060 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1063 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1064 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1065 if (!cap.isPresent()) {
1066 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1071 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1072 List<String> reducedPath = capability.getPath();
1073 if(capability.getOwnerId() !=null){
1074 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1076 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1077 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1078 if (buildCapNameRes.isRight()) {
1080 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1081 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1084 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1085 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1086 if (buildReqNameRes.isRight()) {
1088 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1089 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1092 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1093 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1094 toscaRequirement.setNode(toInstance.getName());
1095 toscaRequirement.setCapability(buildCapNameRes.left().value());
1096 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1097 toscaRequirements.add(toscaReqMap);
1101 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1102 for(List<RequirementDefinition> reqList: reqMap.values()){
1103 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1104 if(reqOpt.isPresent()){
1108 return Optional.empty();
1112 * Allows detecting the requirement belonging to the received relationship
1113 * The detection logic is: A requirement belongs to a relationship IF 1.The
1114 * name of the requirement equals to the "requirement" field of the
1115 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1116 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1117 * toInstance equals to capabilityOwnerId of the relation
1119 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1120 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1121 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1122 requirement.getName(), reqAndRelationshipPair.getRequirement());
1125 return ModelConverter.isAtomicComponent(originComponent) ||
1126 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1129 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1130 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1133 private boolean isCvfc(Component component) {
1134 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1135 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1138 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1139 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1141 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1142 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1143 .convertSubstitutionMappingCapabilities(componentCache, component);
1144 if (toscaCapabilitiesRes.isRight()) {
1145 result = Either.right(toscaCapabilitiesRes.right().value());
1146 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1147 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1148 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1149 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1151 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1155 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1156 Map<String, DataTypeDefinition> dataTypes) {
1157 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1159 if (!toscaCapabilities.isEmpty()) {
1160 nodeType.setCapabilities(toscaCapabilities);
1162 log.debug("Finish convert Capabilities for node type");
1164 return Either.left(nodeType);
1167 private static class CustomRepresenter extends Representer {
1168 public CustomRepresenter() {
1170 // null representer is exceptional and it is stored as an instance
1172 this.nullRepresenter = new RepresentNull();
1177 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1179 if (propertyValue == null) {
1182 // skip not relevant for Tosca property
1183 if ("dependencies".equals(property.getName())) {
1186 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1188 return "_defaultp_".equals(property.getName())
1189 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1194 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1195 // remove the bean type from the output yaml (!! ...)
1196 if (!classTags.containsKey(javaBean.getClass())) {
1197 addClassTag(javaBean.getClass(), Tag.MAP);
1200 return super.representJavaBean(properties, javaBean);
1203 private class RepresentNull implements Represent {
1205 public Node representData(Object data) {
1206 // possible values are here http://yaml.org/type/null.html
1207 return representScalar(Tag.NULL, "");
1212 private static class UnsortedPropertyUtils extends PropertyUtils {
1214 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1215 throws IntrospectionException {
1216 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1217 return new LinkedHashSet<>(fields);
1221 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1222 ObjectMapper objectMapper = new ObjectMapper();
1223 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1225 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1226 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1227 interfaceAsMap.remove("empty");
1229 if(MapUtils.isNotEmpty(operations)) {
1230 interfaceAsMap.putAll(operations);
1233 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1235 return interfaceObject;