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 static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
24 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
26 import fj.data.Either;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.apache.commons.lang3.tuple.ImmutableTriple;
30 import org.apache.commons.lang3.tuple.Triple;
31 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
34 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
35 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
36 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
37 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
38 import org.openecomp.sdc.be.model.ArtifactDefinition;
39 import org.openecomp.sdc.be.model.CapabilityDefinition;
40 import org.openecomp.sdc.be.model.Component;
41 import org.openecomp.sdc.be.model.ComponentInstance;
42 import org.openecomp.sdc.be.model.ComponentInstanceInput;
43 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
44 import org.openecomp.sdc.be.model.ComponentParametersView;
45 import org.openecomp.sdc.be.model.DataTypeDefinition;
46 import org.openecomp.sdc.be.model.GroupInstance;
47 import org.openecomp.sdc.be.model.InputDefinition;
48 import org.openecomp.sdc.be.model.PropertyDefinition;
49 import org.openecomp.sdc.be.model.RelationshipInfo;
50 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
51 import org.openecomp.sdc.be.model.RequirementDefinition;
52 import org.openecomp.sdc.be.model.Resource;
53 import org.openecomp.sdc.be.model.Service;
54 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
55 import org.openecomp.sdc.be.model.category.CategoryDefinition;
56 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
57 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
58 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
59 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
60 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
61 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
62 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
63 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
64 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
65 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
66 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
67 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
68 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
69 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
70 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
71 import org.openecomp.sdc.be.tosca.utils.InputConverter;
72 import org.openecomp.sdc.common.log.wrappers.Logger;
73 import org.springframework.beans.factory.annotation.Autowired;
74 import org.yaml.snakeyaml.DumperOptions;
75 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
76 import org.yaml.snakeyaml.Yaml;
77 import org.yaml.snakeyaml.introspector.BeanAccess;
78 import org.yaml.snakeyaml.introspector.Property;
79 import org.yaml.snakeyaml.introspector.PropertyUtils;
80 import org.yaml.snakeyaml.nodes.MappingNode;
81 import org.yaml.snakeyaml.nodes.Node;
82 import org.yaml.snakeyaml.nodes.NodeTuple;
83 import org.yaml.snakeyaml.nodes.Tag;
84 import org.yaml.snakeyaml.representer.Represent;
85 import org.yaml.snakeyaml.representer.Representer;
87 import java.beans.IntrospectionException;
88 import java.util.ArrayList;
89 import java.util.Collection;
90 import java.util.HashMap;
91 import java.util.LinkedHashSet;
92 import java.util.List;
94 import java.util.Map.Entry;
95 import java.util.Optional;
97 import java.util.function.Supplier;
98 import java.util.stream.Collectors;
100 import static org.apache.commons.collections.CollectionUtils.isEmpty;
101 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
102 import static org.apache.commons.collections.MapUtils.isNotEmpty;
103 import static org.apache.commons.lang.StringUtils.isNotEmpty;
105 @org.springframework.stereotype.Component("tosca-export-handler")
106 public class ToscaExportHandler {
108 private ApplicationDataTypeCache dataTypeCache;
109 private ToscaOperationFacade toscaOperationFacade;
110 private CapabilityRequirementConverter capabilityRequirementConverter;
111 private PolicyExportParser policyExportParser;
112 private GroupExportParser groupExportParser;
113 private PropertyConvertor propertyConvertor;
114 private InputConverter inputConverter;
117 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
118 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
119 GroupExportParser groupExportParser, InputConverter inputConverter) {
120 this.dataTypeCache = dataTypeCache;
121 this.toscaOperationFacade = toscaOperationFacade;
122 this.capabilityRequirementConverter = capabilityRequirementConverter;
123 this.policyExportParser = policyExportParser;
124 this.groupExportParser = groupExportParser;
125 this.propertyConvertor = PropertyConvertor.getInstance();
126 this.inputConverter = inputConverter;
130 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
132 public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
133 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
134 private static final String IMPORTS_FILE_KEY = "file";
135 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
136 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
137 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
138 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
139 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
140 .getConfigurationManager().getConfiguration().getDefaultImports();
142 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
144 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
145 if (toscaTemplateRes.isRight()) {
146 return Either.right(toscaTemplateRes.right().value());
149 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
150 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
151 return Either.left(toscaRepresentation);
154 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
155 boolean isAssociatedResourceComponent) {
156 if (null == DEFAULT_IMPORTS) {
157 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
158 return Either.right(ToscaError.GENERAL_ERROR);
161 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
162 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
163 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
164 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
165 toscaTemplate, nodeTypes, isAssociatedResourceComponent);
166 if (toscaTemplateRes.isRight()) {
167 return Either.right(toscaTemplateRes.right().value());
170 toscaTemplate = toscaTemplateRes.left().value();
171 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
172 return Either.left(toscaRepresentation);
175 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
176 CustomRepresenter representer = new CustomRepresenter();
177 DumperOptions options = new DumperOptions();
178 options.setAllowReadOnlyProperties(false);
179 options.setPrettyFlow(true);
181 options.setDefaultFlowStyle(FlowStyle.FLOW);
182 options.setCanonical(false);
184 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
186 representer.setPropertyUtils(new UnsortedPropertyUtils());
187 Yaml yaml = new Yaml(representer, options);
189 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
191 StringBuilder sb = new StringBuilder();
192 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
193 sb.append(yamlAsString);
194 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
196 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
197 toscaRepresentation.setMainYaml(sb.toString());
198 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
200 return toscaRepresentation;
203 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
204 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
205 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
207 if (fillImports.isRight()) {
208 return Either.right(fillImports.right().value());
210 return Either.left(fillImports.left().value().left);
213 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
214 if (null == DEFAULT_IMPORTS) {
215 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
216 return Either.right(ToscaError.GENERAL_ERROR);
219 log.trace("start tosca export for {}", component.getUniqueId());
220 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
222 toscaTemplate.setMetadata(convertMetadata(component));
223 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
224 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
225 if (ModelConverter.isAtomicComponent(component)) {
226 log.trace("convert component as node type");
227 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
229 log.trace("convert component as topology template");
230 return convertToscaTemplate(component, toscaTemplate);
235 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
237 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
239 if (importsRes.isRight()) {
240 return Either.right(importsRes.right().value());
242 toscaNode = importsRes.left().value().left;
243 Map<String, Component> componentCache = importsRes.left().value().right;
244 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
245 if (nodeTypesMapEither.isRight()) {
246 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
247 nodeTypesMapEither.right().value());
248 return Either.right(nodeTypesMapEither.right().value());
250 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
251 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
252 toscaNode.setNode_types(nodeTypesMap);
256 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
257 if (dataTypesEither.isRight()) {
258 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
259 return Either.right(ToscaError.GENERAL_ERROR);
261 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
262 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
263 List<InputDefinition> inputDef = component.getInputs();
264 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
266 if (!inputs.isEmpty()) {
267 topologyTemplate.setInputs(inputs);
270 List<ComponentInstance> componentInstances = component.getComponentInstances();
271 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
272 .getComponentInstancesProperties();
273 if (componentInstances != null && !componentInstances.isEmpty()) {
275 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
276 componentInstances, componentInstancesProperties, 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 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<ComponentInstance> componentInstances = component.getComponentInstances();
434 if (componentInstances != null && !componentInstances.isEmpty()) {
436 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
437 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
439 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
441 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
442 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
444 Map<String, Map<String, String>> importsListMember = new HashMap<>();
445 Map<String, String> interfaceFiles = new HashMap<>();
446 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
447 StringBuilder keyNameBuilder = new StringBuilder();
448 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
449 keyNameBuilder.append("-");
450 keyNameBuilder.append(component.getName());
451 keyNameBuilder.append("-interface");
452 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
453 additionalImports.add(importsListMember);
455 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
456 toscaTemplate.setDependencies(dependecies);
457 toscaTemplate.setImports(additionalImports);
460 log.debug("currently imports supported for VF and service only");
462 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
465 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
466 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
467 Map<String, String> files = new HashMap<>();
468 Map<String, Map<String, String>> importsListMember = new HashMap<>();
469 StringBuilder keyNameBuilder;
471 Component componentRI = componentCache.get(ci.getComponentUid());
472 if (componentRI == null) {
473 // all resource must be only once!
474 Either<Component, StorageOperationStatus> resource = toscaOperationFacade
475 .getToscaFullElement(ci.getComponentUid());
476 if ((resource.isRight()) && (log.isDebugEnabled())) {
477 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
481 Component fetchedComponent = resource.left().value();
482 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
484 if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
485 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
486 .getToscaFullElement(ci.getSourceModelUid());
487 if (sourceService.isRight() && (log.isDebugEnabled())) {
488 log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
490 Component fetchedSource = sourceService.left().value();
491 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
494 componentRI = fetchedComponent;
496 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
497 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
498 if (artifactDefinition != null) {
499 String artifactName = artifactDefinition.getArtifactName();
500 files.put(IMPORTS_FILE_KEY, artifactName);
501 keyNameBuilder = new StringBuilder();
502 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
503 keyNameBuilder.append("-");
504 keyNameBuilder.append(ci.getComponentName());
505 importsListMember.put(keyNameBuilder.toString(), files);
506 imports.add(importsListMember);
507 dependecies.add(new ImmutableTriple<>(artifactName,
508 artifactDefinition.getEsId(), fetchedComponent));
510 if (!ModelConverter.isAtomicComponent(componentRI)) {
511 importsListMember = new HashMap<>();
512 Map<String, String> interfaceFiles = new HashMap<>();
513 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
514 keyNameBuilder.append("-interface");
515 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
516 imports.add(importsListMember);
522 public static String getInterfaceFilename(String artifactName) {
523 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
526 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
527 Map<String, ToscaNodeType> nodeTypes) {
528 log.debug("start convert node type for {}", component.getUniqueId());
529 ToscaNodeType toscaNodeType = createNodeType(component);
531 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
532 if (dataTypesEither.isRight()) {
533 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
534 return Either.right(ToscaError.GENERAL_ERROR);
537 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
538 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
540 if (properties.isRight()) {
541 return Either.right(properties.right().value());
543 toscaNodeType = properties.left().value();
544 log.debug("Properties converted for {}", component.getUniqueId());
546 // Extracted to method for code reuse
547 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
550 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
551 Component component, ToscaTemplate toscaNode,
552 Map<String, ToscaNodeType> nodeTypes,
553 boolean isAssociatedResourceComponent) {
554 log.debug("start convert node type for {}", component.getUniqueId());
555 ToscaNodeType toscaNodeType = createNodeType(component);
556 toscaNode.setInterface_types(addInterfaceTypeElement(component));
557 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
558 if (dataTypesEither.isRight()) {
559 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
560 return Either.right(ToscaError.GENERAL_ERROR);
563 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
565 List<InputDefinition> inputDef = component.getInputs();
566 Map<String, ToscaProperty> inputs = new HashMap<>();
567 addInterfaceDefinitionElement(component, toscaNodeType, isAssociatedResourceComponent);
568 if (inputDef != null) {
569 inputDef.forEach(i -> {
570 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
571 inputs.put(i.getName(), property);
573 if (!inputs.isEmpty()) {
574 toscaNodeType.setProperties(inputs);
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 private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
620 List<ComponentInstance> componentInstances,
621 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
622 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
623 ToscaTopolgyTemplate topologyTemplate) {
625 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
626 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
627 component.getComponentType());
628 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
629 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
631 Map<String, ToscaGroupTemplate> groupsMap = null;
632 for (ComponentInstance componentInstance : componentInstances) {
633 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
634 nodeTemplate.setType(componentInstance.getToscaComponentName());
636 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
637 .getOriginComponent(componentCache, componentInstance);
638 if (originComponentRes.isRight()) {
639 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
642 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
643 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
644 originComponentRes.left().value(), componentCache);
645 if (requirements.isRight()) {
646 convertNodeTemplatesRes = Either.right(requirements.right().value());
649 String instanceUniqueId = componentInstance.getUniqueId();
650 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
652 nodeTemplate = requirements.left().value();
654 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
656 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
657 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
658 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
660 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
663 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
664 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
665 if (capabilities.isRight()) {
666 convertNodeTemplatesRes = Either.right(capabilities.right().value());
669 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
671 nodeTemplate = capabilities.left().value();
672 Map<String, Object> props = new HashMap<>();
674 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
675 // Adds the properties of parent component to map
676 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
679 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
680 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
681 instanceUniqueId, props);
684 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
685 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
688 if (!props.isEmpty()) {
689 nodeTemplate.setProperties(props);
692 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
693 if (groupInstances != null) {
694 if (groupsMap == null) {
695 groupsMap = new HashMap<>();
697 for (GroupInstance groupInst : groupInstances) {
698 boolean addToTosca = true;
700 List<String> artifacts = groupInst.getArtifacts();
701 if (artifacts == null || artifacts.isEmpty()) {
706 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
707 groupsMap.put(groupInst.getName(), toscaGroup);
712 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
714 if (groupsMap != null) {
715 log.debug("instance groups added");
716 topologyTemplate.addGroups(groupsMap);
718 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
719 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
720 component.getName());
721 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
722 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
723 component.getName());
725 if (convertNodeTemplatesRes == null) {
726 convertNodeTemplatesRes = Either.left(nodeTemplates);
728 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
729 component.getComponentType());
730 return convertNodeTemplatesRes;
733 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
734 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
735 String instanceUniqueId, Map<String, Object> props) {
737 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
738 if (instanceInputsList != null) {
739 instanceInputsList.forEach(input -> {
741 Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
742 ? input.getValue() : input.getDefaultValue();
743 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
748 private void addPropertiesOfComponentInstance(
749 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
750 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
751 Map<String, Object> props) {
753 if (isNotEmpty(componentInstancesProperties)) {
754 componentInstancesProperties.get(instanceUniqueId)
755 // Converts and adds each value to property map
756 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
761 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
762 Component componentOfInstance, Map<String, Object> props) {
764 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
765 if (isNotEmpty(componentProperties)) {
766 componentProperties.stream()
767 // Filters out properties with empty default values
768 .filter(prop -> isNotEmpty(prop.getDefaultValue()))
769 // Converts and adds each value to property map
770 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
771 prop::getDefaultValue));
775 private ToscaNodeType createNodeType(Component component) {
776 ToscaNodeType toscaNodeType = new ToscaNodeType();
777 if (ModelConverter.isAtomicComponent(component)) {
778 if (((Resource) component).getDerivedFrom() != null) {
779 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
781 toscaNodeType.setDescription(component.getDescription());
783 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
784 : "tosca.nodes.Root";
785 toscaNodeType.setDerived_from(derivedFrom);
787 return toscaNodeType;
790 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
792 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
793 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
795 List<ComponentInstance> componentInstances = container.getComponentInstances();
797 if (componentInstances == null || componentInstances.isEmpty()) {
800 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
801 List<ComponentInstance> proxyInst = componentInstances.stream()
802 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
803 .collect(Collectors.toList());
804 if (proxyInst != null && !proxyInst.isEmpty()) {
805 for (ComponentInstance inst : proxyInst) {
806 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
810 if (serviceProxyInstanceList.isEmpty()) {
813 ComponentParametersView filter = new ComponentParametersView(true);
814 filter.setIgnoreCapabilities(false);
815 filter.setIgnoreComponentInstances(false);
816 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
817 .getLatestByName("serviceProxy");
818 if (serviceProxyOrigin.isRight()) {
819 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
820 serviceProxyOrigin.right().value());
821 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
823 Component origComponent = serviceProxyOrigin.left().value();
825 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
826 Component serviceComponent = null;
827 ComponentParametersView componentParametersView = new ComponentParametersView();
828 componentParametersView.disableAll();
829 componentParametersView.setIgnoreCategories(false);
830 Either<Component, StorageOperationStatus> service = toscaOperationFacade
831 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
832 if (service.isRight()) {
833 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
835 serviceComponent = service.left().value();
838 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
839 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
842 return Either.left(nodeTypesMap);
845 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
846 ComponentInstance instance) {
847 ToscaNodeType toscaNodeType = new ToscaNodeType();
848 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
850 toscaNodeType.setDerived_from(derivedFrom);
851 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
852 if (dataTypesEither.isRight()) {
853 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
855 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
856 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
857 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
859 toscaNodeType.setCapabilities(capabilities);
861 return toscaNodeType;
864 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
865 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
866 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
868 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
869 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
870 log.debug("Failed to convert component instance requirements for the component instance {}. ",
871 componentInstance.getName());
872 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
874 if (!toscaRequirements.isEmpty()) {
875 nodeTypeTemplate.setRequirements(toscaRequirements);
877 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
878 return Either.left(nodeTypeTemplate);
881 private boolean addRequirements(Component component, ComponentInstance componentInstance,
882 List<RequirementCapabilityRelDef> relations, Component originComponent,
883 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
884 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
885 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
886 return isEmpty(filteredRelations) ||
887 filteredRelations.stream()
888 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
891 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
892 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
893 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
895 boolean result = true;
896 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
897 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
898 Either<Component, StorageOperationStatus> getOriginRes = null;
899 Optional<RequirementDefinition> reqOpt = Optional.empty();
900 Component toOriginComponent = null;
901 Optional<CapabilityDefinition> capOpt = Optional.empty();
903 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
904 .findFirst().orElse(null);
905 if (toInstance == null) {
906 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
911 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
912 if (!reqOpt.isPresent()) {
913 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
914 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
919 ComponentParametersView filter = new ComponentParametersView(true);
920 filter.setIgnoreComponentInstances(false);
921 filter.setIgnoreCapabilities(false);
922 filter.setIgnoreGroups(false);
923 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
924 if (getOriginRes.isRight()) {
925 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
926 reqOpt.get().getName(), toInstance.getActualComponentUid());
931 toOriginComponent = getOriginRes.left().value();
932 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
933 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
934 if (!capOpt.isPresent()) {
935 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
936 if(!capOpt.isPresent()){
938 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
939 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
944 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
945 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
950 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
951 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
954 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
955 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
956 if (!cap.isPresent()) {
957 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
962 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
963 List<String> reducedPath = capability.getPath();
964 if(capability.getOwnerId() !=null){
965 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
967 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
968 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
969 if (buildCapNameRes.isRight()) {
971 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
972 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
975 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
976 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
977 if (buildReqNameRes.isRight()) {
979 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
980 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
983 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
984 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
985 toscaRequirement.setNode(toInstance.getName());
986 toscaRequirement.setCapability(buildCapNameRes.left().value());
987 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
988 toscaRequirements.add(toscaReqMap);
992 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
993 for(List<RequirementDefinition> reqList: reqMap.values()){
994 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
995 if(reqOpt.isPresent()){
999 return Optional.empty();
1003 * Allows detecting the requirement belonging to the received relationship
1004 * The detection logic is: A requirement belongs to a relationship IF 1.The
1005 * name of the requirement equals to the "requirement" field of the
1006 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1007 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1008 * toInstance equals to capabilityOwnerId of the relation
1010 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1011 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1012 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1013 requirement.getName(), reqAndRelationshipPair.getRequirement());
1016 return ModelConverter.isAtomicComponent(originComponent) ||
1017 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1020 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1021 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1024 private boolean isCvfc(Component component) {
1025 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1026 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1029 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1030 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1032 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1033 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1034 .convertSubstitutionMappingCapabilities(componentCache, component);
1035 if (toscaCapabilitiesRes.isRight()) {
1036 result = Either.right(toscaCapabilitiesRes.right().value());
1037 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1038 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1039 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1040 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1042 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1046 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1047 Map<String, DataTypeDefinition> dataTypes) {
1048 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1050 if (!toscaCapabilities.isEmpty()) {
1051 nodeType.setCapabilities(toscaCapabilities);
1053 log.debug("Finish convert Capabilities for node type");
1055 return Either.left(nodeType);
1058 private static class CustomRepresenter extends Representer {
1059 public CustomRepresenter() {
1061 // null representer is exceptional and it is stored as an instance
1063 this.nullRepresenter = new RepresentNull();
1068 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1070 if (propertyValue == null) {
1073 // skip not relevant for Tosca property
1074 if ("dependencies".equals(property.getName())) {
1077 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1079 return "_defaultp_".equals(property.getName())
1080 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1085 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1086 // remove the bean type from the output yaml (!! ...)
1087 if (!classTags.containsKey(javaBean.getClass())) {
1088 addClassTag(javaBean.getClass(), Tag.MAP);
1091 return super.representJavaBean(properties, javaBean);
1094 private class RepresentNull implements Represent {
1096 public Node representData(Object data) {
1097 // possible values are here http://yaml.org/type/null.html
1098 return representScalar(Tag.NULL, "");
1103 private static class UnsortedPropertyUtils extends PropertyUtils {
1105 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1106 throws IntrospectionException {
1107 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1108 return new LinkedHashSet<>(fields);