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;
28 import java.beans.IntrospectionException;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.LinkedHashSet;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
40 import java.util.function.Supplier;
41 import java.util.stream.Collectors;
42 import org.apache.commons.collections.CollectionUtils;
43 import org.apache.commons.collections.MapUtils;
44 import org.apache.commons.lang.StringUtils;
45 import org.apache.commons.lang3.tuple.ImmutablePair;
46 import org.apache.commons.lang3.tuple.ImmutableTriple;
47 import org.apache.commons.lang3.tuple.Triple;
48 import org.onap.sdc.tosca.services.YamlUtil;
49 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
50 import org.openecomp.sdc.be.config.ConfigurationManager;
51 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
52 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition;
61 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition;
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;
124 import com.fasterxml.jackson.databind.ObjectMapper;
125 import com.fasterxml.jackson.databind.SerializationFeature;
126 import fj.data.Either;
128 @org.springframework.stereotype.Component("tosca-export-handler")
129 public class ToscaExportHandler {
131 private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
133 private ApplicationDataTypeCache dataTypeCache;
134 private ToscaOperationFacade toscaOperationFacade;
135 private CapabilityRequirementConverter capabilityRequirementConverter;
136 private PolicyExportParser policyExportParser;
137 private GroupExportParser groupExportParser;
138 private PropertyConvertor propertyConvertor;
139 private InputConverter inputConverter;
140 private InterfaceLifecycleOperation interfaceLifecycleOperation;
141 private InterfacesOperationsConverter interfacesOperationsConverter;
144 public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade,
145 CapabilityRequirementConverter capabilityRequirementConverter,
146 PolicyExportParser policyExportParser,
147 GroupExportParser groupExportParser, PropertyConvertor propertyConvertor,
148 InputConverter inputConverter,
149 InterfaceLifecycleOperation interfaceLifecycleOperation,
150 InterfacesOperationsConverter interfacesOperationsConverter) {
151 this.dataTypeCache = dataTypeCache;
152 this.toscaOperationFacade = toscaOperationFacade;
153 this.capabilityRequirementConverter = capabilityRequirementConverter;
154 this.policyExportParser = policyExportParser;
155 this.groupExportParser = groupExportParser;
156 this.propertyConvertor = propertyConvertor;
157 this.inputConverter = inputConverter;
158 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
159 this.interfacesOperationsConverter = interfacesOperationsConverter;
162 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
163 private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
164 private static final String IMPORTS_FILE_KEY = "file";
165 private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
166 public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
167 private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
168 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
169 private static final String NATIVE_ROOT = "tosca.nodes.Root";
170 private static YamlUtil yamlUtil = new YamlUtil();
172 public ToscaExportHandler() {
175 public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
176 return convertToToscaTemplate(component).left().map(this::createToscaRepresentation);
179 public Either<ToscaRepresentation, ToscaError> exportComponentInterface(final Component component,
180 final boolean isAssociatedComponent) {
181 final List<Map<String, Map<String, String>>> defaultToscaImportConfig = getDefaultToscaImportConfig();
182 if (CollectionUtils.isEmpty(defaultToscaImportConfig)) {
183 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
184 return Either.right(ToscaError.GENERAL_ERROR);
187 String toscaVersion = null;
188 if (component instanceof Resource) {
189 toscaVersion = ((Resource) component).getToscaVersion();
191 ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
192 toscaTemplate.setImports(new ArrayList<>(defaultToscaImportConfig));
193 final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
194 final Either<ToscaTemplate, ToscaError> toscaTemplateRes =
195 convertInterfaceNodeType(new HashMap<>(), component, 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 return ToscaRepresentation.make(sb.toString().getBytes(), toscaTemplate);
229 public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
230 ToscaTemplate toscaTemplate = new ToscaTemplate(null);
231 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
233 if (fillImports.isRight()) {
234 return Either.right(fillImports.right().value());
236 return Either.left(fillImports.left().value().left);
239 public Either<ToscaTemplate, ToscaError> convertToToscaTemplate(final Component component) {
240 final List<Map<String, Map<String, String>>> defaultToscaImportConfig = getDefaultToscaImportConfig();
241 if (CollectionUtils.isEmpty(defaultToscaImportConfig)) {
242 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
243 return Either.right(ToscaError.GENERAL_ERROR);
245 log.trace("start tosca export for {}", component.getUniqueId());
246 String toscaVersion = null;
247 if (component instanceof Resource) {
248 toscaVersion = ((Resource) component).getToscaVersion();
250 final ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
251 toscaTemplate.setMetadata(convertMetadata(component));
252 toscaTemplate.setImports(new ArrayList<>(defaultToscaImportConfig));
253 final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
254 if (ModelConverter.isAtomicComponent(component)) {
255 log.trace("convert component as node type");
256 return convertNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes);
258 log.trace("convert component as topology template");
259 return convertToscaTemplate(component, toscaTemplate);
264 private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
266 Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
268 if (importsRes.isRight()) {
269 return Either.right(importsRes.right().value());
271 toscaNode = importsRes.left().value().left;
272 Map<String, Component> componentCache = importsRes.left().value().right;
273 Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache,
275 if (nodeTypesMapEither.isRight()) {
276 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
277 nodeTypesMapEither.right().value());
278 return Either.right(nodeTypesMapEither.right().value());
280 Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
281 if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
282 toscaNode.setNode_types(nodeTypesMap);
285 createServiceSubstitutionNodeTypes(componentCache, component, toscaNode);
287 Either<Map<String, Object>, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component);
288 if (proxyInterfaceTypesEither.isRight()) {
289 log.debug("Failed to populate service proxy local interface types in tosca, error {}",
290 nodeTypesMapEither.right().value());
291 return Either.right(proxyInterfaceTypesEither.right().value());
293 Map<String, Object> proxyInterfaceTypes = proxyInterfaceTypesEither.left().value();
294 if (MapUtils.isNotEmpty(proxyInterfaceTypes)) {
295 toscaNode.setInterface_types(proxyInterfaceTypes);
298 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
299 if (dataTypesEither.isRight()) {
300 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
301 return Either.right(ToscaError.GENERAL_ERROR);
303 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
304 ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
305 List<InputDefinition> inputDef = component.getInputs();
306 Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
308 if (!inputs.isEmpty()) {
309 topologyTemplate.setInputs(inputs);
312 final List<ComponentInstance> componentInstances = component.getComponentInstances();
313 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
314 component.getComponentInstancesProperties();
315 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
316 component.getComponentInstancesInterfaces();
317 SubstitutionMapping substitutionMapping = new SubstitutionMapping();
318 if (CollectionUtils.isNotEmpty(componentInstances)) {
319 final Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates =
320 convertNodeTemplates(component, componentInstances,
321 componentInstancesProperties, componentInstanceInterfaces,
322 componentCache, dataTypes, topologyTemplate);
323 if (nodeTemplates.isRight()) {
324 return Either.right(nodeTemplates.right().value());
326 log.debug("node templates converted");
327 topologyTemplate.setNode_templates(nodeTemplates.left().value());
329 convertSubstitutionMappingFilter(componentInstances, substitutionMapping);
332 addGroupsToTopologyTemplate(component, topologyTemplate);
335 addPoliciesToTopologyTemplate(component, topologyTemplate);
336 } catch (SdcResourceNotFoundException e) {
337 log.debug("Fail to add policies to topology template:", e);
338 return Either.right(ToscaError.GENERAL_ERROR);
341 String toscaResourceName;
342 switch (component.getComponentType()) {
344 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
345 .getMetadataDataDefinition()).getToscaResourceName();
348 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
349 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
352 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
353 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
355 substitutionMapping.setNode_type(toscaResourceName);
356 Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
358 if (capabilities.isRight()) {
359 return Either.right(capabilities.right().value());
361 substitutionMapping = capabilities.left().value();
363 Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
364 .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
365 if (requirements.isRight()) {
366 return Either.right(requirements.right().value());
368 substitutionMapping = requirements.left().value();
370 final Optional<Map<String, ToscaProperty>> proxyInputProperties = getProxyNodeTypeInputProperties(component, dataTypes);
371 proxyInputProperties.ifPresent(substitutionMapping::setProperties);
373 topologyTemplate.setSubstitution_mappings(substitutionMapping);
375 toscaNode.setTopology_template(topologyTemplate);
377 return Either.left(toscaNode);
380 private void convertSubstitutionMappingFilter(final List<ComponentInstance> componentInstances,
381 final SubstitutionMapping substitutionMapping) {
382 componentInstances.stream()
383 .filter(componentInstance -> hasSubstitutionFilterDataDefinition(componentInstance.getSubstitutionFilter()))
384 .forEach(componentInstance -> substitutionMapping
385 .setSubstitution_filter(convertToSubstitutionFilterComponent(componentInstance.getSubstitutionFilter())));
388 private boolean hasSubstitutionFilterDataDefinition(
389 final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
391 return substitutionFilterDataDefinition != null && substitutionFilterDataDefinition.getProperties() != null
392 && CollectionUtils.isNotEmpty(substitutionFilterDataDefinition.getProperties().getListToscaDataDefinition());
395 private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) {
396 Map<String, ToscaGroupTemplate> groups = groupExportParser.getGroups(component);
397 if (groups != null) {
398 topologyTemplate.addGroups(groups);
402 private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
403 throws SdcResourceNotFoundException {
404 Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
405 if (policies != null) {
406 topologyTemplate.addPolicies(policies);
410 private ToscaMetadata convertMetadata(Component component) {
411 return convertMetadata(component, false, null);
414 private ToscaMetadata convertMetadata(Component component, boolean isInstance,
415 ComponentInstance componentInstance) {
416 ToscaMetadata toscaMetadata = new ToscaMetadata();
417 toscaMetadata.setInvariantUUID(component.getInvariantUUID());
418 toscaMetadata.setUUID(component.getUUID());
419 toscaMetadata.setDescription(component.getDescription());
420 toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
422 List<CategoryDefinition> categories = component.getCategories();
423 CategoryDefinition categoryDefinition = categories.get(0);
424 toscaMetadata.setCategory(categoryDefinition.getName());
427 toscaMetadata.setVersion(component.getVersion());
428 toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
429 if (componentInstance.getSourceModelInvariant() != null
430 && !componentInstance.getSourceModelInvariant().isEmpty()) {
431 toscaMetadata.setVersion(componentInstance.getComponentVersion());
432 toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
433 toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
434 toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
435 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
436 toscaMetadata.setName(componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
437 } else if (componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
438 toscaMetadata.setName(componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceSubstitution.getDisplayValue());
440 toscaMetadata.setDescription(componentInstance.getDescription());
444 switch (component.getComponentType()) {
446 Resource resource = (Resource) component;
448 if (isInstance && (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution)) {
449 toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
451 toscaMetadata.setType(resource.getResourceType().name());
453 toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
454 toscaMetadata.setResourceVendor(resource.getVendorName());
455 toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
456 toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
459 Service service = (Service) component;
460 toscaMetadata.setType(component.getComponentType().getValue());
461 toscaMetadata.setServiceType(service.getServiceType());
462 toscaMetadata.setServiceRole(service.getServiceRole());
463 toscaMetadata.setServiceFunction(service.getServiceFunction());
464 toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
465 resolveInstantiationTypeAndSetItToToscaMetaData(toscaMetadata, service);
468 toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
469 toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
470 toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
474 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
476 return toscaMetadata;
479 private void resolveInstantiationTypeAndSetItToToscaMetaData(ToscaMetadata toscaMetadata, Service service) {
480 if (service.getInstantiationType() != null) {
481 toscaMetadata.setInstantiationType(service.getInstantiationType());
483 toscaMetadata.setInstantiationType(StringUtils.EMPTY);
487 private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
488 ToscaTemplate toscaTemplate) {
490 final List<Map<String, Map<String, String>>> defaultToscaImportConfig = getDefaultToscaImportConfig();
491 if (CollectionUtils.isEmpty(defaultToscaImportConfig)) {
492 log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
493 return Either.right(ToscaError.GENERAL_ERROR);
495 Map<String, Component> componentCache = new HashMap<>();
497 if (!ModelConverter.isAtomicComponent(component)) {
498 final List<Map<String, Map<String, String>>> additionalImports =
499 toscaTemplate.getImports() == null ? new ArrayList<>(defaultToscaImportConfig)
500 : new ArrayList<>(toscaTemplate.getImports());
502 List<Triple<String, String, Component>> dependecies = new ArrayList<>();
504 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
505 if (isNotEmpty(toscaArtifacts)) {
506 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
507 if (artifactDefinition != null) {
508 Map<String, Map<String, String>> importsListMember = new HashMap<>();
509 Map<String, String> interfaceFiles = new HashMap<>();
510 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
511 StringBuilder keyNameBuilder = new StringBuilder();
512 keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
513 .append(component.getName()).append("-interface");
514 importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
515 additionalImports.add(importsListMember);
518 List<ComponentInstance> componentInstances = component.getComponentInstances();
519 if (componentInstances != null && !componentInstances.isEmpty()) {
520 componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
522 toscaTemplate.setDependencies(dependecies);
523 toscaTemplate.setImports(additionalImports);
525 log.debug("currently imports supported for VF and service only");
527 return Either.left(new ImmutablePair<>(toscaTemplate, componentCache));
530 private List<Map<String, Map<String, String>>> getDefaultToscaImportConfig() {
531 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports();
534 private void createDependency(final Map<String, Component> componentCache,
535 final List<Map<String, Map<String, String>>> imports,
536 final List<Triple<String, String, Component>> dependencies,
537 final ComponentInstance componentInstance) {
538 log.debug("createDependency componentCache {}", componentCache);
539 final Component componentRI = componentCache.get(componentInstance.getComponentUid());
540 if (componentRI == null) {
541 // all resource must be only once!
542 final Either<Component, StorageOperationStatus> resource = toscaOperationFacade
543 .getToscaFullElement(componentInstance.getComponentUid());
544 if ((resource.isRight()) && (log.isDebugEnabled())) {
545 log.debug("Failed to fetch resource with id {} for instance {}", componentInstance.getComponentUid(),
546 componentInstance.getUniqueId());
549 final Component fetchedComponent = resource.left().value();
550 setComponentCache(componentCache, componentInstance, fetchedComponent);
551 addDependencies(imports, dependencies, fetchedComponent);
556 * Sets a componentCache from the given component/resource.
558 private void setComponentCache(final Map<String, Component> componentCache,
559 final ComponentInstance componentInstance,
560 final Component fetchedComponent) {
561 componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
562 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
563 final Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
564 .getToscaFullElement(componentInstance.getSourceModelUid());
565 if (sourceService.isRight() && (log.isDebugEnabled())) {
566 log.debug("Failed to fetch source service with id {} for proxy {}",
567 componentInstance.getSourceModelUid(), componentInstance.getUniqueId());
569 final Component fetchedSource = sourceService.left().value();
570 componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
575 * Retrieves all derived_from nodes and stores it in a predictable order.
577 private void addDependencies(final List<Map<String, Map<String, String>>> imports,
578 final List<Triple<String, String, Component>> dependencies,
579 final Component fetchedComponent) {
580 final Set<Component> componentsList = new LinkedHashSet<>();
581 if (fetchedComponent instanceof Resource) {
582 log.debug("fetchedComponent is a resource {}", fetchedComponent);
584 final Optional<Map<String, String>> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent,
586 if (derivedFromMapOfIdToName.isPresent()) {
587 derivedFromMapOfIdToName.get().entrySet().forEach(entry -> {
588 log.debug("Started entry.getValue() : {}", entry.getValue());
589 if (!NATIVE_ROOT.equals(entry.getValue())) {
590 Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
591 .getToscaElement(entry.getKey());
592 if (resourcefetched != null && resourcefetched.isLeft()) {
593 componentsList.add(resourcefetched.left().value());
598 setImports(imports, dependencies, componentsList);
603 * Returns all derived_from nodes found.
605 private Optional<Map<String, String>> getDerivedFromMapOfIdToName(final Component fetchedComponent,
606 final Set<Component> componentsList) {
607 final Resource parentResource = (Resource) fetchedComponent;
608 Map<String, String> derivedFromMapOfIdToName = new HashMap<>();
609 if (CollectionUtils.isNotEmpty(parentResource.getComponentInstances())) {
610 componentsList.add(fetchedComponent);
611 for (final ComponentInstance componentInstance : parentResource.getComponentInstances()) {
612 final Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
613 .getToscaElement(componentInstance.getComponentUid());
614 if (resourcefetched != null && resourcefetched.isLeft()) {
615 final Map<String, String> derivedWithId = resourcefetched.left().value()
616 .getDerivedFromMapOfIdToName();
617 if (MapUtils.isNotEmpty(derivedWithId)) {
618 derivedFromMapOfIdToName.putAll(derivedWithId);
623 derivedFromMapOfIdToName = parentResource.getDerivedFromMapOfIdToName();
625 log.debug("Started derivedFromMapOfIdToName: {}", derivedFromMapOfIdToName);
626 return Optional.ofNullable(derivedFromMapOfIdToName);
630 * Creates a resource map and adds it to the import list.
632 private void setImports(final List<Map<String, Map<String, String>>> imports,
633 final List<Triple<String, String, Component>> dependencies,
634 final Set<Component> componentsList) {
635 componentsList.forEach(component -> {
636 final Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
637 final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
638 if (artifactDefinition != null) {
639 final Map<String, String> files = new HashMap<>();
640 final String artifactName = artifactDefinition.getArtifactName();
641 files.put(IMPORTS_FILE_KEY, artifactName);
642 final StringBuilder keyNameBuilder = new StringBuilder();
643 keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
644 keyNameBuilder.append("-");
645 keyNameBuilder.append(component.getName());
646 addImports(imports, keyNameBuilder, files);
648 .add(new ImmutableTriple<String, String, Component>(artifactName, artifactDefinition.getEsId(),
651 if (!ModelConverter.isAtomicComponent(component)) {
652 final Map<String, String> interfaceFiles = new HashMap<>();
653 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
654 keyNameBuilder.append("-interface");
655 addImports(imports, keyNameBuilder, interfaceFiles);
662 * Adds the found resource to the import definition list.
664 private void addImports(final List<Map<String, Map<String, String>>> imports,
665 final StringBuilder keyNameBuilder,
666 final Map<String, String> files) {
667 final String mapKey = keyNameBuilder.toString();
668 if (imports.stream().allMatch(stringMapMap -> stringMapMap.get(mapKey) == null)) {
669 final Map<String, Map<String, String>> importsListMember = new HashMap<>();
670 importsListMember.put(keyNameBuilder.toString(), files);
671 imports.add(importsListMember);
675 public static String getInterfaceFilename(String artifactName) {
676 return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
679 private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache,
680 Component component, ToscaTemplate toscaNode,
681 Map<String, ToscaNodeType> nodeTypes) {
682 return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
685 public Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
686 Component component, ToscaTemplate toscaNode,
687 Map<String, ToscaNodeType> nodeTypes,
688 boolean isAssociatedComponent) {
689 log.debug("start convert node type for {}", component.getUniqueId());
690 ToscaNodeType toscaNodeType = createNodeType(component);
692 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
693 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
694 if (lifecycleTypeEither.isRight()) {
695 log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
696 return Either.right(ToscaError.GENERAL_ERROR);
698 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
701 .map(InterfaceDataDefinition::getType)
702 .collect(Collectors.toList());
703 toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
705 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
706 if (dataTypesEither.isRight()) {
707 log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
708 return Either.right(ToscaError.GENERAL_ERROR);
711 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
713 List<InputDefinition> inputDef = component.getInputs();
714 Map<String, ToscaProperty> mergedProperties = new HashMap<>();
715 interfacesOperationsConverter
716 .addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
717 addInputsToProperties(dataTypes, inputDef, mergedProperties);
719 if (CollectionUtils.isNotEmpty(component.getProperties())) {
720 List<PropertyDefinition> properties = component.getProperties();
721 Map<String, ToscaProperty> convertedProperties = properties.stream()
722 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs()))
723 .collect(Collectors.toMap(PropertyDataDefinition::getName,
724 property -> propertyConvertor.convertProperty(dataTypes, property,
725 PropertyConvertor.PropertyType.PROPERTY)));
726 // merge component properties and inputs properties
727 mergedProperties.putAll(convertedProperties);
729 if (MapUtils.isNotEmpty(mergedProperties)) {
730 toscaNodeType.setProperties(mergedProperties);
733 /* convert private data_types */
734 List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
735 if (CollectionUtils.isNotEmpty(privateDataTypes)) {
736 Map<String, ToscaDataType> toscaDataTypeMap = new HashMap<>();
737 for (DataTypeDefinition dataType : privateDataTypes) {
738 log.debug("Emitting private data type: component.name={} dataType.name={}",
739 component.getNormalizedName(), dataType.getName());
740 ToscaDataType toscaDataType = new ToscaDataType();
741 toscaDataType.setDerived_from(dataType.getDerivedFromName());
742 toscaDataType.setDescription(dataType.getDescription());
743 toscaDataType.setVersion(dataType.getVersion());
744 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
745 toscaDataType.setProperties(dataType.getProperties().stream()
746 .collect(Collectors.toMap(
748 s -> propertyConvertor
749 .convertProperty(dataTypes, s, PropertyConvertor.PropertyType.PROPERTY)
752 toscaDataTypeMap.put(dataType.getName(), toscaDataType);
754 toscaNode.setData_types(toscaDataTypeMap);
757 // Extracted to method for code reuse
758 return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
761 private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Map<String, Component> componentsCache,
762 Component component, ToscaTemplate toscaNode,
763 Map<String, ToscaNodeType> nodeTypes,
764 ToscaNodeType toscaNodeType,
765 Map<String, DataTypeDefinition> dataTypes) {
766 Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(componentsCache, component, toscaNodeType,
768 if (capabilities.isRight()) {
769 return Either.right(capabilities.right().value());
771 toscaNodeType = capabilities.left().value();
772 log.debug("Capabilities converted for {}", component.getUniqueId());
774 Either<ToscaNodeType, ToscaError> requirements = capabilityRequirementConverter
775 .convertRequirements(componentsCache, component,
777 if (requirements.isRight()) {
778 return Either.right(requirements.right().value());
780 toscaNodeType = requirements.left().value();
781 log.debug("Requirements converted for {}", component.getUniqueId());
783 String toscaResourceName;
784 switch (component.getComponentType()) {
786 toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
787 .getMetadataDataDefinition()).getToscaResourceName();
790 toscaResourceName = SERVICE_NODE_TYPE_PREFIX
791 + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
794 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
795 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
798 nodeTypes.put(toscaResourceName, toscaNodeType);
799 toscaNode.setNode_types(nodeTypes);
800 log.debug("finish convert node type for {}", component.getUniqueId());
801 return Either.left(toscaNode);
804 protected Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(
806 List<ComponentInstance> componentInstances,
807 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
808 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
809 Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
810 ToscaTopolgyTemplate topologyTemplate) {
812 Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
813 log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
814 component.getComponentType());
815 Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
816 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
818 Map<String, ToscaGroupTemplate> groupsMap = null;
819 for (ComponentInstance componentInstance : componentInstances) {
820 ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
821 if (MapUtils.isNotEmpty(componentInstance.getToscaArtifacts())) {
822 nodeTemplate.setArtifacts(convertToNodeTemplateArtifacts(componentInstance.getToscaArtifacts()));
824 nodeTemplate.setType(componentInstance.getToscaComponentName());
825 nodeTemplate.setDirectives(componentInstance.getDirectives());
826 nodeTemplate.setNode_filter(convertToNodeTemplateNodeFilterComponent(componentInstance.getNodeFilter()));
828 Either<Component, Boolean> originComponentRes = capabilityRequirementConverter
829 .getOriginComponent(componentCache, componentInstance);
830 if (originComponentRes.isRight()) {
831 convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
834 Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
835 componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
836 originComponentRes.left().value(), componentCache);
837 if (requirements.isRight()) {
838 convertNodeTemplatesRes = Either.right(requirements.right().value());
841 String instanceUniqueId = componentInstance.getUniqueId();
842 log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
844 nodeTemplate = requirements.left().value();
846 Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
848 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
849 Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
850 nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
852 nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
855 Either<ToscaNodeTemplate, ToscaError> capabilities = capabilityRequirementConverter
856 .convertComponentInstanceCapabilities(componentInstance, dataTypes, nodeTemplate);
857 if (capabilities.isRight()) {
858 convertNodeTemplatesRes = Either.right(capabilities.right().value());
861 log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
863 nodeTemplate = capabilities.left().value();
864 Map<String, Object> props = new HashMap<>();
866 if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
867 // Adds the properties of parent component to map
868 addPropertiesOfParentComponent(dataTypes, originalComponent, props);
871 if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
872 addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, instanceUniqueId,
876 if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)
877 && !isComponentOfTypeServiceProxy(componentInstance)) {
878 //For service proxy the inputs are already handled under instance properties above
879 addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId,
882 //M3[00001] - NODE TEMPLATE INTERFACES - START
883 handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate,
884 instanceUniqueId, component);
885 //M3[00001] - NODE TEMPLATE INTERFACES - END
886 if (props != null && !props.isEmpty()) {
887 nodeTemplate.setProperties(props);
890 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
891 if (groupInstances != null) {
892 if (groupsMap == null) {
893 groupsMap = new HashMap<>();
895 for (GroupInstance groupInst : groupInstances) {
896 boolean addToTosca = true;
898 List<String> artifacts = groupInst.getArtifacts();
899 if (artifacts == null || artifacts.isEmpty()) {
904 ToscaGroupTemplate toscaGroup = groupExportParser
905 .getToscaGroupTemplate(groupInst, componentInstance.getInvariantName());
906 groupsMap.put(groupInst.getName(), toscaGroup);
911 nodeTemplates.put(componentInstance.getName(), nodeTemplate);
913 if (groupsMap != null) {
914 log.debug("instance groups added");
915 topologyTemplate.addGroups(groupsMap);
917 if (component.getComponentType() == ComponentTypeEnum.SERVICE && isNotEmpty(
918 ((Service) component).getForwardingPaths())) {
919 log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
920 component.getName());
921 ForwardingPathToscaUtil
922 .addForwardingPaths((Service) component, nodeTemplates, capabilityRequirementConverter, componentCache,
923 toscaOperationFacade);
924 log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
925 component.getName());
927 if (convertNodeTemplatesRes == null) {
928 convertNodeTemplatesRes = Either.left(nodeTemplates);
930 log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
931 component.getComponentType());
932 return convertNodeTemplatesRes;
935 private void handleInstanceInterfaces(
936 Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
937 ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate,
938 String instanceUniqueId,
939 Component parentComponent) {
941 Map<String, Object> interfaces;
943 // we need to handle service proxy interfaces
944 if (isComponentOfTypeServiceProxy(componentInstance)) {
945 if (MapUtils.isEmpty(componentInstanceInterfaces)
946 || !componentInstanceInterfaces.containsKey(instanceUniqueId)) {
949 List<ComponentInstanceInterface> currServiceInterfaces =
950 componentInstanceInterfaces.get(instanceUniqueId);
952 Map<String, InterfaceDefinition> tmpInterfaces = new HashMap<>();
953 currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface
954 .getUniqueId(), instInterface));
956 interfaces = interfacesOperationsConverter
957 .getInterfacesMap(parentComponent, componentInstance, tmpInterfaces, dataTypes, true, true);
961 getComponentInstanceInterfaceInstances(componentInstanceInterfaces,
962 componentInstance, instanceUniqueId);
964 nodeTemplate.setInterfaces(interfaces);
967 private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) {
968 return Objects.nonNull(componentInstance.getOriginType())
969 && componentInstance.getOriginType().getValue().equals("Service Proxy");
972 //M3[00001] - NODE TEMPLATE INTERFACES - START
973 private Map<String, Object> getComponentInstanceInterfaceInstances(
974 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces,
975 ComponentInstance componentInstance,
976 String instanceUniqueId) {
977 if (MapUtils.isEmpty(componentInstancesInterfaces)) {
981 List<ComponentInstanceInterface> componentInstanceInterfaces =
982 componentInstancesInterfaces.get(instanceUniqueId);
984 if (CollectionUtils.isEmpty(componentInstanceInterfaces)) {
988 Map<String, Object> interfaces = new HashMap<>();
989 for (ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) {
990 interfaces.put(componentInstanceInterface.getInterfaceId(),
991 removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition()));
994 componentInstance.setInterfaces(interfaces);
999 private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
1000 Map<String, List<ComponentInstanceInput>> componentInstancesInputs,
1001 String instanceUniqueId, Map<String, Object> props) {
1003 List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
1004 if (instanceInputsList != null) {
1005 instanceInputsList.forEach(input -> {
1007 Supplier<String> supplier = () -> input.getValue() != null && !Objects.isNull(input.getValue())
1008 ? input.getValue() : input.getDefaultValue();
1009 propertyConvertor.convertAndAddValue(dataTypes, props, input, supplier);
1014 private void addPropertiesOfComponentInstance(
1015 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
1016 Map<String, DataTypeDefinition> dataTypes, String instanceUniqueId,
1017 Map<String, Object> props) {
1019 if (isNotEmpty(componentInstancesProperties)) {
1020 componentInstancesProperties.get(instanceUniqueId)
1021 // Converts and adds each value to property map
1022 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
1027 private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
1028 Component componentOfInstance, Map<String, Object> props) {
1030 List<PropertyDefinition> componentProperties = componentOfInstance.getProperties();
1031 if (isNotEmpty(componentProperties)) {
1032 componentProperties.stream()
1033 // Filters out properties with empty default values
1034 .filter(prop -> StringUtils.isNotEmpty(prop.getDefaultValue()))
1035 // Converts and adds each value to property map
1036 .forEach(prop -> propertyConvertor.convertAndAddValue(dataTypes, props, prop,
1037 prop::getDefaultValue));
1044 private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
1045 Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
1046 Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
1047 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
1048 props.put(prop.getName(), convertedValue);
1052 private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
1053 ComponentInstance componentInstance, T input,
1054 Supplier<String> supplier) {
1055 log.debug("Convert property or input value {} for instance {}", input.getName(),
1056 componentInstance.getUniqueId());
1057 String propertyType = input.getType();
1058 String innerType = null;
1059 if (input.getSchema() != null && input.getSchema().getProperty() != null) {
1060 innerType = input.getSchema().getProperty().getType();
1062 return propertyConvertor.convertToToscaObject(input, supplier.get(), dataTypes, true);
1065 private ToscaNodeType createNodeType(Component component) {
1066 ToscaNodeType toscaNodeType = new ToscaNodeType();
1067 if (ModelConverter.isAtomicComponent(component)) {
1068 if (((Resource) component).getDerivedFrom() != null) {
1069 toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
1071 toscaNodeType.setDescription(component.getDescription());
1073 String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
1075 toscaNodeType.setDerived_from(derivedFrom);
1077 if (component instanceof Resource) {
1078 final List<AttributeDataDefinition> attributes = ((Resource) component).getAttributes();
1079 if (CollectionUtils.isNotEmpty(attributes)) {
1080 final Map<String, AttributeDataDefinition> attributeDataDefinitionMap
1081 = attributes.stream().collect(Collectors.toMap(AttributeDataDefinition::getName, a -> a));
1082 toscaNodeType.setAttributes(attributeDataDefinitionMap);
1085 return toscaNodeType;
1088 private Either<Map<String, Object>, ToscaError> createProxyInterfaceTypes(Component container) {
1090 Map<String, Object> proxyInterfaceTypes = new HashMap<>();
1091 Either<Map<String, Object>, ToscaError> res = Either.left(proxyInterfaceTypes);
1092 List<ComponentInstance> componentInstances = container.getComponentInstances();
1093 if (CollectionUtils.isEmpty(componentInstances)) {
1096 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1097 componentInstances.stream()
1098 .filter(this::isComponentOfTypeServiceProxy)
1099 .forEach(inst -> serviceProxyInstanceList.put(inst.getToscaComponentName(), inst));
1100 if (MapUtils.isEmpty(serviceProxyInstanceList)) {
1103 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1104 Component serviceComponent;
1105 ComponentParametersView componentParametersView = new ComponentParametersView();
1106 componentParametersView.disableAll();
1107 componentParametersView.setIgnoreInterfaces(false);
1108 Either<Component, StorageOperationStatus> service = toscaOperationFacade
1109 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1110 if (service.isRight()) {
1111 log.debug("Failed to fetch original service component with id {} for instance {}",
1112 entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1113 return Either.right(ToscaError.GENERAL_ERROR);
1115 serviceComponent = service.left().value();
1118 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
1119 interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
1120 if (lifecycleTypeEither.isRight()) {
1121 log.debug("Failed to retrieve global interface types :", lifecycleTypeEither.right().value());
1122 return Either.right(ToscaError.GENERAL_ERROR);
1125 List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream()
1126 .map(InterfaceDataDefinition::getType)
1127 .collect(Collectors.toList());
1128 //Add interface types for local interfaces in the original service component for proxy
1129 Map<String, Object> localInterfaceTypes = addInterfaceTypeElement(serviceComponent,
1130 allGlobalInterfaceTypes);
1131 if (MapUtils.isNotEmpty(localInterfaceTypes)) {
1132 proxyInterfaceTypes.putAll(localInterfaceTypes);
1136 return Either.left(proxyInterfaceTypes);
1139 private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache,
1140 Component container) {
1142 Map<String, ToscaNodeType> nodeTypesMap = new HashMap<>();
1143 Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
1145 List<ComponentInstance> componentInstances = container.getComponentInstances();
1147 if (componentInstances == null || componentInstances.isEmpty()) {
1150 Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
1151 List<ComponentInstance> proxyInst = componentInstances.stream()
1152 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
1153 .collect(Collectors.toList());
1154 if (proxyInst != null && !proxyInst.isEmpty()) {
1155 for (ComponentInstance inst : proxyInst) {
1156 serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
1160 if (serviceProxyInstanceList.isEmpty()) {
1163 Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
1164 .getLatestByName("serviceProxy");
1165 if (serviceProxyOrigin.isRight()) {
1166 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
1167 serviceProxyOrigin.right().value());
1168 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
1170 Component origComponent = serviceProxyOrigin.left().value();
1172 for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
1173 Component serviceComponent = null;
1174 ComponentParametersView componentParametersView = new ComponentParametersView();
1175 componentParametersView.disableAll();
1176 componentParametersView.setIgnoreCategories(false);
1177 componentParametersView.setIgnoreProperties(false);
1178 componentParametersView.setIgnoreInputs(false);
1179 componentParametersView.setIgnoreInterfaces(false);
1180 componentParametersView.setIgnoreRequirements(false);
1181 Either<Component, StorageOperationStatus> service = toscaOperationFacade
1182 .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
1183 if (service.isRight()) {
1184 log.debug("Failed to fetch resource with id {} for instance {}",
1185 entryProxy.getValue().getSourceModelUid(), entryProxy.getValue().getName());
1187 serviceComponent = service.left().value();
1190 ToscaNodeType toscaNodeType = createProxyNodeType(componentCache, origComponent, serviceComponent,
1191 entryProxy.getValue());
1192 nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
1195 return Either.left(nodeTypesMap);
1198 private void createServiceSubstitutionNodeTypes(final Map<String, Component> componentCache,
1199 final Component container, final ToscaTemplate toscaNode) {
1200 final List<ComponentInstance> componentInstances = container.getComponentInstances();
1202 if (CollectionUtils.isEmpty(componentInstances)) {
1205 final List<ComponentInstance> serviceSubstitutionInstanceList = componentInstances.stream()
1206 .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceSubstitution.name()))
1207 .collect(Collectors.toList());
1208 if (CollectionUtils.isNotEmpty(serviceSubstitutionInstanceList)) {
1209 for (ComponentInstance inst : serviceSubstitutionInstanceList) {
1210 final Map<String, ToscaNodeType> nodeTypes = toscaNode.getNode_types() == null ? new HashMap<>() : toscaNode.getNode_types();
1211 convertInterfaceNodeType(new HashMap<>(), componentCache.get(inst.getSourceModelUid()), toscaNode, nodeTypes, true);
1216 private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache, Component origComponent,
1217 Component proxyComponent, ComponentInstance instance) {
1218 ToscaNodeType toscaNodeType = new ToscaNodeType();
1219 String derivedFrom = ((Resource) origComponent).getToscaResourceName();
1221 toscaNodeType.setDerived_from(derivedFrom);
1222 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
1223 if (dataTypesEither.isRight()) {
1224 log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
1226 Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
1227 Map<String, ToscaCapability> capabilities = this.capabilityRequirementConverter
1228 .convertProxyCapabilities(componentCache, instance, dataTypes);
1230 if (MapUtils.isNotEmpty(capabilities)) {
1231 toscaNodeType.setCapabilities(capabilities);
1233 List<Map<String, ToscaRequirement>> proxyNodeTypeRequirements = this.capabilityRequirementConverter
1234 .convertProxyRequirements(componentCache, instance);
1235 if (CollectionUtils.isNotEmpty(proxyNodeTypeRequirements)) {
1236 toscaNodeType.setRequirements(proxyNodeTypeRequirements);
1238 Optional<Map<String, ToscaProperty>> proxyProperties = getProxyNodeTypeProperties(proxyComponent, dataTypes);
1239 proxyProperties.ifPresent(toscaNodeType::setProperties);
1241 Optional<Map<String, Object>> proxyInterfaces = getProxyNodeTypeInterfaces(proxyComponent, dataTypes);
1242 proxyInterfaces.ifPresent(toscaNodeType::setInterfaces);
1244 return toscaNodeType;
1247 private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
1248 ComponentInstance componentInstance,
1249 List<RequirementCapabilityRelDef> relations,
1250 ToscaNodeTemplate nodeTypeTemplate,
1251 Component originComponent,
1252 Map<String, Component> componentCache) {
1254 List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
1255 if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements,
1257 log.debug("Failed to convert component instance requirements for the component instance {}. ",
1258 componentInstance.getName());
1259 return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
1261 if (!toscaRequirements.isEmpty()) {
1262 nodeTypeTemplate.setRequirements(toscaRequirements);
1264 log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
1265 return Either.left(nodeTypeTemplate);
1268 private boolean addRequirements(Component component, ComponentInstance componentInstance,
1269 List<RequirementCapabilityRelDef> relations, Component originComponent,
1270 List<Map<String, ToscaTemplateRequirement>> toscaRequirements,
1271 Map<String, Component> componentCache) {
1272 List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
1273 .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
1274 return isEmpty(filteredRelations) ||
1275 filteredRelations.stream()
1277 rel -> addRequirement(componentInstance, originComponent, component.getComponentInstances(), rel,
1278 toscaRequirements, componentCache));
1281 private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
1282 List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
1283 List<Map<String, ToscaTemplateRequirement>> toscaRequirements,
1284 Map<String, Component> componentCache) {
1286 boolean result = true;
1287 Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
1288 RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
1289 Either<Component, StorageOperationStatus> getOriginRes = null;
1290 Optional<RequirementDefinition> reqOpt = Optional.empty();
1291 Component toOriginComponent = null;
1292 Optional<CapabilityDefinition> capOpt = Optional.empty();
1294 ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
1295 .findFirst().orElse(null);
1296 if (toInstance == null) {
1297 log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
1302 reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
1303 if (!reqOpt.isPresent()) {
1304 log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
1305 reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
1310 ComponentParametersView filter = new ComponentParametersView(true);
1311 filter.setIgnoreComponentInstances(false);
1312 filter.setIgnoreCapabilities(false);
1313 filter.setIgnoreGroups(false);
1314 getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
1315 if (getOriginRes.isRight()) {
1317 "Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
1318 reqOpt.get().getName(), toInstance.getActualComponentUid());
1323 toOriginComponent = getOriginRes.left().value();
1324 capOpt = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
1325 .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
1326 if (!capOpt.isPresent()) {
1327 capOpt = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get());
1328 if (!capOpt.isPresent()) {
1330 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1331 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1336 result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, capOpt.get(),
1337 reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
1342 private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair,
1343 CapabilityDefinition capability) {
1344 return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() != null
1345 && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
1348 private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair,
1349 Component toOriginComponent, Component fromOriginComponent,
1350 RequirementDefinition requirement) {
1351 Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability())
1352 .stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
1353 if (!cap.isPresent()) {
1354 log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
1355 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1360 private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements,
1361 Component fromOriginComponent, Component toOriginComponent,
1362 CapabilityDefinition capability, RequirementDefinition requirement,
1363 RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance,
1364 Map<String, Component> componentCache) {
1365 List<String> reducedPath = capability.getPath();
1366 if (capability.getOwnerId() != null) {
1367 reducedPath = capabilityRequirementConverter
1368 .getReducedPathByOwner(capability.getPath(), capability.getOwnerId());
1370 Either<String, Boolean> buildCapNameRes = capabilityRequirementConverter.buildSubstitutedName(componentCache,
1371 toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability(), capability.getPreviousName());
1372 if (buildCapNameRes.isRight()) {
1374 "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
1375 reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
1378 Either<String, Boolean> buildReqNameRes = capabilityRequirementConverter
1379 .buildSubstitutedName(componentCache, fromOriginComponent,
1380 requirement.getPath(), reqAndRelationshipPair.getRequirement(), requirement.getPreviousName());
1381 if (buildReqNameRes.isRight()) {
1383 "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
1384 reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
1387 ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
1388 Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
1389 toscaRequirement.setNode(toInstance.getName());
1390 toscaRequirement.setCapability(buildCapNameRes.left().value());
1391 toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
1392 toscaRequirements.add(toscaReqMap);
1396 private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent,
1397 Map<String, List<RequirementDefinition>> reqMap,
1398 RelationshipInfo reqAndRelationshipPair,
1399 String fromInstanceId) {
1400 for (List<RequirementDefinition> reqList : reqMap.values()) {
1401 Optional<RequirementDefinition> reqOpt = reqList.stream().filter(
1402 r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId))
1404 if (reqOpt.isPresent()) {
1408 return Optional.empty();
1412 * Allows detecting the requirement belonging to the received relationship The detection logic is: A requirement
1413 * belongs to a relationship IF 1.The name of the requirement equals to the "requirement" field of the relation; AND
1414 * 2. In case of a non-atomic resource, OwnerId of the requirement equals to requirementOwnerId of the relation OR
1415 * uniqueId of toInstance equals to capabilityOwnerId of the relation
1417 private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair,
1418 RequirementDefinition requirement, String fromInstanceId) {
1419 if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
1420 log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
1421 requirement.getName(), reqAndRelationshipPair.getRequirement());
1424 return ModelConverter.isAtomicComponent(originComponent) ||
1425 isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
1428 private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair,
1429 RequirementDefinition requirement, String fromInstanceId,
1430 Component originComponent) {
1431 return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId())
1432 || (isCvfc(originComponent) && StringUtils
1433 .equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())
1434 || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId()));
1437 private boolean isCvfc(Component component) {
1438 return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
1439 ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
1442 private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
1443 SubstitutionMapping substitutionMappings,
1444 Map<String, Component> componentCache) {
1446 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
1447 Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
1448 .convertSubstitutionMappingCapabilities(componentCache, component);
1449 if (toscaCapabilitiesRes.isRight()) {
1450 result = Either.right(toscaCapabilitiesRes.right().value());
1451 log.debug("Failed convert capabilities for the component {}. ", component.getName());
1452 } else if (isNotEmpty(toscaCapabilitiesRes.left().value())) {
1453 substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
1454 log.debug("Finish convert capabilities for the component {}. ", component.getName());
1456 log.debug("Finished to convert capabilities for the component {}. ", component.getName());
1460 private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache,
1461 Component component, ToscaNodeType nodeType,
1462 Map<String, DataTypeDefinition> dataTypes) {
1463 Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter
1464 .convertCapabilities(componentsCache, component,
1466 if (!toscaCapabilities.isEmpty()) {
1467 nodeType.setCapabilities(toscaCapabilities);
1469 log.debug("Finish convert Capabilities for node type");
1471 return Either.left(nodeType);
1474 private Map<String, ToscaTemplateArtifact> convertToNodeTemplateArtifacts(
1475 Map<String, ToscaArtifactDataDefinition> artifacts) {
1476 if (artifacts == null) {
1479 Map<String, ToscaTemplateArtifact> arts = new HashMap<>();
1480 for (Map.Entry<String, ToscaArtifactDataDefinition> entry : artifacts.entrySet()) {
1481 ToscaTemplateArtifact artifact = new ToscaTemplateArtifact();
1482 artifact.setFile(entry.getValue().getFile());
1483 artifact.setType(entry.getValue().getType());
1484 arts.put(entry.getKey(), artifact);
1489 protected NodeFilter convertToNodeTemplateNodeFilterComponent(CINodeFilterDataDefinition inNodeFilter) {
1490 if (inNodeFilter == null) {
1493 NodeFilter nodeFilter = new NodeFilter();
1495 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
1496 inNodeFilter.getCapabilities();
1498 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
1500 List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
1501 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1503 copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
1504 copyNodeFilterProperties(origProperties, propertiesCopy);
1506 if (CollectionUtils.isNotEmpty(capabilitiesCopy)) {
1507 nodeFilter.setCapabilities(capabilitiesCopy);
1510 if (CollectionUtils.isNotEmpty(propertiesCopy)) {
1511 nodeFilter.setProperties(propertiesCopy);
1514 nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
1516 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1521 private NodeFilter convertToSubstitutionFilterComponent(
1522 final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
1524 NodeFilter nodeFilter = new NodeFilter();
1526 final List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1527 copySubstitutionFilterProperties(substitutionFilterDataDefinition.getProperties(), propertiesCopy);
1529 if (CollectionUtils.isNotEmpty(propertiesCopy)) {
1530 nodeFilter.setProperties(propertiesCopy);
1532 nodeFilter.setTosca_id(cloneToscaId(substitutionFilterDataDefinition.getTosca_id()));
1533 nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
1538 private Object cloneToscaId(Object toscaId) {
1539 return Objects.isNull(toscaId) ? null
1540 : cloneObjectFromYml(toscaId, toscaId.getClass());
1543 private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
1544 String objectAsYml = yamlUtil.objectToYaml(objToClone);
1545 return yamlUtil.yamlToObject(objectAsYml, classOfObj);
1548 private void copyNodeFilterCapabilitiesTemplate(
1549 ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
1550 List<Map<String, CapabilityFilter>> capabilitiesCopy) {
1551 if (origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
1552 origCapabilities.getListToscaDataDefinition().isEmpty()) {
1555 for (RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
1556 Map<String, CapabilityFilter> capabilityFilterCopyMap = new HashMap<>();
1557 CapabilityFilter capabilityFilter = new CapabilityFilter();
1558 List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
1559 copyNodeFilterProperties(capability.getProperties(), propertiesCopy);
1560 capabilityFilter.setProperties(propertiesCopy);
1561 capabilityFilterCopyMap.put(capability.getName(), capabilityFilter);
1562 capabilitiesCopy.add(capabilityFilterCopyMap);
1566 private void copyNodeFilterProperties(
1567 ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
1568 List<Map<String, List<Object>>> propertiesCopy) {
1569 if (origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1570 origProperties.isEmpty()) {
1573 Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1574 for (RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties
1575 .getListToscaDataDefinition()) {
1576 for (String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1577 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1578 String propertyName = propertyDataDefinition.getName();
1579 if (propertyMapCopy.containsKey(propertyName)) {
1580 addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
1582 if (propertyName != null) {
1583 List propsList = new ArrayList();
1584 addPropertyConstraintValueToList(propertyName, propertyValObj, propsList);
1585 propertyMapCopy.put(propertyName, propsList);
1587 propertyMapCopy.putAll(propertyValObj);
1592 propertyMapCopy.entrySet().stream().forEach(entry ->
1593 addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
1596 private void copySubstitutionFilterProperties(
1597 final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> origProperties,
1598 final List<Map<String, List<Object>>> propertiesCopy) {
1599 if (origProperties == null || origProperties.getListToscaDataDefinition() == null ||
1600 origProperties.isEmpty()) {
1603 final Map<String, List<Object>> propertyMapCopy = new HashMap<>();
1604 for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties
1605 .getListToscaDataDefinition()) {
1606 for (final String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
1607 final Map<String, List<Object>> propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
1608 final String propertyName = propertyDataDefinition.getName();
1609 if (propertyMapCopy.containsKey(propertyName)) {
1610 addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
1612 if (propertyName != null) {
1613 final List<Object> propsList = new ArrayList();
1614 addPropertyConstraintValueToList(propertyName, propertyValObj, propsList);
1615 propertyMapCopy.put(propertyName, propsList);
1617 propertyMapCopy.putAll(propertyValObj);
1622 propertyMapCopy.entrySet().forEach(entry ->
1623 addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
1626 private void addPropertyConstraintValueToList(String propertyName, Map propertyValObj, List propsList) {
1627 if (propertyValObj.containsKey(propertyName)) {
1628 propsList.add(propertyValObj.get(propertyName));
1630 propsList.add(propertyValObj);
1634 private void addCalculatedConstraintsIntoPropertiesList(List<Map<String, List<Object>>> propertiesCopy,
1635 Entry<String, List<Object>> entry) {
1636 Map<String, List<Object>> tempMap = new HashMap<>();
1637 tempMap.put(entry.getKey(), entry.getValue());
1638 propertiesCopy.add(tempMap);
1641 private static class CustomRepresenter extends Representer {
1643 CustomRepresenter() {
1645 // null representer is exceptional and it is stored as an instance
1647 this.nullRepresenter = new RepresentNull();
1652 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
1654 if (propertyValue == null) {
1657 // skip not relevant for Tosca property
1658 if ("dependencies".equals(property.getName())) {
1661 removeDefaultP(propertyValue);
1662 NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
1664 return "_defaultp_".equals(property.getName())
1665 ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
1668 private void removeDefaultP(final Object propertyValue) {
1669 if (propertyValue instanceof Map) {
1670 final Map mapPropertyValue = ((Map) propertyValue);
1672 final Iterator<Entry> iter = mapPropertyValue.entrySet().iterator();
1673 Object defaultValue = null;
1674 while (iter.hasNext()) {
1675 final Map.Entry entry = iter.next();
1677 if ("_defaultp_".equals(entry.getKey())) {
1678 defaultValue = entry.getValue();
1680 } else if (entry.getValue() instanceof Map) {
1681 removeDefaultP(entry.getValue());
1684 if (defaultValue != null) {
1685 mapPropertyValue.putIfAbsent("default", defaultValue);
1691 protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
1692 // remove the bean type from the output yaml (!! ...)
1693 if (!classTags.containsKey(javaBean.getClass())) {
1694 addClassTag(javaBean.getClass(), Tag.MAP);
1697 return super.representJavaBean(properties, javaBean);
1700 private class RepresentNull implements Represent {
1703 public Node representData(Object data) {
1704 // possible values are here http://yaml.org/type/null.html
1705 return representScalar(Tag.NULL, "");
1710 private static class UnsortedPropertyUtils extends PropertyUtils {
1713 protected Set<Property> createPropertySet(Class type, BeanAccess bAccess)
1714 throws IntrospectionException {
1715 Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
1716 return new LinkedHashSet<>(fields);
1720 private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) {
1721 ObjectMapper objectMapper = new ObjectMapper();
1722 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1724 Map<String, Object> interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition);
1725 Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.remove("operations");
1726 interfaceAsMap.remove("empty");
1728 if (MapUtils.isNotEmpty(operations)) {
1729 interfaceAsMap.putAll(operations);
1732 Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class);
1734 return interfaceObject;
1738 private Optional<Map<String, ToscaProperty>> getProxyNodeTypeInputProperties(final Component proxyComponent,
1739 final Map<String, DataTypeDefinition> dataTypes) {
1740 if (Objects.isNull(proxyComponent)) {
1741 return Optional.empty();
1743 final Map<String, ToscaProperty> proxyInputProperties = new HashMap<>();
1744 addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyInputProperties);
1745 return MapUtils.isNotEmpty(proxyInputProperties) ? Optional.of(proxyInputProperties) : Optional.empty();
1748 Optional<Map<String, ToscaProperty>> getProxyNodeTypeProperties(Component proxyComponent,
1749 Map<String, DataTypeDefinition>
1751 if (Objects.isNull(proxyComponent)) {
1752 return Optional.empty();
1754 Map<String, ToscaProperty> proxyProperties = new HashMap<>();
1755 addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties);
1756 if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) {
1757 proxyProperties.putAll(proxyComponent.getProperties().stream()
1758 .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition,
1759 proxyComponent.getInputs()))
1760 .collect(Collectors.toMap(PropertyDataDefinition::getName,
1761 property -> propertyConvertor.convertProperty(dataTypes, property,
1762 PropertyConvertor.PropertyType.PROPERTY))));
1764 return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty();
1767 void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
1768 List<InputDefinition> componentInputs,
1769 Map<String, ToscaProperty> mergedProperties) {
1770 if (CollectionUtils.isEmpty(componentInputs)) {
1773 for (InputDefinition input : componentInputs) {
1774 ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input,
1775 PropertyConvertor.PropertyType.INPUT);
1776 mergedProperties.put(input.getName(), property);
1780 Optional<Map<String, Object>> getProxyNodeTypeInterfaces(Component proxyComponent,
1781 Map<String, DataTypeDefinition> dataTypes) {
1782 if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) {
1783 return Optional.empty();
1785 Map<String, InterfaceDefinition> proxyComponentInterfaces = proxyComponent.getInterfaces();
1786 //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is
1787 // always available in the proxy node template
1788 removeOperationImplementationForProxyNodeType(proxyComponentInterfaces);
1789 return Optional.ofNullable(interfacesOperationsConverter
1790 .getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes,
1794 private static void removeOperationImplementationForProxyNodeType(
1795 Map<String, InterfaceDefinition> proxyComponentInterfaces) {
1796 if (MapUtils.isEmpty(proxyComponentInterfaces)) {
1799 proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations)
1800 .filter(MapUtils::isNotEmpty)
1801 .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null)));