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.translator.services.heattotosca;
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.collections4.MapUtils;
25 import org.openecomp.core.translator.api.HeatToToscaTranslator;
26 import org.openecomp.core.translator.datatypes.TranslatorOutput;
27 import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory;
28 import org.openecomp.core.utilities.file.FileContentHandler;
29 import org.openecomp.core.utilities.file.FileUtils;
30 import org.openecomp.sdc.tosca.services.YamlUtil;
31 import org.openecomp.core.validation.util.MessageContainerUtil;
32 import org.openecomp.sdc.common.errors.CoreException;
33 import org.openecomp.sdc.common.utils.SdcCommon;
34 import org.openecomp.sdc.datatypes.error.ErrorLevel;
35 import org.openecomp.sdc.datatypes.error.ErrorMessage;
36 import org.openecomp.sdc.heat.datatypes.HeatBoolean;
37 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
38 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
39 import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
40 import org.openecomp.sdc.heat.datatypes.model.Resource;
41 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
42 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
43 import org.openecomp.sdc.heat.services.HeatConstants;
44 import org.openecomp.sdc.heat.services.tree.HeatTreeManager;
45 import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil;
46 import org.openecomp.sdc.logging.api.Logger;
47 import org.openecomp.sdc.logging.api.LoggerFactory;
48 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
49 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
50 import org.openecomp.sdc.logging.types.LoggerConstants;
51 import org.openecomp.sdc.logging.types.LoggerErrorCode;
52 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
53 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
54 import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType;
55 import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
56 import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
57 import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType;
58 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
59 import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition;
60 import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition;
61 import org.openecomp.sdc.tosca.datatypes.model.Import;
62 import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate;
63 import org.openecomp.sdc.tosca.datatypes.model.NodeType;
64 import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition;
65 import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition;
66 import org.openecomp.sdc.tosca.datatypes.model.PropertyType;
67 import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment;
68 import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition;
69 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
70 import org.openecomp.sdc.tosca.datatypes.model.Template;
71 import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate;
72 import org.openecomp.sdc.tosca.services.DataModelUtil;
73 import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
74 import org.openecomp.sdc.tosca.services.ToscaConstants;
75 import org.openecomp.sdc.tosca.services.ToscaUtil;
76 import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
77 import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil;
78 import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal;
79 import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId;
80 import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType;
81 import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext;
82 import org.openecomp.sdc.translator.datatypes.heattotosca.to.FileDataCollection;
83 import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo;
84 import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder;
85 import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator;
86 import org.openecomp.sdc.translator.services.heattotosca.helper.FunctionTranslationHelper;
87 import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter;
89 import java.io.IOException;
90 import java.io.InputStream;
91 import java.util.ArrayList;
92 import java.util.Collection;
93 import java.util.HashMap;
94 import java.util.HashSet;
95 import java.util.List;
97 import java.util.Objects;
98 import java.util.Optional;
100 import java.util.stream.Collectors;
103 * The type Heat to tosca util.
105 public class HeatToToscaUtil {
107 protected static Logger logger = (Logger) LoggerFactory.getLogger(HeatToToscaUtil.class);
108 protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
112 * Load and translate template data translator output.
114 * @param fileNameContentMap the file name content map
115 * @return the translator output
117 public static TranslatorOutput loadAndTranslateTemplateData(
118 FileContentHandler fileNameContentMap) {
119 mdcDataDebugMessage.debugEntryMessage(null, null);
120 HeatToToscaTranslator heatToToscaTranslator =
121 HeatToToscaTranslatorFactory.getInstance().createInterface();
122 InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME);
124 heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
126 fileNameContentMap.getFileList().stream()
127 .filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))).forEach(
128 fileName -> heatToToscaTranslator
129 .addFile(fileName, FileUtils.toByteArray
130 (fileNameContentMap.getFileContent(fileName))));
132 Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate();
133 if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) {
134 TranslatorOutput translatorOutput = new TranslatorOutput();
135 translatorOutput.setErrorMessages(errors);
136 return translatorOutput;
139 try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) {
140 heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
142 mdcDataDebugMessage.debugExitMessage(null, null);
143 return heatToToscaTranslator.translate();
144 } catch (IOException e) {
145 // rethrow as a RuntimeException to keep the signature backward compatible
146 throw new RuntimeException(e);
151 private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) {
152 HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap);
153 heatTreeManager.createTree();
154 HeatStructureTree tree = heatTreeManager.getTree();
155 ValidationStructureList validationStructureList = new ValidationStructureList(tree);
156 return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON);
160 * Build list of files to search optional.
162 * @param heatFileName the heat file name
163 * @param filesDataList the files data list
164 * @param types the types
165 * @return the optional
167 public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName,
168 List<FileData> filesDataList,
169 FileData.Type... types) {
170 List<FileData> list = new ArrayList<>(filesDataList);
171 Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList);
172 if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) {
173 list.addAll(resourceFileData.get().getData());
175 return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
179 * Gets filtered list of file data by types.
181 * @param filesToSearch the files to search
182 * @param types the types
183 * @return the filtered list of file data by types
185 public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch,
186 FileData.Type... types) {
187 return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types))
188 .collect(Collectors.toList());
192 * Gets file data from the list according to the input heat file name.
194 * @param heatFileName the heat file name
195 * @param fileDataList the file data list
196 * @return the file data
198 public static Optional<FileData> getFileData(String heatFileName,
199 Collection<FileData> fileDataList) {
200 for (FileData file : fileDataList) {
201 if (file.getFile().equals(heatFileName)) {
202 return Optional.of(file);
205 return Optional.empty();
209 * Gets file data which is supported by the translator, from the context according the input heat
212 * @param heatFileName the heat file name
213 * @param context the translation context
214 * @return the file data
216 public static FileData getFileData(String heatFileName, TranslationContext context) {
218 List<FileData> fileDataList = context.getManifest().getContent().getData();
219 for (FileData fileData : fileDataList) {
220 if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType())
221 && fileData.getFile().equals(heatFileName)) {
228 static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList,
229 Set<FileData.Type> typeFilter,
230 TranslationContext translationContext) {
231 FileDataCollection fileDataCollection = new FileDataCollection();
232 Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter);
233 Set<String> referenced = new HashSet<>();
234 List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values());
236 for (FileData fileData : filteredFiles.values()) {
237 String fileName = fileData.getFile();
239 if (FileData.isHeatFile(fileData.getType())) {
240 if (fileData.getBase() != null && fileData.getBase().equals(true)) {
241 fileDataCollection.addBaseFiles(fileData);
243 HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil()
244 .yamlToObject(translationContext.getFileContent(fileName),
245 HeatOrchestrationTemplate.class);
246 if (!MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) {
247 for (Resource resource : heatOrchestrationTemplate.getResources().values()) {
248 if (filenames.contains(resource.getType())) {
249 handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced,
251 } else if (resource.getType()
252 .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
254 resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
255 Object innerTypeDef = ((Map) resourceDef).get("type");
256 if (innerTypeDef instanceof String) {
257 String internalResourceType = (String) innerTypeDef;
258 if (filenames.contains(internalResourceType)) {
259 handleNestedFile(translationContext, fileDataCollection, filteredFiles,
261 internalResourceType);
269 fileDataCollection.addArtifactFiles(fileData);
270 filteredFiles.remove(fileData.getFile());
274 referenced.forEach(filteredFiles::remove);
275 if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
276 for (FileData fileData : fileDataCollection.getBaseFile()) {
277 filteredFiles.remove(fileData.getFile());
280 fileDataCollection.setAddOnFiles(filteredFiles.values());
281 return fileDataCollection;
284 private static void handleNestedFile(TranslationContext translationContext,
285 FileDataCollection fileDataCollection,
286 Map<String, FileData> filteredFiles, Set<String> referenced,
287 String nestedFileName) {
290 mdcDataDebugMessage.debugEntryMessage(null, null);
292 referenced.add(nestedFileName);
293 fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
294 translationContext.getNestedHeatsFiles().add(nestedFileName);
296 mdcDataDebugMessage.debugExitMessage(null, null);
299 private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList,
300 Set<FileData.Type> typesToGet) {
301 Map<String, FileData> filtered = new HashMap<>();
302 fileDataList.stream().filter(file -> typesToGet.contains(file.getType()))
303 .forEach(file -> filtered.put(file.getFile(), file));
307 private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
308 return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
312 * Extract attached resource id optional.
314 * @param translateTo the translate to
315 * @param propertyName the property name
316 * @return the optional
318 public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo,
319 String propertyName) {
322 mdcDataDebugMessage.debugEntryMessage(null, null);
324 Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
325 if (propertyValue == null) {
326 return Optional.empty();
329 mdcDataDebugMessage.debugExitMessage(null, null);
330 return extractAttachedResourceId(translateTo.getHeatFileName(),
331 translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue);
335 * Extract attached resource id optional.
337 * @param heatFileName the heat file name
338 * @param heatOrchestrationTemplate the heat orchestration template
339 * @param context the context
340 * @param propertyValue the property value
341 * @return the optional
343 public static Optional<AttachedResourceId> extractAttachedResourceId(
345 HeatOrchestrationTemplate heatOrchestrationTemplate,
346 TranslationContext context,
347 Object propertyValue) {
352 if (Objects.isNull(propertyValue)) {
353 return Optional.empty();
356 ReferenceType referenceType = ReferenceType.OTHER;
357 if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
358 Map<String, Object> propMap = (Map) propertyValue;
359 Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
360 entity = entry.getValue();
361 String key = entry.getKey();
364 referenceType = ReferenceType.GET_RESOURCE;
367 referenceType = ReferenceType.GET_PARAM;
370 referenceType = ReferenceType.GET_ATTR;
373 referenceType = ReferenceType.OTHER;
377 if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
380 translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get()
381 .translateFunction(null, null, null, entry.getKey(), entry.getValue(), heatFileName,
382 heatOrchestrationTemplate, null, context);
384 if (translatedId instanceof String
385 && !FunctionTranslationHelper.isResourceSupported((String) translatedId)) {
390 translatedId = propertyValue;
391 entity = propertyValue;
394 return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
398 * Gets contrail attached heat resource id.
400 * @param attachedResource the attached resource
401 * @return the contrail attached heat resource id
403 public static Optional<String> getContrailAttachedHeatResourceId(
404 AttachedResourceId attachedResource) {
407 mdcDataDebugMessage.debugEntryMessage(null, null);
409 if (attachedResource == null) {
410 return Optional.empty();
413 if (attachedResource.isGetResource()) {
414 return Optional.of((String) attachedResource.getEntityId());
416 if (attachedResource.isGetAttr() && (attachedResource.getEntityId() instanceof List)
417 && ((List) attachedResource.getEntityId()).size() > 1
418 && ((List) attachedResource.getEntityId()).get(1).equals("fq_name")) {
419 return Optional.of((String) ((List) attachedResource.getEntityId()).get(0));
422 mdcDataDebugMessage.debugExitMessage(null, null);
423 return Optional.empty();
427 * Extract property optional.
429 * @param propertyValue the property value
430 * @return the optional
432 public static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
434 mdcDataDebugMessage.debugEntryMessage(null, null);
435 Object attachedPropertyVal;
436 if (Objects.isNull(propertyValue)) {
437 return Optional.empty();
440 ReferenceType referenceType = ReferenceType.OTHER;
441 if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
442 Map<String, Object> propMap = (Map) propertyValue;
443 Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
444 attachedPropertyVal = entry.getValue();
445 String key = entry.getKey();
448 referenceType = ReferenceType.GET_RESOURCE;
451 referenceType = ReferenceType.GET_PARAM;
454 referenceType = ReferenceType.GET_ATTR;
461 attachedPropertyVal = propertyValue;
464 mdcDataDebugMessage.debugExitMessage(null, null);
465 return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
471 * @param nodeTemplate the node template
472 * @param propertyKey the property key
474 public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
475 mdcDataDebugMessage.debugEntryMessage(null, null);
477 Object value = nodeTemplate.getProperties().get(propertyKey);
478 if (value != null && !(value instanceof Map)) {
479 nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
482 mdcDataDebugMessage.debugExitMessage(null, null);
488 * @param nodeTemplate the node template
489 * @param propertyListKey the property list key
491 public static void mapBooleanList(NodeTemplate nodeTemplate, String propertyListKey) {
492 Object listValue = nodeTemplate.getProperties().get(propertyListKey);
493 if (listValue instanceof List) {
494 List booleanList = ((List) listValue);
495 for (int i = 0; i < booleanList.size(); i++) {
496 Object value = booleanList.get(i);
497 if (value != null && !(value instanceof Map)) {
498 booleanList.set(i, HeatBoolean.eval(value));
506 * Is yml file type boolean.
508 * @param filename the filename
509 * @return the boolean
511 public static boolean isYmlFileType(String filename) {
512 return (filename.indexOf("yaml") > 0 || filename.indexOf("yml") > 0);
516 * Is nested resource boolean.
518 * @param resource the resource
519 * @return the boolean
521 public static boolean isNestedResource(Resource resource) {
522 mdcDataDebugMessage.debugEntryMessage(null, null);
524 String resourceType = resource.getType();
526 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
527 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
528 if (!(((Map) resourceDef).get("type") instanceof String)) {
529 //currently only resource group which is poinitng to nested heat file is supported
530 //dynamic type is currently not supported
533 String internalResourceType = (String) ((Map) resourceDef).get("type");
534 if (isYamlFile(internalResourceType)) {
537 } else if (isYamlFile(resourceType)) {
541 mdcDataDebugMessage.debugExitMessage(null, null);
546 * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at
547 * least one or more compute nodes).
549 * @param resource the resource
550 * @param context the context
551 * @return true if the resource represents a VFC and false otherwise.
553 public static boolean isNestedVfcResource(Resource resource, TranslationContext context) {
554 mdcDataDebugMessage.debugEntryMessage(null, null);
555 Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
556 HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
557 .yamlToObject(context.getFileContent(nestedHeatFileName.get()),
558 HeatOrchestrationTemplate.class);
559 if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) {
560 for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) {
561 if (ConsolidationDataUtil
562 .isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) {
567 mdcDataDebugMessage.debugExitMessage(null, null);
572 * Get nested heat file name in case of nested resource.
574 * @param resource the resource
575 * @return the nested heat file name
577 public static Optional<String> getNestedHeatFileName(Resource resource) {
578 mdcDataDebugMessage.debugEntryMessage(null, null);
580 if (!isNestedResource(resource)) {
581 return Optional.empty();
584 String resourceType = resource.getType();
586 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
587 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
588 String internalResourceType = (String) ((Map) resourceDef).get("type");
589 return Optional.of(internalResourceType);
592 mdcDataDebugMessage.debugExitMessage(null, null);
593 return Optional.of(resourceType);
599 * @param resource the resource
600 * @return the nested file
602 public static Optional<String> getNestedFile(Resource resource) {
605 mdcDataDebugMessage.debugEntryMessage(null, null);
607 if (!isNestedResource(resource)) {
608 return Optional.empty();
610 String resourceType = resource.getType();
611 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
612 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
613 String internalResourceType = (String) ((Map) resourceDef).get("type");
615 mdcDataDebugMessage.debugExitMessage(null, null);
616 return Optional.of(internalResourceType);
618 mdcDataDebugMessage.debugExitMessage(null, null);
619 return Optional.of(resourceType);
623 private static boolean isYamlFile(String fileName) {
624 return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
630 * @param heatOrchestrationTemplate the heat orchestration template
631 * @param resourceId the resource id
632 * @param heatFileName the heat file name
633 * @return the resource
635 public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate,
636 String resourceId, String heatFileName) {
639 mdcDataDebugMessage.debugEntryMessage(null, null);
641 Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
642 if (resource == null) {
643 MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
644 LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(),
645 LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT);
646 throw new CoreException(
647 new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
650 mdcDataDebugMessage.debugExitMessage(null, null);
658 * @param resourceId the resource id
659 * @param heatOrchestrationTemplate heat orchestration template
660 * @param heatFileName heat file name
661 * @return resource type
663 public static String getResourceType(String resourceId,
664 HeatOrchestrationTemplate heatOrchestrationTemplate,
665 String heatFileName) {
668 mdcDataDebugMessage.debugEntryMessage(null, null);
670 mdcDataDebugMessage.debugExitMessage(null, null);
671 return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName)
676 * Is heat file nested boolean.
678 * @param translateTo the translate to
679 * @param heatFileName the heat file name
680 * @return the boolean
682 public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
683 return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName);
687 * Extract contrail get resource attached heat resource id optional.
689 * @param propertyValue the property value
690 * @return the optional
692 public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(
693 Object propertyValue) {
696 mdcDataDebugMessage.debugEntryMessage(null, null);
698 if (propertyValue == null) {
699 return Optional.empty();
703 if (propertyValue instanceof Map) {
704 if (((Map) propertyValue).containsKey("get_attr")) {
705 value = ((Map) propertyValue).get("get_attr");
706 if (value instanceof List) {
707 if (((List) value).size() == 2 && ((List) value).get(1).equals("fq_name")) {
708 if (((List) value).get(0) instanceof String) {
709 return Optional.of((String) ((List) value).get(0));
711 logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString());
715 } else if (((Map) propertyValue).containsKey("get_resource")) {
716 value = ((Map) propertyValue).get("get_resource");
717 if (value instanceof String) {
718 return Optional.of((String) value);
720 logger.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
723 Collection<Object> valCollection = ((Map) propertyValue).values();
724 for (Object entryValue : valCollection) {
725 Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(entryValue);
726 if (ret.isPresent()) {
732 } else if (propertyValue instanceof List) {
733 for (Object prop : (List) propertyValue) {
734 Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
735 if (ret.isPresent()) {
741 mdcDataDebugMessage.debugExitMessage(null, null);
742 return Optional.empty();
746 * Gets tosca service model.
748 * @param context translation context
749 * @return the tosca service model
751 public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
752 mdcDataDebugMessage.debugEntryMessage(null, null);
753 mdcDataDebugMessage.debugExitMessage(null, null);
755 Map<String, String> metadata = new HashMap<>();
756 metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
757 return getToscaServiceModel(context, metadata);
761 * Gets tosca service model.
763 * @param context translation context
764 * @param entryDefinitionMetadata template name of the entry definition servie template
765 * @return the tosca service model
767 public static ToscaServiceModel getToscaServiceModel(
768 TranslationContext context,
769 Map<String, String> entryDefinitionMetadata) {
770 mdcDataDebugMessage.debugEntryMessage(null, null);
772 Map<String, ServiceTemplate> serviceTemplates =
773 new HashMap<>(context.getGlobalServiceTemplates());
774 Collection<ServiceTemplate> tmpServiceTemplates =
775 context.getTranslatedServiceTemplates().values();
776 for (ServiceTemplate serviceTemplate : tmpServiceTemplates) {
777 ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
780 mdcDataDebugMessage.debugExitMessage(null, null);
781 return new ToscaServiceModel(null, serviceTemplates,
782 ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
786 * Gets service template from context.
788 * @param serviceTemplateFileName the service template file name
789 * @param context the context
790 * @return the service template from context
792 public static Optional<ServiceTemplate> getServiceTemplateFromContext(
793 String serviceTemplateFileName, TranslationContext context) {
796 mdcDataDebugMessage.debugEntryMessage(null, null);
798 for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
799 if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
800 mdcDataDebugMessage.debugExitMessage(null, null);
801 return Optional.of(serviceTemplate);
805 mdcDataDebugMessage.debugExitMessage(null, null);
806 return Optional.empty();
810 * Adding link requerment from port node template to network node template.
812 * @param portNodeTemplate port node template
813 * @param networkTranslatedId network node template id
815 public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
816 String networkTranslatedId) {
819 mdcDataDebugMessage.debugEntryMessage(null, null);
821 RequirementAssignment requirement = new RequirementAssignment();
822 requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE);
823 requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO);
824 requirement.setNode(networkTranslatedId);
825 DataModelUtil.addRequirementAssignment(portNodeTemplate,
826 ToscaConstants.LINK_REQUIREMENT_ID, requirement);
828 mdcDataDebugMessage.debugExitMessage(null, null);
834 * Adding binding requerment from sub interface node template to interface (port) node template.
836 * @param subInterfaceNodeTemplate sub interface template
837 * @param interfaceTranslatedId interface node template id
839 public static void addBindingReqFromSubInterfaceToInterface(
840 NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) {
843 mdcDataDebugMessage.debugEntryMessage(null, null);
845 RequirementAssignment requirement = new RequirementAssignment();
846 requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
847 requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
848 requirement.setNode(interfaceTranslatedId);
850 .addRequirementAssignment(subInterfaceNodeTemplate,
851 ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
853 mdcDataDebugMessage.debugExitMessage(null, null);
857 * Get property Parameter Name Value.
859 * @param property property
860 * @return Parameter name in case the property include "get_param" function
862 public static Optional<String> getPropertyParameterNameValue(Object property) {
863 if (Objects.isNull(property)) {
864 return Optional.empty();
866 Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
867 if (extractedProperty.isPresent()) {
868 return getParameterName(extractedProperty.get());
870 return Optional.empty();
873 private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
874 if (!extractedProperty.isGetParam()) {
875 return Optional.empty();
877 Object getParamFuncValue = extractedProperty.getPropertyValue();
878 if (getParamFuncValue instanceof String) {
879 return Optional.of((String) getParamFuncValue);
881 return Optional.of((String) ((List) getParamFuncValue).get(0));
885 public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
886 String heatPropertyName) {
887 return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
891 * Gets tosca property name.
893 * @param translateTo the translate to
894 * @param heatPropertyName the heat property name
895 * @return the tosca property name
897 public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
898 return translateTo.getContext()
899 .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
903 * Gets tosca attribute name.
905 * @param context the context
906 * @param heatResourceType the heat resource type
907 * @param heatAttrName the heat attr name
908 * @return the tosca attribute name
910 public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
911 String heatAttrName) {
912 return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
916 * Gets tosca attribute name.
918 * @param translateTo the translate to
919 * @param heatAttrName the heat attr name
920 * @return the tosca attribute name
922 public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
923 return translateTo.getContext()
924 .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
928 * Create init substitution service template service template.
930 * @param templateName the template name
931 * @return the service template
933 public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) {
934 ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate();
935 Map<String, String> templateMetadata = new HashMap<>();
936 templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
937 nestedSubstitutionServiceTemplate.setMetadata(templateMetadata);
938 nestedSubstitutionServiceTemplate
939 .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
940 nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate());
941 List<Map<String, Import>> globalTypesImportList =
942 GlobalTypesGenerator.getGlobalTypesImportList();
943 globalTypesImportList.addAll(
944 HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
945 nestedSubstitutionServiceTemplate.setImports(globalTypesImportList);
946 return nestedSubstitutionServiceTemplate;
950 * Create init global substitution service template service template.
952 * @return the service template
954 public static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() {
955 ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate();
956 Map<String, String> templateMetadata = new HashMap<>();
957 templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME,
958 Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
959 globalSubstitutionServiceTemplate.setMetadata(templateMetadata);
960 globalSubstitutionServiceTemplate
961 .setImports(GlobalTypesGenerator.getGlobalTypesImportList());
962 globalSubstitutionServiceTemplate
963 .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
964 return globalSubstitutionServiceTemplate;
968 * Create substitution node type node type.
970 * @param substitutionServiceTemplate the substitution service template
971 * @return the node type
973 public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
974 NodeType substitutionNodeType = new NodeType();
975 substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
976 substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
978 .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
980 .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
981 return substitutionNodeType;
984 private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
985 ServiceTemplate substitutionServiceTemplate) {
986 mdcDataDebugMessage.debugEntryMessage(null, null);
988 Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
989 Map<String, ParameterDefinition> properties =
990 substitutionServiceTemplate.getTopology_template().getInputs();
991 if (properties == null) {
992 mdcDataDebugMessage.debugExitMessage(null, null);
996 PropertyDefinition propertyDefinition;
997 String toscaPropertyName;
998 for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
999 toscaPropertyName = entry.getKey();
1000 propertyDefinition = new PropertyDefinition();
1001 ParameterDefinition parameterDefinition =
1002 substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
1003 propertyDefinition.setType(parameterDefinition.getType());
1004 propertyDefinition.setDescription(parameterDefinition.getDescription());
1005 propertyDefinition.setRequired(parameterDefinition.getRequired());
1006 propertyDefinition.set_default(parameterDefinition.get_default());
1007 propertyDefinition.setConstraints(parameterDefinition.getConstraints());
1008 propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
1009 propertyDefinition.setStatus(parameterDefinition.getStatus());
1010 substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
1013 mdcDataDebugMessage.debugExitMessage(null, null);
1014 return substitutionNodeTypeProperties;
1017 private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
1018 ServiceTemplate substitutionServiceTemplate) {
1021 mdcDataDebugMessage.debugEntryMessage(null, null);
1023 Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
1024 Map<String, ParameterDefinition> attributes =
1025 substitutionServiceTemplate.getTopology_template().getOutputs();
1026 if (attributes == null) {
1027 mdcDataDebugMessage.debugExitMessage(null, null);
1030 AttributeDefinition attributeDefinition;
1031 String toscaAttributeName;
1033 for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
1034 attributeDefinition = new AttributeDefinition();
1035 toscaAttributeName = entry.getKey();
1036 ParameterDefinition parameterDefinition =
1037 substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
1038 if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
1039 attributeDefinition.setType(parameterDefinition.getType());
1041 attributeDefinition.setType(PropertyType.STRING.getDisplayName());
1043 attributeDefinition.setDescription(parameterDefinition.getDescription());
1044 attributeDefinition.set_default(parameterDefinition.get_default());
1045 attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
1046 attributeDefinition.setStatus(parameterDefinition.getStatus());
1047 substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
1050 mdcDataDebugMessage.debugExitMessage(null, null);
1051 return substitutionNodeTypeAttributes;
1056 * Create and add substitution mapping to the nested substitution service template, and update
1057 * the subtitution node type accordingly with the exposed requerments and capabilities
1059 * @param context the translation context
1060 * @param substitutionNodeTypeKey the substitution node type key
1061 * @param nestedSubstitutionServiceTemplate the nested substitution service template
1062 * @param substitutionNodeType the substitution node type
1064 public static void handleSubstitutionMapping(
1065 TranslationContext context,
1066 String substitutionNodeTypeKey,
1067 ServiceTemplate nestedSubstitutionServiceTemplate,
1068 NodeType substitutionNodeType) {
1069 Map<String, Map<String, List<String>>> substitutionMapping =
1070 getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType,
1071 nestedSubstitutionServiceTemplate, context);
1072 //add substitution mapping after capability and requirement expose calculation
1073 nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(
1074 DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeKey,
1075 substitutionNodeType, substitutionMapping));
1079 * Gets node type with flat hierarchy.
1081 * @param nodeTypeId the node type id
1082 * @param serviceTemplate the service template
1083 * @param context the context
1084 * @return the node type with flat hierarchy
1086 public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId,
1087 ServiceTemplate serviceTemplate,
1088 TranslationContext context) {
1089 ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1090 ToscaServiceModel toscaServiceModel = HeatToToscaUtil
1091 .getToscaServiceModel(context, serviceTemplate.getMetadata());
1092 NodeType flatNodeType = (NodeType) toscaAnalyzerService
1093 .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel);
1094 return flatNodeType;
1098 * Create substitution node template node template.
1100 * @param translateTo the translate to
1101 * @param templateName the template name
1102 * @param substitutionNodeTypeKey the substitution node type key
1103 * @return the node template
1105 public NodeTemplate createSubstitutionNodeTemplate(TranslateTo translateTo, String templateName,
1106 String substitutionNodeTypeKey) {
1107 NodeTemplate substitutionNodeTemplate = new NodeTemplate();
1108 List<String> directiveList = new ArrayList<>();
1109 directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
1110 substitutionNodeTemplate.setDirectives(directiveList);
1111 substitutionNodeTemplate.setType(substitutionNodeTypeKey);
1112 substitutionNodeTemplate.setProperties(
1113 managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
1115 return substitutionNodeTemplate;
1119 * Create abstract substitution node template.
1121 * @param translateTo the translate to
1122 * @param templateName the template name
1123 * @param substitutionNodeTypeKey the substitution node type key
1124 * @return the abstract substitute node template
1126 public static NodeTemplate createAbstractSubstitutionNodeTemplate(
1127 TranslateTo translateTo,
1128 String templateName,
1129 String substitutionNodeTypeKey) {
1130 NodeTemplate substitutionNodeTemplate = new NodeTemplate();
1131 List<String> directiveList = new ArrayList<>();
1132 directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
1133 substitutionNodeTemplate.setDirectives(directiveList);
1134 substitutionNodeTemplate.setType(substitutionNodeTypeKey);
1135 substitutionNodeTemplate.setProperties(
1136 managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
1138 return substitutionNodeTemplate;
1143 * Checks if the source and target resource is a valid candidate for adding tosca dependency
1146 * @param heatOrchestrationTemplate the heat orchestration template
1147 * @param sourceResource the source resource
1148 * @param targetResource the target resource
1149 * @param dependencyEntity the dependency entity
1150 * @return true if the candidate resources are a valid combination for the dependency relationship
1151 * and false otherwise
1153 public static boolean isValidDependsOnCandidate(HeatOrchestrationTemplate
1154 heatOrchestrationTemplate,
1155 Resource sourceResource,
1156 Resource targetResource,
1157 ConsolidationEntityType dependencyEntity,
1158 TranslationContext context) {
1160 .setEntityType(heatOrchestrationTemplate, sourceResource, targetResource, context);
1161 ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
1162 ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
1164 //Ignore Compute->Port, Compute->volume, Compute->Compute and Compute->VFC Nested relationships
1165 if (sourceEntityType == ConsolidationEntityType.COMPUTE) {
1166 if (targetEntityType == ConsolidationEntityType.COMPUTE
1167 || targetEntityType == ConsolidationEntityType.VOLUME
1168 || targetEntityType == ConsolidationEntityType.PORT
1169 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1173 //Ignore Port->Compute, Port->volume, Port->Port and Port->VFC Nested relationships
1174 if (sourceEntityType == ConsolidationEntityType.PORT) {
1175 if (targetEntityType == ConsolidationEntityType.COMPUTE
1176 || targetEntityType == ConsolidationEntityType.VOLUME
1177 || targetEntityType == ConsolidationEntityType.PORT
1178 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1183 //Ignore Volume->Compute, Volume->Volume, Volume->Port and Volume->VFC Nested relationships
1184 if (sourceEntityType == ConsolidationEntityType.VOLUME) {
1185 if (targetEntityType == ConsolidationEntityType.COMPUTE
1186 || targetEntityType == ConsolidationEntityType.VOLUME
1187 || targetEntityType == ConsolidationEntityType.PORT
1188 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1193 //Ignore VFC Nested->Compute, VFC Nested->Volume, VFC Nested->Port and
1194 // VFC Nested->VFC Nested relationships
1195 if (sourceEntityType == ConsolidationEntityType.VFC_NESTED) {
1196 if (targetEntityType == ConsolidationEntityType.COMPUTE
1197 || targetEntityType == ConsolidationEntityType.VOLUME
1198 || targetEntityType == ConsolidationEntityType.PORT
1199 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1206 private static Map<String, Object> managerSubstitutionNodeTemplateProperties(
1207 TranslateTo translateTo,
1209 String templateName) {
1210 mdcDataDebugMessage.debugEntryMessage(null, null);
1212 Map<String, Object> substitutionProperties = new HashMap<>();
1213 Map<String, Object> heatProperties = translateTo.getResource().getProperties();
1214 if (Objects.nonNull(heatProperties)) {
1215 for (Map.Entry<String, Object> entry : heatProperties.entrySet()) {
1216 Object property = TranslatorHeatToToscaPropertyConverter
1217 .getToscaPropertyValue(translateTo.getServiceTemplate(),
1218 translateTo.getTranslatedId(), entry.getKey(),
1219 entry.getValue(), null, translateTo.getHeatFileName(),
1220 translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext());
1221 substitutionProperties.put(entry.getKey(), property);
1225 mdcDataDebugMessage.debugExitMessage(null, null);
1226 return addAbstractSubstitutionProperty(templateName, substitutionProperties);
1229 private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
1231 substitutionProperties) {
1234 mdcDataDebugMessage.debugEntryMessage(null, null);
1236 Map<String, Object> innerProps = new HashMap<>();
1237 innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME,
1238 ToscaUtil.getServiceTemplateFileName(templateName));
1239 substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
1241 mdcDataDebugMessage.debugExitMessage(null, null);
1242 return substitutionProperties;
1245 private static Map<String, Map<String, List<String>>>
1246 getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
1247 ServiceTemplate substitutionServiceTemplate,
1248 TranslationContext context) {
1249 mdcDataDebugMessage.debugEntryMessage(null, null);
1251 Map<String, NodeTemplate> nodeTemplates =
1252 substitutionServiceTemplate.getTopology_template().getNode_templates();
1253 String nodeTemplateId;
1254 NodeTemplate nodeTemplate;
1256 Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
1257 if (nodeTemplates == null) {
1258 return substitutionMapping;
1261 Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
1262 Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
1263 substitutionMapping.put("capability", capabilitySubstitutionMapping);
1264 substitutionMapping.put("requirement", requirementSubstitutionMapping);
1265 List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
1266 Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
1267 List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
1268 Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
1270 Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
1271 Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
1272 ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1274 for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
1275 nodeTemplateId = entry.getKey();
1276 nodeTemplate = entry.getValue();
1277 nodeType = nodeTemplate.getType();
1280 nodeTypeRequirementsDefinition =
1281 getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate,
1282 requirementSubstitutionMapping, context);
1283 nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
1284 fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
1285 //set substitution node type requirements
1286 exposedRequirementsDefinition =
1287 toscaAnalyzerService.calculateExposedRequirements(nodeTypeRequirementsDefinition,
1288 nodeTemplateRequirementsAssignment);
1290 .addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
1294 addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
1295 capabilitySubstitutionMapping, nodeType,
1296 nodeTemplateId, substitutionServiceTemplate, context);
1299 exposedCapabilitiesDefinition =
1300 toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
1301 fullFilledRequirementsDefinition);
1302 DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
1304 mdcDataDebugMessage.debugExitMessage(null, null);
1305 return substitutionMapping;
1308 private static void addNodeTypeCapabilitiesToSubMapping(
1309 Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
1310 Map<String, List<String>> capabilitySubstitutionMapping, String type, String templateName,
1311 ServiceTemplate serviceTemplate, TranslationContext context) {
1312 mdcDataDebugMessage.debugEntryMessage(null, null);
1314 NodeType flatNodeType =
1315 getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
1316 String capabilityKey;
1317 List<String> capabilityMapping;
1318 if (flatNodeType.getCapabilities() != null) {
1319 for (Map.Entry<String, CapabilityDefinition> capabilityNodeEntry : flatNodeType
1322 capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName;
1323 nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
1324 capabilityMapping = new ArrayList<>();
1325 capabilityMapping.add(templateName);
1326 capabilityMapping.add(capabilityNodeEntry.getKey());
1327 capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
1330 mdcDataDebugMessage.debugExitMessage(null, null);
1333 private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(
1335 String templateName,
1336 ServiceTemplate serviceTemplate,
1337 Map<String, List<String>> requirementSubstitutionMapping,
1338 TranslationContext context) {
1339 mdcDataDebugMessage.debugEntryMessage(null, null);
1340 List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
1341 NodeType flatNodeType =
1342 getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
1343 List<String> requirementMapping;
1345 if (flatNodeType.getRequirements() != null) {
1346 for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
1347 for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
1349 ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
1350 RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil
1351 .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
1352 RequirementDefinition.class);
1353 if (requirementNodeEntryValue.getOccurrences() == null) {
1354 requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
1356 Map<String, RequirementDefinition> requirementDef = new HashMap<>();
1357 requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
1358 DataModelUtil.addRequirementToList(requirementList, requirementDef);
1359 requirementMapping = new ArrayList<>();
1360 requirementMapping.add(templateName);
1361 requirementMapping.add(requirementNodeEntry.getKey());
1362 requirementSubstitutionMapping
1363 .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping);
1364 if (requirementNodeEntryValue.getNode() == null) {
1365 requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
1371 mdcDataDebugMessage.debugExitMessage(null, null);
1372 return requirementList;
1376 * Fetch global substitution service template service template.
1378 * @param serviceTemplate the service template
1379 * @param context the context
1380 * @return the service template
1382 public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(
1383 ServiceTemplate serviceTemplate,
1384 TranslationContext context) {
1385 ServiceTemplate globalSubstitutionServiceTemplate =
1386 context.getTranslatedServiceTemplates()
1387 .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1388 if (globalSubstitutionServiceTemplate == null) {
1389 globalSubstitutionServiceTemplate =
1390 HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate();
1391 context.getTranslatedServiceTemplates()
1392 .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME,
1393 globalSubstitutionServiceTemplate);
1395 boolean isImportAddedToServiceTemplate =
1396 DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants
1397 .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1398 if (!isImportAddedToServiceTemplate) {
1399 serviceTemplate.getImports()
1401 HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
1403 return globalSubstitutionServiceTemplate;
1406 public static List<Map<String, Import>> createImportList(String templateName) {
1407 List<Map<String, Import>> imports = new ArrayList<>();
1408 Map<String, Import> importsMap = new HashMap<>();
1409 importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName));
1410 imports.add(importsMap);
1415 * Create service template import import.
1417 * @param serviceTemplate the service template
1418 * @return the import
1420 public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
1421 Import serviceTemplateImport = new Import();
1422 serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
1423 return serviceTemplateImport;
1427 * Create service template import import.
1429 * @param metadataTemplateName the service template name
1430 * @return the import
1432 public static Import createServiceTemplateImport(String metadataTemplateName) {
1433 Import serviceTemplateImport = new Import();
1434 serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
1435 return serviceTemplateImport;
1438 public static ToscaServiceModel createToscaServiceModel(ServiceTemplate
1439 entryDefinitionServiceTemplate,
1440 TranslationContext translationContext) {
1443 mdcDataDebugMessage.debugEntryMessage(null, null);
1445 mdcDataDebugMessage.debugExitMessage(null, null);
1446 return new ToscaServiceModel(getCsarArtifactFiles(translationContext),
1447 getServiceTemplates(translationContext),
1448 ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
1451 private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
1453 mdcDataDebugMessage.debugEntryMessage(null, null);
1455 FileContentHandler artifactFiles = new FileContentHandler();
1456 artifactFiles.setFiles(translationContext.getFiles());
1457 artifactFiles.setFiles(translationContext.getExternalArtifacts());
1459 HeatTreeManager heatTreeManager =
1460 HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles());
1461 heatTreeManager.createTree();
1462 ValidationStructureList validationStructureList =
1463 new ValidationStructureList(heatTreeManager.getTree());
1464 byte[] validationStructureFile =
1465 FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON);
1466 artifactFiles.addFile("HEAT.meta", validationStructureFile);
1468 mdcDataDebugMessage.debugExitMessage(null, null);
1469 return artifactFiles;
1473 private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext
1474 translationContext) {
1477 mdcDataDebugMessage.debugEntryMessage(null, null);
1479 List<ServiceTemplate> serviceTemplates = new ArrayList<>();
1480 serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate().values());
1481 serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values());
1482 Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>();
1484 for (ServiceTemplate template : serviceTemplates) {
1485 serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
1488 mdcDataDebugMessage.debugExitMessage(null, null);
1489 return serviceTemplatesMap;