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)) {
560 if (Objects.nonNull(inputDef)) {
561 resolveDefaultPropertyValue(inputDef, mergedProperties, dataTypes);
563 toscaNodeType.setProperties(mergedProperties);
565 // Extracted to method for code reuse
566 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
569 private void resolveDefaultPropertyValue(List<InputDefinition> inputDef,
570 Map<String, ToscaProperty> mergedProperties,
571 Map<String, DataTypeDefinition> dataTypes) {
572 for (Map.Entry<String, ToscaProperty> mergedPropertyEntry : mergedProperties.entrySet()) {
573 ToscaProperty value = mergedPropertyEntry.getValue();
574 if (Objects.nonNull(value) && value.getDefaultp() instanceof Map) {
575 Map<String, String> valueAsMap = (Map<String, String>) value.getDefaultp();
576 String inputName = valueAsMap.get(ToscaFunctions.GET_INPUT.getFunctionName());
577 Optional<InputDefinition> matchedInputDefinition = inputDef.stream()
578 .filter(componentInput -> componentInput.getName().equals(inputName))
580 if (matchedInputDefinition.isPresent()) {
581 InputDefinition matchedInput = matchedInputDefinition.get();
582 Object resolvedDefaultValue = new PropertyConvertor().convertToToscaObject(matchedInput.getType(),
583 matchedInput.getDefaultValue(), matchedInput.getSchemaType(), dataTypes, false);
584 value.setDefaultp(resolvedDefaultValue);
585 mergedProperties.put(mergedPropertyEntry.getKey(), value);
591 private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
592 List<InputDefinition> inputDef,
593 Map<String, ToscaProperty> mergedProperties) {
594 for(InputDefinition input : inputDef) {
595 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
596 mergedProperties.put(input.getName(), property);
600 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
601 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
602 Map<String, DataTypeDefinition> dataTypes) {
603 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
604 if (capabilities.isRight()) {
605 return Either.right(capabilities.right().value());
607 toscaNodeType = capabilities.left().value();
608 log.debug("Capabilities converted for {}", component.getUniqueId());
610 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
612 if (requirements.isRight()) {
613 return Either.right(requirements.right().value());
615 toscaNodeType = requirements.left().value();
616 log.debug("Requirements converted for {}", component.getUniqueId());
618 String toscaResourceName;
619 switch (component.getComponentType()) {
621 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
622 .getMetadataDataDefinition()).getToscaResourceName();
625 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
626 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
629 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
630 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
633 nodeTypes.put(toscaResourceName, toscaNodeType);
634 toscaNode.setNode_types(nodeTypes);
635 log.debug("finish convert node type for {}", component.getUniqueId());
636 return Either.left(toscaNode);
639 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
641 List<ComponentInstance> componentInstances,
642 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
643 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
644 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
645 ToscaTopolgyTemplate topologyTemplate) {
647 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
648 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
649 component.getComponentType());
650 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
651 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
653 Map<String, ToscaGroupTemplate> groupsMap = null;
654 for (ComponentInstance componentInstance : componentInstances) {
655 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
656 nodeTemplate.setType(componentInstance.getToscaComponentName());
657 nodeTemplate.setDirectives(componentInstance.getDirectives());
658 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
660 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
661 .getOriginComponent(componentCache, componentInstance);
662 if (originComponentRes.isRight()) {
663 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
666 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
667 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
668 originComponentRes.left().value(), componentCache);
669 if (requirements.isRight()) {
670 convertNodeTemplatesRes = Either.right(requirements.right().value());
673 String instanceUniqueId = componentInstance.getUniqueId();
674 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
676 nodeTemplate = requirements.left().value();
678 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
680 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
681 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
682 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
684 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
687 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
688 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
689 if (capabilities.isRight()) {
690 convertNodeTemplatesRes = Either.right(capabilities.right().value());
693 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
695 nodeTemplate = capabilities.left().value();
696 Map<String, Object> props = new HashMap<>();
698 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
699 // Adds the properties of parent component to map
700 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
703 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)
704 && !isComponentOfTypeServiceProxy(componentInstance)) {
705 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
706 instanceUniqueId, props);
709 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
710 && !isComponentOfTypeServiceProxy(componentInstance)) {
711 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
714 //M3[00001] - NODE TEMPLATE INTERFACES - START
715 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
716 instanceUniqueId, component);
717 //M3[00001] - NODE TEMPLATE INTERFACES - END
718 if (props != null && !props.isEmpty()) {
719 nodeTemplate.setProperties(props);
722 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
723 if (groupInstances != null) {
724 if (groupsMap == null) {
725 groupsMap = new HashMap<>();
727 for (GroupInstance groupInst : groupInstances) {
728 boolean addToTosca = true;
730 List<String> artifacts = groupInst.getArtifacts();
731 if (artifacts == null || artifacts.isEmpty()) {
736 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
737 groupsMap.put(groupInst.getName(), toscaGroup);
742 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
744 if (groupsMap != null) {
745 log.debug("instance groups added");
746 topologyTemplate.addGroups(groupsMap);
748 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
749 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
750 component.getName());
751 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
752 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
753 component.getName());
755 if (convertNodeTemplatesRes == null) {
756 convertNodeTemplatesRes = Either.left(nodeTemplates);
758 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
759 component.getComponentType());
760 return convertNodeTemplatesRes;
763 private void handleInstanceInterfaces(
764 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
765 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
766 String instanceUniqueId,
767 Component parentComponent) {
769 Map<String, Object> interfaces;
771 // we need to handle service proxy interfaces
772 if(isComponentOfTypeServiceProxy(componentInstance)) {
773 if(MapUtils.isEmpty(componentInstanceInterfaces)
774 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
777 List<ComponentInstanceInterface> currServiceInterfaces =
778 componentInstanceInterfaces.get(instanceUniqueId);
780 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
781 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
782 .getUniqueId(), instInterface));
784 interfaces = InterfacesOperationsToscaUtil
785 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
789 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
790 componentInstance, instanceUniqueId);
792 nodeTemplate.setInterfaces(interfaces);
795 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
796 return Objects.nonNull(componentInstance.getOriginType())
797 && componentInstance.getOriginType().getValue().equals("Service Proxy");
800 //M3[00001] - NODE TEMPLATE INTERFACES - START
801 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
802 ComponentInstance componentInstance,
803 String instanceUniqueId) {
804 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
808 List<ComponentInstanceInterface> componentInstanceInterfaces =
809 componentInstancesInterfaces.get(instanceUniqueId);
811 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
815 Map<String, Object> interfaces = new HashMap<>();
816 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
817 interfaces.put(componentInstanceInterface.getInterfaceId(),
818 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
821 componentInstance.setInterfaces(interfaces);
826 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
827 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
828 String instanceUniqueId, Map<String, Object> props) {
830 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
831 if (instanceInputsList != null) {
832 instanceInputsList.forEach(input -> {
834 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
835 ? input.getValue() : input.getDefaultValue();
836 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
841 private void addPropertiesOfComponentInstance(
842 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
843 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
844 Map<String, Object> props) {
846 if (isNotEmpty(componentInstancesProperties)) {
847 componentInstancesProperties.get(instanceUniqueId)
848 // Converts and adds each value to property map
849 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
854 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
855 Component componentOfInstance, Map<String, Object> props) {
857 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
858 if (isNotEmpty(componentProperties)) {
859 componentProperties.stream()
860 // Filters out properties with empty default values
861 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
862 // Converts and adds each value to property map
863 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
864 prop::getDefaultValue));
870 * @param componentInstance
875 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
876 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
877 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
878 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
879 props.put(prop.getName(), convertedValue);
883 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
884 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
885 log.debug("Convert property or input value {} for instance {}", input.getName(),
886 componentInstance.getUniqueId());
887 String propertyType = input.getType();
888 String innerType = null;
889 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
890 innerType = input.getSchema().getProperty().getType();
892 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
896 private ToscaNodeType createNodeType(Component component) {
897 ToscaNodeType toscaNodeType = new ToscaNodeType();
898 if (ModelConverter.isAtomicComponent(component)) {
899 if (((Resource) component).getDerivedFrom() != null) {
900 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
902 toscaNodeType.setDescription(component.getDescription());
904 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
905 : "tosca.nodes.Root";
906 toscaNodeType.setDerived_from(derivedFrom);
908 return toscaNodeType;
911 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
913 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
914 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
916 List<ComponentInstance> componentInstances = container.getComponentInstances();
918 if (componentInstances == null || componentInstances.isEmpty()) {
921 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
922 List<ComponentInstance> proxyInst = componentInstances.stream()
923 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
924 .collect(Collectors.toList());
925 if (proxyInst != null && !proxyInst.isEmpty()) {
926 for (ComponentInstance inst : proxyInst) {
927 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
931 if (serviceProxyInstanceList.isEmpty()) {
934 ComponentParametersView filter = new ComponentParametersView(true);
935 filter.setIgnoreCapabilities(false);
936 filter.setIgnoreComponentInstances(false);
937 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
938 .getLatestByName("serviceProxy");
939 if (serviceProxyOrigin.isRight()) {
940 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
941 serviceProxyOrigin.right().value());
942 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
944 Component origComponent = serviceProxyOrigin.left().value();
946 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
947 Component serviceComponent = null;
948 ComponentParametersView componentParametersView = new ComponentParametersView();
949 componentParametersView.disableAll();
950 componentParametersView.setIgnoreCategories(false);
951 Either<Component, StorageOperationStatus> service = toscaOperationFacade
952 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
953 if (service.isRight()) {
954 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
956 serviceComponent = service.left().value();
959 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
960 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
963 return Either.left(nodeTypesMap);
966 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
967 ComponentInstance instance) {
968 ToscaNodeType toscaNodeType = new ToscaNodeType();
969 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
971 toscaNodeType.setDerived_from(derivedFrom);
972 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
973 if (dataTypesEither.isRight()) {
974 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
976 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
977 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
978 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
980 toscaNodeType.setCapabilities(capabilities);
982 return toscaNodeType;
985 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
986 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
987 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
989 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
990 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
991 log.debug("Failed to convert component instance requirements for the component instance {}. ",
992 componentInstance.getName());
993 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
995 if (!toscaRequirements.isEmpty()) {
996 nodeTypeTemplate.setRequirements(toscaRequirements);
998 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
999 return Either.left(nodeTypeTemplate);
1002 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1003 List<RequirementCapabilityRelDef> relations, Component originComponent,
1004 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1005 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1006 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1007 return isEmpty(filteredRelations) ||
1008 filteredRelations.stream()
1009 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1012 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1013 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1014 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1016 boolean result = true;
1017 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1018 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1019 Either<Component, StorageOperationStatus> getOriginRes = null;
1020 Optional<RequirementDefinition> reqOpt = Optional.empty();
1021 Component toOriginComponent = null;
1022 Optional<CapabilityDefinition> capOpt = Optional.empty();
1024 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1025 .findFirst().orElse(null);
1026 if (toInstance == null) {
1027 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1032 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1033 if (!reqOpt.isPresent()) {
1034 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1035 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1040 ComponentParametersView filter = new ComponentParametersView(true);
1041 filter.setIgnoreComponentInstances(false);
1042 filter.setIgnoreCapabilities(false);
1043 filter.setIgnoreGroups(false);
1044 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1045 if (getOriginRes.isRight()) {
1046 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1047 reqOpt.get().getName(), toInstance.getActualComponentUid());
1052 toOriginComponent = getOriginRes.left().value();
1053 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1054 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1055 if (!capOpt.isPresent()) {
1056 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1057 if(!capOpt.isPresent()){
1059 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1060 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1065 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1066 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1071 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1072 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1075 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1076 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1077 if (!cap.isPresent()) {
1078 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1083 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1084 List<String> reducedPath = capability.getPath();
1085 if(capability.getOwnerId() !=null){
1086 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1088 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1089 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1090 if (buildCapNameRes.isRight()) {
1092 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1093 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1096 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1097 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1098 if (buildReqNameRes.isRight()) {
1100 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1101 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1104 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1105 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1106 toscaRequirement.setNode(toInstance.getName());
1107 toscaRequirement.setCapability(buildCapNameRes.left().value());
1108 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1109 toscaRequirements.add(toscaReqMap);
1113 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1114 for(List<RequirementDefinition> reqList: reqMap.values()){
1115 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1116 if(reqOpt.isPresent()){
1120 return Optional.empty();
1124 * Allows detecting the requirement belonging to the received relationship
1125 * The detection logic is: A requirement belongs to a relationship IF 1.The
1126 * name of the requirement equals to the "requirement" field of the
1127 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1128 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1129 * toInstance equals to capabilityOwnerId of the relation
1131 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1132 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1133 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1134 requirement.getName(), reqAndRelationshipPair.getRequirement());
1137 return ModelConverter.isAtomicComponent(originComponent) ||
1138 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1141 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1142 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1145 private boolean isCvfc(Component component) {
1146 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1147 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1150 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1151 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1153 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1154 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1155 .convertSubstitutionMappingCapabilities(componentCache, component);
1156 if (toscaCapabilitiesRes.isRight()) {
1157 result = Either.right(toscaCapabilitiesRes.right().value());
1158 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1159 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1160 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1161 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1163 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1167 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1168 Map<String, DataTypeDefinition> dataTypes) {
1169 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1171 if (!toscaCapabilities.isEmpty()) {
1172 nodeType.setCapabilities(toscaCapabilities);
1174 log.debug("Finish convert Capabilities for node type");
1176 return Either.left(nodeType);
1180 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1181 if (inNodeFilter == null){
1184 NodeFilter nodeFilter = new NodeFilter();
1186 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1187 inNodeFilter.getCapabilities();
1189 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1191 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1192 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1194 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1195 copyNodeFilterProperties(origProperties, propertiesCopy);
1197 if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1198 nodeFilter.setCapabilities(capabilitiesCopy);
1201 if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1202 nodeFilter.setProperties(propertiesCopy);
1205 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1208 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1213 private Object cloneToscaId(Object toscaId) {
1214 return Objects.isNull(toscaId) ? null
1215 : cloneObjectFromYml(toscaId, toscaId.getClass());
1219 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1220 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1221 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1223 private void copyNodeFilterCapabilitiesTemplate(
1224 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1225 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1226 if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1227 origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1230 for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1231 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1232 CapabilityFilter capabilityFilter = new CapabilityFilter();
1233 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1234 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1235 capabilityFilter.setProperties(propertiesCopy);
1236 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1237 capabilitiesCopy.add(capabilityFilterCopyMap);
1241 private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1242 String listAsString = yamlUtil.objectToYaml(propertyList);
1243 return yamlUtil.yamlToObject(listAsString, List.class);
1247 private void copyNodeFilterProperties(
1248 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1249 List<Map<String, List<Object>>> propertiesCopy) {
1250 if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1251 origProperties.isEmpty()) {
1254 for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1255 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1256 for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1257 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1258 if (propertyMapCopy.containsKey(propertyDataDefinition.getName())){
1259 propertyMapCopy.get(propertyDataDefinition.getName()).add(propertyValObj);
1261 if (propertyDataDefinition.getName() != null) {
1262 List propsList =new ArrayList();
1263 propsList.add(propertyValObj);
1264 propertyMapCopy.put(propertyDataDefinition.getName(), propsList);
1266 propertyMapCopy.putAll(propertyValObj);
1270 propertiesCopy.add(propertyMapCopy);
1275 private static class CustomRepresenter extends Representer {
1276 public CustomRepresenter() {
1278 // null representer is exceptional and it is stored as an instance
1280 this.nullRepresenter = new RepresentNull();
1285 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1287 if (propertyValue == null) {
1290 // skip not relevant for Tosca property
1291 if ("dependencies".equals(property.getName())) {
1294 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1296 return "_defaultp_".equals(property.getName())
1297 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1302 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1303 // remove the bean type from the output yaml (!! ...)
1304 if (!classTags.containsKey(javaBean.getClass())) {
1305 addClassTag(javaBean.getClass(), Tag.MAP);
1308 return super.representJavaBean(properties, javaBean);
1311 private class RepresentNull implements Represent {
1313 public Node representData(Object data) {
1314 // possible values are here http://yaml.org/type/null.html
1315 return representScalar(Tag.NULL, "");
1320 private static class UnsortedPropertyUtils extends PropertyUtils {
1322 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1323 throws IntrospectionException {
1324 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1325 return new LinkedHashSet<>(fields);
1329 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1330 ObjectMapper objectMapper = new ObjectMapper();
1331 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1333 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1334 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1335 interfaceAsMap.remove("empty");
1337 if(MapUtils.isNotEmpty(operations)) {
1338 interfaceAsMap.putAll(operations);
1341 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1343 return interfaceObject;