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.InputStream;
90 import java.util.ArrayList;
91 import java.util.Collection;
92 import java.util.HashMap;
93 import java.util.HashSet;
94 import java.util.List;
96 import java.util.Objects;
97 import java.util.Optional;
99 import java.util.stream.Collectors;
102 * The type Heat to tosca util.
104 public class HeatToToscaUtil {
106 protected static Logger logger = (Logger) LoggerFactory.getLogger(HeatToToscaUtil.class);
107 protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
111 * Load and translate template data translator output.
113 * @param fileNameContentMap the file name content map
114 * @return the translator output
116 public static TranslatorOutput loadAndTranslateTemplateData(
117 FileContentHandler fileNameContentMap) {
118 mdcDataDebugMessage.debugEntryMessage(null, null);
119 HeatToToscaTranslator heatToToscaTranslator =
120 HeatToToscaTranslatorFactory.getInstance().createInterface();
121 InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME);
123 heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
125 fileNameContentMap.getFileList().stream()
126 .filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))).forEach(
127 fileName -> heatToToscaTranslator
128 .addFile(fileName, FileUtils.toByteArray
129 (fileNameContentMap.getFileContent(fileName))));
131 Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate();
132 if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) {
133 TranslatorOutput translatorOutput = new TranslatorOutput();
134 translatorOutput.setErrorMessages(errors);
135 return translatorOutput;
138 InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap);
139 heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
141 mdcDataDebugMessage.debugExitMessage(null, null);
142 return heatToToscaTranslator.translate();
146 private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) {
147 HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap);
148 heatTreeManager.createTree();
149 HeatStructureTree tree = heatTreeManager.getTree();
150 ValidationStructureList validationStructureList = new ValidationStructureList(tree);
151 return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON);
155 * Build list of files to search optional.
157 * @param heatFileName the heat file name
158 * @param filesDataList the files data list
159 * @param types the types
160 * @return the optional
162 public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName,
163 List<FileData> filesDataList,
164 FileData.Type... types) {
165 List<FileData> list = new ArrayList<>(filesDataList);
166 Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList);
167 if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) {
168 list.addAll(resourceFileData.get().getData());
170 return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
174 * Gets filtered list of file data by types.
176 * @param filesToSearch the files to search
177 * @param types the types
178 * @return the filtered list of file data by types
180 public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch,
181 FileData.Type... types) {
182 return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types))
183 .collect(Collectors.toList());
187 * Gets file data from the list according to the input heat file name.
189 * @param heatFileName the heat file name
190 * @param fileDataList the file data list
191 * @return the file data
193 public static Optional<FileData> getFileData(String heatFileName,
194 Collection<FileData> fileDataList) {
195 for (FileData file : fileDataList) {
196 if (file.getFile().equals(heatFileName)) {
197 return Optional.of(file);
200 return Optional.empty();
204 * Gets file data which is supported by the translator, from the context according the input heat
207 * @param heatFileName the heat file name
208 * @param context the translation context
209 * @return the file data
211 public static FileData getFileData(String heatFileName, TranslationContext context) {
213 List<FileData> fileDataList = context.getManifest().getContent().getData();
214 for (FileData fileData : fileDataList) {
215 if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType())
216 && fileData.getFile().equals(heatFileName)) {
223 static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList,
224 Set<FileData.Type> typeFilter,
225 TranslationContext translationContext) {
226 FileDataCollection fileDataCollection = new FileDataCollection();
227 Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter);
228 Set<String> referenced = new HashSet<>();
229 List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values());
231 for (FileData fileData : filteredFiles.values()) {
232 String fileName = fileData.getFile();
234 if (FileData.isHeatFile(fileData.getType())) {
235 if (fileData.getBase() != null && fileData.getBase().equals(true)) {
236 fileDataCollection.addBaseFiles(fileData);
238 HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil()
239 .yamlToObject(translationContext.getFileContent(fileName),
240 HeatOrchestrationTemplate.class);
241 if (!MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) {
242 for (Resource resource : heatOrchestrationTemplate.getResources().values()) {
243 if (filenames.contains(resource.getType())) {
244 handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced,
246 } else if (resource.getType()
247 .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
249 resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
250 Object innerTypeDef = ((Map) resourceDef).get("type");
251 if (innerTypeDef instanceof String) {
252 String internalResourceType = (String) innerTypeDef;
253 if (filenames.contains(internalResourceType)) {
254 handleNestedFile(translationContext, fileDataCollection, filteredFiles,
256 internalResourceType);
264 fileDataCollection.addArtifactFiles(fileData);
265 filteredFiles.remove(fileData.getFile());
269 referenced.forEach(filteredFiles::remove);
270 if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
271 for (FileData fileData : fileDataCollection.getBaseFile()) {
272 filteredFiles.remove(fileData.getFile());
275 fileDataCollection.setAddOnFiles(filteredFiles.values());
276 return fileDataCollection;
279 private static void handleNestedFile(TranslationContext translationContext,
280 FileDataCollection fileDataCollection,
281 Map<String, FileData> filteredFiles, Set<String> referenced,
282 String nestedFileName) {
285 mdcDataDebugMessage.debugEntryMessage(null, null);
287 referenced.add(nestedFileName);
288 fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
289 translationContext.getNestedHeatsFiles().add(nestedFileName);
291 mdcDataDebugMessage.debugExitMessage(null, null);
294 private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList,
295 Set<FileData.Type> typesToGet) {
296 Map<String, FileData> filtered = new HashMap<>();
297 fileDataList.stream().filter(file -> typesToGet.contains(file.getType()))
298 .forEach(file -> filtered.put(file.getFile(), file));
302 private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
303 return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
307 * Extract attached resource id optional.
309 * @param translateTo the translate to
310 * @param propertyName the property name
311 * @return the optional
313 public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo,
314 String propertyName) {
317 mdcDataDebugMessage.debugEntryMessage(null, null);
319 Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
320 if (propertyValue == null) {
321 return Optional.empty();
324 mdcDataDebugMessage.debugExitMessage(null, null);
325 return extractAttachedResourceId(translateTo.getHeatFileName(),
326 translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue);
330 * Extract attached resource id optional.
332 * @param heatFileName the heat file name
333 * @param heatOrchestrationTemplate the heat orchestration template
334 * @param context the context
335 * @param propertyValue the property value
336 * @return the optional
338 public static Optional<AttachedResourceId> extractAttachedResourceId(
340 HeatOrchestrationTemplate heatOrchestrationTemplate,
341 TranslationContext context,
342 Object propertyValue) {
347 if (Objects.isNull(propertyValue)) {
348 return Optional.empty();
351 ReferenceType referenceType = ReferenceType.OTHER;
352 if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
353 Map<String, Object> propMap = (Map) propertyValue;
354 Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
355 entity = entry.getValue();
356 String key = entry.getKey();
359 referenceType = ReferenceType.GET_RESOURCE;
362 referenceType = ReferenceType.GET_PARAM;
365 referenceType = ReferenceType.GET_ATTR;
368 referenceType = ReferenceType.OTHER;
372 if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
375 translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get()
376 .translateFunction(null, null, null, entry.getKey(), entry.getValue(), heatFileName,
377 heatOrchestrationTemplate, null, context);
379 if (translatedId instanceof String
380 && !FunctionTranslationHelper.isResourceSupported((String) translatedId)) {
385 translatedId = propertyValue;
386 entity = propertyValue;
389 return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
393 * Gets contrail attached heat resource id.
395 * @param attachedResource the attached resource
396 * @return the contrail attached heat resource id
398 public static Optional<String> getContrailAttachedHeatResourceId(
399 AttachedResourceId attachedResource) {
402 mdcDataDebugMessage.debugEntryMessage(null, null);
404 if (attachedResource == null) {
405 return Optional.empty();
408 if (attachedResource.isGetResource()) {
409 return Optional.of((String) attachedResource.getEntityId());
411 if (attachedResource.isGetAttr() && (attachedResource.getEntityId() instanceof List)
412 && ((List) attachedResource.getEntityId()).size() > 1
413 && ((List) attachedResource.getEntityId()).get(1).equals("fq_name")) {
414 return Optional.of((String) ((List) attachedResource.getEntityId()).get(0));
417 mdcDataDebugMessage.debugExitMessage(null, null);
418 return Optional.empty();
422 * Extract property optional.
424 * @param propertyValue the property value
425 * @return the optional
427 public static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
429 mdcDataDebugMessage.debugEntryMessage(null, null);
430 Object attachedPropertyVal;
431 if (Objects.isNull(propertyValue)) {
432 return Optional.empty();
435 ReferenceType referenceType = ReferenceType.OTHER;
436 if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
437 Map<String, Object> propMap = (Map) propertyValue;
438 Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
439 attachedPropertyVal = entry.getValue();
440 String key = entry.getKey();
443 referenceType = ReferenceType.GET_RESOURCE;
446 referenceType = ReferenceType.GET_PARAM;
449 referenceType = ReferenceType.GET_ATTR;
456 attachedPropertyVal = propertyValue;
459 mdcDataDebugMessage.debugExitMessage(null, null);
460 return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
466 * @param nodeTemplate the node template
467 * @param propertyKey the property key
469 public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
470 mdcDataDebugMessage.debugEntryMessage(null, null);
472 Object value = nodeTemplate.getProperties().get(propertyKey);
473 if (value != null && !(value instanceof Map)) {
474 nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
477 mdcDataDebugMessage.debugExitMessage(null, null);
483 * @param nodeTemplate the node template
484 * @param propertyListKey the property list key
486 public static void mapBooleanList(NodeTemplate nodeTemplate, String propertyListKey) {
487 Object listValue = nodeTemplate.getProperties().get(propertyListKey);
488 if (listValue instanceof List) {
489 List booleanList = ((List) listValue);
490 for (int i = 0; i < booleanList.size(); i++) {
491 Object value = booleanList.get(i);
492 if (value != null && !(value instanceof Map)) {
493 booleanList.set(i, HeatBoolean.eval(value));
501 * Is yml file type boolean.
503 * @param filename the filename
504 * @return the boolean
506 public static boolean isYmlFileType(String filename) {
507 return (filename.indexOf("yaml") > 0 || filename.indexOf("yml") > 0);
511 * Is nested resource boolean.
513 * @param resource the resource
514 * @return the boolean
516 public static boolean isNestedResource(Resource resource) {
517 mdcDataDebugMessage.debugEntryMessage(null, null);
519 String resourceType = resource.getType();
521 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
522 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
523 if (!(((Map) resourceDef).get("type") instanceof String)) {
524 //currently only resource group which is poinitng to nested heat file is supported
525 //dynamic type is currently not supported
528 String internalResourceType = (String) ((Map) resourceDef).get("type");
529 if (isYamlFile(internalResourceType)) {
532 } else if (isYamlFile(resourceType)) {
536 mdcDataDebugMessage.debugExitMessage(null, null);
541 * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at
542 * least one or more compute nodes).
544 * @param resource the resource
545 * @param context the context
546 * @return true if the resource represents a VFC and false otherwise.
548 public static boolean isNestedVfcResource(Resource resource, TranslationContext context) {
549 mdcDataDebugMessage.debugEntryMessage(null, null);
550 Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
551 HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
552 .yamlToObject(context.getFileContent(nestedHeatFileName.get()),
553 HeatOrchestrationTemplate.class);
554 if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) {
555 for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) {
556 if (ConsolidationDataUtil
557 .isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) {
562 mdcDataDebugMessage.debugExitMessage(null, null);
567 * Get nested heat file name in case of nested resource.
569 * @param resource the resource
570 * @return the nested heat file name
572 public static Optional<String> getNestedHeatFileName(Resource resource) {
573 mdcDataDebugMessage.debugEntryMessage(null, null);
575 if (!isNestedResource(resource)) {
576 return Optional.empty();
579 String resourceType = resource.getType();
581 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
582 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
583 String internalResourceType = (String) ((Map) resourceDef).get("type");
584 return Optional.of(internalResourceType);
587 mdcDataDebugMessage.debugExitMessage(null, null);
588 return Optional.of(resourceType);
594 * @param resource the resource
595 * @return the nested file
597 public static Optional<String> getNestedFile(Resource resource) {
600 mdcDataDebugMessage.debugEntryMessage(null, null);
602 if (!isNestedResource(resource)) {
603 return Optional.empty();
605 String resourceType = resource.getType();
606 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
607 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
608 String internalResourceType = (String) ((Map) resourceDef).get("type");
610 mdcDataDebugMessage.debugExitMessage(null, null);
611 return Optional.of(internalResourceType);
613 mdcDataDebugMessage.debugExitMessage(null, null);
614 return Optional.of(resourceType);
618 private static boolean isYamlFile(String fileName) {
619 return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
625 * @param heatOrchestrationTemplate the heat orchestration template
626 * @param resourceId the resource id
627 * @param heatFileName the heat file name
628 * @return the resource
630 public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate,
631 String resourceId, String heatFileName) {
634 mdcDataDebugMessage.debugEntryMessage(null, null);
636 Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
637 if (resource == null) {
638 MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
639 LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(),
640 LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT);
641 throw new CoreException(
642 new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
645 mdcDataDebugMessage.debugExitMessage(null, null);
653 * @param resourceId the resource id
654 * @param heatOrchestrationTemplate heat orchestration template
655 * @param heatFileName heat file name
656 * @return resource type
658 public static String getResourceType(String resourceId,
659 HeatOrchestrationTemplate heatOrchestrationTemplate,
660 String heatFileName) {
663 mdcDataDebugMessage.debugEntryMessage(null, null);
665 mdcDataDebugMessage.debugExitMessage(null, null);
666 return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName)
671 * Is heat file nested boolean.
673 * @param translateTo the translate to
674 * @param heatFileName the heat file name
675 * @return the boolean
677 public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
678 return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName);
682 * Extract contrail get resource attached heat resource id optional.
684 * @param propertyValue the property value
685 * @return the optional
687 public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(
688 Object propertyValue) {
691 mdcDataDebugMessage.debugEntryMessage(null, null);
693 if (propertyValue == null) {
694 return Optional.empty();
698 if (propertyValue instanceof Map) {
699 if (((Map) propertyValue).containsKey("get_attr")) {
700 value = ((Map) propertyValue).get("get_attr");
701 if (value instanceof List) {
702 if (((List) value).size() == 2 && ((List) value).get(1).equals("fq_name")) {
703 if (((List) value).get(0) instanceof String) {
704 return Optional.of((String) ((List) value).get(0));
706 logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString());
710 } else if (((Map) propertyValue).containsKey("get_resource")) {
711 value = ((Map) propertyValue).get("get_resource");
712 if (value instanceof String) {
713 return Optional.of((String) value);
715 logger.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
718 Collection<Object> valCollection = ((Map) propertyValue).values();
719 for (Object entryValue : valCollection) {
720 Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(entryValue);
721 if (ret.isPresent()) {
727 } else if (propertyValue instanceof List) {
728 for (Object prop : (List) propertyValue) {
729 Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
730 if (ret.isPresent()) {
736 mdcDataDebugMessage.debugExitMessage(null, null);
737 return Optional.empty();
741 * Gets tosca service model.
743 * @param context translation context
744 * @return the tosca service model
746 public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
747 mdcDataDebugMessage.debugEntryMessage(null, null);
748 mdcDataDebugMessage.debugExitMessage(null, null);
750 Map<String, String> metadata = new HashMap<>();
751 metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
752 return getToscaServiceModel(context, metadata);
756 * Gets tosca service model.
758 * @param context translation context
759 * @param entryDefinitionMetadata template name of the entry definition servie template
760 * @return the tosca service model
762 public static ToscaServiceModel getToscaServiceModel(
763 TranslationContext context,
764 Map<String, String> entryDefinitionMetadata) {
765 mdcDataDebugMessage.debugEntryMessage(null, null);
767 Map<String, ServiceTemplate> serviceTemplates =
768 new HashMap<>(context.getGlobalServiceTemplates());
769 Collection<ServiceTemplate> tmpServiceTemplates =
770 context.getTranslatedServiceTemplates().values();
771 for (ServiceTemplate serviceTemplate : tmpServiceTemplates) {
772 ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
775 mdcDataDebugMessage.debugExitMessage(null, null);
776 return new ToscaServiceModel(null, serviceTemplates,
777 ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
781 * Gets service template from context.
783 * @param serviceTemplateFileName the service template file name
784 * @param context the context
785 * @return the service template from context
787 public static Optional<ServiceTemplate> getServiceTemplateFromContext(
788 String serviceTemplateFileName, TranslationContext context) {
791 mdcDataDebugMessage.debugEntryMessage(null, null);
793 for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
794 if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
795 mdcDataDebugMessage.debugExitMessage(null, null);
796 return Optional.of(serviceTemplate);
800 mdcDataDebugMessage.debugExitMessage(null, null);
801 return Optional.empty();
805 * Adding link requerment from port node template to network node template.
807 * @param portNodeTemplate port node template
808 * @param networkTranslatedId network node template id
810 public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
811 String networkTranslatedId) {
814 mdcDataDebugMessage.debugEntryMessage(null, null);
816 RequirementAssignment requirement = new RequirementAssignment();
817 requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE);
818 requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO);
819 requirement.setNode(networkTranslatedId);
820 DataModelUtil.addRequirementAssignment(portNodeTemplate,
821 ToscaConstants.LINK_REQUIREMENT_ID, requirement);
823 mdcDataDebugMessage.debugExitMessage(null, null);
829 * Adding binding requerment from sub interface node template to interface (port) node template.
831 * @param subInterfaceNodeTemplate sub interface template
832 * @param interfaceTranslatedId interface node template id
834 public static void addBindingReqFromSubInterfaceToInterface(
835 NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) {
838 mdcDataDebugMessage.debugEntryMessage(null, null);
840 RequirementAssignment requirement = new RequirementAssignment();
841 requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
842 requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
843 requirement.setNode(interfaceTranslatedId);
845 .addRequirementAssignment(subInterfaceNodeTemplate,
846 ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
848 mdcDataDebugMessage.debugExitMessage(null, null);
852 * Get property Parameter Name Value.
854 * @param property property
855 * @return Parameter name in case the property include "get_param" function
857 public static Optional<String> getPropertyParameterNameValue(Object property) {
858 if (Objects.isNull(property)) {
859 return Optional.empty();
861 Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
862 if (extractedProperty.isPresent()) {
863 return getParameterName(extractedProperty.get());
865 return Optional.empty();
868 private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
869 if (!extractedProperty.isGetParam()) {
870 return Optional.empty();
872 Object getParamFuncValue = extractedProperty.getPropertyValue();
873 if (getParamFuncValue instanceof String) {
874 return Optional.of((String) getParamFuncValue);
876 return Optional.of((String) ((List) getParamFuncValue).get(0));
880 public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
881 String heatPropertyName) {
882 return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
886 * Gets tosca property name.
888 * @param translateTo the translate to
889 * @param heatPropertyName the heat property name
890 * @return the tosca property name
892 public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
893 return translateTo.getContext()
894 .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
898 * Gets tosca attribute name.
900 * @param context the context
901 * @param heatResourceType the heat resource type
902 * @param heatAttrName the heat attr name
903 * @return the tosca attribute name
905 public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
906 String heatAttrName) {
907 return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
911 * Gets tosca attribute name.
913 * @param translateTo the translate to
914 * @param heatAttrName the heat attr name
915 * @return the tosca attribute name
917 public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
918 return translateTo.getContext()
919 .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
923 * Create init substitution service template service template.
925 * @param templateName the template name
926 * @return the service template
928 public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) {
929 ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate();
930 Map<String, String> templateMetadata = new HashMap<>();
931 templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
932 nestedSubstitutionServiceTemplate.setMetadata(templateMetadata);
933 nestedSubstitutionServiceTemplate
934 .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
935 nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate());
936 List<Map<String, Import>> globalTypesImportList =
937 GlobalTypesGenerator.getGlobalTypesImportList();
938 globalTypesImportList.addAll(
939 HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
940 nestedSubstitutionServiceTemplate.setImports(globalTypesImportList);
941 return nestedSubstitutionServiceTemplate;
945 * Create init global substitution service template service template.
947 * @return the service template
949 public static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() {
950 ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate();
951 Map<String, String> templateMetadata = new HashMap<>();
952 templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME,
953 Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
954 globalSubstitutionServiceTemplate.setMetadata(templateMetadata);
955 globalSubstitutionServiceTemplate
956 .setImports(GlobalTypesGenerator.getGlobalTypesImportList());
957 globalSubstitutionServiceTemplate
958 .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
959 return globalSubstitutionServiceTemplate;
963 * Create substitution node type node type.
965 * @param substitutionServiceTemplate the substitution service template
966 * @return the node type
968 public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
969 NodeType substitutionNodeType = new NodeType();
970 substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
971 substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
973 .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
975 .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
976 return substitutionNodeType;
979 private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
980 ServiceTemplate substitutionServiceTemplate) {
981 mdcDataDebugMessage.debugEntryMessage(null, null);
983 Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
984 Map<String, ParameterDefinition> properties =
985 substitutionServiceTemplate.getTopology_template().getInputs();
986 if (properties == null) {
987 mdcDataDebugMessage.debugExitMessage(null, null);
991 PropertyDefinition propertyDefinition;
992 String toscaPropertyName;
993 for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
994 toscaPropertyName = entry.getKey();
995 propertyDefinition = new PropertyDefinition();
996 ParameterDefinition parameterDefinition =
997 substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
998 propertyDefinition.setType(parameterDefinition.getType());
999 propertyDefinition.setDescription(parameterDefinition.getDescription());
1000 propertyDefinition.setRequired(parameterDefinition.getRequired());
1001 propertyDefinition.set_default(parameterDefinition.get_default());
1002 propertyDefinition.setConstraints(parameterDefinition.getConstraints());
1003 propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
1004 propertyDefinition.setStatus(parameterDefinition.getStatus());
1005 substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
1008 mdcDataDebugMessage.debugExitMessage(null, null);
1009 return substitutionNodeTypeProperties;
1012 private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
1013 ServiceTemplate substitutionServiceTemplate) {
1016 mdcDataDebugMessage.debugEntryMessage(null, null);
1018 Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
1019 Map<String, ParameterDefinition> attributes =
1020 substitutionServiceTemplate.getTopology_template().getOutputs();
1021 if (attributes == null) {
1022 mdcDataDebugMessage.debugExitMessage(null, null);
1025 AttributeDefinition attributeDefinition;
1026 String toscaAttributeName;
1028 for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
1029 attributeDefinition = new AttributeDefinition();
1030 toscaAttributeName = entry.getKey();
1031 ParameterDefinition parameterDefinition =
1032 substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
1033 if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
1034 attributeDefinition.setType(parameterDefinition.getType());
1036 attributeDefinition.setType(PropertyType.STRING.getDisplayName());
1038 attributeDefinition.setDescription(parameterDefinition.getDescription());
1039 attributeDefinition.set_default(parameterDefinition.get_default());
1040 attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
1041 attributeDefinition.setStatus(parameterDefinition.getStatus());
1042 substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
1045 mdcDataDebugMessage.debugExitMessage(null, null);
1046 return substitutionNodeTypeAttributes;
1051 * Create and add substitution mapping to the nested substitution service template, and update
1052 * the subtitution node type accordingly with the exposed requerments and capabilities
1054 * @param context the translation context
1055 * @param substitutionNodeTypeKey the substitution node type key
1056 * @param nestedSubstitutionServiceTemplate the nested substitution service template
1057 * @param substitutionNodeType the substitution node type
1059 public static void handleSubstitutionMapping(
1060 TranslationContext context,
1061 String substitutionNodeTypeKey,
1062 ServiceTemplate nestedSubstitutionServiceTemplate,
1063 NodeType substitutionNodeType) {
1064 Map<String, Map<String, List<String>>> substitutionMapping =
1065 getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType,
1066 nestedSubstitutionServiceTemplate, context);
1067 //add substitution mapping after capability and requirement expose calculation
1068 nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(
1069 DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeKey,
1070 substitutionNodeType, substitutionMapping));
1074 * Gets node type with flat hierarchy.
1076 * @param nodeTypeId the node type id
1077 * @param serviceTemplate the service template
1078 * @param context the context
1079 * @return the node type with flat hierarchy
1081 public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId,
1082 ServiceTemplate serviceTemplate,
1083 TranslationContext context) {
1084 ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1085 ToscaServiceModel toscaServiceModel = HeatToToscaUtil
1086 .getToscaServiceModel(context, serviceTemplate.getMetadata());
1087 NodeType flatNodeType = (NodeType) toscaAnalyzerService
1088 .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel);
1089 return flatNodeType;
1093 * Create substitution node template node template.
1095 * @param translateTo the translate to
1096 * @param templateName the template name
1097 * @param substitutionNodeTypeKey the substitution node type key
1098 * @return the node template
1100 public NodeTemplate createSubstitutionNodeTemplate(TranslateTo translateTo, String templateName,
1101 String substitutionNodeTypeKey) {
1102 NodeTemplate substitutionNodeTemplate = new NodeTemplate();
1103 List<String> directiveList = new ArrayList<>();
1104 directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
1105 substitutionNodeTemplate.setDirectives(directiveList);
1106 substitutionNodeTemplate.setType(substitutionNodeTypeKey);
1107 substitutionNodeTemplate.setProperties(
1108 managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
1110 return substitutionNodeTemplate;
1114 * Create abstract substitution node template.
1116 * @param translateTo the translate to
1117 * @param templateName the template name
1118 * @param substitutionNodeTypeKey the substitution node type key
1119 * @return the abstract substitute node template
1121 public static NodeTemplate createAbstractSubstitutionNodeTemplate(
1122 TranslateTo translateTo,
1123 String templateName,
1124 String substitutionNodeTypeKey) {
1125 NodeTemplate substitutionNodeTemplate = new NodeTemplate();
1126 List<String> directiveList = new ArrayList<>();
1127 directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
1128 substitutionNodeTemplate.setDirectives(directiveList);
1129 substitutionNodeTemplate.setType(substitutionNodeTypeKey);
1130 substitutionNodeTemplate.setProperties(
1131 managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
1133 return substitutionNodeTemplate;
1138 * Checks if the source and target resource is a valid candidate for adding tosca dependency
1141 * @param heatOrchestrationTemplate the heat orchestration template
1142 * @param sourceResource the source resource
1143 * @param targetResource the target resource
1144 * @param dependencyEntity the dependency entity
1145 * @return true if the candidate resources are a valid combination for the dependency relationship
1146 * and false otherwise
1148 public static boolean isValidDependsOnCandidate(HeatOrchestrationTemplate
1149 heatOrchestrationTemplate,
1150 Resource sourceResource,
1151 Resource targetResource,
1152 ConsolidationEntityType dependencyEntity,
1153 TranslationContext context) {
1155 .setEntityType(heatOrchestrationTemplate, sourceResource, targetResource, context);
1156 ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
1157 ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
1159 //Ignore Compute->Port, Compute->volume, Compute->Compute and Compute->VFC Nested relationships
1160 if (sourceEntityType == ConsolidationEntityType.COMPUTE) {
1161 if (targetEntityType == ConsolidationEntityType.COMPUTE
1162 || targetEntityType == ConsolidationEntityType.VOLUME
1163 || targetEntityType == ConsolidationEntityType.PORT
1164 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1168 //Ignore Port->Compute, Port->volume, Port->Port and Port->VFC Nested relationships
1169 if (sourceEntityType == ConsolidationEntityType.PORT) {
1170 if (targetEntityType == ConsolidationEntityType.COMPUTE
1171 || targetEntityType == ConsolidationEntityType.VOLUME
1172 || targetEntityType == ConsolidationEntityType.PORT
1173 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1178 //Ignore Volume->Compute, Volume->Volume, Volume->Port and Volume->VFC Nested relationships
1179 if (sourceEntityType == ConsolidationEntityType.VOLUME) {
1180 if (targetEntityType == ConsolidationEntityType.COMPUTE
1181 || targetEntityType == ConsolidationEntityType.VOLUME
1182 || targetEntityType == ConsolidationEntityType.PORT
1183 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1188 //Ignore VFC Nested->Compute, VFC Nested->Volume, VFC Nested->Port and
1189 // VFC Nested->VFC Nested relationships
1190 if (sourceEntityType == ConsolidationEntityType.VFC_NESTED) {
1191 if (targetEntityType == ConsolidationEntityType.COMPUTE
1192 || targetEntityType == ConsolidationEntityType.VOLUME
1193 || targetEntityType == ConsolidationEntityType.PORT
1194 || targetEntityType == ConsolidationEntityType.VFC_NESTED) {
1201 private static Map<String, Object> managerSubstitutionNodeTemplateProperties(
1202 TranslateTo translateTo,
1204 String templateName) {
1205 mdcDataDebugMessage.debugEntryMessage(null, null);
1207 Map<String, Object> substitutionProperties = new HashMap<>();
1208 Map<String, Object> heatProperties = translateTo.getResource().getProperties();
1209 if (Objects.nonNull(heatProperties)) {
1210 for (Map.Entry<String, Object> entry : heatProperties.entrySet()) {
1211 Object property = TranslatorHeatToToscaPropertyConverter
1212 .getToscaPropertyValue(translateTo.getServiceTemplate(),
1213 translateTo.getTranslatedId(), entry.getKey(),
1214 entry.getValue(), null, translateTo.getHeatFileName(),
1215 translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext());
1216 substitutionProperties.put(entry.getKey(), property);
1220 mdcDataDebugMessage.debugExitMessage(null, null);
1221 return addAbstractSubstitutionProperty(templateName, substitutionProperties);
1224 private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
1226 substitutionProperties) {
1229 mdcDataDebugMessage.debugEntryMessage(null, null);
1231 Map<String, Object> innerProps = new HashMap<>();
1232 innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME,
1233 ToscaUtil.getServiceTemplateFileName(templateName));
1234 substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
1236 mdcDataDebugMessage.debugExitMessage(null, null);
1237 return substitutionProperties;
1240 private static Map<String, Map<String, List<String>>>
1241 getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
1242 ServiceTemplate substitutionServiceTemplate,
1243 TranslationContext context) {
1244 mdcDataDebugMessage.debugEntryMessage(null, null);
1246 Map<String, NodeTemplate> nodeTemplates =
1247 substitutionServiceTemplate.getTopology_template().getNode_templates();
1248 String nodeTemplateId;
1249 NodeTemplate nodeTemplate;
1251 Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
1252 if (nodeTemplates == null) {
1253 return substitutionMapping;
1256 Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
1257 Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
1258 substitutionMapping.put("capability", capabilitySubstitutionMapping);
1259 substitutionMapping.put("requirement", requirementSubstitutionMapping);
1260 List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
1261 Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
1262 List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
1263 Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
1265 Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
1266 Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
1267 ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1269 for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
1270 nodeTemplateId = entry.getKey();
1271 nodeTemplate = entry.getValue();
1272 nodeType = nodeTemplate.getType();
1275 nodeTypeRequirementsDefinition =
1276 getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate,
1277 requirementSubstitutionMapping, context);
1278 nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
1279 fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
1280 //set substitution node type requirements
1281 exposedRequirementsDefinition =
1282 toscaAnalyzerService.calculateExposedRequirements(nodeTypeRequirementsDefinition,
1283 nodeTemplateRequirementsAssignment);
1285 .addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
1289 addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
1290 capabilitySubstitutionMapping, nodeType,
1291 nodeTemplateId, substitutionServiceTemplate, context);
1294 exposedCapabilitiesDefinition =
1295 toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
1296 fullFilledRequirementsDefinition);
1297 DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
1299 mdcDataDebugMessage.debugExitMessage(null, null);
1300 return substitutionMapping;
1303 private static void addNodeTypeCapabilitiesToSubMapping(
1304 Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
1305 Map<String, List<String>> capabilitySubstitutionMapping, String type, String templateName,
1306 ServiceTemplate serviceTemplate, TranslationContext context) {
1307 mdcDataDebugMessage.debugEntryMessage(null, null);
1309 NodeType flatNodeType =
1310 getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
1311 String capabilityKey;
1312 List<String> capabilityMapping;
1313 if (flatNodeType.getCapabilities() != null) {
1314 for (Map.Entry<String, CapabilityDefinition> capabilityNodeEntry : flatNodeType
1317 capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName;
1318 nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
1319 capabilityMapping = new ArrayList<>();
1320 capabilityMapping.add(templateName);
1321 capabilityMapping.add(capabilityNodeEntry.getKey());
1322 capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
1325 mdcDataDebugMessage.debugExitMessage(null, null);
1328 private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(
1330 String templateName,
1331 ServiceTemplate serviceTemplate,
1332 Map<String, List<String>> requirementSubstitutionMapping,
1333 TranslationContext context) {
1334 mdcDataDebugMessage.debugEntryMessage(null, null);
1335 List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
1336 NodeType flatNodeType =
1337 getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
1338 List<String> requirementMapping;
1340 if (flatNodeType.getRequirements() != null) {
1341 for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
1342 for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
1344 ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
1345 RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil
1346 .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
1347 RequirementDefinition.class);
1348 if (requirementNodeEntryValue.getOccurrences() == null) {
1349 requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
1351 Map<String, RequirementDefinition> requirementDef = new HashMap<>();
1352 requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
1353 DataModelUtil.addRequirementToList(requirementList, requirementDef);
1354 requirementMapping = new ArrayList<>();
1355 requirementMapping.add(templateName);
1356 requirementMapping.add(requirementNodeEntry.getKey());
1357 requirementSubstitutionMapping
1358 .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping);
1359 if (requirementNodeEntryValue.getNode() == null) {
1360 requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
1366 mdcDataDebugMessage.debugExitMessage(null, null);
1367 return requirementList;
1371 * Fetch global substitution service template service template.
1373 * @param serviceTemplate the service template
1374 * @param context the context
1375 * @return the service template
1377 public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(
1378 ServiceTemplate serviceTemplate,
1379 TranslationContext context) {
1380 ServiceTemplate globalSubstitutionServiceTemplate =
1381 context.getTranslatedServiceTemplates()
1382 .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1383 if (globalSubstitutionServiceTemplate == null) {
1384 globalSubstitutionServiceTemplate =
1385 HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate();
1386 context.getTranslatedServiceTemplates()
1387 .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME,
1388 globalSubstitutionServiceTemplate);
1390 boolean isImportAddedToServiceTemplate =
1391 DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants
1392 .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1393 if (!isImportAddedToServiceTemplate) {
1394 serviceTemplate.getImports()
1396 HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
1398 return globalSubstitutionServiceTemplate;
1401 public static List<Map<String, Import>> createImportList(String templateName) {
1402 List<Map<String, Import>> imports = new ArrayList<>();
1403 Map<String, Import> importsMap = new HashMap<>();
1404 importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName));
1405 imports.add(importsMap);
1410 * Create service template import import.
1412 * @param serviceTemplate the service template
1413 * @return the import
1415 public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
1416 Import serviceTemplateImport = new Import();
1417 serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
1418 return serviceTemplateImport;
1422 * Create service template import import.
1424 * @param metadataTemplateName the service template name
1425 * @return the import
1427 public static Import createServiceTemplateImport(String metadataTemplateName) {
1428 Import serviceTemplateImport = new Import();
1429 serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
1430 return serviceTemplateImport;
1433 public static ToscaServiceModel createToscaServiceModel(ServiceTemplate
1434 entryDefinitionServiceTemplate,
1435 TranslationContext translationContext) {
1438 mdcDataDebugMessage.debugEntryMessage(null, null);
1440 mdcDataDebugMessage.debugExitMessage(null, null);
1441 return new ToscaServiceModel(getCsarArtifactFiles(translationContext),
1442 getServiceTemplates(translationContext),
1443 ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
1446 private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
1448 mdcDataDebugMessage.debugEntryMessage(null, null);
1450 FileContentHandler artifactFiles = new FileContentHandler();
1451 artifactFiles.setFiles(translationContext.getFiles());
1452 artifactFiles.setFiles(translationContext.getExternalArtifacts());
1454 HeatTreeManager heatTreeManager =
1455 HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles());
1456 heatTreeManager.createTree();
1457 ValidationStructureList validationStructureList =
1458 new ValidationStructureList(heatTreeManager.getTree());
1459 byte[] validationStructureFile =
1460 FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON);
1461 artifactFiles.addFile("HEAT.meta", validationStructureFile);
1463 mdcDataDebugMessage.debugExitMessage(null, null);
1464 return artifactFiles;
1468 private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext
1469 translationContext) {
1472 mdcDataDebugMessage.debugEntryMessage(null, null);
1474 List<ServiceTemplate> serviceTemplates = new ArrayList<>();
1475 serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate().values());
1476 serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values());
1477 Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>();
1479 for (ServiceTemplate template : serviceTemplates) {
1480 serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
1483 mdcDataDebugMessage.debugExitMessage(null, null);
1484 return serviceTemplatesMap;