2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.tosca;
23 import static org.apache.commons.collections.CollectionUtils.isEmpty;
24 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
25 import static org.apache.commons.collections.MapUtils.isNotEmpty;
26 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.resolvePropertyValueFromInput;
27 import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.addInterfaceTypeElement;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.fasterxml.jackson.databind.SerializationFeature;
31 import fj.data.Either;
32 import java.beans.IntrospectionException;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.LinkedHashSet;
37 import java.util.List;
39 import java.util.Map.Entry;
40 import java.util.Objects;
41 import java.util.Optional;
43 import java.util.function.Supplier;
44 import java.util.stream.Collectors;
45 import org.apache.commons.collections.CollectionUtils;
46 import org.apache.commons.collections.MapUtils;
47 import org.apache.commons.lang.StringUtils;
48 import org.apache.commons.lang3.tuple.ImmutablePair;
49 import org.apache.commons.lang3.tuple.ImmutableTriple;
50 import org.apache.commons.lang3.tuple.Triple;
51 import org.onap.sdc.tosca.services.YamlUtil;
52 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
53 import org.openecomp.sdc.be.config.ConfigurationManager;
54 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
55 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition;
61 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition;
62 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.CapabilityDefinition;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentInstanceInput;
71 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
72 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
73 import org.openecomp.sdc.be.model.ComponentParametersView;
74 import org.openecomp.sdc.be.model.DataTypeDefinition;
75 import org.openecomp.sdc.be.model.GroupInstance;
76 import org.openecomp.sdc.be.model.InputDefinition;
77 import org.openecomp.sdc.be.model.InterfaceDefinition;
78 import org.openecomp.sdc.be.model.PropertyDefinition;
79 import org.openecomp.sdc.be.model.RelationshipInfo;
80 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
81 import org.openecomp.sdc.be.model.RequirementDefinition;
82 import org.openecomp.sdc.be.model.Resource;
83 import org.openecomp.sdc.be.model.Service;
84 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
85 import org.openecomp.sdc.be.model.category.CategoryDefinition;
86 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
87 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
88 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
89 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
90 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
91 import org.openecomp.sdc.be.tosca.model.CapabilityFilter;
92 import org.openecomp.sdc.be.tosca.model.NodeFilter;
93 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
94 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
95 import org.openecomp.sdc.be.tosca.model.ToscaDataType;
96 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
97 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
98 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
99 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
100 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
101 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
102 import org.openecomp.sdc.be.tosca.model.ToscaRequirement;
103 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
104 import org.openecomp.sdc.be.tosca.model.ToscaTemplateArtifact;
105 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
106 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
107 import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
108 import org.openecomp.sdc.be.tosca.utils.InputConverter;
109 import org.openecomp.sdc.common.log.wrappers.Logger;
110 import org.openecomp.sdc.externalupload.utils.ServiceUtils;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.yaml.snakeyaml.DumperOptions;
113 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
114 import org.yaml.snakeyaml.Yaml;
115 import org.yaml.snakeyaml.introspector.BeanAccess;
116 import org.yaml.snakeyaml.introspector.Property;
117 import org.yaml.snakeyaml.introspector.PropertyUtils;
118 import org.yaml.snakeyaml.nodes.MappingNode;
119 import org.yaml.snakeyaml.nodes.Node;
120 import org.yaml.snakeyaml.nodes.NodeTuple;
121 import org.yaml.snakeyaml.nodes.Tag;
122 import org.yaml.snakeyaml.representer.Represent;
123 import org.yaml.snakeyaml.representer.Representer;
125 @org.springframework.stereotype.Component("tosca-export-handler")
126 public class ToscaExportHandler {
128 private ApplicationDataTypeCache dataTypeCache;
129 private ToscaOperationFacade toscaOperationFacade;
130 private CapabilityRequirementConverter capabilityRequirementConverter;
131 private PolicyExportParser policyExportParser;
132 private GroupExportParser groupExportParser;
133 private PropertyConvertor propertyConvertor;
134 private InputConverter inputConverter;
135 private InterfaceLifecycleOperation interfaceLifecycleOperation;
136 private InterfacesOperationsConverter interfacesOperationsConverter;
139 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
140 CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser,
141 GroupExportParser groupExportParser, PropertyConvertor propertyConvertor, InputConverter inputConverter,
142 InterfaceLifecycleOperation interfaceLifecycleOperation,
143 InterfacesOperationsConverter interfacesOperationsConverter) {
144 this.dataTypeCache = dataTypeCache;
145 this.toscaOperationFacade = toscaOperationFacade;
146 this.capabilityRequirementConverter = capabilityRequirementConverter;
147 this.policyExportParser = policyExportParser;
148 this.groupExportParser = groupExportParser;
149 this.propertyConvertor = propertyConvertor;
150 this.inputConverter = inputConverter;
151 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
152 this.interfacesOperationsConverter = interfacesOperationsConverter;
156 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
158 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
159 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
160 private static final String IMPORTS_FILE_KEY = "file";
161 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
162 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
163 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
164 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
165 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
166 .getConfigurationManager().getConfiguration().getDefaultImports();
167 private static final String NATIVE_ROOT = "tosca.nodes.Root";
168 private static YamlUtil yamlUtil = new YamlUtil();
170 public ToscaExportHandler(){}
172 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
174 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
175 if (toscaTemplateRes.isRight()) {
176 return Either.right(toscaTemplateRes.right().value());
179 ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
180 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
181 return Either.left(toscaRepresentation);
184 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component,
185 boolean isAssociatedComponent) {
186 if (null == DEFAULT_IMPORTS) {
187 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
188 return Either.right(ToscaError.GENERAL_ERROR);
191 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
192 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
193 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
194 Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component,
195 toscaTemplate, nodeTypes, isAssociatedComponent);
196 if (toscaTemplateRes.isRight()) {
197 return Either.right(toscaTemplateRes.right().value());
200 toscaTemplate = toscaTemplateRes.left().value();
201 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
202 return Either.left(toscaRepresentation);
205 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
206 CustomRepresenter representer = new CustomRepresenter();
207 DumperOptions options = new DumperOptions();
208 options.setAllowReadOnlyProperties(false);
209 options.setPrettyFlow(true);
211 options.setDefaultFlowStyle(FlowStyle.FLOW);
212 options.setCanonical(false);
214 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
216 representer.setPropertyUtils(new UnsortedPropertyUtils());
217 Yaml yaml = new Yaml(representer, options);
219 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
221 StringBuilder sb = new StringBuilder();
222 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
223 sb.append(yamlAsString);
224 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
226 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
227 toscaRepresentation.setMainYaml(sb.toString());
228 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
230 return toscaRepresentation;
233 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
234 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
235 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
237 if (fillImports.isRight()) {
238 return Either.right(fillImports.right().value());
240 return Either.left(fillImports.left().value().left);
243 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
244 if (null == DEFAULT_IMPORTS) {
245 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
246 return Either.right(ToscaError.GENERAL_ERROR);
249 log.trace("start tosca export for {}", component.getUniqueId());
250 ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
252 toscaTemplate.setMetadata(convertMetadata(component));
253 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
254 Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
255 if (ModelConverter.isAtomicComponent(component)) {
256 log.trace("convert component as node type");
257 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
259 log.trace("convert component as topology template");
260 return convertToscaTemplate(component, toscaTemplate);
265 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
267 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
269 if (importsRes.isRight()) {
270 return Either.right(importsRes.right().value());
272 toscaNode = importsRes.left().value().left;
273 Map<String, Component> componentCache = importsRes.left().value().right;
274 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache,
276 if (nodeTypesMapEither.isRight()) {
277 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
278 nodeTypesMapEither.right().value());
279 return Either.right(nodeTypesMapEither.right().value());
281 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
282 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
283 toscaNode.setNode_types(nodeTypesMap);
286 Either<Map<String, Object>, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component);
287 if (proxyInterfaceTypesEither.isRight()) {
288 log.debug("Failed to populate service proxy local interface types in tosca, error {}",
289 nodeTypesMapEither.right().value());
290 return Either.right(proxyInterfaceTypesEither.right().value());
292 Map<String, Object> proxyInterfaceTypes = proxyInterfaceTypesEither.left().value();
293 if (MapUtils.isNotEmpty(proxyInterfaceTypes)) {
294 toscaNode.setInterface_types(proxyInterfaceTypes);
297 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
298 if (dataTypesEither.isRight()) {
299 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
300 return Either.right(ToscaError.GENERAL_ERROR);
302 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
303 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
304 List<InputDefinition> inputDef = component.getInputs();
305 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
307 if (!inputs.isEmpty()) {
308 topologyTemplate.setInputs(inputs);
311 List<ComponentInstance> componentInstances = component.getComponentInstances();
312 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
313 component.getComponentInstancesProperties();
314 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
315 component.getComponentInstancesInterfaces();
316 if (componentInstances != null && !componentInstances.isEmpty()) {
318 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
319 convertNodeTemplates(component, componentInstances,
320 componentInstancesProperties, componentInstanceInterfaces,
321 componentCache, dataTypes, topologyTemplate);
322 if (nodeTemplates.isRight()) {
323 return Either.right(nodeTemplates.right().value());
325 log.debug("node templates converted");
327 topologyTemplate.setNode_templates(nodeTemplates.left().value());
331 addGroupsToTopologyTemplate(component, topologyTemplate);
334 addPoliciesToTopologyTemplate(component, topologyTemplate);
335 } catch (SdcResourceNotFoundException e) {
336 log.debug("Fail to add policies to topology template:",e);
337 return Either.right(ToscaError.GENERAL_ERROR);
341 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
342 String toscaResourceName;
343 switch (component.getComponentType()) {
345 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
346 .getMetadataDataDefinition()).getToscaResourceName();
349 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
350 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
353 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
354 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
356 substitutionMapping.setNode_type(toscaResourceName);
358 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
359 if (capabilities.isRight()) {
360 return Either.right(capabilities.right().value());
362 substitutionMapping = capabilities.left().value();
364 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
365 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
366 if (requirements.isRight()) {
367 return Either.right(requirements.right().value());
369 substitutionMapping = requirements.left().value();
371 topologyTemplate.setSubstitution_mappings(substitutionMapping);
373 toscaNode.setTopology_template(topologyTemplate);
375 return Either.left(toscaNode);
378 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
379 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
381 topologyTemplate.addGroups(groups);
385 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
386 throws SdcResourceNotFoundException {
387 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
388 if(policies!= null) {
389 topologyTemplate.addPolicies(policies);
393 private ToscaMetadata convertMetadata(Component component) {
394 return convertMetadata(component, false, null);
397 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
398 ComponentInstance componentInstance) {
399 ToscaMetadata toscaMetadata = new ToscaMetadata();
400 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
401 toscaMetadata.setUUID(component.getUUID());
402 toscaMetadata.setDescription(component.getDescription());
403 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
405 List<CategoryDefinition> categories = component.getCategories();
406 CategoryDefinition categoryDefinition = categories.get(0);
407 toscaMetadata.setCategory(categoryDefinition.getName());
410 toscaMetadata.setVersion(component.getVersion());
411 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
412 if (componentInstance.getSourceModelInvariant() != null
413 && !componentInstance.getSourceModelInvariant().isEmpty()) {
414 toscaMetadata.setVersion(componentInstance.getComponentVersion());
415 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
416 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
417 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
418 toscaMetadata.setName(
419 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
420 toscaMetadata.setDescription(componentInstance.getDescription());
424 switch (component.getComponentType()) {
426 Resource resource = (Resource) component;
428 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
429 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
431 toscaMetadata.setType(resource.getResourceType().name());
433 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
434 toscaMetadata.setResourceVendor(resource.getVendorName());
435 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
436 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
439 Service service = (Service) component;
440 toscaMetadata.setType(component.getComponentType().getValue());
441 toscaMetadata.setServiceType(service.getServiceType());
442 toscaMetadata.setServiceRole(service.getServiceRole());
443 toscaMetadata.setServiceFunction(service.getServiceFunction());
444 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
445 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
448 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
449 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
450 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
454 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
456 return toscaMetadata;
459 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
460 if (service.getInstantiationType() != null) {
461 toscaMetadata.setInstantiationType(service.getInstantiationType());
464 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
468 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
469 ToscaTemplate toscaTemplate) {
471 if (null == DEFAULT_IMPORTS) {
472 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
473 return Either.right(ToscaError.GENERAL_ERROR);
475 Map<String, Component> componentCache = new HashMap<>();
477 if (!ModelConverter.isAtomicComponent(component)) {
478 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
479 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
481 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
483 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
484 if (isNotEmpty(toscaArtifacts)) {
485 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
486 if(artifactDefinition != null) {
487 Map<String, Map<String, String>> importsListMember = new HashMap<>();
488 Map<String, String> interfaceFiles = new HashMap<>();
489 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
490 StringBuilder keyNameBuilder = new StringBuilder();
491 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
492 .append(component.getName()).append("-interface");
493 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
494 additionalImports.add(importsListMember);
497 List<ComponentInstance> componentInstances = component.getComponentInstances();
498 if (componentInstances != null && !componentInstances.isEmpty()) {
499 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
501 toscaTemplate.setDependencies(dependecies);
502 toscaTemplate.setImports(additionalImports);
504 log.debug("currently imports supported for VF and service only");
506 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
509 private void createDependency(final Map<String, Component> componentCache,
510 final List<Map<String, Map<String, String>>> imports,
511 final List<Triple<String, String, Component>> dependencies,
512 final ComponentInstance componentInstance) {
513 log.debug("createDependency componentCache {}",componentCache);
514 final Component componentRI = componentCache.get(componentInstance.getComponentUid());
515 if (componentRI == null) {
516 // all resource must be only once!
517 final Either<Component, StorageOperationStatus> resource = toscaOperationFacade
518 .getToscaFullElement(componentInstance.getComponentUid());
519 if ((resource.isRight()) && (log.isDebugEnabled())) {
520 log.debug("Failed to fetch resource with id {} for instance {}", componentInstance.getComponentUid(),
521 componentInstance.getUniqueId());
524 final Component fetchedComponent = resource.left().value();
525 setComponentCache(componentCache, componentInstance, fetchedComponent);
526 addDependencies(imports, dependencies, fetchedComponent);
531 * Sets a componentCache from the given component/resource.
533 private void setComponentCache(final Map<String, Component> componentCache,
534 final ComponentInstance componentInstance,
535 final Component fetchedComponent) {
536 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
537 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
538 final Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
539 .getToscaFullElement(componentInstance.getSourceModelUid());
540 if (sourceService.isRight() && (log.isDebugEnabled())) {
541 log.debug("Failed to fetch source service with id {} for proxy {}",
542 componentInstance.getSourceModelUid(), componentInstance.getUniqueId());
544 final Component fetchedSource = sourceService.left().value();
545 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
550 * Retrieves all derived_from nodes and stores it in a predictable order.
552 private void addDependencies(final List<Map<String, Map<String, String>>> imports,
553 final List<Triple<String, String, Component>> dependencies,
554 final Component fetchedComponent) {
555 final Set<Component> componentsList = new LinkedHashSet<>();
556 if (fetchedComponent instanceof Resource) {
557 log.debug("fetchedComponent is a resource {}",fetchedComponent);
559 final Optional<Map<String, String>> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent, componentsList);
560 if (derivedFromMapOfIdToName.isPresent()) {
561 derivedFromMapOfIdToName.get().entrySet().forEach(entry -> {
562 log.debug("Started entry.getValue() : {}",entry.getValue());
563 if (!NATIVE_ROOT.equals(entry.getValue())) {
564 Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
565 .getToscaElement(entry.getKey());
566 if (resourcefetched != null && resourcefetched.isLeft()) {
567 componentsList.add(resourcefetched.left().value());
572 setImports(imports, dependencies, componentsList);
577 * Returns all derived_from nodes found.
579 private Optional<Map<String, String>> getDerivedFromMapOfIdToName(final Component fetchedComponent,
580 final Set<Component> componentsList) {
581 final Resource parentResource = (Resource) fetchedComponent;
582 Map<String, String> derivedFromMapOfIdToName = new HashMap<>();
583 if(CollectionUtils.isNotEmpty(parentResource.getComponentInstances())) {
584 componentsList.add(fetchedComponent);
585 for (final ComponentInstance componentInstance : parentResource.getComponentInstances()) {
586 final Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
587 .getToscaElement(componentInstance.getComponentUid());
588 if (resourcefetched != null && resourcefetched.isLeft()) {
589 final Map<String, String> derivedWithId = resourcefetched.left().value().getDerivedFromMapOfIdToName();
590 if (MapUtils.isNotEmpty(derivedWithId)) {
591 derivedFromMapOfIdToName.putAll(derivedWithId);
596 derivedFromMapOfIdToName = parentResource.getDerivedFromMapOfIdToName();
598 log.debug("Started derivedFromMapOfIdToName: {}", derivedFromMapOfIdToName);
599 return Optional.ofNullable(derivedFromMapOfIdToName);
603 * Creates a resource map and adds it to the import list.
605 private void setImports(final List<Map<String, Map<String, String>>> imports,
606 final List<Triple<String, String, Component>> dependencies,
607 final Set<Component> componentsList) {
608 componentsList.forEach(component -> {
609 final Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
610 final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
611 if (artifactDefinition != null) {
612 final Map<String, String> files = new HashMap<>();
613 final String artifactName = artifactDefinition.getArtifactName();
614 files.put(IMPORTS_FILE_KEY, artifactName);
615 final StringBuilder keyNameBuilder = new StringBuilder();
616 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
617 keyNameBuilder.append("-");
618 keyNameBuilder.append(component.getName());
619 addImports(imports, keyNameBuilder, files);
621 .add(new ImmutableTriple<String, String, Component>(artifactName, artifactDefinition.getEsId(),
624 if (!ModelConverter.isAtomicComponent(component)) {
625 final Map<String, String> interfaceFiles = new HashMap<>();
626 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
627 keyNameBuilder.append("-interface");
628 addImports(imports, keyNameBuilder, interfaceFiles);
635 * Adds the found resource to the import definition list.
637 private void addImports(final List<Map<String, Map<String, String>>> imports,
638 final StringBuilder keyNameBuilder,
639 final Map<String, String> files) {
640 final String mapKey = keyNameBuilder.toString();
641 if (imports.stream().allMatch(stringMapMap -> stringMapMap.get(mapKey) == null)) {
642 final Map<String, Map<String, String>> importsListMember = new HashMap<>();
643 importsListMember.put(keyNameBuilder.toString(), files);
644 imports.add(importsListMember);
648 public static String getInterfaceFilename(String artifactName) {
649 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
652 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
653 Map<String, ToscaNodeType> nodeTypes) {
654 return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
657 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
658 Component component, ToscaTemplate toscaNode,
659 Map<String, ToscaNodeType> nodeTypes,
660 boolean isAssociatedComponent) {
661 log.debug("start convert node type for {}", component.getUniqueId());
662 ToscaNodeType toscaNodeType = createNodeType(component);
664 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
665 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
666 if(lifecycleTypeEither.isRight()){
667 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
668 return Either.right(ToscaError.GENERAL_ERROR);
670 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
673 .map(InterfaceDataDefinition::getType)
674 .collect(Collectors.toList());
675 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
677 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
678 if (dataTypesEither.isRight()) {
679 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
680 return Either.right(ToscaError.GENERAL_ERROR);
683 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
685 List<InputDefinition> inputDef = component.getInputs();
686 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
687 interfacesOperationsConverter.addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
688 addInputsToProperties(dataTypes, inputDef, mergedProperties);
690 if(CollectionUtils.isNotEmpty(component.getProperties())) {
691 List<PropertyDefinition> properties = component.getProperties();
692 Map<String, ToscaProperty> convertedProperties = properties.stream()
693 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs()))
694 .collect(Collectors.toMap(PropertyDataDefinition::getName,
695 property -> propertyConvertor.convertProperty(dataTypes, property,
696 PropertyConvertor.PropertyType.PROPERTY)));
697 // merge component properties and inputs properties
698 mergedProperties.putAll(convertedProperties);
700 if (MapUtils.isNotEmpty(mergedProperties)) {
701 toscaNodeType.setProperties(mergedProperties);
704 /* convert private data_types */
705 List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
706 if (CollectionUtils.isNotEmpty(privateDataTypes) ) {
707 Map<String, ToscaDataType> toscaDataTypeMap = new HashMap<>();
708 for (DataTypeDefinition dataType: privateDataTypes) {
709 log.debug("Emitting private data type: component.name={} dataType.name={}",
710 component.getNormalizedName(), dataType.getName());
711 ToscaDataType toscaDataType = new ToscaDataType();
712 toscaDataType.setDerived_from(dataType.getDerivedFromName());
713 toscaDataType.setDescription(dataType.getDescription());
714 toscaDataType.setVersion(dataType.getVersion());
715 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
716 toscaDataType.setProperties(dataType.getProperties().stream()
717 .collect(Collectors.toMap(
719 s -> propertyConvertor.convertProperty(dataTypes, s, PropertyConvertor.PropertyType.PROPERTY)
722 toscaDataTypeMap.put(dataType.getName(), toscaDataType);
724 toscaNode.setData_types(toscaDataTypeMap);
727 // Extracted to method for code reuse
728 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
731 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
732 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
733 Map<String, DataTypeDefinition> dataTypes) {
734 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
735 if (capabilities.isRight()) {
736 return Either.right(capabilities.right().value());
738 toscaNodeType = capabilities.left().value();
739 log.debug("Capabilities converted for {}", component.getUniqueId());
741 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
743 if (requirements.isRight()) {
744 return Either.right(requirements.right().value());
746 toscaNodeType = requirements.left().value();
747 log.debug("Requirements converted for {}", component.getUniqueId());
749 String toscaResourceName;
750 switch (component.getComponentType()) {
752 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
753 .getMetadataDataDefinition()).getToscaResourceName();
756 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
757 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
760 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
761 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
764 nodeTypes.put(toscaResourceName, toscaNodeType);
765 toscaNode.setNode_types(nodeTypes);
766 log.debug("finish convert node type for {}", component.getUniqueId());
767 return Either.left(toscaNode);
770 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
772 List<ComponentInstance> componentInstances,
773 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
774 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
775 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
776 ToscaTopolgyTemplate topologyTemplate) {
778 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
779 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
780 component.getComponentType());
781 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
782 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
784 Map<String, ToscaGroupTemplate> groupsMap = null;
785 for (ComponentInstance componentInstance : componentInstances) {
786 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
787 if (MapUtils.isNotEmpty(componentInstance.getToscaArtifacts())) {
788 nodeTemplate.setArtifacts(convertToNodeTemplateArtifacts(componentInstance.getToscaArtifacts()));
790 nodeTemplate.setType(componentInstance.getToscaComponentName());
791 nodeTemplate.setDirectives(componentInstance.getDirectives());
792 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
794 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
795 .getOriginComponent(componentCache, componentInstance);
796 if (originComponentRes.isRight()) {
797 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
800 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
801 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
802 originComponentRes.left().value(), componentCache);
803 if (requirements.isRight()) {
804 convertNodeTemplatesRes = Either.right(requirements.right().value());
807 String instanceUniqueId = componentInstance.getUniqueId();
808 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
810 nodeTemplate = requirements.left().value();
812 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
814 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
815 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
816 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
818 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
821 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
822 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
823 if (capabilities.isRight()) {
824 convertNodeTemplatesRes = Either.right(capabilities.right().value());
827 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
829 nodeTemplate = capabilities.left().value();
830 Map<String, Object> props = new HashMap<>();
832 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
833 // Adds the properties of parent component to map
834 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
837 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
838 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, instanceUniqueId,
842 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
843 && !isComponentOfTypeServiceProxy(componentInstance)) {
844 //For service proxy the inputs are already handled under instance properties above
845 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
848 //M3[00001] - NODE TEMPLATE INTERFACES - START
849 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
850 instanceUniqueId, component);
851 //M3[00001] - NODE TEMPLATE INTERFACES - END
852 if (props != null && !props.isEmpty()) {
853 nodeTemplate.setProperties(props);
856 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
857 if (groupInstances != null) {
858 if (groupsMap == null) {
859 groupsMap = new HashMap<>();
861 for (GroupInstance groupInst : groupInstances) {
862 boolean addToTosca = true;
864 List<String> artifacts = groupInst.getArtifacts();
865 if (artifacts == null || artifacts.isEmpty()) {
870 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
871 groupsMap.put(groupInst.getName(), toscaGroup);
876 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
878 if (groupsMap != null) {
879 log.debug("instance groups added");
880 topologyTemplate.addGroups(groupsMap);
882 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
883 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
884 component.getName());
885 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
886 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
887 component.getName());
889 if (convertNodeTemplatesRes == null) {
890 convertNodeTemplatesRes = Either.left(nodeTemplates);
892 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
893 component.getComponentType());
894 return convertNodeTemplatesRes;
897 private void handleInstanceInterfaces(
898 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
899 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
900 String instanceUniqueId,
901 Component parentComponent) {
903 Map<String, Object> interfaces;
905 // we need to handle service proxy interfaces
906 if(isComponentOfTypeServiceProxy(componentInstance)) {
907 if(MapUtils.isEmpty(componentInstanceInterfaces)
908 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
911 List<ComponentInstanceInterface> currServiceInterfaces =
912 componentInstanceInterfaces.get(instanceUniqueId);
914 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
915 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
916 .getUniqueId(), instInterface));
918 interfaces = interfacesOperationsConverter
919 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
923 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
924 componentInstance, instanceUniqueId);
926 nodeTemplate.setInterfaces(interfaces);
929 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
930 return Objects.nonNull(componentInstance.getOriginType())
931 && componentInstance.getOriginType().getValue().equals("Service Proxy");
934 //M3[00001] - NODE TEMPLATE INTERFACES - START
935 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
936 ComponentInstance componentInstance,
937 String instanceUniqueId) {
938 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
942 List<ComponentInstanceInterface> componentInstanceInterfaces =
943 componentInstancesInterfaces.get(instanceUniqueId);
945 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
949 Map<String, Object> interfaces = new HashMap<>();
950 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
951 interfaces.put(componentInstanceInterface.getInterfaceId(),
952 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
955 componentInstance.setInterfaces(interfaces);
960 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
961 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
962 String instanceUniqueId, Map<String, Object> props) {
964 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
965 if (instanceInputsList != null) {
966 instanceInputsList.forEach(input -> {
968 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
969 ? input.getValue() : input.getDefaultValue();
970 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
975 private void addPropertiesOfComponentInstance(
976 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
977 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
978 Map<String, Object> props) {
980 if (isNotEmpty(componentInstancesProperties)) {
981 componentInstancesProperties.get(instanceUniqueId)
982 // Converts and adds each value to property map
983 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
988 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
989 Component componentOfInstance, Map<String, Object> props) {
991 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
992 if (isNotEmpty(componentProperties)) {
993 componentProperties.stream()
994 // Filters out properties with empty default values
995 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
996 // Converts and adds each value to property map
997 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
998 prop::getDefaultValue));
1004 * @param componentInstance
1009 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
1010 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
1011 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
1012 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
1013 props.put(prop.getName(), convertedValue);
1017 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
1018 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
1019 log.debug("Convert property or input value {} for instance {}", input.getName(),
1020 componentInstance.getUniqueId());
1021 String propertyType = input.getType();
1022 String innerType = null;
1023 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
1024 innerType = input.getSchema().getProperty().getType();
1026 return propertyConvertor.convertToToscaObject(input, supplier.get(), dataTypes, true);
1029 private ToscaNodeType createNodeType(Component component) {
1030 ToscaNodeType toscaNodeType = new ToscaNodeType();
1031 if (ModelConverter.isAtomicComponent(component)) {
1032 if (((Resource) component).getDerivedFrom() != null) {
1033 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
1035 toscaNodeType.setDescription(component.getDescription());
1037 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
1039 toscaNodeType.setDerived_from(derivedFrom);
1041 return toscaNodeType;
1044 private Either<Map<String, Object>, ToscaError> createProxyInterfaceTypes(Component container) {
1046 Map<String, Object> proxyInterfaceTypes = new HashMap<>();
1047 Either<Map<String, Object>, ToscaError> res = Either.left(proxyInterfaceTypes);
1048 List<ComponentInstance> componentInstances = container.getComponentInstances();
1049 if (CollectionUtils.isEmpty(componentInstances)) {
1052 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1053 componentInstances.stream()
1054 .filter(this::isComponentOfTypeServiceProxy)
1055 .forEach(inst -> serviceProxyInstanceList.put(inst.getToscaComponentName(), inst));
1056 if (MapUtils.isEmpty(serviceProxyInstanceList)) {
1059 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1060 Component serviceComponent;
1061 ComponentParametersView componentParametersView = new ComponentParametersView();
1062 componentParametersView.disableAll();
1063 componentParametersView.setIgnoreInterfaces(false);
1064 Either<Component, StorageOperationStatus> service = toscaOperationFacade
1065 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1066 if (service.isRight()) {
1067 log.debug("Failed to fetch original service component with id {} for instance {}",
1068 entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1069 return Either.right(ToscaError.GENERAL_ERROR);
1071 serviceComponent = service.left().value();
1074 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
1075 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
1076 if(lifecycleTypeEither.isRight()){
1077 log.debug("Failed to retrieve global interface types :", lifecycleTypeEither.right().value());
1078 return Either.right(ToscaError.GENERAL_ERROR);
1081 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream()
1082 .map(InterfaceDataDefinition::getType)
1083 .collect(Collectors.toList());
1084 //Add interface types for local interfaces in the original service component for proxy
1085 Map<String, Object> localInterfaceTypes = addInterfaceTypeElement(serviceComponent,
1086 allGlobalInterfaceTypes);
1087 if (MapUtils.isNotEmpty(localInterfaceTypes)) {
1088 proxyInterfaceTypes.putAll(localInterfaceTypes);
1092 return Either.left(proxyInterfaceTypes);
1095 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache,
1096 Component container) {
1098 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
1099 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
1101 List<ComponentInstance> componentInstances = container.getComponentInstances();
1103 if (componentInstances == null || componentInstances.isEmpty()) {
1106 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1107 List<ComponentInstance> proxyInst = componentInstances.stream()
1108 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
1109 .collect(Collectors.toList());
1110 if (proxyInst != null && !proxyInst.isEmpty()) {
1111 for (ComponentInstance inst : proxyInst) {
1112 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
1116 if (serviceProxyInstanceList.isEmpty()) {
1119 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
1120 .getLatestByName("serviceProxy");
1121 if (serviceProxyOrigin.isRight()) {
1122 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
1123 serviceProxyOrigin.right().value());
1124 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
1126 Component origComponent = serviceProxyOrigin.left().value();
1128 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1129 Component serviceComponent = null;
1130 ComponentParametersView componentParametersView = new ComponentParametersView();
1131 componentParametersView.disableAll();
1132 componentParametersView.setIgnoreCategories(false);
1133 componentParametersView.setIgnoreProperties(false);
1134 componentParametersView.setIgnoreInputs(false);
1135 componentParametersView.setIgnoreInterfaces(false);
1136 componentParametersView.setIgnoreRequirements(false);
1137 Either<Component, StorageOperationStatus> service = toscaOperationFacade
1138 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1139 if (service.isRight()) {
1140 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1142 serviceComponent = service.left().value();
1145 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache, origComponent, serviceComponent,
1146 entryProxy.getValue());
1147 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
1150 return Either.left(nodeTypesMap);
1153 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent,
1154 Component proxyComponent, ComponentInstance instance) {
1155 ToscaNodeType toscaNodeType = new ToscaNodeType();
1156 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1158 toscaNodeType.setDerived_from(derivedFrom);
1159 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
1160 if (dataTypesEither.isRight()) {
1161 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1163 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1164 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1165 .convertProxyCapabilities(componentCache, instance, dataTypes);
1167 if (MapUtils.isNotEmpty(capabilities)) {
1168 toscaNodeType.setCapabilities(capabilities);
1170 List<Map<String, ToscaRequirement>> proxyNodeTypeRequirements = this.capabilityRequirementConverter
1171 .convertProxyRequirements(componentCache, instance);
1172 if (CollectionUtils.isNotEmpty(proxyNodeTypeRequirements)) {
1173 toscaNodeType.setRequirements(proxyNodeTypeRequirements);
1175 Optional<Map<String, ToscaProperty>> proxyProperties = getProxyNodeTypeProperties(proxyComponent, dataTypes);
1176 proxyProperties.ifPresent(toscaNodeType::setProperties);
1178 Optional<Map<String, Object>> proxyInterfaces = getProxyNodeTypeInterfaces(proxyComponent, dataTypes);
1179 proxyInterfaces.ifPresent(toscaNodeType::setInterfaces);
1181 return toscaNodeType;
1184 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1185 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
1186 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
1188 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1189 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
1190 log.debug("Failed to convert component instance requirements for the component instance {}. ",
1191 componentInstance.getName());
1192 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1194 if (!toscaRequirements.isEmpty()) {
1195 nodeTypeTemplate.setRequirements(toscaRequirements);
1197 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1198 return Either.left(nodeTypeTemplate);
1201 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1202 List<RequirementCapabilityRelDef> relations, Component originComponent,
1203 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1204 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1205 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1206 return isEmpty(filteredRelations) ||
1207 filteredRelations.stream()
1208 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1211 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1212 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1213 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1215 boolean result = true;
1216 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1217 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1218 Either<Component, StorageOperationStatus> getOriginRes = null;
1219 Optional<RequirementDefinition> reqOpt = Optional.empty();
1220 Component toOriginComponent = null;
1221 Optional<CapabilityDefinition> capOpt = Optional.empty();
1223 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1224 .findFirst().orElse(null);
1225 if (toInstance == null) {
1226 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1231 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1232 if (!reqOpt.isPresent()) {
1233 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1234 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1239 ComponentParametersView filter = new ComponentParametersView(true);
1240 filter.setIgnoreComponentInstances(false);
1241 filter.setIgnoreCapabilities(false);
1242 filter.setIgnoreGroups(false);
1243 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1244 if (getOriginRes.isRight()) {
1245 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1246 reqOpt.get().getName(), toInstance.getActualComponentUid());
1251 toOriginComponent = getOriginRes.left().value();
1252 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1253 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1254 if (!capOpt.isPresent()) {
1255 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1256 if(!capOpt.isPresent()){
1258 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1259 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1264 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1265 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1270 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1271 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1274 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1275 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1276 if (!cap.isPresent()) {
1277 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1282 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1283 List<String> reducedPath = capability.getPath();
1284 if(capability.getOwnerId() !=null){
1285 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1287 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1288 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1289 if (buildCapNameRes.isRight()) {
1291 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1292 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1295 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1296 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1297 if (buildReqNameRes.isRight()) {
1299 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1300 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1303 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1304 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1305 toscaRequirement.setNode(toInstance.getName());
1306 toscaRequirement.setCapability(buildCapNameRes.left().value());
1307 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1308 toscaRequirements.add(toscaReqMap);
1312 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1313 for(List<RequirementDefinition> reqList: reqMap.values()){
1314 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1315 if(reqOpt.isPresent()){
1319 return Optional.empty();
1323 * Allows detecting the requirement belonging to the received relationship
1324 * The detection logic is: A requirement belongs to a relationship IF 1.The
1325 * name of the requirement equals to the "requirement" field of the
1326 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1327 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1328 * toInstance equals to capabilityOwnerId of the relation
1330 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1331 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1332 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1333 requirement.getName(), reqAndRelationshipPair.getRequirement());
1336 return ModelConverter.isAtomicComponent(originComponent) ||
1337 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1340 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1341 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId())
1342 || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())
1343 || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId()));
1346 private boolean isCvfc(Component component) {
1347 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1348 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1351 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1352 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1354 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1355 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1356 .convertSubstitutionMappingCapabilities(componentCache, component);
1357 if (toscaCapabilitiesRes.isRight()) {
1358 result = Either.right(toscaCapabilitiesRes.right().value());
1359 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1360 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1361 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1362 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1364 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1368 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1369 Map<String, DataTypeDefinition> dataTypes) {
1370 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1372 if (!toscaCapabilities.isEmpty()) {
1373 nodeType.setCapabilities(toscaCapabilities);
1375 log.debug("Finish convert Capabilities for node type");
1377 return Either.left(nodeType);
1380 private Map<String, ToscaTemplateArtifact> convertToNodeTemplateArtifacts(Map<String, ToscaArtifactDataDefinition> artifacts) {
1381 if (artifacts == null) {
1384 Map<String, ToscaTemplateArtifact> arts = new HashMap<>();
1385 for (Map.Entry<String, ToscaArtifactDataDefinition> entry : artifacts.entrySet()) {
1386 ToscaTemplateArtifact artifact = new ToscaTemplateArtifact();
1387 artifact.setFile(entry.getValue().getFile());
1388 artifact.setType(entry.getValue().getType());
1389 arts.put(entry.getKey(), artifact);
1394 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1395 if (inNodeFilter == null){
1398 NodeFilter nodeFilter = new NodeFilter();
1400 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1401 inNodeFilter.getCapabilities();
1403 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1405 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1406 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1408 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1409 copyNodeFilterProperties(origProperties, propertiesCopy);
1411 if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1412 nodeFilter.setCapabilities(capabilitiesCopy);
1415 if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1416 nodeFilter.setProperties(propertiesCopy);
1419 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1422 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1427 private Object cloneToscaId(Object toscaId) {
1428 return Objects.isNull(toscaId) ? null
1429 : cloneObjectFromYml(toscaId, toscaId.getClass());
1433 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1434 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1435 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1437 private void copyNodeFilterCapabilitiesTemplate(
1438 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1439 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1440 if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1441 origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1444 for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1445 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1446 CapabilityFilter capabilityFilter = new CapabilityFilter();
1447 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1448 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1449 capabilityFilter.setProperties(propertiesCopy);
1450 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1451 capabilitiesCopy.add(capabilityFilterCopyMap);
1455 private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1456 String listAsString = yamlUtil.objectToYaml(propertyList);
1457 return yamlUtil.yamlToObject(listAsString, List.class);
1461 private void copyNodeFilterProperties(
1462 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1463 List<Map<String, List<Object>>> propertiesCopy) {
1464 if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1465 origProperties.isEmpty()) {
1468 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1469 for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1470 for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1471 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1472 String propertyName = propertyDataDefinition.getName();
1473 if (propertyMapCopy.containsKey(propertyName)){
1474 addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
1476 if (propertyName != null) {
1477 List propsList = new ArrayList();
1478 addPropertyConstraintValueToList(propertyName, propertyValObj, propsList);
1479 propertyMapCopy.put(propertyName, propsList);
1481 propertyMapCopy.putAll(propertyValObj);
1486 propertyMapCopy.entrySet().stream().forEach(entry ->
1487 addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
1490 private void addPropertyConstraintValueToList(String propertyName, Map propertyValObj, List propsList) {
1491 if(propertyValObj.containsKey(propertyName)) {
1492 propsList.add(propertyValObj.get(propertyName));
1494 propsList.add(propertyValObj);
1500 private void addCalculatedConstraintsIntoPropertiesList(List<Map<String, List<Object>>> propertiesCopy,
1501 Entry<String, List<Object>> entry) {
1502 Map<String, List<Object>> tempMap = new HashMap<>();
1503 tempMap.put(entry.getKey(), entry.getValue());
1504 propertiesCopy.add(tempMap);
1507 private static class CustomRepresenter extends Representer {
1508 CustomRepresenter() {
1510 // null representer is exceptional and it is stored as an instance
1512 this.nullRepresenter = new RepresentNull();
1517 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1519 if (propertyValue == null) {
1522 // skip not relevant for Tosca property
1523 if ("dependencies".equals(property.getName())) {
1526 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1528 return "_defaultp_".equals(property.getName())
1529 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1533 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1534 // remove the bean type from the output yaml (!! ...)
1535 if (!classTags.containsKey(javaBean.getClass())) {
1536 addClassTag(javaBean.getClass(), Tag.MAP);
1539 return super.representJavaBean(properties, javaBean);
1542 private class RepresentNull implements Represent {
1544 public Node representData(Object data) {
1545 // possible values are here http://yaml.org/type/null.html
1546 return representScalar(Tag.NULL, "");
1551 private static class UnsortedPropertyUtils extends PropertyUtils {
1553 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1554 throws IntrospectionException {
1555 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1556 return new LinkedHashSet<>(fields);
1560 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1561 ObjectMapper objectMapper = new ObjectMapper();
1562 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1564 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1565 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1566 interfaceAsMap.remove("empty");
1568 if(MapUtils.isNotEmpty(operations)) {
1569 interfaceAsMap.putAll(operations);
1572 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1574 return interfaceObject;
1578 Optional<Map<String, ToscaProperty>> getProxyNodeTypeProperties(Component proxyComponent,
1579 Map<String, DataTypeDefinition>
1581 if (Objects.isNull(proxyComponent)) {
1582 return Optional.empty();
1584 Map<String, ToscaProperty> proxyProperties = new HashMap<>();
1585 addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties);
1586 if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) {
1587 proxyProperties.putAll(proxyComponent.getProperties().stream()
1588 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition,
1589 proxyComponent.getInputs()))
1590 .collect(Collectors.toMap(PropertyDataDefinition::getName,
1591 property -> propertyConvertor.convertProperty(dataTypes, property,
1592 PropertyConvertor.PropertyType.PROPERTY))));
1594 return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty();
1597 void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
1598 List<InputDefinition> componentInputs,
1599 Map<String, ToscaProperty> mergedProperties) {
1600 if (CollectionUtils.isEmpty(componentInputs)) {
1603 for(InputDefinition input : componentInputs) {
1604 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input,
1605 PropertyConvertor.PropertyType.INPUT);
1606 mergedProperties.put(input.getName(), property);
1610 Optional<Map<String, Object>> getProxyNodeTypeInterfaces(Component proxyComponent,
1611 Map<String, DataTypeDefinition> dataTypes) {
1612 if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) {
1613 return Optional.empty();
1615 Map<String, InterfaceDefinition> proxyComponentInterfaces = proxyComponent.getInterfaces();
1616 //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is
1617 // always available in the proxy node template
1618 removeOperationImplementationForProxyNodeType(proxyComponentInterfaces);
1619 return Optional.ofNullable(interfacesOperationsConverter
1620 .getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes,
1624 private static void removeOperationImplementationForProxyNodeType(
1625 Map<String, InterfaceDefinition> proxyComponentInterfaces) {
1626 if (MapUtils.isEmpty(proxyComponentInterfaces)) {
1629 proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations)
1630 .filter(MapUtils::isNotEmpty)
1631 .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null)));