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.InterfaceDefinition;
49 import org.openecomp.sdc.be.model.PropertyDefinition;
50 import org.openecomp.sdc.be.model.RelationshipInfo;
51 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
52 import org.openecomp.sdc.be.model.RequirementDefinition;
53 import org.openecomp.sdc.be.model.Resource;
54 import org.openecomp.sdc.be.model.Service;
55 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
56 import org.openecomp.sdc.be.model.category.CategoryDefinition;
57 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
58 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
59 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
60 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
61 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
62 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
63 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
64 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
65 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
66 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
67 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
68 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
69 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
70 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
71 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
72 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
73 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
74 import org.openecomp.sdc.be.tosca.utils.InputConverter;
75 import org.openecomp.sdc.common.log.wrappers.Logger;
76 import org.openecomp.sdc.exception.ResponseFormat;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.yaml.snakeyaml.DumperOptions;
79 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
80 import org.yaml.snakeyaml.Yaml;
81 import org.yaml.snakeyaml.introspector.BeanAccess;
82 import org.yaml.snakeyaml.introspector.Property;
83 import org.yaml.snakeyaml.introspector.PropertyUtils;
84 import org.yaml.snakeyaml.nodes.MappingNode;
85 import org.yaml.snakeyaml.nodes.Node;
86 import org.yaml.snakeyaml.nodes.NodeTuple;
87 import org.yaml.snakeyaml.nodes.Tag;
88 import org.yaml.snakeyaml.representer.Represent;
89 import org.yaml.snakeyaml.representer.Representer;
91 import java.beans.IntrospectionException;
92 import java.util.ArrayList;
93 import java.util.Collection;
94 import java.util.HashMap;
95 import java.util.LinkedHashSet;
96 import java.util.List;
98 import java.util.Map.Entry;
99 import java.util.Optional;
100 import java.util.Set;
101 import java.util.function.Supplier;
102 import java.util.stream.Collectors;
104 import static org.apache.commons.collections.CollectionUtils.isEmpty;
105 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
106 import static org.apache.commons.collections.MapUtils.isNotEmpty;
107 import static org.apache.commons.lang.StringUtils.isNotEmpty;
109 @org.springframework.stereotype.Component("tosca-export-handler")
110 public class ToscaExportHandler {
112 private ApplicationDataTypeCache dataTypeCache;
113 private ToscaOperationFacade toscaOperationFacade;
114 private CapabilityRequirementConverter capabilityRequirementConverter;
115 private PolicyExportParser policyExportParser;
116 private GroupExportParser groupExportParser;
117 private PropertyConvertor propertyConvertor;
118 private InputConverter inputConverter;
119 private InterfaceLifecycleOperation interfaceLifecycleOperation;
122 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
123 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
124 GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
125 this.dataTypeCache = dataTypeCache;
126 this.toscaOperationFacade = toscaOperationFacade;
127 this.capabilityRequirementConverter = capabilityRequirementConverter;
128 this.policyExportParser = policyExportParser;
129 this.groupExportParser = groupExportParser;
130 this.propertyConvertor = PropertyConvertor.getInstance();
131 this.inputConverter = inputConverter;
132 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
136 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
138 public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
139 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
140 private static final String IMPORTS_FILE_KEY = "file";
141 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
142 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
143 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
144 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
145 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
146 .getConfigurationManager().getConfiguration().getDefaultImports();
148 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
150 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
151 if (toscaTemplateRes.isRight()) {
152 return Either.right(toscaTemplateRes.right().value());
155 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
156 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
157 return Either.left(toscaRepresentation);
160 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
161 boolean isAssociatedResourceComponent) {
162 if (null == DEFAULT_IMPORTS) {
163 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
164 return Either.right(ToscaError.GENERAL_ERROR);
167 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
168 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
169 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
170 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
171 toscaTemplate, nodeTypes, isAssociatedResourceComponent);
172 if (toscaTemplateRes.isRight()) {
173 return Either.right(toscaTemplateRes.right().value());
176 toscaTemplate = toscaTemplateRes.left().value();
177 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
178 return Either.left(toscaRepresentation);
181 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
182 CustomRepresenter representer = new CustomRepresenter();
183 DumperOptions options = new DumperOptions();
184 options.setAllowReadOnlyProperties(false);
185 options.setPrettyFlow(true);
187 options.setDefaultFlowStyle(FlowStyle.FLOW);
188 options.setCanonical(false);
190 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
192 representer.setPropertyUtils(new UnsortedPropertyUtils());
193 Yaml yaml = new Yaml(representer, options);
195 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
197 StringBuilder sb = new StringBuilder();
198 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
199 sb.append(yamlAsString);
200 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
202 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
203 toscaRepresentation.setMainYaml(sb.toString());
204 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
206 return toscaRepresentation;
209 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
210 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
211 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
213 if (fillImports.isRight()) {
214 return Either.right(fillImports.right().value());
216 return Either.left(fillImports.left().value().left);
219 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
220 if (null == DEFAULT_IMPORTS) {
221 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
222 return Either.right(ToscaError.GENERAL_ERROR);
225 log.trace("start tosca export for {}", component.getUniqueId());
226 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
228 toscaTemplate.setMetadata(convertMetadata(component));
229 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
230 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
231 if (ModelConverter.isAtomicComponent(component)) {
232 log.trace("convert component as node type");
233 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
235 log.trace("convert component as topology template");
236 return convertToscaTemplate(component, toscaTemplate);
241 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
243 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
245 if (importsRes.isRight()) {
246 return Either.right(importsRes.right().value());
248 toscaNode = importsRes.left().value().left;
249 Map<String, Component> componentCache = importsRes.left().value().right;
250 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
251 if (nodeTypesMapEither.isRight()) {
252 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
253 nodeTypesMapEither.right().value());
254 return Either.right(nodeTypesMapEither.right().value());
256 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
257 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
258 toscaNode.setNode_types(nodeTypesMap);
262 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
263 if (dataTypesEither.isRight()) {
264 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
265 return Either.right(ToscaError.GENERAL_ERROR);
267 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
268 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
269 List<InputDefinition> inputDef = component.getInputs();
270 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
272 if (!inputs.isEmpty()) {
273 topologyTemplate.setInputs(inputs);
276 List<ComponentInstance> componentInstances = component.getComponentInstances();
277 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
278 .getComponentInstancesProperties();
279 if (componentInstances != null && !componentInstances.isEmpty()) {
281 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
282 componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
283 if (nodeTemplates.isRight()) {
284 return Either.right(nodeTemplates.right().value());
286 log.debug("node templates converted");
288 topologyTemplate.setNode_templates(nodeTemplates.left().value());
292 addGroupsToTopologyTemplate(component, topologyTemplate);
295 addPoliciesToTopologyTemplate(component, topologyTemplate);
296 } catch (SdcResourceNotFoundException e) {
297 log.debug("Fail to add policies to topology template:",e);
298 Either.right(ToscaError.GENERAL_ERROR);
302 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
303 String toscaResourceName;
304 switch (component.getComponentType()) {
306 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
307 .getMetadataDataDefinition()).getToscaResourceName();
310 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
311 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
314 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
315 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
317 substitutionMapping.setNode_type(toscaResourceName);
319 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
320 if (capabilities.isRight()) {
321 return Either.right(capabilities.right().value());
323 substitutionMapping = capabilities.left().value();
325 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
326 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
327 if (requirements.isRight()) {
328 return Either.right(requirements.right().value());
330 substitutionMapping = requirements.left().value();
332 topologyTemplate.setSubstitution_mappings(substitutionMapping);
334 toscaNode.setTopology_template(topologyTemplate);
335 return Either.left(toscaNode);
338 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
341 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
343 topologyTemplate.addGroups(groups);
347 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
348 throws SdcResourceNotFoundException {
349 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
350 if(policies!= null) {
351 topologyTemplate.addPolicies(policies);
355 private ToscaMetadata convertMetadata(Component component) {
356 return convertMetadata(component, false, null);
359 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
360 ComponentInstance componentInstance) {
361 ToscaMetadata toscaMetadata = new ToscaMetadata();
362 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
363 toscaMetadata.setUUID(component.getUUID());
364 toscaMetadata.setDescription(component.getDescription());
365 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
367 List<CategoryDefinition> categories = component.getCategories();
368 CategoryDefinition categoryDefinition = categories.get(0);
369 toscaMetadata.setCategory(categoryDefinition.getName());
372 toscaMetadata.setVersion(component.getVersion());
373 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
374 if (componentInstance.getSourceModelInvariant() != null
375 && !componentInstance.getSourceModelInvariant().isEmpty()) {
376 toscaMetadata.setVersion(componentInstance.getComponentVersion());
377 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
378 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
379 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
380 toscaMetadata.setName(
381 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
382 toscaMetadata.setDescription(componentInstance.getDescription());
386 switch (component.getComponentType()) {
388 Resource resource = (Resource) component;
390 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
391 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
393 toscaMetadata.setType(resource.getResourceType().name());
395 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
396 toscaMetadata.setResourceVendor(resource.getVendorName());
397 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
398 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
401 Service service = (Service) component;
402 toscaMetadata.setType(component.getComponentType().getValue());
403 toscaMetadata.setServiceType(service.getServiceType());
404 toscaMetadata.setServiceRole(service.getServiceRole());
405 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
406 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
409 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
410 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
411 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
415 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
417 return toscaMetadata;
420 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
421 if (service.getInstantiationType() != null) {
422 toscaMetadata.setInstantiationType(service.getInstantiationType());
425 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
429 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
430 ToscaTemplate toscaTemplate) {
432 if (null == DEFAULT_IMPORTS) {
433 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
434 return Either.right(ToscaError.GENERAL_ERROR);
436 Map<String, Component> componentCache = new HashMap<>();
438 if (!ModelConverter.isAtomicComponent(component)) {
439 List<ComponentInstance> componentInstances = component.getComponentInstances();
440 if (componentInstances != null && !componentInstances.isEmpty()) {
442 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
443 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
445 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
447 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
448 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
450 Map<String, Map<String, String>> importsListMember = new HashMap<>();
451 Map<String, String> interfaceFiles = new HashMap<>();
452 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
453 StringBuilder keyNameBuilder = new StringBuilder();
454 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
455 keyNameBuilder.append("-");
456 keyNameBuilder.append(component.getName());
457 keyNameBuilder.append("-interface");
458 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
459 additionalImports.add(importsListMember);
461 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
462 toscaTemplate.setDependencies(dependecies);
463 toscaTemplate.setImports(additionalImports);
466 log.debug("currently imports supported for VF and service only");
468 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
471 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
472 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
473 Map<String, String> files = new HashMap<>();
474 Map<String, Map<String, String>> importsListMember = new HashMap<>();
475 StringBuilder keyNameBuilder;
477 Component componentRI = componentCache.get(ci.getComponentUid());
478 if (componentRI == null) {
479 // all resource must be only once!
480 Either<Component, StorageOperationStatus> resource = toscaOperationFacade
481 .getToscaFullElement(ci.getComponentUid());
482 if ((resource.isRight()) && (log.isDebugEnabled())) {
483 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
487 Component fetchedComponent = resource.left().value();
488 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
490 if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
491 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
492 .getToscaFullElement(ci.getSourceModelUid());
493 if (sourceService.isRight() && (log.isDebugEnabled())) {
494 log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
496 Component fetchedSource = sourceService.left().value();
497 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
500 componentRI = fetchedComponent;
502 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
503 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
504 if (artifactDefinition != null) {
505 String artifactName = artifactDefinition.getArtifactName();
506 files.put(IMPORTS_FILE_KEY, artifactName);
507 keyNameBuilder = new StringBuilder();
508 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
509 keyNameBuilder.append("-");
510 keyNameBuilder.append(ci.getComponentName());
511 importsListMember.put(keyNameBuilder.toString(), files);
512 imports.add(importsListMember);
513 dependecies.add(new ImmutableTriple<>(artifactName,
514 artifactDefinition.getEsId(), fetchedComponent));
516 if (!ModelConverter.isAtomicComponent(componentRI)) {
517 importsListMember = new HashMap<>();
518 Map<String, String> interfaceFiles = new HashMap<>();
519 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
520 keyNameBuilder.append("-interface");
521 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
522 imports.add(importsListMember);
528 public static String getInterfaceFilename(String artifactName) {
529 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
532 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
533 Map<String, ToscaNodeType> nodeTypes) {
534 log.debug("start convert node type for {}", component.getUniqueId());
535 ToscaNodeType toscaNodeType = createNodeType(component);
537 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
538 if (dataTypesEither.isRight()) {
539 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
540 return Either.right(ToscaError.GENERAL_ERROR);
543 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
544 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
546 if (properties.isRight()) {
547 return Either.right(properties.right().value());
549 toscaNodeType = properties.left().value();
550 log.debug("Properties converted for {}", component.getUniqueId());
552 // Extracted to method for code reuse
553 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
556 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
557 Component component, ToscaTemplate toscaNode,
558 Map<String, ToscaNodeType> nodeTypes,
559 boolean isAssociatedResourceComponent) {
560 log.debug("start convert node type for {}", component.getUniqueId());
561 ToscaNodeType toscaNodeType = createNodeType(component);
563 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither = interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
564 if(lifecycleTypeEither.isRight()){
565 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
566 return Either.right(ToscaError.GENERAL_ERROR);
568 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream().map(interfaceDef -> interfaceDef.getType()).collect(Collectors.toList());
569 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
571 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
572 if (dataTypesEither.isRight()) {
573 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
574 return Either.right(ToscaError.GENERAL_ERROR);
577 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
579 List<InputDefinition> inputDef = component.getInputs();
580 Map<String, ToscaProperty> inputs = new HashMap<>();
581 addInterfaceDefinitionElement(component, toscaNodeType, isAssociatedResourceComponent);
582 if (inputDef != null) {
583 inputDef.forEach(i -> {
584 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
585 inputs.put(i.getName(), property);
587 if (!inputs.isEmpty()) {
588 toscaNodeType.setProperties(inputs);
591 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
594 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
595 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
596 Map<String, DataTypeDefinition> dataTypes) {
597 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
598 if (capabilities.isRight()) {
599 return Either.right(capabilities.right().value());
601 toscaNodeType = capabilities.left().value();
602 log.debug("Capabilities converted for {}", component.getUniqueId());
604 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
606 if (requirements.isRight()) {
607 return Either.right(requirements.right().value());
609 toscaNodeType = requirements.left().value();
610 log.debug("Requirements converted for {}", component.getUniqueId());
612 String toscaResourceName;
613 switch (component.getComponentType()) {
615 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
616 .getMetadataDataDefinition()).getToscaResourceName();
619 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
620 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
623 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
624 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
627 nodeTypes.put(toscaResourceName, toscaNodeType);
628 toscaNode.setNode_types(nodeTypes);
629 log.debug("finish convert node type for {}", component.getUniqueId());
630 return Either.left(toscaNode);
633 private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
634 List<ComponentInstance> componentInstances,
635 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
636 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
637 ToscaTopolgyTemplate topologyTemplate) {
639 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
640 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
641 component.getComponentType());
642 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
643 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
645 Map<String, ToscaGroupTemplate> groupsMap = null;
646 for (ComponentInstance componentInstance : componentInstances) {
647 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
648 nodeTemplate.setType(componentInstance.getToscaComponentName());
650 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
651 .getOriginComponent(componentCache, componentInstance);
652 if (originComponentRes.isRight()) {
653 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
656 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
657 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
658 originComponentRes.left().value(), componentCache);
659 if (requirements.isRight()) {
660 convertNodeTemplatesRes = Either.right(requirements.right().value());
663 String instanceUniqueId = componentInstance.getUniqueId();
664 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
666 nodeTemplate = requirements.left().value();
668 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
670 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
671 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
672 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
674 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
677 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
678 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
679 if (capabilities.isRight()) {
680 convertNodeTemplatesRes = Either.right(capabilities.right().value());
683 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
685 nodeTemplate = capabilities.left().value();
686 Map<String, Object> props = new HashMap<>();
688 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
689 // Adds the properties of parent component to map
690 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
693 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
694 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
695 instanceUniqueId, props);
698 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
699 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
702 if (!props.isEmpty()) {
703 nodeTemplate.setProperties(props);
706 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
707 if (groupInstances != null) {
708 if (groupsMap == null) {
709 groupsMap = new HashMap<>();
711 for (GroupInstance groupInst : groupInstances) {
712 boolean addToTosca = true;
714 List<String> artifacts = groupInst.getArtifacts();
715 if (artifacts == null || artifacts.isEmpty()) {
720 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
721 groupsMap.put(groupInst.getName(), toscaGroup);
726 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
728 if (groupsMap != null) {
729 log.debug("instance groups added");
730 topologyTemplate.addGroups(groupsMap);
732 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
733 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
734 component.getName());
735 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
736 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
737 component.getName());
739 if (convertNodeTemplatesRes == null) {
740 convertNodeTemplatesRes = Either.left(nodeTemplates);
742 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
743 component.getComponentType());
744 return convertNodeTemplatesRes;
747 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
748 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
749 String instanceUniqueId, Map<String, Object> props) {
751 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
752 if (instanceInputsList != null) {
753 instanceInputsList.forEach(input -> {
755 Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
756 ? input.getValue() : input.getDefaultValue();
757 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
762 private void addPropertiesOfComponentInstance(
763 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
764 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
765 Map<String, Object> props) {
767 if (isNotEmpty(componentInstancesProperties)) {
768 componentInstancesProperties.get(instanceUniqueId)
769 // Converts and adds each value to property map
770 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
775 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
776 Component componentOfInstance, Map<String, Object> props) {
778 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
779 if (isNotEmpty(componentProperties)) {
780 componentProperties.stream()
781 // Filters out properties with empty default values
782 .filter(prop -> isNotEmpty(prop.getDefaultValue()))
783 // Converts and adds each value to property map
784 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
785 prop::getDefaultValue));
789 private ToscaNodeType createNodeType(Component component) {
790 ToscaNodeType toscaNodeType = new ToscaNodeType();
791 if (ModelConverter.isAtomicComponent(component)) {
792 if (((Resource) component).getDerivedFrom() != null) {
793 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
795 toscaNodeType.setDescription(component.getDescription());
797 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
798 : "tosca.nodes.Root";
799 toscaNodeType.setDerived_from(derivedFrom);
801 return toscaNodeType;
804 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
806 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
807 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
809 List<ComponentInstance> componentInstances = container.getComponentInstances();
811 if (componentInstances == null || componentInstances.isEmpty()) {
814 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
815 List<ComponentInstance> proxyInst = componentInstances.stream()
816 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
817 .collect(Collectors.toList());
818 if (proxyInst != null && !proxyInst.isEmpty()) {
819 for (ComponentInstance inst : proxyInst) {
820 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
824 if (serviceProxyInstanceList.isEmpty()) {
827 ComponentParametersView filter = new ComponentParametersView(true);
828 filter.setIgnoreCapabilities(false);
829 filter.setIgnoreComponentInstances(false);
830 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
831 .getLatestByName("serviceProxy");
832 if (serviceProxyOrigin.isRight()) {
833 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
834 serviceProxyOrigin.right().value());
835 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
837 Component origComponent = serviceProxyOrigin.left().value();
839 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
840 Component serviceComponent = null;
841 ComponentParametersView componentParametersView = new ComponentParametersView();
842 componentParametersView.disableAll();
843 componentParametersView.setIgnoreCategories(false);
844 Either<Component, StorageOperationStatus> service = toscaOperationFacade
845 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
846 if (service.isRight()) {
847 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
849 serviceComponent = service.left().value();
852 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
853 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
856 return Either.left(nodeTypesMap);
859 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
860 ComponentInstance instance) {
861 ToscaNodeType toscaNodeType = new ToscaNodeType();
862 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
864 toscaNodeType.setDerived_from(derivedFrom);
865 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
866 if (dataTypesEither.isRight()) {
867 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
869 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
870 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
871 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
873 toscaNodeType.setCapabilities(capabilities);
875 return toscaNodeType;
878 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
879 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
880 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
882 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
883 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
884 log.debug("Failed to convert component instance requirements for the component instance {}. ",
885 componentInstance.getName());
886 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
888 if (!toscaRequirements.isEmpty()) {
889 nodeTypeTemplate.setRequirements(toscaRequirements);
891 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
892 return Either.left(nodeTypeTemplate);
895 private boolean addRequirements(Component component, ComponentInstance componentInstance,
896 List<RequirementCapabilityRelDef> relations, Component originComponent,
897 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
898 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
899 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
900 return isEmpty(filteredRelations) ||
901 filteredRelations.stream()
902 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
905 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
906 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
907 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
909 boolean result = true;
910 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
911 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
912 Either<Component, StorageOperationStatus> getOriginRes = null;
913 Optional<RequirementDefinition> reqOpt = Optional.empty();
914 Component toOriginComponent = null;
915 Optional<CapabilityDefinition> capOpt = Optional.empty();
917 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
918 .findFirst().orElse(null);
919 if (toInstance == null) {
920 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
925 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
926 if (!reqOpt.isPresent()) {
927 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
928 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
933 ComponentParametersView filter = new ComponentParametersView(true);
934 filter.setIgnoreComponentInstances(false);
935 filter.setIgnoreCapabilities(false);
936 filter.setIgnoreGroups(false);
937 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
938 if (getOriginRes.isRight()) {
939 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
940 reqOpt.get().getName(), toInstance.getActualComponentUid());
945 toOriginComponent = getOriginRes.left().value();
946 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
947 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
948 if (!capOpt.isPresent()) {
949 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
950 if(!capOpt.isPresent()){
952 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
953 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
958 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
959 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
964 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
965 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
968 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
969 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
970 if (!cap.isPresent()) {
971 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
976 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
977 List<String> reducedPath = capability.getPath();
978 if(capability.getOwnerId() !=null){
979 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
981 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
982 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
983 if (buildCapNameRes.isRight()) {
985 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
986 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
989 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
990 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
991 if (buildReqNameRes.isRight()) {
993 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
994 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
997 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
998 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
999 toscaRequirement.setNode(toInstance.getName());
1000 toscaRequirement.setCapability(buildCapNameRes.left().value());
1001 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1002 toscaRequirements.add(toscaReqMap);
1006 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1007 for(List<RequirementDefinition> reqList: reqMap.values()){
1008 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1009 if(reqOpt.isPresent()){
1013 return Optional.empty();
1017 * Allows detecting the requirement belonging to the received relationship
1018 * The detection logic is: A requirement belongs to a relationship IF 1.The
1019 * name of the requirement equals to the "requirement" field of the
1020 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1021 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1022 * toInstance equals to capabilityOwnerId of the relation
1024 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1025 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1026 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1027 requirement.getName(), reqAndRelationshipPair.getRequirement());
1030 return ModelConverter.isAtomicComponent(originComponent) ||
1031 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1034 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1035 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1038 private boolean isCvfc(Component component) {
1039 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1040 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1043 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1044 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1046 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1047 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1048 .convertSubstitutionMappingCapabilities(componentCache, component);
1049 if (toscaCapabilitiesRes.isRight()) {
1050 result = Either.right(toscaCapabilitiesRes.right().value());
1051 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1052 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1053 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1054 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1056 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1060 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1061 Map<String, DataTypeDefinition> dataTypes) {
1062 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1064 if (!toscaCapabilities.isEmpty()) {
1065 nodeType.setCapabilities(toscaCapabilities);
1067 log.debug("Finish convert Capabilities for node type");
1069 return Either.left(nodeType);
1072 private static class CustomRepresenter extends Representer {
1073 public CustomRepresenter() {
1075 // null representer is exceptional and it is stored as an instance
1077 this.nullRepresenter = new RepresentNull();
1082 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1084 if (propertyValue == null) {
1087 // skip not relevant for Tosca property
1088 if ("dependencies".equals(property.getName())) {
1091 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1093 return "_defaultp_".equals(property.getName())
1094 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1099 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1100 // remove the bean type from the output yaml (!! ...)
1101 if (!classTags.containsKey(javaBean.getClass())) {
1102 addClassTag(javaBean.getClass(), Tag.MAP);
1105 return super.representJavaBean(properties, javaBean);
1108 private class RepresentNull implements Represent {
1110 public Node representData(Object data) {
1111 // possible values are here http://yaml.org/type/null.html
1112 return representScalar(Tag.NULL, "");
1117 private static class UnsortedPropertyUtils extends PropertyUtils {
1119 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1120 throws IntrospectionException {
1121 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1122 return new LinkedHashSet<>(fields);