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(final Component component,
185 final boolean isAssociatedComponent) {
186 if (null == DEFAULT_IMPORTS) {
187 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
188 return Either.right(ToscaError.GENERAL_ERROR);
191 String toscaVersion = null;
192 if (component instanceof Resource) {
193 toscaVersion = ((Resource) component).getToscaVersion();
195 ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
196 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
197 final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
198 final Either<ToscaTemplate, ToscaError> toscaTemplateRes =
199 convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes, isAssociatedComponent);
200 if (toscaTemplateRes.isRight()) {
201 return Either.right(toscaTemplateRes.right().value());
204 toscaTemplate = toscaTemplateRes.left().value();
205 ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
206 return Either.left(toscaRepresentation);
209 public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
210 CustomRepresenter representer = new CustomRepresenter();
211 DumperOptions options = new DumperOptions();
212 options.setAllowReadOnlyProperties(false);
213 options.setPrettyFlow(true);
215 options.setDefaultFlowStyle(FlowStyle.FLOW);
216 options.setCanonical(false);
218 representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
220 representer.setPropertyUtils(new UnsortedPropertyUtils());
221 Yaml yaml = new Yaml(representer, options);
223 String yamlAsString = yaml.dumpAsMap(toscaTemplate);
225 StringBuilder sb = new StringBuilder();
226 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
227 sb.append(yamlAsString);
228 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
230 ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
231 toscaRepresentation.setMainYaml(sb.toString());
232 toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
234 return toscaRepresentation;
237 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
238 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
239 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
241 if (fillImports.isRight()) {
242 return Either.right(fillImports.right().value());
244 return Either.left(fillImports.left().value().left);
247 private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(final Component component) {
248 if (null == DEFAULT_IMPORTS) {
249 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
250 return Either.right(ToscaError.GENERAL_ERROR);
252 log.trace("start tosca export for {}", component.getUniqueId());
253 String toscaVersion = null;
254 if (component instanceof Resource) {
255 toscaVersion = ((Resource) component).getToscaVersion();
257 final ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
258 toscaTemplate.setMetadata(convertMetadata(component));
259 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
260 final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
261 if (ModelConverter.isAtomicComponent(component)) {
262 log.trace("convert component as node type");
263 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
265 log.trace("convert component as topology template");
266 return convertToscaTemplate(component, toscaTemplate);
271 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
273 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
275 if (importsRes.isRight()) {
276 return Either.right(importsRes.right().value());
278 toscaNode = importsRes.left().value().left;
279 Map<String, Component> componentCache = importsRes.left().value().right;
280 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache,
282 if (nodeTypesMapEither.isRight()) {
283 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
284 nodeTypesMapEither.right().value());
285 return Either.right(nodeTypesMapEither.right().value());
287 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
288 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
289 toscaNode.setNode_types(nodeTypesMap);
292 Either<Map<String, Object>, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component);
293 if (proxyInterfaceTypesEither.isRight()) {
294 log.debug("Failed to populate service proxy local interface types in tosca, error {}",
295 nodeTypesMapEither.right().value());
296 return Either.right(proxyInterfaceTypesEither.right().value());
298 Map<String, Object> proxyInterfaceTypes = proxyInterfaceTypesEither.left().value();
299 if (MapUtils.isNotEmpty(proxyInterfaceTypes)) {
300 toscaNode.setInterface_types(proxyInterfaceTypes);
303 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
304 if (dataTypesEither.isRight()) {
305 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
306 return Either.right(ToscaError.GENERAL_ERROR);
308 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
309 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
310 List<InputDefinition> inputDef = component.getInputs();
311 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
313 if (!inputs.isEmpty()) {
314 topologyTemplate.setInputs(inputs);
317 List<ComponentInstance> componentInstances = component.getComponentInstances();
318 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
319 component.getComponentInstancesProperties();
320 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
321 component.getComponentInstancesInterfaces();
322 if (componentInstances != null && !componentInstances.isEmpty()) {
324 Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
325 convertNodeTemplates(component, componentInstances,
326 componentInstancesProperties, componentInstanceInterfaces,
327 componentCache, dataTypes, topologyTemplate);
328 if (nodeTemplates.isRight()) {
329 return Either.right(nodeTemplates.right().value());
331 log.debug("node templates converted");
333 topologyTemplate.setNode_templates(nodeTemplates.left().value());
337 addGroupsToTopologyTemplate(component, topologyTemplate);
340 addPoliciesToTopologyTemplate(component, topologyTemplate);
341 } catch (SdcResourceNotFoundException e) {
342 log.debug("Fail to add policies to topology template:",e);
343 return Either.right(ToscaError.GENERAL_ERROR);
347 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
348 String toscaResourceName;
349 switch (component.getComponentType()) {
351 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
352 .getMetadataDataDefinition()).getToscaResourceName();
355 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
356 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
359 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
360 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
362 substitutionMapping.setNode_type(toscaResourceName);
364 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
365 if (capabilities.isRight()) {
366 return Either.right(capabilities.right().value());
368 substitutionMapping = capabilities.left().value();
370 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
371 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
372 if (requirements.isRight()) {
373 return Either.right(requirements.right().value());
375 substitutionMapping = requirements.left().value();
377 topologyTemplate.setSubstitution_mappings(substitutionMapping);
379 toscaNode.setTopology_template(topologyTemplate);
381 return Either.left(toscaNode);
384 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
385 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
387 topologyTemplate.addGroups(groups);
391 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
392 throws SdcResourceNotFoundException {
393 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
394 if(policies!= null) {
395 topologyTemplate.addPolicies(policies);
399 private ToscaMetadata convertMetadata(Component component) {
400 return convertMetadata(component, false, null);
403 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
404 ComponentInstance componentInstance) {
405 ToscaMetadata toscaMetadata = new ToscaMetadata();
406 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
407 toscaMetadata.setUUID(component.getUUID());
408 toscaMetadata.setDescription(component.getDescription());
409 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
411 List<CategoryDefinition> categories = component.getCategories();
412 CategoryDefinition categoryDefinition = categories.get(0);
413 toscaMetadata.setCategory(categoryDefinition.getName());
416 toscaMetadata.setVersion(component.getVersion());
417 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
418 if (componentInstance.getSourceModelInvariant() != null
419 && !componentInstance.getSourceModelInvariant().isEmpty()) {
420 toscaMetadata.setVersion(componentInstance.getComponentVersion());
421 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
422 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
423 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
424 toscaMetadata.setName(
425 componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
426 toscaMetadata.setDescription(componentInstance.getDescription());
430 switch (component.getComponentType()) {
432 Resource resource = (Resource) component;
434 if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
435 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
437 toscaMetadata.setType(resource.getResourceType().name());
439 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
440 toscaMetadata.setResourceVendor(resource.getVendorName());
441 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
442 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
445 Service service = (Service) component;
446 toscaMetadata.setType(component.getComponentType().getValue());
447 toscaMetadata.setServiceType(service.getServiceType());
448 toscaMetadata.setServiceRole(service.getServiceRole());
449 toscaMetadata.setServiceFunction(service.getServiceFunction());
450 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
451 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
454 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
455 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
456 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
460 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
462 return toscaMetadata;
465 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
466 if (service.getInstantiationType() != null) {
467 toscaMetadata.setInstantiationType(service.getInstantiationType());
470 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
474 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
475 ToscaTemplate toscaTemplate) {
477 if (null == DEFAULT_IMPORTS) {
478 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
479 return Either.right(ToscaError.GENERAL_ERROR);
481 Map<String, Component> componentCache = new HashMap<>();
483 if (!ModelConverter.isAtomicComponent(component)) {
484 List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
485 ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
487 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
489 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
490 if (isNotEmpty(toscaArtifacts)) {
491 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
492 if(artifactDefinition != null) {
493 Map<String, Map<String, String>> importsListMember = new HashMap<>();
494 Map<String, String> interfaceFiles = new HashMap<>();
495 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
496 StringBuilder keyNameBuilder = new StringBuilder();
497 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
498 .append(component.getName()).append("-interface");
499 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
500 additionalImports.add(importsListMember);
503 List<ComponentInstance> componentInstances = component.getComponentInstances();
504 if (componentInstances != null && !componentInstances.isEmpty()) {
505 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
507 toscaTemplate.setDependencies(dependecies);
508 toscaTemplate.setImports(additionalImports);
510 log.debug("currently imports supported for VF and service only");
512 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
515 private void createDependency(final Map<String, Component> componentCache,
516 final List<Map<String, Map<String, String>>> imports,
517 final List<Triple<String, String, Component>> dependencies,
518 final ComponentInstance componentInstance) {
519 log.debug("createDependency componentCache {}",componentCache);
520 final Component componentRI = componentCache.get(componentInstance.getComponentUid());
521 if (componentRI == null) {
522 // all resource must be only once!
523 final Either<Component, StorageOperationStatus> resource = toscaOperationFacade
524 .getToscaFullElement(componentInstance.getComponentUid());
525 if ((resource.isRight()) && (log.isDebugEnabled())) {
526 log.debug("Failed to fetch resource with id {} for instance {}", componentInstance.getComponentUid(),
527 componentInstance.getUniqueId());
530 final Component fetchedComponent = resource.left().value();
531 setComponentCache(componentCache, componentInstance, fetchedComponent);
532 addDependencies(imports, dependencies, fetchedComponent);
537 * Sets a componentCache from the given component/resource.
539 private void setComponentCache(final Map<String, Component> componentCache,
540 final ComponentInstance componentInstance,
541 final Component fetchedComponent) {
542 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
543 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
544 final Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
545 .getToscaFullElement(componentInstance.getSourceModelUid());
546 if (sourceService.isRight() && (log.isDebugEnabled())) {
547 log.debug("Failed to fetch source service with id {} for proxy {}",
548 componentInstance.getSourceModelUid(), componentInstance.getUniqueId());
550 final Component fetchedSource = sourceService.left().value();
551 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
556 * Retrieves all derived_from nodes and stores it in a predictable order.
558 private void addDependencies(final List<Map<String, Map<String, String>>> imports,
559 final List<Triple<String, String, Component>> dependencies,
560 final Component fetchedComponent) {
561 final Set<Component> componentsList = new LinkedHashSet<>();
562 if (fetchedComponent instanceof Resource) {
563 log.debug("fetchedComponent is a resource {}",fetchedComponent);
565 final Optional<Map<String, String>> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent, componentsList);
566 if (derivedFromMapOfIdToName.isPresent()) {
567 derivedFromMapOfIdToName.get().entrySet().forEach(entry -> {
568 log.debug("Started entry.getValue() : {}",entry.getValue());
569 if (!NATIVE_ROOT.equals(entry.getValue())) {
570 Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
571 .getToscaElement(entry.getKey());
572 if (resourcefetched != null && resourcefetched.isLeft()) {
573 componentsList.add(resourcefetched.left().value());
578 setImports(imports, dependencies, componentsList);
583 * Returns all derived_from nodes found.
585 private Optional<Map<String, String>> getDerivedFromMapOfIdToName(final Component fetchedComponent,
586 final Set<Component> componentsList) {
587 final Resource parentResource = (Resource) fetchedComponent;
588 Map<String, String> derivedFromMapOfIdToName = new HashMap<>();
589 if(CollectionUtils.isNotEmpty(parentResource.getComponentInstances())) {
590 componentsList.add(fetchedComponent);
591 for (final ComponentInstance componentInstance : parentResource.getComponentInstances()) {
592 final Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
593 .getToscaElement(componentInstance.getComponentUid());
594 if (resourcefetched != null && resourcefetched.isLeft()) {
595 final Map<String, String> derivedWithId = resourcefetched.left().value().getDerivedFromMapOfIdToName();
596 if (MapUtils.isNotEmpty(derivedWithId)) {
597 derivedFromMapOfIdToName.putAll(derivedWithId);
602 derivedFromMapOfIdToName = parentResource.getDerivedFromMapOfIdToName();
604 log.debug("Started derivedFromMapOfIdToName: {}", derivedFromMapOfIdToName);
605 return Optional.ofNullable(derivedFromMapOfIdToName);
609 * Creates a resource map and adds it to the import list.
611 private void setImports(final List<Map<String, Map<String, String>>> imports,
612 final List<Triple<String, String, Component>> dependencies,
613 final Set<Component> componentsList) {
614 componentsList.forEach(component -> {
615 final Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
616 final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
617 if (artifactDefinition != null) {
618 final Map<String, String> files = new HashMap<>();
619 final String artifactName = artifactDefinition.getArtifactName();
620 files.put(IMPORTS_FILE_KEY, artifactName);
621 final StringBuilder keyNameBuilder = new StringBuilder();
622 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
623 keyNameBuilder.append("-");
624 keyNameBuilder.append(component.getName());
625 addImports(imports, keyNameBuilder, files);
627 .add(new ImmutableTriple<String, String, Component>(artifactName, artifactDefinition.getEsId(),
630 if (!ModelConverter.isAtomicComponent(component)) {
631 final Map<String, String> interfaceFiles = new HashMap<>();
632 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
633 keyNameBuilder.append("-interface");
634 addImports(imports, keyNameBuilder, interfaceFiles);
641 * Adds the found resource to the import definition list.
643 private void addImports(final List<Map<String, Map<String, String>>> imports,
644 final StringBuilder keyNameBuilder,
645 final Map<String, String> files) {
646 final String mapKey = keyNameBuilder.toString();
647 if (imports.stream().allMatch(stringMapMap -> stringMapMap.get(mapKey) == null)) {
648 final Map<String, Map<String, String>> importsListMember = new HashMap<>();
649 importsListMember.put(keyNameBuilder.toString(), files);
650 imports.add(importsListMember);
654 public static String getInterfaceFilename(String artifactName) {
655 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
658 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
659 Map<String, ToscaNodeType> nodeTypes) {
660 return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
663 private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
664 Component component, ToscaTemplate toscaNode,
665 Map<String, ToscaNodeType> nodeTypes,
666 boolean isAssociatedComponent) {
667 log.debug("start convert node type for {}", component.getUniqueId());
668 ToscaNodeType toscaNodeType = createNodeType(component);
670 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
671 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
672 if(lifecycleTypeEither.isRight()){
673 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
674 return Either.right(ToscaError.GENERAL_ERROR);
676 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
679 .map(InterfaceDataDefinition::getType)
680 .collect(Collectors.toList());
681 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
683 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
684 if (dataTypesEither.isRight()) {
685 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
686 return Either.right(ToscaError.GENERAL_ERROR);
689 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
691 List<InputDefinition> inputDef = component.getInputs();
692 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
693 interfacesOperationsConverter.addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
694 addInputsToProperties(dataTypes, inputDef, mergedProperties);
696 if(CollectionUtils.isNotEmpty(component.getProperties())) {
697 List<PropertyDefinition> properties = component.getProperties();
698 Map<String, ToscaProperty> convertedProperties = properties.stream()
699 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs()))
700 .collect(Collectors.toMap(PropertyDataDefinition::getName,
701 property -> propertyConvertor.convertProperty(dataTypes, property,
702 PropertyConvertor.PropertyType.PROPERTY)));
703 // merge component properties and inputs properties
704 mergedProperties.putAll(convertedProperties);
706 if (MapUtils.isNotEmpty(mergedProperties)) {
707 toscaNodeType.setProperties(mergedProperties);
710 /* convert private data_types */
711 List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
712 if (CollectionUtils.isNotEmpty(privateDataTypes) ) {
713 Map<String, ToscaDataType> toscaDataTypeMap = new HashMap<>();
714 for (DataTypeDefinition dataType: privateDataTypes) {
715 log.debug("Emitting private data type: component.name={} dataType.name={}",
716 component.getNormalizedName(), dataType.getName());
717 ToscaDataType toscaDataType = new ToscaDataType();
718 toscaDataType.setDerived_from(dataType.getDerivedFromName());
719 toscaDataType.setDescription(dataType.getDescription());
720 toscaDataType.setVersion(dataType.getVersion());
721 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
722 toscaDataType.setProperties(dataType.getProperties().stream()
723 .collect(Collectors.toMap(
725 s -> propertyConvertor.convertProperty(dataTypes, s, PropertyConvertor.PropertyType.PROPERTY)
728 toscaDataTypeMap.put(dataType.getName(), toscaDataType);
730 toscaNode.setData_types(toscaDataTypeMap);
733 // Extracted to method for code reuse
734 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
737 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
738 Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
739 Map<String, DataTypeDefinition> dataTypes) {
740 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType, dataTypes);
741 if (capabilities.isRight()) {
742 return Either.right(capabilities.right().value());
744 toscaNodeType = capabilities.left().value();
745 log.debug("Capabilities converted for {}", component.getUniqueId());
747 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter.convertRequirements(componentsCache, component,
749 if (requirements.isRight()) {
750 return Either.right(requirements.right().value());
752 toscaNodeType = requirements.left().value();
753 log.debug("Requirements converted for {}", component.getUniqueId());
755 String toscaResourceName;
756 switch (component.getComponentType()) {
758 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
759 .getMetadataDataDefinition()).getToscaResourceName();
762 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
763 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
766 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
767 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
770 nodeTypes.put(toscaResourceName, toscaNodeType);
771 toscaNode.setNode_types(nodeTypes);
772 log.debug("finish convert node type for {}", component.getUniqueId());
773 return Either.left(toscaNode);
776 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
778 List<ComponentInstance> componentInstances,
779 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
780 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
781 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
782 ToscaTopolgyTemplate topologyTemplate) {
784 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
785 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
786 component.getComponentType());
787 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
788 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
790 Map<String, ToscaGroupTemplate> groupsMap = null;
791 for (ComponentInstance componentInstance : componentInstances) {
792 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
793 if (MapUtils.isNotEmpty(componentInstance.getToscaArtifacts())) {
794 nodeTemplate.setArtifacts(convertToNodeTemplateArtifacts(componentInstance.getToscaArtifacts()));
796 nodeTemplate.setType(componentInstance.getToscaComponentName());
797 nodeTemplate.setDirectives(componentInstance.getDirectives());
798 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
800 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
801 .getOriginComponent(componentCache, componentInstance);
802 if (originComponentRes.isRight()) {
803 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
806 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
807 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
808 originComponentRes.left().value(), componentCache);
809 if (requirements.isRight()) {
810 convertNodeTemplatesRes = Either.right(requirements.right().value());
813 String instanceUniqueId = componentInstance.getUniqueId();
814 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
816 nodeTemplate = requirements.left().value();
818 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
820 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
821 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
822 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
824 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
827 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
828 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
829 if (capabilities.isRight()) {
830 convertNodeTemplatesRes = Either.right(capabilities.right().value());
833 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
835 nodeTemplate = capabilities.left().value();
836 Map<String, Object> props = new HashMap<>();
838 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
839 // Adds the properties of parent component to map
840 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
843 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
844 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, instanceUniqueId,
848 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
849 && !isComponentOfTypeServiceProxy(componentInstance)) {
850 //For service proxy the inputs are already handled under instance properties above
851 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
854 //M3[00001] - NODE TEMPLATE INTERFACES - START
855 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
856 instanceUniqueId, component);
857 //M3[00001] - NODE TEMPLATE INTERFACES - END
858 if (props != null && !props.isEmpty()) {
859 nodeTemplate.setProperties(props);
862 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
863 if (groupInstances != null) {
864 if (groupsMap == null) {
865 groupsMap = new HashMap<>();
867 for (GroupInstance groupInst : groupInstances) {
868 boolean addToTosca = true;
870 List<String> artifacts = groupInst.getArtifacts();
871 if (artifacts == null || artifacts.isEmpty()) {
876 ToscaGroupTemplate toscaGroup = groupExportParser.getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
877 groupsMap.put(groupInst.getName(), toscaGroup);
882 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
884 if (groupsMap != null) {
885 log.debug("instance groups added");
886 topologyTemplate.addGroups(groupsMap);
888 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(((Service) component).getForwardingPaths())) {
889 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
890 component.getName());
891 ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache, toscaOperationFacade);
892 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
893 component.getName());
895 if (convertNodeTemplatesRes == null) {
896 convertNodeTemplatesRes = Either.left(nodeTemplates);
898 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
899 component.getComponentType());
900 return convertNodeTemplatesRes;
903 private void handleInstanceInterfaces(
904 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
905 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
906 String instanceUniqueId,
907 Component parentComponent) {
909 Map<String, Object> interfaces;
911 // we need to handle service proxy interfaces
912 if(isComponentOfTypeServiceProxy(componentInstance)) {
913 if(MapUtils.isEmpty(componentInstanceInterfaces)
914 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
917 List<ComponentInstanceInterface> currServiceInterfaces =
918 componentInstanceInterfaces.get(instanceUniqueId);
920 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
921 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
922 .getUniqueId(), instInterface));
924 interfaces = interfacesOperationsConverter
925 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
929 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
930 componentInstance, instanceUniqueId);
932 nodeTemplate.setInterfaces(interfaces);
935 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
936 return Objects.nonNull(componentInstance.getOriginType())
937 && componentInstance.getOriginType().getValue().equals("Service Proxy");
940 //M3[00001] - NODE TEMPLATE INTERFACES - START
941 private Map<String, Object> getComponentInstanceInterfaceInstances(Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
942 ComponentInstance componentInstance,
943 String instanceUniqueId) {
944 if(MapUtils.isEmpty(componentInstancesInterfaces)) {
948 List<ComponentInstanceInterface> componentInstanceInterfaces =
949 componentInstancesInterfaces.get(instanceUniqueId);
951 if(CollectionUtils.isEmpty(componentInstanceInterfaces)) {
955 Map<String, Object> interfaces = new HashMap<>();
956 for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
957 interfaces.put(componentInstanceInterface.getInterfaceId(),
958 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
961 componentInstance.setInterfaces(interfaces);
966 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
967 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
968 String instanceUniqueId, Map<String, Object> props) {
970 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
971 if (instanceInputsList != null) {
972 instanceInputsList.forEach(input -> {
974 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
975 ? input.getValue() : input.getDefaultValue();
976 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
981 private void addPropertiesOfComponentInstance(
982 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
983 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
984 Map<String, Object> props) {
986 if (isNotEmpty(componentInstancesProperties)) {
987 componentInstancesProperties.get(instanceUniqueId)
988 // Converts and adds each value to property map
989 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
994 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
995 Component componentOfInstance, Map<String, Object> props) {
997 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
998 if (isNotEmpty(componentProperties)) {
999 componentProperties.stream()
1000 // Filters out properties with empty default values
1001 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
1002 // Converts and adds each value to property map
1003 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
1004 prop::getDefaultValue));
1010 * @param componentInstance
1015 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
1016 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
1017 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
1018 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
1019 props.put(prop.getName(), convertedValue);
1023 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
1024 ComponentInstance componentInstance, T input, Supplier<String> supplier) {
1025 log.debug("Convert property or input value {} for instance {}", input.getName(),
1026 componentInstance.getUniqueId());
1027 String propertyType = input.getType();
1028 String innerType = null;
1029 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
1030 innerType = input.getSchema().getProperty().getType();
1032 return propertyConvertor.convertToToscaObject(input, supplier.get(), dataTypes, true);
1035 private ToscaNodeType createNodeType(Component component) {
1036 ToscaNodeType toscaNodeType = new ToscaNodeType();
1037 if (ModelConverter.isAtomicComponent(component)) {
1038 if (((Resource) component).getDerivedFrom() != null) {
1039 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
1041 toscaNodeType.setDescription(component.getDescription());
1043 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
1045 toscaNodeType.setDerived_from(derivedFrom);
1047 return toscaNodeType;
1050 private Either<Map<String, Object>, ToscaError> createProxyInterfaceTypes(Component container) {
1052 Map<String, Object> proxyInterfaceTypes = new HashMap<>();
1053 Either<Map<String, Object>, ToscaError> res = Either.left(proxyInterfaceTypes);
1054 List<ComponentInstance> componentInstances = container.getComponentInstances();
1055 if (CollectionUtils.isEmpty(componentInstances)) {
1058 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1059 componentInstances.stream()
1060 .filter(this::isComponentOfTypeServiceProxy)
1061 .forEach(inst -> serviceProxyInstanceList.put(inst.getToscaComponentName(), inst));
1062 if (MapUtils.isEmpty(serviceProxyInstanceList)) {
1065 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1066 Component serviceComponent;
1067 ComponentParametersView componentParametersView = new ComponentParametersView();
1068 componentParametersView.disableAll();
1069 componentParametersView.setIgnoreInterfaces(false);
1070 Either<Component, StorageOperationStatus> service = toscaOperationFacade
1071 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1072 if (service.isRight()) {
1073 log.debug("Failed to fetch original service component with id {} for instance {}",
1074 entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1075 return Either.right(ToscaError.GENERAL_ERROR);
1077 serviceComponent = service.left().value();
1080 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
1081 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
1082 if(lifecycleTypeEither.isRight()){
1083 log.debug("Failed to retrieve global interface types :", lifecycleTypeEither.right().value());
1084 return Either.right(ToscaError.GENERAL_ERROR);
1087 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream()
1088 .map(InterfaceDataDefinition::getType)
1089 .collect(Collectors.toList());
1090 //Add interface types for local interfaces in the original service component for proxy
1091 Map<String, Object> localInterfaceTypes = addInterfaceTypeElement(serviceComponent,
1092 allGlobalInterfaceTypes);
1093 if (MapUtils.isNotEmpty(localInterfaceTypes)) {
1094 proxyInterfaceTypes.putAll(localInterfaceTypes);
1098 return Either.left(proxyInterfaceTypes);
1101 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache,
1102 Component container) {
1104 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
1105 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
1107 List<ComponentInstance> componentInstances = container.getComponentInstances();
1109 if (componentInstances == null || componentInstances.isEmpty()) {
1112 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1113 List<ComponentInstance> proxyInst = componentInstances.stream()
1114 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
1115 .collect(Collectors.toList());
1116 if (proxyInst != null && !proxyInst.isEmpty()) {
1117 for (ComponentInstance inst : proxyInst) {
1118 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
1122 if (serviceProxyInstanceList.isEmpty()) {
1125 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
1126 .getLatestByName("serviceProxy");
1127 if (serviceProxyOrigin.isRight()) {
1128 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
1129 serviceProxyOrigin.right().value());
1130 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
1132 Component origComponent = serviceProxyOrigin.left().value();
1134 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1135 Component serviceComponent = null;
1136 ComponentParametersView componentParametersView = new ComponentParametersView();
1137 componentParametersView.disableAll();
1138 componentParametersView.setIgnoreCategories(false);
1139 componentParametersView.setIgnoreProperties(false);
1140 componentParametersView.setIgnoreInputs(false);
1141 componentParametersView.setIgnoreInterfaces(false);
1142 componentParametersView.setIgnoreRequirements(false);
1143 Either<Component, StorageOperationStatus> service = toscaOperationFacade
1144 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1145 if (service.isRight()) {
1146 log.debug("Failed to fetch resource with id {} for instance {}", entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1148 serviceComponent = service.left().value();
1151 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache, origComponent, serviceComponent,
1152 entryProxy.getValue());
1153 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
1156 return Either.left(nodeTypesMap);
1159 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent,
1160 Component proxyComponent, ComponentInstance instance) {
1161 ToscaNodeType toscaNodeType = new ToscaNodeType();
1162 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1164 toscaNodeType.setDerived_from(derivedFrom);
1165 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
1166 if (dataTypesEither.isRight()) {
1167 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1169 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1170 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1171 .convertProxyCapabilities(componentCache, instance, dataTypes);
1173 if (MapUtils.isNotEmpty(capabilities)) {
1174 toscaNodeType.setCapabilities(capabilities);
1176 List<Map<String, ToscaRequirement>> proxyNodeTypeRequirements = this.capabilityRequirementConverter
1177 .convertProxyRequirements(componentCache, instance);
1178 if (CollectionUtils.isNotEmpty(proxyNodeTypeRequirements)) {
1179 toscaNodeType.setRequirements(proxyNodeTypeRequirements);
1181 Optional<Map<String, ToscaProperty>> proxyProperties = getProxyNodeTypeProperties(proxyComponent, dataTypes);
1182 proxyProperties.ifPresent(toscaNodeType::setProperties);
1184 Optional<Map<String, Object>> proxyInterfaces = getProxyNodeTypeInterfaces(proxyComponent, dataTypes);
1185 proxyInterfaces.ifPresent(toscaNodeType::setInterfaces);
1187 return toscaNodeType;
1190 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1191 ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
1192 ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
1194 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1195 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
1196 log.debug("Failed to convert component instance requirements for the component instance {}. ",
1197 componentInstance.getName());
1198 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1200 if (!toscaRequirements.isEmpty()) {
1201 nodeTypeTemplate.setRequirements(toscaRequirements);
1203 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1204 return Either.left(nodeTypeTemplate);
1207 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1208 List<RequirementCapabilityRelDef> relations, Component originComponent,
1209 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1210 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1211 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1212 return isEmpty(filteredRelations) ||
1213 filteredRelations.stream()
1214 .allMatch(rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements, componentCache));
1217 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1218 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1219 List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
1221 boolean result = true;
1222 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1223 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1224 Either<Component, StorageOperationStatus> getOriginRes = null;
1225 Optional<RequirementDefinition> reqOpt = Optional.empty();
1226 Component toOriginComponent = null;
1227 Optional<CapabilityDefinition> capOpt = Optional.empty();
1229 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1230 .findFirst().orElse(null);
1231 if (toInstance == null) {
1232 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1237 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1238 if (!reqOpt.isPresent()) {
1239 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1240 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1245 ComponentParametersView filter = new ComponentParametersView(true);
1246 filter.setIgnoreComponentInstances(false);
1247 filter.setIgnoreCapabilities(false);
1248 filter.setIgnoreGroups(false);
1249 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1250 if (getOriginRes.isRight()) {
1251 log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1252 reqOpt.get().getName(), toInstance.getActualComponentUid());
1257 toOriginComponent = getOriginRes.left().value();
1258 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1259 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1260 if (!capOpt.isPresent()) {
1261 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1262 if(!capOpt.isPresent()){
1264 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1265 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1270 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1271 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1276 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
1277 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1280 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement) {
1281 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1282 if (!cap.isPresent()) {
1283 log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1288 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
1289 List<String> reducedPath = capability.getPath();
1290 if(capability.getOwnerId() !=null){
1291 reducedPath = capabilityRequirementConverter.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
1293 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1294 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1295 if (buildCapNameRes.isRight()) {
1297 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1298 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1301 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache, fromOriginComponent,
1302 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1303 if (buildReqNameRes.isRight()) {
1305 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1306 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1309 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1310 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1311 toscaRequirement.setNode(toInstance.getName());
1312 toscaRequirement.setCapability(buildCapNameRes.left().value());
1313 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1314 toscaRequirements.add(toscaReqMap);
1318 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
1319 for(List<RequirementDefinition> reqList: reqMap.values()){
1320 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
1321 if(reqOpt.isPresent()){
1325 return Optional.empty();
1329 * Allows detecting the requirement belonging to the received relationship
1330 * The detection logic is: A requirement belongs to a relationship IF 1.The
1331 * name of the requirement equals to the "requirement" field of the
1332 * relation; AND 2. In case of a non-atomic resource, OwnerId of the
1333 * requirement equals to requirementOwnerId of the relation OR uniqueId of
1334 * toInstance equals to capabilityOwnerId of the relation
1336 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
1337 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1338 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1339 requirement.getName(), reqAndRelationshipPair.getRequirement());
1342 return ModelConverter.isAtomicComponent(originComponent) ||
1343 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1346 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
1347 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId())
1348 || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())
1349 || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId()));
1352 private boolean isCvfc(Component component) {
1353 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1354 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1357 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1358 SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
1360 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1361 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1362 .convertSubstitutionMappingCapabilities(componentCache, component);
1363 if (toscaCapabilitiesRes.isRight()) {
1364 result = Either.right(toscaCapabilitiesRes.right().value());
1365 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1366 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1367 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1368 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1370 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1374 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
1375 Map<String, DataTypeDefinition> dataTypes) {
1376 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component,
1378 if (!toscaCapabilities.isEmpty()) {
1379 nodeType.setCapabilities(toscaCapabilities);
1381 log.debug("Finish convert Capabilities for node type");
1383 return Either.left(nodeType);
1386 private Map<String, ToscaTemplateArtifact> convertToNodeTemplateArtifacts(Map<String, ToscaArtifactDataDefinition> artifacts) {
1387 if (artifacts == null) {
1390 Map<String, ToscaTemplateArtifact> arts = new HashMap<>();
1391 for (Map.Entry<String, ToscaArtifactDataDefinition> entry : artifacts.entrySet()) {
1392 ToscaTemplateArtifact artifact = new ToscaTemplateArtifact();
1393 artifact.setFile(entry.getValue().getFile());
1394 artifact.setType(entry.getValue().getType());
1395 arts.put(entry.getKey(), artifact);
1400 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1401 if (inNodeFilter == null){
1404 NodeFilter nodeFilter = new NodeFilter();
1406 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1407 inNodeFilter.getCapabilities();
1409 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1411 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1412 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1414 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1415 copyNodeFilterProperties(origProperties, propertiesCopy);
1417 if(CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1418 nodeFilter.setCapabilities(capabilitiesCopy);
1421 if(CollectionUtils.isNotEmpty(propertiesCopy)) {
1422 nodeFilter.setProperties(propertiesCopy);
1425 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1428 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1433 private Object cloneToscaId(Object toscaId) {
1434 return Objects.isNull(toscaId) ? null
1435 : cloneObjectFromYml(toscaId, toscaId.getClass());
1439 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1440 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1441 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1443 private void copyNodeFilterCapabilitiesTemplate(
1444 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1445 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1446 if(origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1447 origCapabilities.getListToscaDataDefinition().isEmpty() ) {
1450 for(RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1451 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1452 CapabilityFilter capabilityFilter = new CapabilityFilter();
1453 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1454 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1455 capabilityFilter.setProperties(propertiesCopy);
1456 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1457 capabilitiesCopy.add(capabilityFilterCopyMap);
1461 private List<Object> copyNodeFilterProperty(List<Object> propertyList) {
1462 String listAsString = yamlUtil.objectToYaml(propertyList);
1463 return yamlUtil.yamlToObject(listAsString, List.class);
1467 private void copyNodeFilterProperties(
1468 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1469 List<Map<String, List<Object>>> propertiesCopy) {
1470 if(origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1471 origProperties.isEmpty()) {
1474 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1475 for(RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
1476 for(String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1477 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1478 String propertyName = propertyDataDefinition.getName();
1479 if (propertyMapCopy.containsKey(propertyName)){
1480 addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
1482 if (propertyName != null) {
1483 List propsList = new ArrayList();
1484 addPropertyConstraintValueToList(propertyName, propertyValObj, propsList);
1485 propertyMapCopy.put(propertyName, propsList);
1487 propertyMapCopy.putAll(propertyValObj);
1492 propertyMapCopy.entrySet().stream().forEach(entry ->
1493 addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
1496 private void addPropertyConstraintValueToList(String propertyName, Map propertyValObj, List propsList) {
1497 if(propertyValObj.containsKey(propertyName)) {
1498 propsList.add(propertyValObj.get(propertyName));
1500 propsList.add(propertyValObj);
1506 private void addCalculatedConstraintsIntoPropertiesList(List<Map<String, List<Object>>> propertiesCopy,
1507 Entry<String, List<Object>> entry) {
1508 Map<String, List<Object>> tempMap = new HashMap<>();
1509 tempMap.put(entry.getKey(), entry.getValue());
1510 propertiesCopy.add(tempMap);
1513 private static class CustomRepresenter extends Representer {
1514 CustomRepresenter() {
1516 // null representer is exceptional and it is stored as an instance
1518 this.nullRepresenter = new RepresentNull();
1523 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1525 if (propertyValue == null) {
1528 // skip not relevant for Tosca property
1529 if ("dependencies".equals(property.getName())) {
1532 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1534 return "_defaultp_".equals(property.getName())
1535 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1539 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1540 // remove the bean type from the output yaml (!! ...)
1541 if (!classTags.containsKey(javaBean.getClass())) {
1542 addClassTag(javaBean.getClass(), Tag.MAP);
1545 return super.representJavaBean(properties, javaBean);
1548 private class RepresentNull implements Represent {
1550 public Node representData(Object data) {
1551 // possible values are here http://yaml.org/type/null.html
1552 return representScalar(Tag.NULL, "");
1557 private static class UnsortedPropertyUtils extends PropertyUtils {
1559 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1560 throws IntrospectionException {
1561 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1562 return new LinkedHashSet<>(fields);
1566 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1567 ObjectMapper objectMapper = new ObjectMapper();
1568 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1570 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1571 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1572 interfaceAsMap.remove("empty");
1574 if(MapUtils.isNotEmpty(operations)) {
1575 interfaceAsMap.putAll(operations);
1578 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1580 return interfaceObject;
1584 Optional<Map<String, ToscaProperty>> getProxyNodeTypeProperties(Component proxyComponent,
1585 Map<String, DataTypeDefinition>
1587 if (Objects.isNull(proxyComponent)) {
1588 return Optional.empty();
1590 Map<String, ToscaProperty> proxyProperties = new HashMap<>();
1591 addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties);
1592 if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) {
1593 proxyProperties.putAll(proxyComponent.getProperties().stream()
1594 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition,
1595 proxyComponent.getInputs()))
1596 .collect(Collectors.toMap(PropertyDataDefinition::getName,
1597 property -> propertyConvertor.convertProperty(dataTypes, property,
1598 PropertyConvertor.PropertyType.PROPERTY))));
1600 return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty();
1603 void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
1604 List<InputDefinition> componentInputs,
1605 Map<String, ToscaProperty> mergedProperties) {
1606 if (CollectionUtils.isEmpty(componentInputs)) {
1609 for(InputDefinition input : componentInputs) {
1610 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input,
1611 PropertyConvertor.PropertyType.INPUT);
1612 mergedProperties.put(input.getName(), property);
1616 Optional<Map<String, Object>> getProxyNodeTypeInterfaces(Component proxyComponent,
1617 Map<String, DataTypeDefinition> dataTypes) {
1618 if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) {
1619 return Optional.empty();
1621 Map<String, InterfaceDefinition> proxyComponentInterfaces = proxyComponent.getInterfaces();
1622 //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is
1623 // always available in the proxy node template
1624 removeOperationImplementationForProxyNodeType(proxyComponentInterfaces);
1625 return Optional.ofNullable(interfacesOperationsConverter
1626 .getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes,
1630 private static void removeOperationImplementationForProxyNodeType(
1631 Map<String, InterfaceDefinition> proxyComponentInterfaces) {
1632 if (MapUtils.isEmpty(proxyComponentInterfaces)) {
1635 proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations)
1636 .filter(MapUtils::isNotEmpty)
1637 .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null)));