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.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement;
80 import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement;
82 @org.springframework.stereotype.Component("tosca-export-handler")
83 public class ToscaExportHandler {
85 private ApplicationDataTypeCache dataTypeCache;
86 private ToscaOperationFacade toscaOperationFacade;
87 private CapabilityRequirementConverter capabilityRequirementConverter;
88 private PolicyExportParser policyExportParser;
89 private GroupExportParser groupExportParser;
90 private PropertyConvertor propertyConvertor;
91 private InputConverter inputConverter;
92 private InterfaceLifecycleOperation interfaceLifecycleOperation;
95 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
96 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
97 GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) {
98 this.dataTypeCache = dataTypeCache;
99 this.toscaOperationFacade = toscaOperationFacade;
100 this.capabilityRequirementConverter = capabilityRequirementConverter;
101 this.policyExportParser = policyExportParser;
102 this.groupExportParser = groupExportParser;
103 this.propertyConvertor = PropertyConvertor.getInstance();
104 this.inputConverter = inputConverter;
105 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
109 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
111 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
112 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
113 private static final String IMPORTS_FILE_KEY = "file";
114 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
115 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
116 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
117 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
118 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
119 .getConfigurationManager().getConfiguration().getDefaultImports();
120 private static YamlUtil yamlUtil = new YamlUtil();
122 public ToscaExportHandler(){}
124 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
126 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
127 if (toscaTemplateRes.isRight()) {
128 return Either.right(toscaTemplateRes.right().value());
131 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
132 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
133 return Either.left(toscaRepresentation);
136 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
137 boolean isAssociatedComponent) {
138 if (null == DEFAULT_IMPORTS) {
139 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
140 return Either.right(ToscaError.GENERAL_ERROR);
143 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
144 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
145 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
146 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
147 toscaTemplate, nodeTypes, isAssociatedComponent);
148 if (toscaTemplateRes.isRight()) {
149 return Either.right(toscaTemplateRes.right().value());
152 toscaTemplate = toscaTemplateRes.left().value();
153 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
154 return Either.left(toscaRepresentation);
157 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
158 CustomRepresenter representer = new CustomRepresenter();
159 DumperOptions options = new DumperOptions();
160 options.setAllowReadOnlyProperties(false);
161 options.setPrettyFlow(true);
163 options.setDefaultFlowStyle(FlowStyle.FLOW);
164 options.setCanonical(false);
166 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
168 representer.setPropertyUtils(new UnsortedPropertyUtils());
169 Yaml yaml = new Yaml(representer, options);
171 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
173 StringBuilder sb = new StringBuilder();
174 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
175 sb.append(yamlAsString);
176 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
178 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
179 toscaRepresentation.setMainYaml(sb.toString());
180 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
182 return toscaRepresentation;
185 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
186 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
187 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
189 if (fillImports.isRight()) {
190 return Either.right(fillImports.right().value());
192 return Either.left(fillImports.left().value().left);
195 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
196 if (null == DEFAULT_IMPORTS) {
197 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
198 return Either.right(ToscaError.GENERAL_ERROR);
201 log.trace("start tosca export for {}", component.getUniqueId());
202 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
204 toscaTemplate.setMetadata(convertMetadata(component));
205 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
206 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
207 if (ModelConverter.isAtomicComponent(component)) {
208 log.trace("convert component as node type");
209 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
211 log.trace("convert component as topology template");
212 return convertToscaTemplate(component, toscaTemplate);
217 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
219 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
221 if (importsRes.isRight()) {
222 return Either.right(importsRes.right().value());
224 toscaNode = importsRes.left().value().left;
225 Map<String, Component> componentCache = importsRes.left().value().right;
226 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
227 if (nodeTypesMapEither.isRight()) {
228 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
229 nodeTypesMapEither.right().value());
230 return Either.right(nodeTypesMapEither.right().value());
232 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
233 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
234 toscaNode.setNode_types(nodeTypesMap);
238 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
239 if (dataTypesEither.isRight()) {
240 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
241 return Either.right(ToscaError.GENERAL_ERROR);
243 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
244 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
245 List<InputDefinition> inputDef = component.getInputs();
246 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
248 if (!inputs.isEmpty()) {
249 topologyTemplate.setInputs(inputs);
252 List<ComponentInstance> componentInstances = component.getComponentInstances();
253 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
254 component.getComponentInstancesProperties();
255 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
256 component.getComponentInstancesInterfaces();
257 if (componentInstances != null && !componentInstances.isEmpty()) {
259 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
260 convertNodeTemplates(component, componentInstances,
261 componentInstancesProperties, componentInstanceInterfaces,
262 componentCache, dataTypes, topologyTemplate);
263 if (nodeTemplates.isRight()) {
264 return Either.right(nodeTemplates.right().value());
266 log.debug("node templates converted");
268 topologyTemplate.setNode_templates(nodeTemplates.left().value());
272 addGroupsToTopologyTemplate(component, topologyTemplate);
275 addPoliciesToTopologyTemplate(component, topologyTemplate);
276 } catch (SdcResourceNotFoundException e) {
277 log.debug("Fail to add policies to topology template:",e);
278 return Either.right(ToscaError.GENERAL_ERROR);
282 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
283 String toscaResourceName;
284 switch (component.getComponentType()) {
286 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
287 .getMetadataDataDefinition()).getToscaResourceName();
290 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
291 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
294 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
295 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
297 substitutionMapping.setNode_type(toscaResourceName);
299 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
300 if (capabilities.isRight()) {
301 return Either.right(capabilities.right().value());
303 substitutionMapping = capabilities.left().value();
305 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
306 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
307 if (requirements.isRight()) {
308 return Either.right(requirements.right().value());
310 substitutionMapping = requirements.left().value();
312 topologyTemplate.setSubstitution_mappings(substitutionMapping);
314 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);
564 /* convert private data_types */
565 List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
566 if (CollectionUtils.isNotEmpty(privateDataTypes) ) {
567 Map<String, ToscaDataType> toscaDataTypeMap = new HashMap<>();
568 for (DataTypeDefinition dataType: privateDataTypes) {
569 log.debug("Emitting private data type: component.name={} dataType.name={}",
570 component.getNormalizedName(), dataType.getName());
571 ToscaDataType toscaDataType = new ToscaDataType();
572 toscaDataType.setDerived_from(dataType.getDerivedFromName());
573 toscaDataType.setDescription(dataType.getDescription());
574 toscaDataType.setVersion(dataType.getVersion());
575 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
576 toscaDataType.setProperties(dataType.getProperties().stream()
577 .collect(Collectors.toMap(
579 s -> propertyConvertor.convertProperty(dataTypes, s, PropertyConvertor.PropertyType.PROPERTY)
582 toscaDataTypeMap.put(dataType.getName(), toscaDataType);
584 toscaNode.setData_types(toscaDataTypeMap);
587 // Extracted to method for code reuse
588 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
591 private void resolveDefaultPropertyValue(List<InputDefinition> inputDef,
592 Map<String, ToscaProperty> mergedProperties,
593 Map<String, DataTypeDefinition> dataTypes) {
594 for (Map.Entry<String, ToscaProperty> mergedPropertyEntry : mergedProperties.entrySet()) {
595 ToscaProperty value = mergedPropertyEntry.getValue();
596 if (Objects.nonNull(value) && value.getDefaultp() instanceof Map) {
597 Map<String, Object> valueAsMap = (Map<String, Object>) value.getDefaultp();
598 Object getInputValue = valueAsMap.get(ToscaFunctions.GET_INPUT.getFunctionName());
599 if (getInputValue instanceof String) {
600 String inputName = (String)getInputValue;
601 Optional<InputDefinition> matchedInputDefinition = inputDef.stream()
602 .filter(componentInput -> componentInput.getName().equals(inputName))
604 if (matchedInputDefinition.isPresent()) {
605 InputDefinition matchedInput = matchedInputDefinition.get();
606 Object resolvedDefaultValue = new PropertyConvertor().convertToToscaObject(matchedInput.getType(),
607 matchedInput.getDefaultValue(), matchedInput.getSchemaType(), dataTypes, false);
608 value.setDefaultp(resolvedDefaultValue);
609 mergedProperties.put(mergedPropertyEntry.getKey(), value);
611 } else if (getInputValue instanceof List) {
612 // new get_input syntax to refer to sub-element (introduced from TOSCA v1.3)
613 // e.g. get_input: [input_name, INDEX, inner_property]
614 // currently resolving default value for the syntax is not supported
615 log.debug("#resolveDefaultPropertyValue: ignore get_input list syntax. propname={}, val={}",
616 mergedPropertyEntry.getKey(), getInputValue);
618 // Ignore unknown get_input syntax
619 log.debug("#resolveDefaultPropertyValue: ignore unknown get_input syntax. propname={}, val={}",
620 mergedPropertyEntry.getKey(), getInputValue);
626 private void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
627 List<InputDefinition> inputDef,
628 Map<String, ToscaProperty> mergedProperties) {
629 for(InputDefinition input : inputDef) {
630 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
631 mergedProperties.put(input.getName(), property);
635 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
636 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
637 Map<String, DataTypeDefinition> dataTypes) {
638 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
639 if (capabilities.isRight()) {
640 return Either.right(capabilities.right().value());
642 toscaNodeType = capabilities.left().value();
643 log.debug("Capabilities converted for {}", component.getUniqueId());
645 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
647 if (requirements.isRight()) {
648 return Either.right(requirements.right().value());
650 toscaNodeType = requirements.left().value();
651 log.debug("Requirements converted for {}", component.getUniqueId());
653 String toscaResourceName;
654 switch (component.getComponentType()) {
656 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
657 .getMetadataDataDefinition()).getToscaResourceName();
660 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
661 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
664 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
665 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
668 nodeTypes.put(toscaResourceName, toscaNodeType);
669 toscaNode.setNode_types(nodeTypes);
670 log.debug("finish convert node type for {}", component.getUniqueId());
671 return Either.left(toscaNode);
674 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
676 List<ComponentInstance> componentInstances,
677 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
678 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
679 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
680 ToscaTopolgyTemplate topologyTemplate) {
682 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
683 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
684 component.getComponentType());
685 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
686 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
688 Map<String, ToscaGroupTemplate> groupsMap = null;
689 for (ComponentInstance componentInstance : componentInstances) {
690 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
691 nodeTemplate.setType(componentInstance.getToscaComponentName());
692 nodeTemplate.setDirectives(componentInstance.getDirectives());
693 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
695 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
696 .getOriginComponent(componentCache, componentInstance);
697 if (originComponentRes.isRight()) {
698 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
701 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
702 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
703 originComponentRes.left().value(), componentCache);
704 if (requirements.isRight()) {
705 convertNodeTemplatesRes = Either.right(requirements.right().value());
708 String instanceUniqueId = componentInstance.getUniqueId();
709 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
711 nodeTemplate = requirements.left().value();
713 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
715 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
716 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
717 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
719 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
722 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
723 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
724 if (capabilities.isRight()) {
725 convertNodeTemplatesRes = Either.right(capabilities.right().value());
728 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
730 nodeTemplate = capabilities.left().value();
731 Map<String, Object> props = new HashMap<>();
733 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
734 // Adds the properties of parent component to map
735 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
738 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)
739 && !isComponentOfTypeServiceProxy(componentInstance)) {
740 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes,
741 instanceUniqueId, props);
744 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
745 && !isComponentOfTypeServiceProxy(componentInstance)) {
746 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
749 //M3[00001] - NODE TEMPLATE INTERFACES - START
750 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
751 instanceUniqueId, component);
752 //M3[00001] - NODE TEMPLATE INTERFACES - END
753 if (props != null && !props.isEmpty()) {
754 nodeTemplate.setProperties(props);
757 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
758 if (groupInstances != null) {
759 if (groupsMap == null) {
760 groupsMap = new HashMap<>();
762 for (GroupInstance groupInst : groupInstances) {
763 boolean addToTosca = true;
765 List<String> artifacts = groupInst.getArtifacts();
766 if (artifacts == null || artifacts.isEmpty()) {
771 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
772 groupsMap.put(groupInst.getName(), toscaGroup);
777 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
779 if (groupsMap != null) {
780 log.debug("instance groups added");
781 topologyTemplate.addGroups(groupsMap);
783 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
784 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
785 component.getName());
786 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
787 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
788 component.getName());
790 if (convertNodeTemplatesRes == null) {
791 convertNodeTemplatesRes = Either.left(nodeTemplates);
793 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
794 component.getComponentType());
795 return convertNodeTemplatesRes;
798 private void handleInstanceInterfaces(
799 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
800 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
801 String instanceUniqueId,
802 Component parentComponent) {
804 Map<String, Object> interfaces;
806 // we need to handle service proxy interfaces
807 if(isComponentOfTypeServiceProxy(componentInstance)) {
808 if(MapUtils.isEmpty(componentInstanceInterfaces)
809 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
812 List<ComponentInstanceInterface> currServiceInterfaces =
813 componentInstanceInterfaces.get(instanceUniqueId);
815 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
816 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
817 .getUniqueId(), instInterface));
819 interfaces = InterfacesOperationsToscaUtil
820 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
824 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
825 componentInstance, instanceUniqueId);
827 nodeTemplate.setInterfaces(interfaces);
830 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
831 return Objects.nonNull(componentInstance.getOriginType())
832 && componentInstance.getOriginType().getValue().equals("Service Proxy");
835 //M3[00001] - NODE TEMPLATE INTERFACES - START
836 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
837 ComponentInstance componentInstance,
838 String instanceUniqueId) {
839 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
843 List<ComponentInstanceInterface> componentInstanceInterfaces =
844 componentInstancesInterfaces.get(instanceUniqueId);
846 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
850 Map<String, Object> interfaces = new HashMap<>();
851 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
852 interfaces.put(componentInstanceInterface.getInterfaceId(),
853 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
856 componentInstance.setInterfaces(interfaces);
861 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
862 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
863 String instanceUniqueId, Map<String, Object> props) {
865 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
866 if (instanceInputsList != null) {
867 instanceInputsList.forEach(input -> {
869 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
870 ? input.getValue() : input.getDefaultValue();
871 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
876 private void addPropertiesOfComponentInstance(
877 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
878 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
879 Map<String, Object> props) {
881 if (isNotEmpty(componentInstancesProperties)) {
882 componentInstancesProperties.get(instanceUniqueId)
883 // Converts and adds each value to property map
884 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
889 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
890 Component componentOfInstance, Map<String, Object> props) {
892 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
893 if (isNotEmpty(componentProperties)) {
894 componentProperties.stream()
895 // Filters out properties with empty default values
896 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
897 // Converts and adds each value to property map
898 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
899 prop::getDefaultValue));
905 * @param componentInstance
910 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
911 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
912 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
913 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
914 props.put(prop.getName(), convertedValue);
918 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
919 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
920 log.debug("Convert property or input value {} for instance {}", input.getName(),
921 componentInstance.getUniqueId());
922 String propertyType = input.getType();
923 String innerType = null;
924 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
925 innerType = input.getSchema().getProperty().getType();
927 return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType,
931 private ToscaNodeType createNodeType(Component component) {
932 ToscaNodeType toscaNodeType = new ToscaNodeType();
933 if (ModelConverter.isAtomicComponent(component)) {
934 if (((Resource) component).getDerivedFrom() != null) {
935 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
937 toscaNodeType.setDescription(component.getDescription());
939 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
940 : "tosca.nodes.Root";
941 toscaNodeType.setDerived_from(derivedFrom);
943 return toscaNodeType;
946 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
948 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
949 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
951 List<ComponentInstance> componentInstances = container.getComponentInstances();
953 if (componentInstances == null || componentInstances.isEmpty()) {
956 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
957 List<ComponentInstance> proxyInst = componentInstances.stream()
958 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
959 .collect(Collectors.toList());
960 if (proxyInst != null && !proxyInst.isEmpty()) {
961 for (ComponentInstance inst : proxyInst) {
962 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
966 if (serviceProxyInstanceList.isEmpty()) {
969 ComponentParametersView filter = new ComponentParametersView(true);
970 filter.setIgnoreCapabilities(false);
971 filter.setIgnoreComponentInstances(false);
972 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
973 .getLatestByName("serviceProxy");
974 if (serviceProxyOrigin.isRight()) {
975 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
976 serviceProxyOrigin.right().value());
977 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
979 Component origComponent = serviceProxyOrigin.left().value();
981 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
982 Component serviceComponent = null;
983 ComponentParametersView componentParametersView = new ComponentParametersView();
984 componentParametersView.disableAll();
985 componentParametersView.setIgnoreCategories(false);
986 Either<Component, StorageOperationStatus> service = toscaOperationFacade
987 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
988 if (service.isRight()) {
989 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
991 serviceComponent = service.left().value();
994 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
995 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
998 return Either.left(nodeTypesMap);
1001 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
1002 ComponentInstance instance) {
1003 ToscaNodeType toscaNodeType = new ToscaNodeType();
1004 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1006 toscaNodeType.setDerived_from(derivedFrom);
1007 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
1008 if (dataTypesEither.isRight()) {
1009 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1011 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1012 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1013 .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
1015 toscaNodeType.setCapabilities(capabilities);
1017 return toscaNodeType;
1020 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1021 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
1022 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
1024 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1025 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
1026 log.debug("Failed to convert component instance requirements for the component instance {}. ",
1027 componentInstance.getName());
1028 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1030 if (!toscaRequirements.isEmpty()) {
1031 nodeTypeTemplate.setRequirements(toscaRequirements);
1033 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1034 return Either.left(nodeTypeTemplate);
1037 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1038 List<RequirementCapabilityRelDef> relations, Component originComponent,
1039 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1040 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1041 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1042 return isEmpty(filteredRelations) ||
1043 filteredRelations.stream()
1044 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1047 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1048 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1049 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1051 boolean result = true;
1052 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1053 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1054 Either<Component, StorageOperationStatus> getOriginRes = null;
1055 Optional<RequirementDefinition> reqOpt = Optional.empty();
1056 Component toOriginComponent = null;
1057 Optional<CapabilityDefinition> capOpt = Optional.empty();
1059 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1060 .findFirst().orElse(null);
1061 if (toInstance == null) {
1062 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1067 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1068 if (!reqOpt.isPresent()) {
1069 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1070 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1075 ComponentParametersView filter = new ComponentParametersView(true);
1076 filter.setIgnoreComponentInstances(false);
1077 filter.setIgnoreCapabilities(false);
1078 filter.setIgnoreGroups(false);
1079 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1080 if (getOriginRes.isRight()) {
1081 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1082 reqOpt.get().getName(), toInstance.getActualComponentUid());
1087 toOriginComponent = getOriginRes.left().value();
1088 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1089 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1090 if (!capOpt.isPresent()) {
1091 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1092 if(!capOpt.isPresent()){
1094 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1095 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1100 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1101 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1106 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1107 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1110 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1111 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1112 if (!cap.isPresent()) {
1113 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1118 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1119 List<String> reducedPath = capability.getPath();
1120 if(capability.getOwnerId() !=null){
1121 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1123 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1124 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1125 if (buildCapNameRes.isRight()) {
1127 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1128 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1131 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1132 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1133 if (buildReqNameRes.isRight()) {
1135 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1136 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1139 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1140 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1141 toscaRequirement.setNode(toInstance.getName());
1142 toscaRequirement.setCapability(buildCapNameRes.left().value());
1143 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1144 toscaRequirements.add(toscaReqMap);
1148 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1149 for(List<RequirementDefinition> reqList: reqMap.values()){
1150 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1151 if(reqOpt.isPresent()){
1155 return Optional.empty();
1159 * Allows detecting the requirement belonging to the received relationship
1160 * The detection logic is: A requirement belongs to a relationship IF 1.The
1161 * name of the requirement equals to the "requirement" field of the
1162 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1163 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1164 * toInstance equals to capabilityOwnerId of the relation
1166 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1167 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1168 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1169 requirement.getName(), reqAndRelationshipPair.getRequirement());
1172 return ModelConverter.isAtomicComponent(originComponent) ||
1173 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1176 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1177 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
1180 private boolean isCvfc(Component component) {
1181 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1182 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1185 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1186 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1188 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1189 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1190 .convertSubstitutionMappingCapabilities(componentCache, component);
1191 if (toscaCapabilitiesRes.isRight()) {
1192 result = Either.right(toscaCapabilitiesRes.right().value());
1193 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1194 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1195 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1196 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1198 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1202 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1203 Map<String, DataTypeDefinition> dataTypes) {
1204 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1206 if (!toscaCapabilities.isEmpty()) {
1207 nodeType.setCapabilities(toscaCapabilities);
1209 log.debug("Finish convert Capabilities for node type");
1211 return Either.left(nodeType);
1215 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1216 if (inNodeFilter == null){
1219 NodeFilter nodeFilter = new NodeFilter();
1221 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1222 inNodeFilter.getCapabilities();
1224 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1226 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1227 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1229 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1230 copyNodeFilterProperties(origProperties, propertiesCopy);
1232 if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1233 nodeFilter.setCapabilities(capabilitiesCopy);
1236 if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1237 nodeFilter.setProperties(propertiesCopy);
1240 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1243 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1248 private Object cloneToscaId(Object toscaId) {
1249 return Objects.isNull(toscaId) ? null
1250 : cloneObjectFromYml(toscaId, toscaId.getClass());
1254 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1255 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1256 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1258 private void copyNodeFilterCapabilitiesTemplate(
1259 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1260 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1261 if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1262 origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1265 for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1266 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1267 CapabilityFilter capabilityFilter = new CapabilityFilter();
1268 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1269 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1270 capabilityFilter.setProperties(propertiesCopy);
1271 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1272 capabilitiesCopy.add(capabilityFilterCopyMap);
1276 private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1277 String listAsString = yamlUtil.objectToYaml(propertyList);
1278 return yamlUtil.yamlToObject(listAsString, List.class);
1282 private void copyNodeFilterProperties(
1283 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1284 List<Map<String, List<Object>>> propertiesCopy) {
1285 if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1286 origProperties.isEmpty()) {
1289 for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1290 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1291 for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1292 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1293 if (propertyMapCopy.containsKey(propertyDataDefinition.getName())){
1294 propertyMapCopy.get(propertyDataDefinition.getName()).add(propertyValObj);
1296 if (propertyDataDefinition.getName() != null) {
1297 List propsList =new ArrayList();
1298 propsList.add(propertyValObj);
1299 propertyMapCopy.put(propertyDataDefinition.getName(), propsList);
1301 propertyMapCopy.putAll(propertyValObj);
1305 propertiesCopy.add(propertyMapCopy);
1310 private static class CustomRepresenter extends Representer {
1311 public CustomRepresenter() {
1313 // null representer is exceptional and it is stored as an instance
1315 this.nullRepresenter = new RepresentNull();
1320 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1322 if (propertyValue == null) {
1325 // skip not relevant for Tosca property
1326 if ("dependencies".equals(property.getName())) {
1329 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1331 return "_defaultp_".equals(property.getName())
1332 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1337 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1338 // remove the bean type from the output yaml (!! ...)
1339 if (!classTags.containsKey(javaBean.getClass())) {
1340 addClassTag(javaBean.getClass(), Tag.MAP);
1343 return super.representJavaBean(properties, javaBean);
1346 private class RepresentNull implements Represent {
1348 public Node representData(Object data) {
1349 // possible values are here http://yaml.org/type/null.html
1350 return representScalar(Tag.NULL, "");
1355 private static class UnsortedPropertyUtils extends PropertyUtils {
1357 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1358 throws IntrospectionException {
1359 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1360 return new LinkedHashSet<>(fields);
1364 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1365 ObjectMapper objectMapper = new ObjectMapper();
1366 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1368 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1369 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1370 interfaceAsMap.remove("empty");
1372 if(MapUtils.isNotEmpty(operations)) {
1373 interfaceAsMap.putAll(operations);
1376 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1378 return interfaceObject;