2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.tosca;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
25 import fj.data.Either;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.apache.commons.lang3.tuple.ImmutableTriple;
31 import org.apache.commons.lang3.tuple.Triple;
32 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
33 import org.openecomp.sdc.be.config.ConfigurationManager;
34 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
35 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
36 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
37 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
38 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
39 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
40 import org.openecomp.sdc.be.model.*;
41 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
42 import org.openecomp.sdc.be.model.category.CategoryDefinition;
43 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
44 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
47 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
48 import org.openecomp.sdc.be.tosca.model.*;
49 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
50 import org.openecomp.sdc.be.tosca.utils.InputConverter;
51 import org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil;
52 import org.openecomp.sdc.common.log.wrappers.Logger;
53 import org.openecomp.sdc.externalupload.utils.ServiceUtils;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.yaml.snakeyaml.DumperOptions;
56 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
57 import org.yaml.snakeyaml.Yaml;
58 import org.yaml.snakeyaml.introspector.BeanAccess;
59 import org.yaml.snakeyaml.introspector.Property;
60 import org.yaml.snakeyaml.introspector.PropertyUtils;
61 import org.yaml.snakeyaml.nodes.MappingNode;
62 import org.yaml.snakeyaml.nodes.Node;
63 import org.yaml.snakeyaml.nodes.NodeTuple;
64 import org.yaml.snakeyaml.nodes.Tag;
65 import org.yaml.snakeyaml.representer.Represent;
66 import org.yaml.snakeyaml.representer.Representer;
68 import java.beans.IntrospectionException;
70 import java.util.Map.Entry;
71 import java.util.function.Supplier;
72 import java.util.stream.Collectors;
74 import static org.apache.commons.collections.CollectionUtils.isEmpty;
75 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
76 import static org.apache.commons.collections.MapUtils.isNotEmpty;
77 import static org.apache.commons.lang.StringUtils.isNotEmpty;
78 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
79 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
81 @org.springframework.stereotype.Component("tosca-export-handler")
82 public class ToscaExportHandler {
84 private ApplicationDataTypeCache dataTypeCache;
85 private ToscaOperationFacade toscaOperationFacade;
86 private CapabilityRequirementConverter capabilityRequirementConverter;
87 private PolicyExportParser policyExportParser;
88 private GroupExportParser groupExportParser;
89 private PropertyConvertor propertyConvertor;
90 private InputConverter inputConverter;
91 private InterfaceLifecycleOperation interfaceLifecycleOperation;
94 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
95 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
96 GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
97 this.dataTypeCache = dataTypeCache;
98 this.toscaOperationFacade = toscaOperationFacade;
99 this.capabilityRequirementConverter = capabilityRequirementConverter;
100 this.policyExportParser = policyExportParser;
101 this.groupExportParser = groupExportParser;
102 this.propertyConvertor = PropertyConvertor.getInstance();
103 this.inputConverter = inputConverter;
104 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
108 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
110 public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
111 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
112 private static final String IMPORTS_FILE_KEY = "file";
113 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
114 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
115 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
116 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
117 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
118 .getConfigurationManager().getConfiguration().getDefaultImports();
120 public ToscaExportHandler(){}
122 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
124 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
125 if (toscaTemplateRes.isRight()) {
126 return Either.right(toscaTemplateRes.right().value());
129 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
130 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
131 return Either.left(toscaRepresentation);
134 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
135 boolean isAssociatedResourceComponent) {
136 if (null == DEFAULT_IMPORTS) {
137 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
138 return Either.right(ToscaError.GENERAL_ERROR);
141 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
142 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
143 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
144 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
145 toscaTemplate, nodeTypes, isAssociatedResourceComponent);
146 if (toscaTemplateRes.isRight()) {
147 return Either.right(toscaTemplateRes.right().value());
150 toscaTemplate = toscaTemplateRes.left().value();
151 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
152 return Either.left(toscaRepresentation);
155 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
156 CustomRepresenter representer = new CustomRepresenter();
157 DumperOptions options = new DumperOptions();
158 options.setAllowReadOnlyProperties(false);
159 options.setPrettyFlow(true);
161 options.setDefaultFlowStyle(FlowStyle.FLOW);
162 options.setCanonical(false);
164 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
166 representer.setPropertyUtils(new UnsortedPropertyUtils());
167 Yaml yaml = new Yaml(representer, options);
169 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
171 StringBuilder sb = new StringBuilder();
172 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
173 sb.append(yamlAsString);
174 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
176 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
177 toscaRepresentation.setMainYaml(sb.toString());
178 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
180 return toscaRepresentation;
183 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
184 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
185 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
187 if (fillImports.isRight()) {
188 return Either.right(fillImports.right().value());
190 return Either.left(fillImports.left().value().left);
193 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
194 if (null == DEFAULT_IMPORTS) {
195 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
196 return Either.right(ToscaError.GENERAL_ERROR);
199 log.trace("start tosca export for {}", component.getUniqueId());
200 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
202 toscaTemplate.setMetadata(convertMetadata(component));
203 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
204 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
205 if (ModelConverter.isAtomicComponent(component)) {
206 log.trace("convert component as node type");
207 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
209 log.trace("convert component as topology template");
210 return convertToscaTemplate(component, toscaTemplate);
215 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
217 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
219 if (importsRes.isRight()) {
220 return Either.right(importsRes.right().value());
222 toscaNode = importsRes.left().value().left;
223 Map<String, Component> componentCache = importsRes.left().value().right;
224 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
225 if (nodeTypesMapEither.isRight()) {
226 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
227 nodeTypesMapEither.right().value());
228 return Either.right(nodeTypesMapEither.right().value());
230 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
231 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
232 toscaNode.setNode_types(nodeTypesMap);
236 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
237 if (dataTypesEither.isRight()) {
238 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
239 return Either.right(ToscaError.GENERAL_ERROR);
241 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
242 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
243 List<InputDefinition> inputDef = component.getInputs();
244 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
246 if (!inputs.isEmpty()) {
247 topologyTemplate.setInputs(inputs);
250 List<ComponentInstance> componentInstances = component.getComponentInstances();
251 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
252 component.getComponentInstancesProperties();
253 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
254 component.getComponentInstancesInterfaces();
255 if (componentInstances != null && !componentInstances.isEmpty()) {
257 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
258 convertNodeTemplates(component, componentInstances,
259 componentInstancesProperties, componentInstanceInterfaces,
260 componentCache, dataTypes, topologyTemplate);
261 if (nodeTemplates.isRight()) {
262 return Either.right(nodeTemplates.right().value());
264 log.debug("node templates converted");
266 topologyTemplate.setNode_templates(nodeTemplates.left().value());
270 addGroupsToTopologyTemplate(component, topologyTemplate);
273 addPoliciesToTopologyTemplate(component, topologyTemplate);
274 } catch (SdcResourceNotFoundException e) {
275 log.debug("Fail to add policies to topology template:",e);
276 Either.right(ToscaError.GENERAL_ERROR);
280 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
281 String toscaResourceName;
282 switch (component.getComponentType()) {
284 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
285 .getMetadataDataDefinition()).getToscaResourceName();
288 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
289 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
292 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
293 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
295 substitutionMapping.setNode_type(toscaResourceName);
297 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
298 if (capabilities.isRight()) {
299 return Either.right(capabilities.right().value());
301 substitutionMapping = capabilities.left().value();
303 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
304 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
305 if (requirements.isRight()) {
306 return Either.right(requirements.right().value());
308 substitutionMapping = requirements.left().value();
310 topologyTemplate.setSubstitution_mappings(substitutionMapping);
312 toscaNode.setTopology_template(topologyTemplate);
313 return Either.left(toscaNode);
316 private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
317 ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
318 if (log.isDebugEnabled()) {
319 log.debug("fillInputs for component {}", component.getUniqueId());
321 List<InputDefinition> inputDef = component.getInputs();
322 Map<String, ToscaProperty> inputs = new HashMap<>();
324 if (inputDef != null) {
325 inputDef.forEach(i -> {
326 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, PropertyConvertor.PropertyType.INPUT);
327 inputs.put(i.getName(), property);
329 if (!inputs.isEmpty()) {
330 topologyTemplate.setInputs(inputs);
333 return Either.left(topologyTemplate);
336 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
339 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
341 topologyTemplate.addGroups(groups);
345 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
346 throws SdcResourceNotFoundException {
347 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
348 if(policies!= null) {
349 topologyTemplate.addPolicies(policies);
353 private ToscaMetadata convertMetadata(Component component) {
354 return convertMetadata(component, false, null);
357 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
358 ComponentInstance componentInstance) {
359 ToscaMetadata toscaMetadata = new ToscaMetadata();
360 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
361 toscaMetadata.setUUID(component.getUUID());
362 toscaMetadata.setDescription(component.getDescription());
363 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
365 List<CategoryDefinition> categories = component.getCategories();
366 CategoryDefinition categoryDefinition = categories.get(0);
367 toscaMetadata.setCategory(categoryDefinition.getName());
370 toscaMetadata.setVersion(component.getVersion());
371 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
372 if (componentInstance.getSourceModelInvariant() != null
373 && !componentInstance.getSourceModelInvariant().isEmpty()) {
374 toscaMetadata.setVersion(componentInstance.getComponentVersion());
375 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
376 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
377 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
378 toscaMetadata.setName(
379 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
380 toscaMetadata.setDescription(componentInstance.getDescription());
384 switch (component.getComponentType()) {
386 Resource resource = (Resource) component;
388 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
389 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
391 toscaMetadata.setType(resource.getResourceType().name());
393 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
394 toscaMetadata.setResourceVendor(resource.getVendorName());
395 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
396 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
399 Service service = (Service) component;
400 toscaMetadata.setType(component.getComponentType().getValue());
401 toscaMetadata.setServiceType(service.getServiceType());
402 toscaMetadata.setServiceRole(service.getServiceRole());
403 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
404 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
407 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
408 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
409 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
413 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
415 return toscaMetadata;
418 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
419 if (service.getInstantiationType() != null) {
420 toscaMetadata.setInstantiationType(service.getInstantiationType());
423 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
427 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
428 ToscaTemplate toscaTemplate) {
430 if (null == DEFAULT_IMPORTS) {
431 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
432 return Either.right(ToscaError.GENERAL_ERROR);
434 Map<String, Component> componentCache = new HashMap<>();
436 if (!ModelConverter.isAtomicComponent(component)) {
437 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
438 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
440 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
442 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
443 if (isNotEmpty(toscaArtifacts)) {
444 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
445 if(artifactDefinition != null) {
446 Map<String, Map<String, String>> importsListMember = new HashMap<>();
447 Map<String, String> interfaceFiles = new HashMap<>();
448 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
449 StringBuilder keyNameBuilder = new StringBuilder();
450 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
451 .append(component.getName()).append("-interface");
452 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
453 additionalImports.add(importsListMember);
456 List<ComponentInstance> componentInstances = component.getComponentInstances();
457 if (componentInstances != null && !componentInstances.isEmpty()) {
458 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
460 toscaTemplate.setDependencies(dependecies);
461 toscaTemplate.setImports(additionalImports);
463 log.debug("currently imports supported for VF and service only");
465 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
468 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
469 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
470 Map<String, String> files = new HashMap<>();
471 Map<String, Map<String, String>> importsListMember = new HashMap<>();
472 StringBuilder keyNameBuilder;
474 Component componentRI = componentCache.get(ci.getComponentUid());
475 if (componentRI == null) {
476 // all resource must be only once!
477 Either<Component, StorageOperationStatus> resource = toscaOperationFacade
478 .getToscaFullElement(ci.getComponentUid());
479 if ((resource.isRight()) && (log.isDebugEnabled())) {
480 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
484 Component fetchedComponent = resource.left().value();
485 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
487 if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
488 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
489 .getToscaFullElement(ci.getSourceModelUid());
490 if (sourceService.isRight() && (log.isDebugEnabled())) {
491 log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
493 Component fetchedSource = sourceService.left().value();
494 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
497 componentRI = fetchedComponent;
499 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
500 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
501 if (artifactDefinition != null) {
502 String artifactName = artifactDefinition.getArtifactName();
503 files.put(IMPORTS_FILE_KEY, artifactName);
504 keyNameBuilder = new StringBuilder();
505 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
506 keyNameBuilder.append("-");
507 keyNameBuilder.append(ci.getComponentName());
508 importsListMember.put(keyNameBuilder.toString(), files);
509 imports.add(importsListMember);
510 dependecies.add(new ImmutableTriple<>(artifactName,
511 artifactDefinition.getEsId(), fetchedComponent));
513 if (!ModelConverter.isAtomicComponent(componentRI)) {
514 importsListMember = new HashMap<>();
515 Map<String, String> interfaceFiles = new HashMap<>();
516 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
517 keyNameBuilder.append("-interface");
518 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
519 imports.add(importsListMember);
525 public static String getInterfaceFilename(String artifactName) {
526 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
529 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
530 Map<String, ToscaNodeType> nodeTypes) {
531 log.debug("start convert node type for {}", component.getUniqueId());
532 ToscaNodeType toscaNodeType = createNodeType(component);
534 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
535 if (dataTypesEither.isRight()) {
536 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
537 return Either.right(ToscaError.GENERAL_ERROR);
540 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
541 Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
543 if (properties.isRight()) {
544 return Either.right(properties.right().value());
546 toscaNodeType = properties.left().value();
547 log.debug("Properties converted for {}", component.getUniqueId());
549 // Extracted to method for code reuse
550 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
553 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
554 Component component, ToscaTemplate toscaNode,
555 Map<String, ToscaNodeType> nodeTypes,
556 boolean isAssociatedResourceComponent) {
557 log.debug("start convert node type for {}", component.getUniqueId());
558 ToscaNodeType toscaNodeType = createNodeType(component);
560 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
561 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
562 if(lifecycleTypeEither.isRight()){
563 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
564 return Either.right(ToscaError.GENERAL_ERROR);
566 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
569 .map(interfaceDef -> interfaceDef.getType())
570 .collect(Collectors.toList());
571 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
573 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
574 if (dataTypesEither.isRight()) {
575 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
576 return Either.right(ToscaError.GENERAL_ERROR);
579 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
581 List<InputDefinition> inputDef = component.getInputs();
582 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
583 addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedResourceComponent);
584 if (inputDef != null) {
585 addInputsToProperties(dataTypes, inputDef, mergedProperties);
588 if(CollectionUtils.isNotEmpty(component.getProperties())) {
589 List<PropertyDefinition> properties = component.getProperties();
590 mergedProperties = properties.stream().collect(Collectors.toMap(
591 PropertyDataDefinition::getName,
592 property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY)));
594 if (!mergedProperties.isEmpty()) {
595 toscaNodeType.setProperties(mergedProperties);
597 // Extracted to method for code reuse
598 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
601 private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
602 List<InputDefinition> inputDef,
603 Map<String, ToscaProperty> mergedProperties) {
604 for(InputDefinition input : inputDef) {
605 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
606 mergedProperties.put(input.getName(), property);
611 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
612 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
613 Map<String, DataTypeDefinition> dataTypes) {
614 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
615 if (capabilities.isRight()) {
616 return Either.right(capabilities.right().value());
618 toscaNodeType = capabilities.left().value();
619 log.debug("Capabilities converted for {}", component.getUniqueId());
621 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
623 if (requirements.isRight()) {
624 return Either.right(requirements.right().value());
626 toscaNodeType = requirements.left().value();
627 log.debug("Requirements converted for {}", component.getUniqueId());
629 String toscaResourceName;
630 switch (component.getComponentType()) {
632 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
633 .getMetadataDataDefinition()).getToscaResourceName();
636 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
637 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
640 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
641 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
644 nodeTypes.put(toscaResourceName, toscaNodeType);
645 toscaNode.setNode_types(nodeTypes);
646 log.debug("finish convert node type for {}", component.getUniqueId());
647 return Either.left(toscaNode);
650 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
652 List<ComponentInstance> componentInstances,
653 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
654 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
655 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
656 ToscaTopolgyTemplate topologyTemplate) {
658 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
659 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
660 component.getComponentType());
661 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
662 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
664 Map<String, ToscaGroupTemplate> groupsMap = null;
665 for (ComponentInstance componentInstance : componentInstances) {
666 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
667 nodeTemplate.setType(componentInstance.getToscaComponentName());
669 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
670 .getOriginComponent(componentCache, componentInstance);
671 if (originComponentRes.isRight()) {
672 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
675 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
676 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
677 originComponentRes.left().value(), componentCache);
678 if (requirements.isRight()) {
679 convertNodeTemplatesRes = Either.right(requirements.right().value());
682 String instanceUniqueId = componentInstance.getUniqueId();
683 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
685 nodeTemplate = requirements.left().value();
687 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
689 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
690 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
691 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
693 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
696 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
697 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
698 if (capabilities.isRight()) {
699 convertNodeTemplatesRes = Either.right(capabilities.right().value());
702 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
704 nodeTemplate = capabilities.left().value();
705 Map<String, Object> props = new HashMap<>();
707 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
708 // Adds the properties of parent component to map
709 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
712 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
713 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
714 instanceUniqueId, props);
717 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
718 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
721 //M3[00001] - NODE TEMPLATE INTERFACES - START
722 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
723 instanceUniqueId, component);
724 //M3[00001] - NODE TEMPLATE INTERFACES - END
725 if (props != null && !props.isEmpty()) {
726 nodeTemplate.setProperties(props);
729 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
730 if (groupInstances != null) {
731 if (groupsMap == null) {
732 groupsMap = new HashMap<>();
734 for (GroupInstance groupInst : groupInstances) {
735 boolean addToTosca = true;
737 List<String> artifacts = groupInst.getArtifacts();
738 if (artifacts == null || artifacts.isEmpty()) {
743 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
744 groupsMap.put(groupInst.getName(), toscaGroup);
749 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
751 if (groupsMap != null) {
752 log.debug("instance groups added");
753 topologyTemplate.addGroups(groupsMap);
755 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
756 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
757 component.getName());
758 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
759 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
760 component.getName());
762 if (convertNodeTemplatesRes == null) {
763 convertNodeTemplatesRes = Either.left(nodeTemplates);
765 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
766 component.getComponentType());
767 return convertNodeTemplatesRes;
770 private void handleInstanceInterfaces(
771 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
772 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
773 String instanceUniqueId,
774 Component parentComponent) {
776 Map<String, Object> interfaces;
778 // we need to handle service proxy interfaces
779 if(isComponentOfTypeServiceProxy(componentInstance)) {
780 if(MapUtils.isEmpty(componentInstanceInterfaces)
781 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
784 List<ComponentInstanceInterface> currServiceInterfaces =
785 componentInstanceInterfaces.get(instanceUniqueId);
787 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
788 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
789 .getUniqueId(), instInterface));
791 interfaces = InterfacesOperationsToscaUtil
792 .getInterfacesMap(parentComponent, tmpInterfaces, dataTypes, true, true);
796 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
797 componentInstance, instanceUniqueId);
799 nodeTemplate.setInterfaces(interfaces);
802 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
803 return Objects.nonNull(componentInstance.getOriginType())
804 && componentInstance.getOriginType().getValue().equals("Service Proxy");
807 //M3[00001] - NODE TEMPLATE INTERFACES - START
808 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
809 ComponentInstance componentInstance,
810 String instanceUniqueId) {
811 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
815 List<ComponentInstanceInterface> componentInstanceInterfaces =
816 componentInstancesInterfaces.get(instanceUniqueId);
818 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
822 Map<String, Object> interfaces = new HashMap<>();
823 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
824 interfaces.put(componentInstanceInterface.getInterfaceId(),
825 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
828 componentInstance.setInterfaces(interfaces);
832 //M3[00001] - NODE TEMPLATE INTERFACES - END
834 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
835 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
836 String instanceUniqueId, Map<String, Object> props) {
838 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
839 if (instanceInputsList != null) {
840 instanceInputsList.forEach(input -> {
842 Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
843 ? input.getValue() : input.getDefaultValue();
844 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
849 private void addPropertiesOfComponentInstance(
850 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
851 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
852 Map<String, Object> props) {
854 if (isNotEmpty(componentInstancesProperties)) {
855 componentInstancesProperties.get(instanceUniqueId)
856 // Converts and adds each value to property map
857 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
862 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
863 Component componentOfInstance, Map<String, Object> props) {
865 List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
866 if (isNotEmpty(componentProperties)) {
867 componentProperties.stream()
868 // Filters out properties with empty default values
869 .filter(prop -> isNotEmpty(prop.getDefaultValue()))
870 // Converts and adds each value to property map
871 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
872 prop::getDefaultValue));
878 * @param componentInstance
883 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
884 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
885 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
886 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
887 props.put(prop.getName(), convertedValue);
891 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
892 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
893 log.debug("Convert property or input value {} for instance {}", input.getName(),
894 componentInstance.getUniqueId());
895 String propertyType = input.getType();
896 String innerType = null;
897 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
898 innerType = input.getSchema().getProperty().getType();
900 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
904 private ToscaNodeType createNodeType(Component component) {
905 ToscaNodeType toscaNodeType = new ToscaNodeType();
906 if (ModelConverter.isAtomicComponent(component)) {
907 if (((Resource) component).getDerivedFrom() != null) {
908 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
910 toscaNodeType.setDescription(component.getDescription());
912 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
913 : "tosca.nodes.Root";
914 toscaNodeType.setDerived_from(derivedFrom);
916 return toscaNodeType;
919 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
921 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
922 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
924 List<ComponentInstance> componentInstances = container.getComponentInstances();
926 if (componentInstances == null || componentInstances.isEmpty()) {
929 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
930 List<ComponentInstance> proxyInst = componentInstances.stream()
931 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
932 .collect(Collectors.toList());
933 if (proxyInst != null && !proxyInst.isEmpty()) {
934 for (ComponentInstance inst : proxyInst) {
935 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
939 if (serviceProxyInstanceList.isEmpty()) {
942 ComponentParametersView filter = new ComponentParametersView(true);
943 filter.setIgnoreCapabilities(false);
944 filter.setIgnoreComponentInstances(false);
945 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
946 .getLatestByName("serviceProxy");
947 if (serviceProxyOrigin.isRight()) {
948 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
949 serviceProxyOrigin.right().value());
950 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
952 Component origComponent = serviceProxyOrigin.left().value();
954 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
955 Component serviceComponent = null;
956 ComponentParametersView componentParametersView = new ComponentParametersView();
957 componentParametersView.disableAll();
958 componentParametersView.setIgnoreCategories(false);
959 Either<Component, StorageOperationStatus> service = toscaOperationFacade
960 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
961 if (service.isRight()) {
962 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
964 serviceComponent = service.left().value();
967 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
968 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
971 return Either.left(nodeTypesMap);
974 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
975 ComponentInstance instance) {
976 ToscaNodeType toscaNodeType = new ToscaNodeType();
977 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
979 toscaNodeType.setDerived_from(derivedFrom);
980 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
981 if (dataTypesEither.isRight()) {
982 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
984 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
985 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
986 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
988 toscaNodeType.setCapabilities(capabilities);
990 return toscaNodeType;
993 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
994 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
995 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
997 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
998 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
999 log.debug("Failed to convert component instance requirements for the component instance {}. ",
1000 componentInstance.getName());
1001 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1003 if (!toscaRequirements.isEmpty()) {
1004 nodeTypeTemplate.setRequirements(toscaRequirements);
1006 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1007 return Either.left(nodeTypeTemplate);
1010 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1011 List<RequirementCapabilityRelDef> relations, Component originComponent,
1012 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1013 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1014 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1015 return isEmpty(filteredRelations) ||
1016 filteredRelations.stream()
1017 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1020 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1021 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1022 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1024 boolean result = true;
1025 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1026 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1027 Either<Component, StorageOperationStatus> getOriginRes = null;
1028 Optional<RequirementDefinition> reqOpt = Optional.empty();
1029 Component toOriginComponent = null;
1030 Optional<CapabilityDefinition> capOpt = Optional.empty();
1032 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1033 .findFirst().orElse(null);
1034 if (toInstance == null) {
1035 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1040 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1041 if (!reqOpt.isPresent()) {
1042 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1043 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1048 ComponentParametersView filter = new ComponentParametersView(true);
1049 filter.setIgnoreComponentInstances(false);
1050 filter.setIgnoreCapabilities(false);
1051 filter.setIgnoreGroups(false);
1052 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1053 if (getOriginRes.isRight()) {
1054 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1055 reqOpt.get().getName(), toInstance.getActualComponentUid());
1060 toOriginComponent = getOriginRes.left().value();
1061 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1062 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1063 if (!capOpt.isPresent()) {
1064 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1065 if(!capOpt.isPresent()){
1067 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1068 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1073 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1074 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1079 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1080 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1083 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1084 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1085 if (!cap.isPresent()) {
1086 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1091 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1092 List<String> reducedPath = capability.getPath();
1093 if(capability.getOwnerId() !=null){
1094 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1096 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1097 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1098 if (buildCapNameRes.isRight()) {
1100 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1101 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1104 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1105 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1106 if (buildReqNameRes.isRight()) {
1108 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1109 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1112 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1113 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1114 toscaRequirement.setNode(toInstance.getName());
1115 toscaRequirement.setCapability(buildCapNameRes.left().value());
1116 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1117 toscaRequirements.add(toscaReqMap);
1121 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1122 for(List<RequirementDefinition> reqList: reqMap.values()){
1123 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1124 if(reqOpt.isPresent()){
1128 return Optional.empty();
1132 * Allows detecting the requirement belonging to the received relationship
1133 * The detection logic is: A requirement belongs to a relationship IF 1.The
1134 * name of the requirement equals to the "requirement" field of the
1135 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1136 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1137 * toInstance equals to capabilityOwnerId of the relation
1139 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1140 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1141 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1142 requirement.getName(), reqAndRelationshipPair.getRequirement());
1145 return ModelConverter.isAtomicComponent(originComponent) ||
1146 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1149 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1150 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1153 private boolean isCvfc(Component component) {
1154 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1155 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1158 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1159 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1161 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1162 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1163 .convertSubstitutionMappingCapabilities(componentCache, component);
1164 if (toscaCapabilitiesRes.isRight()) {
1165 result = Either.right(toscaCapabilitiesRes.right().value());
1166 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1167 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1168 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1169 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1171 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1175 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1176 Map<String, DataTypeDefinition> dataTypes) {
1177 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1179 if (!toscaCapabilities.isEmpty()) {
1180 nodeType.setCapabilities(toscaCapabilities);
1182 log.debug("Finish convert Capabilities for node type");
1184 return Either.left(nodeType);
1187 private static class CustomRepresenter extends Representer {
1188 public CustomRepresenter() {
1190 // null representer is exceptional and it is stored as an instance
1192 this.nullRepresenter = new RepresentNull();
1197 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1199 if (propertyValue == null) {
1202 // skip not relevant for Tosca property
1203 if ("dependencies".equals(property.getName())) {
1206 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1208 return "_defaultp_".equals(property.getName())
1209 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1214 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1215 // remove the bean type from the output yaml (!! ...)
1216 if (!classTags.containsKey(javaBean.getClass())) {
1217 addClassTag(javaBean.getClass(), Tag.MAP);
1220 return super.representJavaBean(properties, javaBean);
1223 private class RepresentNull implements Represent {
1225 public Node representData(Object data) {
1226 // possible values are here http://yaml.org/type/null.html
1227 return representScalar(Tag.NULL, "");
1232 private static class UnsortedPropertyUtils extends PropertyUtils {
1234 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1235 throws IntrospectionException {
1236 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1237 return new LinkedHashSet<>(fields);
1241 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1242 ObjectMapper objectMapper = new ObjectMapper();
1243 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1245 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1246 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1247 interfaceAsMap.remove("empty");
1249 if(MapUtils.isNotEmpty(operations)) {
1250 interfaceAsMap.putAll(operations);
1253 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1255 return interfaceObject;