2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.tosca;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
25 import fj.data.Either;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.apache.commons.lang3.tuple.ImmutableTriple;
31 import org.apache.commons.lang3.tuple.Triple;
32 import org.onap.sdc.tosca.services.YamlUtil;
33 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
34 import org.openecomp.sdc.be.config.ConfigurationManager;
35 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
36 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
37 import org.openecomp.sdc.be.datatypes.elements.*;
38 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
39 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
40 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
41 import org.openecomp.sdc.be.model.*;
42 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
43 import org.openecomp.sdc.be.model.category.CategoryDefinition;
44 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
45 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
46 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
47 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
48 import org.openecomp.sdc.be.model.tosca.ToscaFunctions;
49 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
50 import org.openecomp.sdc.be.tosca.model.*;
51 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
52 import org.openecomp.sdc.be.tosca.utils.InputConverter;
53 import org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil;
54 import org.openecomp.sdc.common.log.wrappers.Logger;
55 import org.openecomp.sdc.externalupload.utils.ServiceUtils;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.yaml.snakeyaml.DumperOptions;
58 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
59 import org.yaml.snakeyaml.Yaml;
60 import org.yaml.snakeyaml.introspector.BeanAccess;
61 import org.yaml.snakeyaml.introspector.Property;
62 import org.yaml.snakeyaml.introspector.PropertyUtils;
63 import org.yaml.snakeyaml.nodes.MappingNode;
64 import org.yaml.snakeyaml.nodes.Node;
65 import org.yaml.snakeyaml.nodes.NodeTuple;
66 import org.yaml.snakeyaml.nodes.Tag;
67 import org.yaml.snakeyaml.representer.Represent;
68 import org.yaml.snakeyaml.representer.Representer;
70 import java.beans.IntrospectionException;
72 import java.util.Map.Entry;
73 import java.util.function.Supplier;
74 import java.util.stream.Collectors;
76 import static org.apache.commons.collections.CollectionUtils.isEmpty;
77 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
78 import static org.apache.commons.collections.MapUtils.isNotEmpty;
79 import static org.apache.commons.lang.StringUtils.isNotEmpty;
80 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
81 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
83 @org.springframework.stereotype.Component("tosca-export-handler")
84 public class ToscaExportHandler {
86 private ApplicationDataTypeCache dataTypeCache;
87 private ToscaOperationFacade toscaOperationFacade;
88 private CapabilityRequirementConverter capabilityRequirementConverter;
89 private PolicyExportParser policyExportParser;
90 private GroupExportParser groupExportParser;
91 private PropertyConvertor propertyConvertor;
92 private InputConverter inputConverter;
93 private InterfaceLifecycleOperation interfaceLifecycleOperation;
96 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
97 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
98 GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
99 this.dataTypeCache = dataTypeCache;
100 this.toscaOperationFacade = toscaOperationFacade;
101 this.capabilityRequirementConverter = capabilityRequirementConverter;
102 this.policyExportParser = policyExportParser;
103 this.groupExportParser = groupExportParser;
104 this.propertyConvertor = PropertyConvertor.getInstance();
105 this.inputConverter = inputConverter;
106 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
110 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
112 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
113 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
114 private static final String IMPORTS_FILE_KEY = "file";
115 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
116 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
117 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
118 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
119 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
120 .getConfigurationManager().getConfiguration().getDefaultImports();
121 private static YamlUtil yamlUtil = new YamlUtil();
123 public ToscaExportHandler(){}
125 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
127 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
128 if (toscaTemplateRes.isRight()) {
129 return Either.right(toscaTemplateRes.right().value());
132 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
133 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
134 return Either.left(toscaRepresentation);
137 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
138 boolean isAssociatedComponent) {
139 if (null == DEFAULT_IMPORTS) {
140 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
141 return Either.right(ToscaError.GENERAL_ERROR);
144 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
145 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
146 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
147 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
148 toscaTemplate, nodeTypes, isAssociatedComponent);
149 if (toscaTemplateRes.isRight()) {
150 return Either.right(toscaTemplateRes.right().value());
153 toscaTemplate = toscaTemplateRes.left().value();
154 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
155 return Either.left(toscaRepresentation);
158 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
159 CustomRepresenter representer = new CustomRepresenter();
160 DumperOptions options = new DumperOptions();
161 options.setAllowReadOnlyProperties(false);
162 options.setPrettyFlow(true);
164 options.setDefaultFlowStyle(FlowStyle.FLOW);
165 options.setCanonical(false);
167 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
169 representer.setPropertyUtils(new UnsortedPropertyUtils());
170 Yaml yaml = new Yaml(representer, options);
172 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
174 StringBuilder sb = new StringBuilder();
175 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
176 sb.append(yamlAsString);
177 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
179 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
180 toscaRepresentation.setMainYaml(sb.toString());
181 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
183 return toscaRepresentation;
186 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
187 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
188 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
190 if (fillImports.isRight()) {
191 return Either.right(fillImports.right().value());
193 return Either.left(fillImports.left().value().left);
196 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
197 if (null == DEFAULT_IMPORTS) {
198 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
199 return Either.right(ToscaError.GENERAL_ERROR);
202 log.trace("start tosca export for {}", component.getUniqueId());
203 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
205 toscaTemplate.setMetadata(convertMetadata(component));
206 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
207 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
208 if (ModelConverter.isAtomicComponent(component)) {
209 log.trace("convert component as node type");
210 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
212 log.trace("convert component as topology template");
213 return convertToscaTemplate(component, toscaTemplate);
218 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
220 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
222 if (importsRes.isRight()) {
223 return Either.right(importsRes.right().value());
225 toscaNode = importsRes.left().value().left;
226 Map<String, Component> componentCache = importsRes.left().value().right;
227 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
228 if (nodeTypesMapEither.isRight()) {
229 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
230 nodeTypesMapEither.right().value());
231 return Either.right(nodeTypesMapEither.right().value());
233 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
234 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
235 toscaNode.setNode_types(nodeTypesMap);
239 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
240 if (dataTypesEither.isRight()) {
241 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
242 return Either.right(ToscaError.GENERAL_ERROR);
244 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
245 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
246 List<InputDefinition> inputDef = component.getInputs();
247 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
249 if (!inputs.isEmpty()) {
250 topologyTemplate.setInputs(inputs);
253 List<ComponentInstance> componentInstances = component.getComponentInstances();
254 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
255 component.getComponentInstancesProperties();
256 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
257 component.getComponentInstancesInterfaces();
258 if (componentInstances != null && !componentInstances.isEmpty()) {
260 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
261 convertNodeTemplates(component, componentInstances,
262 componentInstancesProperties, componentInstanceInterfaces,
263 componentCache, dataTypes, topologyTemplate);
264 if (nodeTemplates.isRight()) {
265 return Either.right(nodeTemplates.right().value());
267 log.debug("node templates converted");
269 topologyTemplate.setNode_templates(nodeTemplates.left().value());
273 addGroupsToTopologyTemplate(component, topologyTemplate);
276 addPoliciesToTopologyTemplate(component, topologyTemplate);
277 } catch (SdcResourceNotFoundException e) {
278 log.debug("Fail to add policies to topology template:",e);
279 return Either.right(ToscaError.GENERAL_ERROR);
283 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
284 String toscaResourceName;
285 switch (component.getComponentType()) {
287 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
288 .getMetadataDataDefinition()).getToscaResourceName();
291 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
292 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
295 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
296 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
298 substitutionMapping.setNode_type(toscaResourceName);
300 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
301 if (capabilities.isRight()) {
302 return Either.right(capabilities.right().value());
304 substitutionMapping = capabilities.left().value();
306 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
307 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
308 if (requirements.isRight()) {
309 return Either.right(requirements.right().value());
311 substitutionMapping = requirements.left().value();
313 topologyTemplate.setSubstitution_mappings(substitutionMapping);
315 toscaNode.setTopology_template(topologyTemplate);
316 return Either.left(toscaNode);
319 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
322 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
324 topologyTemplate.addGroups(groups);
328 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
329 throws SdcResourceNotFoundException {
330 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
331 if(policies!= null) {
332 topologyTemplate.addPolicies(policies);
336 private ToscaMetadata convertMetadata(Component component) {
337 return convertMetadata(component, false, null);
340 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
341 ComponentInstance componentInstance) {
342 ToscaMetadata toscaMetadata = new ToscaMetadata();
343 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
344 toscaMetadata.setUUID(component.getUUID());
345 toscaMetadata.setDescription(component.getDescription());
346 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
348 List<CategoryDefinition> categories = component.getCategories();
349 CategoryDefinition categoryDefinition = categories.get(0);
350 toscaMetadata.setCategory(categoryDefinition.getName());
353 toscaMetadata.setVersion(component.getVersion());
354 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
355 if (componentInstance.getSourceModelInvariant() != null
356 && !componentInstance.getSourceModelInvariant().isEmpty()) {
357 toscaMetadata.setVersion(componentInstance.getComponentVersion());
358 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
359 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
360 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
361 toscaMetadata.setName(
362 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
363 toscaMetadata.setDescription(componentInstance.getDescription());
367 switch (component.getComponentType()) {
369 Resource resource = (Resource) component;
371 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
372 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
374 toscaMetadata.setType(resource.getResourceType().name());
376 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
377 toscaMetadata.setResourceVendor(resource.getVendorName());
378 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
379 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
382 Service service = (Service) component;
383 toscaMetadata.setType(component.getComponentType().getValue());
384 toscaMetadata.setServiceType(service.getServiceType());
385 toscaMetadata.setServiceRole(service.getServiceRole());
386 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
387 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
390 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
391 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
392 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
396 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
398 return toscaMetadata;
401 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
402 if (service.getInstantiationType() != null) {
403 toscaMetadata.setInstantiationType(service.getInstantiationType());
406 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
410 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
411 ToscaTemplate toscaTemplate) {
413 if (null == DEFAULT_IMPORTS) {
414 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
415 return Either.right(ToscaError.GENERAL_ERROR);
417 Map<String, Component> componentCache = new HashMap<>();
419 if (!ModelConverter.isAtomicComponent(component)) {
420 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
421 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
423 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
425 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
426 if (isNotEmpty(toscaArtifacts)) {
427 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
428 if(artifactDefinition != null) {
429 Map<String, Map<String, String>> importsListMember = new HashMap<>();
430 Map<String, String> interfaceFiles = new HashMap<>();
431 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
432 StringBuilder keyNameBuilder = new StringBuilder();
433 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
434 .append(component.getName()).append("-interface");
435 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
436 additionalImports.add(importsListMember);
439 List<ComponentInstance> componentInstances = component.getComponentInstances();
440 if (componentInstances != null && !componentInstances.isEmpty()) {
441 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
443 toscaTemplate.setDependencies(dependecies);
444 toscaTemplate.setImports(additionalImports);
446 log.debug("currently imports supported for VF and service only");
448 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
451 private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
452 List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
453 Map<String, String> files = new HashMap<>();
454 Map<String, Map<String, String>> importsListMember = new HashMap<>();
455 StringBuilder keyNameBuilder;
457 Component componentRI = componentCache.get(ci.getComponentUid());
458 if (componentRI == null) {
459 // all resource must be only once!
460 Either<Component, StorageOperationStatus> resource = toscaOperationFacade
461 .getToscaFullElement(ci.getComponentUid());
462 if ((resource.isRight()) && (log.isDebugEnabled())) {
463 log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
467 Component fetchedComponent = resource.left().value();
468 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
470 if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
471 Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
472 .getToscaFullElement(ci.getSourceModelUid());
473 if (sourceService.isRight() && (log.isDebugEnabled())) {
474 log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
476 Component fetchedSource = sourceService.left().value();
477 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
480 componentRI = fetchedComponent;
482 Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
483 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
484 if (artifactDefinition != null) {
485 String artifactName = artifactDefinition.getArtifactName();
486 files.put(IMPORTS_FILE_KEY, artifactName);
487 keyNameBuilder = new StringBuilder();
488 keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
489 keyNameBuilder.append("-");
490 keyNameBuilder.append(ci.getComponentName());
491 importsListMember.put(keyNameBuilder.toString(), files);
492 imports.add(importsListMember);
493 dependecies.add(new ImmutableTriple<>(artifactName,
494 artifactDefinition.getEsId(), fetchedComponent));
496 if (!ModelConverter.isAtomicComponent(componentRI)) {
497 importsListMember = new HashMap<>();
498 Map<String, String> interfaceFiles = new HashMap<>();
499 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
500 keyNameBuilder.append("-interface");
501 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
502 imports.add(importsListMember);
508 public static String getInterfaceFilename(String artifactName) {
509 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
512 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
513 Map<String, ToscaNodeType> nodeTypes) {
514 return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
517 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
518 Component component, ToscaTemplate toscaNode,
519 Map<String, ToscaNodeType> nodeTypes,
520 boolean isAssociatedComponent) {
521 log.debug("start convert node type for {}", component.getUniqueId());
522 ToscaNodeType toscaNodeType = createNodeType(component);
524 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
525 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
526 if(lifecycleTypeEither.isRight()){
527 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
528 return Either.right(ToscaError.GENERAL_ERROR);
530 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
533 .map(InterfaceDataDefinition::getType)
534 .collect(Collectors.toList());
535 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
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();
545 List<InputDefinition> inputDef = component.getInputs();
546 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
547 addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
548 if (inputDef != null) {
549 addInputsToProperties(dataTypes, inputDef, mergedProperties);
552 if(CollectionUtils.isNotEmpty(component.getProperties())) {
553 List<PropertyDefinition> properties = component.getProperties();
554 mergedProperties = properties.stream().collect(Collectors.toMap(
555 PropertyDataDefinition::getName,
556 property -> propertyConvertor.convertProperty(dataTypes, property,
557 PropertyConvertor.PropertyType.PROPERTY)));
559 if (MapUtils.isNotEmpty(mergedProperties) && Objects.nonNull(inputDef)) {
560 resolveDefaultPropertyValue(inputDef, mergedProperties, dataTypes);
561 toscaNodeType.setProperties(mergedProperties);
563 // Extracted to method for code reuse
564 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
567 private void resolveDefaultPropertyValue(List<InputDefinition> inputDef,
568 Map<String, ToscaProperty> mergedProperties,
569 Map<String, DataTypeDefinition> dataTypes) {
570 for (Map.Entry<String, ToscaProperty> mergedPropertyEntry : mergedProperties.entrySet()) {
571 ToscaProperty value = mergedPropertyEntry.getValue();
572 if (Objects.nonNull(value) && value.getDefaultp() instanceof Map) {
573 Map<String, String> valueAsMap = (Map<String, String>) value.getDefaultp();
574 String inputName = valueAsMap.get(ToscaFunctions.GET_INPUT.getFunctionName());
575 Optional<InputDefinition> matchedInputDefinition = inputDef.stream()
576 .filter(componentInput -> componentInput.getName().equals(inputName))
578 if (matchedInputDefinition.isPresent()) {
579 InputDefinition matchedInput = matchedInputDefinition.get();
580 Object resolvedDefaultValue = new PropertyConvertor().convertToToscaObject(matchedInput.getType(),
581 matchedInput.getDefaultValue(), matchedInput.getSchemaType(), dataTypes, false);
582 value.setDefaultp(resolvedDefaultValue);
583 mergedProperties.put(mergedPropertyEntry.getKey(), value);
589 private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
590 List<InputDefinition> inputDef,
591 Map<String, ToscaProperty> mergedProperties) {
592 for(InputDefinition input : inputDef) {
593 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
594 mergedProperties.put(input.getName(), property);
598 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
599 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
600 Map<String, DataTypeDefinition> dataTypes) {
601 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
602 if (capabilities.isRight()) {
603 return Either.right(capabilities.right().value());
605 toscaNodeType = capabilities.left().value();
606 log.debug("Capabilities converted for {}", component.getUniqueId());
608 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
610 if (requirements.isRight()) {
611 return Either.right(requirements.right().value());
613 toscaNodeType = requirements.left().value();
614 log.debug("Requirements converted for {}", component.getUniqueId());
616 String toscaResourceName;
617 switch (component.getComponentType()) {
619 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
620 .getMetadataDataDefinition()).getToscaResourceName();
623 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
624 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
627 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
628 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
631 nodeTypes.put(toscaResourceName, toscaNodeType);
632 toscaNode.setNode_types(nodeTypes);
633 log.debug("finish convert node type for {}", component.getUniqueId());
634 return Either.left(toscaNode);
637 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
639 List<ComponentInstance> componentInstances,
640 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
641 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
642 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
643 ToscaTopolgyTemplate topologyTemplate) {
645 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
646 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
647 component.getComponentType());
648 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
649 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
651 Map<String, ToscaGroupTemplate> groupsMap = null;
652 for (ComponentInstance componentInstance : componentInstances) {
653 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
654 nodeTemplate.setType(componentInstance.getToscaComponentName());
655 nodeTemplate.setDirectives(componentInstance.getDirectives());
656 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
658 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
659 .getOriginComponent(componentCache, componentInstance);
660 if (originComponentRes.isRight()) {
661 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
664 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
665 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
666 originComponentRes.left().value(), componentCache);
667 if (requirements.isRight()) {
668 convertNodeTemplatesRes = Either.right(requirements.right().value());
671 String instanceUniqueId = componentInstance.getUniqueId();
672 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
674 nodeTemplate = requirements.left().value();
676 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
678 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
679 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
680 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
682 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
685 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
686 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
687 if (capabilities.isRight()) {
688 convertNodeTemplatesRes = Either.right(capabilities.right().value());
691 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
693 nodeTemplate = capabilities.left().value();
694 Map<String, Object> props = new HashMap<>();
696 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
697 // Adds the properties of parent component to map
698 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
701 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)
702 && !isComponentOfTypeServiceProxy(componentInstance)) {
703 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
704 instanceUniqueId, props);
707 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
708 && !isComponentOfTypeServiceProxy(componentInstance)) {
709 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
712 //M3[00001] - NODE TEMPLATE INTERFACES - START
713 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
714 instanceUniqueId, component);
715 //M3[00001] - NODE TEMPLATE INTERFACES - END
716 if (props != null && !props.isEmpty()) {
717 nodeTemplate.setProperties(props);
720 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
721 if (groupInstances != null) {
722 if (groupsMap == null) {
723 groupsMap = new HashMap<>();
725 for (GroupInstance groupInst : groupInstances) {
726 boolean addToTosca = true;
728 List<String> artifacts = groupInst.getArtifacts();
729 if (artifacts == null || artifacts.isEmpty()) {
734 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
735 groupsMap.put(groupInst.getName(), toscaGroup);
740 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
742 if (groupsMap != null) {
743 log.debug("instance groups added");
744 topologyTemplate.addGroups(groupsMap);
746 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
747 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
748 component.getName());
749 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
750 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
751 component.getName());
753 if (convertNodeTemplatesRes == null) {
754 convertNodeTemplatesRes = Either.left(nodeTemplates);
756 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
757 component.getComponentType());
758 return convertNodeTemplatesRes;
761 private void handleInstanceInterfaces(
762 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
763 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
764 String instanceUniqueId,
765 Component parentComponent) {
767 Map<String, Object> interfaces;
769 // we need to handle service proxy interfaces
770 if(isComponentOfTypeServiceProxy(componentInstance)) {
771 if(MapUtils.isEmpty(componentInstanceInterfaces)
772 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
775 List<ComponentInstanceInterface> currServiceInterfaces =
776 componentInstanceInterfaces.get(instanceUniqueId);
778 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
779 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
780 .getUniqueId(), instInterface));
782 interfaces = InterfacesOperationsToscaUtil
783 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
787 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
788 componentInstance, instanceUniqueId);
790 nodeTemplate.setInterfaces(interfaces);
793 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
794 return Objects.nonNull(componentInstance.getOriginType())
795 && componentInstance.getOriginType().getValue().equals("Service Proxy");
798 //M3[00001] - NODE TEMPLATE INTERFACES - START
799 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
800 ComponentInstance componentInstance,
801 String instanceUniqueId) {
802 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
806 List<ComponentInstanceInterface> componentInstanceInterfaces =
807 componentInstancesInterfaces.get(instanceUniqueId);
809 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
813 Map<String, Object> interfaces = new HashMap<>();
814 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
815 interfaces.put(componentInstanceInterface.getInterfaceId(),
816 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
819 componentInstance.setInterfaces(interfaces);
824 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
825 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
826 String instanceUniqueId, Map<String, Object> props) {
828 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
829 if (instanceInputsList != null) {
830 instanceInputsList.forEach(input -> {
832 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
833 ? input.getValue() : input.getDefaultValue();
834 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
839 private void addPropertiesOfComponentInstance(
840 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
841 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
842 Map<String, Object> props) {
844 if (isNotEmpty(componentInstancesProperties)) {
845 componentInstancesProperties.get(instanceUniqueId)
846 // Converts and adds each value to property map
847 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
852 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
853 Component componentOfInstance, Map<String, Object> props) {
855 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
856 if (isNotEmpty(componentProperties)) {
857 componentProperties.stream()
858 // Filters out properties with empty default values
859 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
860 // Converts and adds each value to property map
861 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
862 prop::getDefaultValue));
868 * @param componentInstance
873 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
874 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
875 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
876 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
877 props.put(prop.getName(), convertedValue);
881 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
882 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
883 log.debug("Convert property or input value {} for instance {}", input.getName(),
884 componentInstance.getUniqueId());
885 String propertyType = input.getType();
886 String innerType = null;
887 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
888 innerType = input.getSchema().getProperty().getType();
890 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
894 private ToscaNodeType createNodeType(Component component) {
895 ToscaNodeType toscaNodeType = new ToscaNodeType();
896 if (ModelConverter.isAtomicComponent(component)) {
897 if (((Resource) component).getDerivedFrom() != null) {
898 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
900 toscaNodeType.setDescription(component.getDescription());
902 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
903 : "tosca.nodes.Root";
904 toscaNodeType.setDerived_from(derivedFrom);
906 return toscaNodeType;
909 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
911 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
912 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
914 List<ComponentInstance> componentInstances = container.getComponentInstances();
916 if (componentInstances == null || componentInstances.isEmpty()) {
919 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
920 List<ComponentInstance> proxyInst = componentInstances.stream()
921 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
922 .collect(Collectors.toList());
923 if (proxyInst != null && !proxyInst.isEmpty()) {
924 for (ComponentInstance inst : proxyInst) {
925 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
929 if (serviceProxyInstanceList.isEmpty()) {
932 ComponentParametersView filter = new ComponentParametersView(true);
933 filter.setIgnoreCapabilities(false);
934 filter.setIgnoreComponentInstances(false);
935 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
936 .getLatestByName("serviceProxy");
937 if (serviceProxyOrigin.isRight()) {
938 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
939 serviceProxyOrigin.right().value());
940 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
942 Component origComponent = serviceProxyOrigin.left().value();
944 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
945 Component serviceComponent = null;
946 ComponentParametersView componentParametersView = new ComponentParametersView();
947 componentParametersView.disableAll();
948 componentParametersView.setIgnoreCategories(false);
949 Either<Component, StorageOperationStatus> service = toscaOperationFacade
950 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
951 if (service.isRight()) {
952 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
954 serviceComponent = service.left().value();
957 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
958 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
961 return Either.left(nodeTypesMap);
964 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
965 ComponentInstance instance) {
966 ToscaNodeType toscaNodeType = new ToscaNodeType();
967 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
969 toscaNodeType.setDerived_from(derivedFrom);
970 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
971 if (dataTypesEither.isRight()) {
972 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
974 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
975 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
976 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
978 toscaNodeType.setCapabilities(capabilities);
980 return toscaNodeType;
983 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
984 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
985 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
987 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
988 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
989 log.debug("Failed to convert component instance requirements for the component instance {}. ",
990 componentInstance.getName());
991 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
993 if (!toscaRequirements.isEmpty()) {
994 nodeTypeTemplate.setRequirements(toscaRequirements);
996 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
997 return Either.left(nodeTypeTemplate);
1000 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1001 List<RequirementCapabilityRelDef> relations, Component originComponent,
1002 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1003 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1004 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1005 return isEmpty(filteredRelations) ||
1006 filteredRelations.stream()
1007 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1010 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1011 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1012 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1014 boolean result = true;
1015 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1016 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1017 Either<Component, StorageOperationStatus> getOriginRes = null;
1018 Optional<RequirementDefinition> reqOpt = Optional.empty();
1019 Component toOriginComponent = null;
1020 Optional<CapabilityDefinition> capOpt = Optional.empty();
1022 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1023 .findFirst().orElse(null);
1024 if (toInstance == null) {
1025 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1030 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1031 if (!reqOpt.isPresent()) {
1032 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1033 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1038 ComponentParametersView filter = new ComponentParametersView(true);
1039 filter.setIgnoreComponentInstances(false);
1040 filter.setIgnoreCapabilities(false);
1041 filter.setIgnoreGroups(false);
1042 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1043 if (getOriginRes.isRight()) {
1044 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1045 reqOpt.get().getName(), toInstance.getActualComponentUid());
1050 toOriginComponent = getOriginRes.left().value();
1051 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1052 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1053 if (!capOpt.isPresent()) {
1054 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1055 if(!capOpt.isPresent()){
1057 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1058 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1063 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1064 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1069 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1070 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1073 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1074 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1075 if (!cap.isPresent()) {
1076 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1081 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1082 List<String> reducedPath = capability.getPath();
1083 if(capability.getOwnerId() !=null){
1084 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1086 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1087 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1088 if (buildCapNameRes.isRight()) {
1090 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1091 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1094 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1095 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1096 if (buildReqNameRes.isRight()) {
1098 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1099 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1102 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1103 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1104 toscaRequirement.setNode(toInstance.getName());
1105 toscaRequirement.setCapability(buildCapNameRes.left().value());
1106 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1107 toscaRequirements.add(toscaReqMap);
1111 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1112 for(List<RequirementDefinition> reqList: reqMap.values()){
1113 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1114 if(reqOpt.isPresent()){
1118 return Optional.empty();
1122 * Allows detecting the requirement belonging to the received relationship
1123 * The detection logic is: A requirement belongs to a relationship IF 1.The
1124 * name of the requirement equals to the "requirement" field of the
1125 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1126 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1127 * toInstance equals to capabilityOwnerId of the relation
1129 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1130 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1131 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1132 requirement.getName(), reqAndRelationshipPair.getRequirement());
1135 return ModelConverter.isAtomicComponent(originComponent) ||
1136 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1139 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1140 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1143 private boolean isCvfc(Component component) {
1144 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1145 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1148 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1149 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1151 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1152 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1153 .convertSubstitutionMappingCapabilities(componentCache, component);
1154 if (toscaCapabilitiesRes.isRight()) {
1155 result = Either.right(toscaCapabilitiesRes.right().value());
1156 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1157 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1158 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1159 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1161 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1165 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1166 Map<String, DataTypeDefinition> dataTypes) {
1167 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1169 if (!toscaCapabilities.isEmpty()) {
1170 nodeType.setCapabilities(toscaCapabilities);
1172 log.debug("Finish convert Capabilities for node type");
1174 return Either.left(nodeType);
1178 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1179 if (inNodeFilter == null){
1182 NodeFilter nodeFilter = new NodeFilter();
1184 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1185 inNodeFilter.getCapabilities();
1187 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1189 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1190 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1192 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1193 copyNodeFilterProperties(origProperties, propertiesCopy);
1195 if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1196 nodeFilter.setCapabilities(capabilitiesCopy);
1199 if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1200 nodeFilter.setProperties(propertiesCopy);
1203 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1206 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1211 private Object cloneToscaId(Object toscaId) {
1212 return Objects.isNull(toscaId) ? null
1213 : cloneObjectFromYml(toscaId, toscaId.getClass());
1217 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1218 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1219 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1221 private void copyNodeFilterCapabilitiesTemplate(
1222 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1223 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1224 if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1225 origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1228 for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1229 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1230 CapabilityFilter capabilityFilter = new CapabilityFilter();
1231 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1232 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1233 capabilityFilter.setProperties(propertiesCopy);
1234 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1235 capabilitiesCopy.add(capabilityFilterCopyMap);
1239 private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1240 String listAsString = yamlUtil.objectToYaml(propertyList);
1241 return yamlUtil.yamlToObject(listAsString, List.class);
1245 private void copyNodeFilterProperties(
1246 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1247 List<Map<String, List<Object>>> propertiesCopy) {
1248 if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1249 origProperties.isEmpty()) {
1252 for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1253 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1254 for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1255 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1256 if (propertyMapCopy.containsKey(propertyDataDefinition.getName())){
1257 propertyMapCopy.get(propertyDataDefinition.getName()).add(propertyValObj);
1259 if (propertyDataDefinition.getName() != null) {
1260 List propsList =new ArrayList();
1261 propsList.add(propertyValObj);
1262 propertyMapCopy.put(propertyDataDefinition.getName(), propsList);
1264 propertyMapCopy.putAll(propertyValObj);
1268 propertiesCopy.add(propertyMapCopy);
1273 private static class CustomRepresenter extends Representer {
1274 public CustomRepresenter() {
1276 // null representer is exceptional and it is stored as an instance
1278 this.nullRepresenter = new RepresentNull();
1283 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1285 if (propertyValue == null) {
1288 // skip not relevant for Tosca property
1289 if ("dependencies".equals(property.getName())) {
1292 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1294 return "_defaultp_".equals(property.getName())
1295 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1300 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1301 // remove the bean type from the output yaml (!! ...)
1302 if (!classTags.containsKey(javaBean.getClass())) {
1303 addClassTag(javaBean.getClass(), Tag.MAP);
1306 return super.representJavaBean(properties, javaBean);
1309 private class RepresentNull implements Represent {
1311 public Node representData(Object data) {
1312 // possible values are here http://yaml.org/type/null.html
1313 return representScalar(Tag.NULL, "");
1318 private static class UnsortedPropertyUtils extends PropertyUtils {
1320 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1321 throws IntrospectionException {
1322 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1323 return new LinkedHashSet<>(fields);
1327 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1328 ObjectMapper objectMapper = new ObjectMapper();
1329 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1331 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1332 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1333 interfaceAsMap.remove("empty");
1335 if(MapUtils.isNotEmpty(operations)) {
1336 interfaceAsMap.putAll(operations);
1339 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1341 return interfaceObject;