c1f69cf3bf4571c877e92f801e841f633e000078
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.translator.services.heattotosca;
22
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;
88
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;
96 import java.util.Map;
97 import java.util.Objects;
98 import java.util.Optional;
99 import java.util.Set;
100 import java.util.stream.Collectors;
101
102 /**
103  * The type Heat to tosca util.
104  */
105 public class HeatToToscaUtil {
106
107   protected static Logger logger = (Logger) LoggerFactory.getLogger(HeatToToscaUtil.class);
108   protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
109
110
111   /**
112    * Load and translate template data translator output.
113    *
114    * @param fileNameContentMap the file name content map
115    * @return the translator output
116    */
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);
123
124     heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
125
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))));
131
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;
137     }
138
139     try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) {
140       heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
141
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);
147     }
148   }
149
150
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);
157   }
158
159   /**
160    * Build list of files to search optional.
161    *
162    * @param heatFileName  the heat file name
163    * @param filesDataList the files data list
164    * @param types         the types
165    * @return the optional
166    */
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());
174     }
175     return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
176   }
177
178   /**
179    * Gets filtered list of file data by types.
180    *
181    * @param filesToSearch the files to search
182    * @param types         the types
183    * @return the filtered list of file data by types
184    */
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());
189   }
190
191   /**
192    * Gets file data from the list according to the input heat file name.
193    *
194    * @param heatFileName the heat file name
195    * @param fileDataList the file data list
196    * @return the file data
197    */
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);
203       }
204     }
205     return Optional.empty();
206   }
207
208   /**
209    * Gets file data which is supported by the translator, from the context according the input heat
210    * file name.
211    *
212    * @param heatFileName the heat file name
213    * @param context      the translation context
214    * @return the file data
215    */
216   public static FileData getFileData(String heatFileName, TranslationContext context) {
217
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)) {
222         return fileData;
223       }
224     }
225     return null;
226   }
227
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());
235
236     for (FileData fileData : filteredFiles.values()) {
237       String fileName = fileData.getFile();
238
239       if (FileData.isHeatFile(fileData.getType())) {
240         if (fileData.getBase() != null && fileData.getBase().equals(true)) {
241           fileDataCollection.addBaseFiles(fileData);
242         }
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,
250                   resource.getType());
251             } else if (resource.getType()
252                 .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
253               Object resourceDef =
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,
260                       referenced,
261                       internalResourceType);
262                 }
263               }
264             }
265           }
266         }
267
268       } else {
269         fileDataCollection.addArtifactFiles(fileData);
270         filteredFiles.remove(fileData.getFile());
271       }
272     }
273
274     referenced.forEach(filteredFiles::remove);
275     if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
276       for (FileData fileData : fileDataCollection.getBaseFile()) {
277         filteredFiles.remove(fileData.getFile());
278       }
279     }
280     fileDataCollection.setAddOnFiles(filteredFiles.values());
281     return fileDataCollection;
282   }
283
284   private static void handleNestedFile(TranslationContext translationContext,
285                                        FileDataCollection fileDataCollection,
286                                        Map<String, FileData> filteredFiles, Set<String> referenced,
287                                        String nestedFileName) {
288
289
290     mdcDataDebugMessage.debugEntryMessage(null, null);
291
292     referenced.add(nestedFileName);
293     fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
294     translationContext.getNestedHeatsFiles().add(nestedFileName);
295
296     mdcDataDebugMessage.debugExitMessage(null, null);
297   }
298
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));
304     return filtered;
305   }
306
307   private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
308     return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
309   }
310
311   /**
312    * Extract attached resource id optional.
313    *
314    * @param translateTo  the translate to
315    * @param propertyName the property name
316    * @return the optional
317    */
318   public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo,
319                                                                        String propertyName) {
320
321
322     mdcDataDebugMessage.debugEntryMessage(null, null);
323
324     Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
325     if (propertyValue == null) {
326       return Optional.empty();
327     }
328
329     mdcDataDebugMessage.debugExitMessage(null, null);
330     return extractAttachedResourceId(translateTo.getHeatFileName(),
331         translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue);
332   }
333
334   /**
335    * Extract attached resource id optional.
336    *
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
342    */
343   public static Optional<AttachedResourceId> extractAttachedResourceId(
344       String heatFileName,
345       HeatOrchestrationTemplate heatOrchestrationTemplate,
346       TranslationContext context,
347       Object propertyValue) {
348
349     Object entity;
350     Object translatedId;
351
352     if (Objects.isNull(propertyValue)) {
353       return Optional.empty();
354     }
355
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();
362       switch (key) {
363         case "get_resource":
364           referenceType = ReferenceType.GET_RESOURCE;
365           break;
366         case "get_param":
367           referenceType = ReferenceType.GET_PARAM;
368           break;
369         case "get_attr":
370           referenceType = ReferenceType.GET_ATTR;
371           break;
372         default:
373           referenceType = ReferenceType.OTHER;
374           break;
375       }
376
377       if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
378         translatedId = null;
379       } else {
380         translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get()
381             .translateFunction(null, null, null, entry.getKey(), entry.getValue(), heatFileName,
382                 heatOrchestrationTemplate, null, context);
383       }
384       if (translatedId instanceof String
385           && !FunctionTranslationHelper.isResourceSupported((String) translatedId)) {
386         translatedId = null;
387       }
388
389     } else {
390       translatedId = propertyValue;
391       entity = propertyValue;
392     }
393
394     return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
395   }
396
397   /**
398    * Gets contrail attached heat resource id.
399    *
400    * @param attachedResource the attached resource
401    * @return the contrail attached heat resource id
402    */
403   public static Optional<String> getContrailAttachedHeatResourceId(
404       AttachedResourceId attachedResource) {
405
406
407     mdcDataDebugMessage.debugEntryMessage(null, null);
408
409     if (attachedResource == null) {
410       return Optional.empty();
411     }
412
413     if (attachedResource.isGetResource()) {
414       return Optional.of((String) attachedResource.getEntityId());
415     }
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));
420     }
421
422     mdcDataDebugMessage.debugExitMessage(null, null);
423     return Optional.empty();
424   }
425
426   /**
427    * Extract property optional.
428    *
429    * @param propertyValue the property value
430    * @return the optional
431    */
432   public static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
433
434     mdcDataDebugMessage.debugEntryMessage(null, null);
435     Object attachedPropertyVal;
436     if (Objects.isNull(propertyValue)) {
437       return Optional.empty();
438     }
439
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();
446       switch (key) {
447         case "get_resource":
448           referenceType = ReferenceType.GET_RESOURCE;
449           break;
450         case "get_param":
451           referenceType = ReferenceType.GET_PARAM;
452           break;
453         case "get_attr":
454           referenceType = ReferenceType.GET_ATTR;
455           break;
456         default:
457           break;
458       }
459
460     } else {
461       attachedPropertyVal = propertyValue;
462     }
463
464     mdcDataDebugMessage.debugExitMessage(null, null);
465     return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
466   }
467
468   /**
469    * Map boolean.
470    *
471    * @param nodeTemplate the node template
472    * @param propertyKey  the property key
473    */
474   public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
475     mdcDataDebugMessage.debugEntryMessage(null, null);
476
477     Object value = nodeTemplate.getProperties().get(propertyKey);
478     if (value != null && !(value instanceof Map)) {
479       nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
480     }
481
482     mdcDataDebugMessage.debugExitMessage(null, null);
483   }
484
485   /**
486    * Map boolean list.
487    *
488    * @param nodeTemplate    the node template
489    * @param propertyListKey the property list key
490    */
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));
499         }
500       }
501     }
502   }
503
504
505   /**
506    * Is yml file type boolean.
507    *
508    * @param filename the filename
509    * @return the boolean
510    */
511   public static boolean isYmlFileType(String filename) {
512     return (filename.indexOf("yaml") > 0 || filename.indexOf("yml") > 0);
513   }
514
515   /**
516    * Is nested resource boolean.
517    *
518    * @param resource the resource
519    * @return the boolean
520    */
521   public static boolean isNestedResource(Resource resource) {
522     mdcDataDebugMessage.debugEntryMessage(null, null);
523
524     String resourceType = resource.getType();
525
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
531         return false;
532       }
533       String internalResourceType = (String) ((Map) resourceDef).get("type");
534       if (isYamlFile(internalResourceType)) {
535         return true;
536       }
537     } else if (isYamlFile(resourceType)) {
538       return true;
539     }
540
541     mdcDataDebugMessage.debugExitMessage(null, null);
542     return false;
543   }
544
545   /**
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).
548    *
549    * @param resource the resource
550    * @param context the context
551    * @return true if the resource represents a VFC and false otherwise.
552    */
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)) {
563           return true;
564         }
565       }
566     }
567     mdcDataDebugMessage.debugExitMessage(null, null);
568     return false;
569   }
570
571   /**
572    * Get nested heat file name in case of nested resource.
573    *
574    * @param resource the resource
575    * @return the nested heat file name
576    */
577   public static Optional<String> getNestedHeatFileName(Resource resource) {
578     mdcDataDebugMessage.debugEntryMessage(null, null);
579
580     if (!isNestedResource(resource)) {
581       return Optional.empty();
582     }
583
584     String resourceType = resource.getType();
585
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);
590     }
591
592     mdcDataDebugMessage.debugExitMessage(null, null);
593     return Optional.of(resourceType);
594   }
595
596   /**
597    * Gets nested file.
598    *
599    * @param resource the resource
600    * @return the nested file
601    */
602   public static Optional<String> getNestedFile(Resource resource) {
603
604
605     mdcDataDebugMessage.debugEntryMessage(null, null);
606
607     if (!isNestedResource(resource)) {
608       return Optional.empty();
609     }
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");
614
615       mdcDataDebugMessage.debugExitMessage(null, null);
616       return Optional.of(internalResourceType);
617     } else {
618       mdcDataDebugMessage.debugExitMessage(null, null);
619       return Optional.of(resourceType);
620     }
621   }
622
623   private static boolean isYamlFile(String fileName) {
624     return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
625   }
626
627   /**
628    * Gets resource.
629    *
630    * @param heatOrchestrationTemplate the heat orchestration template
631    * @param resourceId                the resource id
632    * @param heatFileName              the heat file name
633    * @return the resource
634    */
635   public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate,
636                                      String resourceId, String heatFileName) {
637
638
639     mdcDataDebugMessage.debugEntryMessage(null, null);
640
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());
648     }
649
650     mdcDataDebugMessage.debugExitMessage(null, null);
651     return resource;
652   }
653
654
655   /**
656    * Get resource type.
657    *
658    * @param resourceId                the resource id
659    * @param heatOrchestrationTemplate heat orchestration template
660    * @param heatFileName              heat file name
661    * @return resource type
662    */
663   public static String getResourceType(String resourceId,
664                                        HeatOrchestrationTemplate heatOrchestrationTemplate,
665                                        String heatFileName) {
666
667
668     mdcDataDebugMessage.debugEntryMessage(null, null);
669
670     mdcDataDebugMessage.debugExitMessage(null, null);
671     return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName)
672         .getType();
673   }
674
675   /**
676    * Is heat file nested boolean.
677    *
678    * @param translateTo  the translate to
679    * @param heatFileName the heat file name
680    * @return the boolean
681    */
682   public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
683     return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName);
684   }
685
686   /**
687    * Extract contrail get resource attached heat resource id optional.
688    *
689    * @param propertyValue the property value
690    * @return the optional
691    */
692   public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(
693       Object propertyValue) {
694
695
696     mdcDataDebugMessage.debugEntryMessage(null, null);
697
698     if (propertyValue == null) {
699       return Optional.empty();
700     }
701
702     Object value;
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));
710             } else {
711               logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString());
712             }
713           }
714         }
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);
719         } else {
720           logger.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
721         }
722       } else {
723         Collection<Object> valCollection = ((Map) propertyValue).values();
724         for (Object entryValue : valCollection) {
725           Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(entryValue);
726           if (ret.isPresent()) {
727             return ret;
728           }
729
730         }
731       }
732     } else if (propertyValue instanceof List) {
733       for (Object prop : (List) propertyValue) {
734         Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
735         if (ret.isPresent()) {
736           return ret;
737         }
738       }
739     }
740
741     mdcDataDebugMessage.debugExitMessage(null, null);
742     return Optional.empty();
743   }
744
745   /**
746    * Gets tosca service model.
747    *
748    * @param context translation context
749    * @return the tosca service model
750    */
751   public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
752     mdcDataDebugMessage.debugEntryMessage(null, null);
753     mdcDataDebugMessage.debugExitMessage(null, null);
754
755     Map<String, String> metadata = new HashMap<>();
756     metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
757     return getToscaServiceModel(context, metadata);
758   }
759
760   /**
761    * Gets tosca service model.
762    *
763    * @param context                 translation context
764    * @param entryDefinitionMetadata template name of the entry definition servie template
765    * @return the tosca service model
766    */
767   public static ToscaServiceModel getToscaServiceModel(
768       TranslationContext context,
769       Map<String, String> entryDefinitionMetadata) {
770     mdcDataDebugMessage.debugEntryMessage(null, null);
771
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);
778     }
779
780     mdcDataDebugMessage.debugExitMessage(null, null);
781     return new ToscaServiceModel(null, serviceTemplates,
782         ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
783   }
784
785   /**
786    * Gets service template from context.
787    *
788    * @param serviceTemplateFileName the service template file name
789    * @param context                 the context
790    * @return the service template from context
791    */
792   public static Optional<ServiceTemplate> getServiceTemplateFromContext(
793       String serviceTemplateFileName, TranslationContext context) {
794
795
796     mdcDataDebugMessage.debugEntryMessage(null, null);
797
798     for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
799       if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
800         mdcDataDebugMessage.debugExitMessage(null, null);
801         return Optional.of(serviceTemplate);
802       }
803     }
804
805     mdcDataDebugMessage.debugExitMessage(null, null);
806     return Optional.empty();
807   }
808
809   /**
810    * Adding link requerment from port node template to network node template.
811    *
812    * @param portNodeTemplate    port node template
813    * @param networkTranslatedId network node template id
814    */
815   public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
816                                                                   String networkTranslatedId) {
817
818
819     mdcDataDebugMessage.debugEntryMessage(null, null);
820
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);
827
828     mdcDataDebugMessage.debugExitMessage(null, null);
829
830     return requirement;
831   }
832
833   /**
834    * Adding binding requerment from sub interface node template to interface (port) node template.
835    *
836    * @param subInterfaceNodeTemplate sub interface template
837    * @param interfaceTranslatedId    interface node template id
838    */
839   public static void addBindingReqFromSubInterfaceToInterface(
840       NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) {
841
842
843     mdcDataDebugMessage.debugEntryMessage(null, null);
844
845     RequirementAssignment requirement = new RequirementAssignment();
846     requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
847     requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
848     requirement.setNode(interfaceTranslatedId);
849     DataModelUtil
850         .addRequirementAssignment(subInterfaceNodeTemplate,
851             ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
852
853     mdcDataDebugMessage.debugExitMessage(null, null);
854   }
855
856   /**
857    * Get property Parameter Name Value.
858    *
859    * @param property property
860    * @return Parameter name in case the property include "get_param" function
861    */
862   public static Optional<String> getPropertyParameterNameValue(Object property) {
863     if (Objects.isNull(property)) {
864       return Optional.empty();
865     }
866     Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
867     if (extractedProperty.isPresent()) {
868       return getParameterName(extractedProperty.get());
869     }
870     return Optional.empty();
871   }
872
873   private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
874     if (!extractedProperty.isGetParam()) {
875       return Optional.empty();
876     }
877     Object getParamFuncValue = extractedProperty.getPropertyValue();
878     if (getParamFuncValue instanceof String) {
879       return Optional.of((String) getParamFuncValue);
880     } else {
881       return Optional.of((String) ((List) getParamFuncValue).get(0));
882     }
883   }
884
885   public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
886                                             String heatPropertyName) {
887     return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
888   }
889
890   /**
891    * Gets tosca property name.
892    *
893    * @param translateTo      the translate to
894    * @param heatPropertyName the heat property name
895    * @return the tosca property name
896    */
897   public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
898     return translateTo.getContext()
899         .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
900   }
901
902   /**
903    * Gets tosca attribute name.
904    *
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
909    */
910   public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
911                                              String heatAttrName) {
912     return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
913   }
914
915   /**
916    * Gets tosca attribute name.
917    *
918    * @param translateTo  the translate to
919    * @param heatAttrName the heat attr name
920    * @return the tosca attribute name
921    */
922   public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
923     return translateTo.getContext()
924         .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
925   }
926
927   /**
928    * Create init substitution service template service template.
929    *
930    * @param templateName the template name
931    * @return the service template
932    */
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;
947   }
948
949   /**
950    * Create init global substitution service template service template.
951    *
952    * @return the service template
953    */
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;
965   }
966
967   /**
968    * Create substitution node type node type.
969    *
970    * @param substitutionServiceTemplate the substitution service template
971    * @return the node type
972    */
973   public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
974     NodeType substitutionNodeType = new NodeType();
975     substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
976     substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
977     substitutionNodeType
978         .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
979     substitutionNodeType
980         .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
981     return substitutionNodeType;
982   }
983
984   private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
985       ServiceTemplate substitutionServiceTemplate) {
986     mdcDataDebugMessage.debugEntryMessage(null, null);
987
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);
993       return null;
994     }
995
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);
1011     }
1012
1013     mdcDataDebugMessage.debugExitMessage(null, null);
1014     return substitutionNodeTypeProperties;
1015   }
1016
1017   private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
1018       ServiceTemplate substitutionServiceTemplate) {
1019
1020
1021     mdcDataDebugMessage.debugEntryMessage(null, null);
1022
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);
1028       return null;
1029     }
1030     AttributeDefinition attributeDefinition;
1031     String toscaAttributeName;
1032
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());
1040       } else {
1041         attributeDefinition.setType(PropertyType.STRING.getDisplayName());
1042       }
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);
1048     }
1049
1050     mdcDataDebugMessage.debugExitMessage(null, null);
1051     return substitutionNodeTypeAttributes;
1052   }
1053
1054   /**
1055    * .
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
1058    *
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
1063    */
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));
1076   }
1077
1078   /**
1079    * Gets node type with flat hierarchy.
1080    *
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
1085    */
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;
1095   }
1096
1097   /**
1098    * Create substitution node template node template.
1099    *
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
1104    */
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,
1114             templateName));
1115     return substitutionNodeTemplate;
1116   }
1117
1118   /**
1119    * Create abstract substitution node template.
1120    *
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
1125    */
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,
1137             templateName));
1138     return substitutionNodeTemplate;
1139   }
1140
1141
1142   /**
1143    * Checks if the source and target resource is a valid candidate for adding tosca dependency
1144    * relationship.
1145    *
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
1152    */
1153   public static boolean isValidDependsOnCandidate(HeatOrchestrationTemplate
1154                                                       heatOrchestrationTemplate,
1155                                                   Resource sourceResource,
1156                                                   Resource targetResource,
1157                                                   ConsolidationEntityType dependencyEntity,
1158                                                   TranslationContext context) {
1159     dependencyEntity
1160         .setEntityType(heatOrchestrationTemplate, sourceResource, targetResource, context);
1161     ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
1162     ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
1163
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) {
1170         return false;
1171       }
1172     }
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) {
1179         return false;
1180       }
1181     }
1182
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) {
1189         return false;
1190       }
1191     }
1192
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) {
1200         return false;
1201       }
1202     }
1203     return true;
1204   }
1205
1206   private static Map<String, Object> managerSubstitutionNodeTemplateProperties(
1207       TranslateTo translateTo,
1208       Template template,
1209       String templateName) {
1210     mdcDataDebugMessage.debugEntryMessage(null, null);
1211
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);
1222       }
1223     }
1224
1225     mdcDataDebugMessage.debugExitMessage(null, null);
1226     return addAbstractSubstitutionProperty(templateName, substitutionProperties);
1227   }
1228
1229   private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
1230                                                                      Map<String, Object>
1231                                                                          substitutionProperties) {
1232
1233
1234     mdcDataDebugMessage.debugEntryMessage(null, null);
1235
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);
1240
1241     mdcDataDebugMessage.debugExitMessage(null, null);
1242     return substitutionProperties;
1243   }
1244
1245   private static Map<String, Map<String, List<String>>>
1246   getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
1247                                                  ServiceTemplate substitutionServiceTemplate,
1248                                                  TranslationContext context) {
1249     mdcDataDebugMessage.debugEntryMessage(null, null);
1250
1251     Map<String, NodeTemplate> nodeTemplates =
1252         substitutionServiceTemplate.getTopology_template().getNode_templates();
1253     String nodeTemplateId;
1254     NodeTemplate nodeTemplate;
1255     String nodeType;
1256     Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
1257     if (nodeTemplates == null) {
1258       return substitutionMapping;
1259     }
1260
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 =
1269         new HashMap<>();
1270     Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
1271     Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
1272     ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1273
1274     for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
1275       nodeTemplateId = entry.getKey();
1276       nodeTemplate = entry.getValue();
1277       nodeType = nodeTemplate.getType();
1278
1279       // get requirements
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);
1289       DataModelUtil
1290           .addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
1291           nodeTemplateId);
1292
1293       //get capabilities
1294       addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
1295           capabilitySubstitutionMapping, nodeType,
1296           nodeTemplateId, substitutionServiceTemplate, context);
1297     }
1298
1299     exposedCapabilitiesDefinition =
1300         toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
1301         fullFilledRequirementsDefinition);
1302     DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
1303
1304     mdcDataDebugMessage.debugExitMessage(null, null);
1305     return substitutionMapping;
1306   }
1307
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);
1313
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
1320           .getCapabilities()
1321           .entrySet()) {
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);
1328       }
1329     }
1330     mdcDataDebugMessage.debugExitMessage(null, null);
1331   }
1332
1333   private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(
1334       String type,
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;
1344
1345     if (flatNodeType.getRequirements() != null) {
1346       for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
1347         for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
1348             .entrySet()) {
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});
1355           }
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});
1366           }
1367         }
1368       }
1369     }
1370
1371     mdcDataDebugMessage.debugExitMessage(null, null);
1372     return requirementList;
1373   }
1374
1375   /**
1376    * Fetch global substitution service template service template.
1377    *
1378    * @param serviceTemplate the service template
1379    * @param context         the context
1380    * @return the service template
1381    */
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);
1394     }
1395     boolean isImportAddedToServiceTemplate =
1396         DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants
1397             .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1398     if (!isImportAddedToServiceTemplate) {
1399       serviceTemplate.getImports()
1400           .addAll(
1401               HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
1402     }
1403     return globalSubstitutionServiceTemplate;
1404   }
1405
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);
1411     return imports;
1412   }
1413
1414   /**
1415    * Create service template import import.
1416    *
1417    * @param serviceTemplate the service template
1418    * @return the import
1419    */
1420   public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
1421     Import serviceTemplateImport = new Import();
1422     serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
1423     return serviceTemplateImport;
1424   }
1425
1426   /**
1427    * Create service template import import.
1428    *
1429    * @param metadataTemplateName the service template name
1430    * @return the import
1431    */
1432   public static Import createServiceTemplateImport(String metadataTemplateName) {
1433     Import serviceTemplateImport = new Import();
1434     serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
1435     return serviceTemplateImport;
1436   }
1437
1438   public static ToscaServiceModel createToscaServiceModel(ServiceTemplate
1439                                                               entryDefinitionServiceTemplate,
1440                                                           TranslationContext translationContext) {
1441
1442
1443     mdcDataDebugMessage.debugEntryMessage(null, null);
1444
1445     mdcDataDebugMessage.debugExitMessage(null, null);
1446     return new ToscaServiceModel(getCsarArtifactFiles(translationContext),
1447         getServiceTemplates(translationContext),
1448         ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
1449   }
1450
1451   private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
1452
1453     mdcDataDebugMessage.debugEntryMessage(null, null);
1454
1455     FileContentHandler artifactFiles = new FileContentHandler();
1456     artifactFiles.setFiles(translationContext.getFiles());
1457     artifactFiles.setFiles(translationContext.getExternalArtifacts());
1458
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);
1467
1468     mdcDataDebugMessage.debugExitMessage(null, null);
1469     return artifactFiles;
1470   }
1471
1472
1473   private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext
1474                                                                       translationContext) {
1475
1476
1477     mdcDataDebugMessage.debugEntryMessage(null, null);
1478
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<>();
1483
1484     for (ServiceTemplate template : serviceTemplates) {
1485       serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
1486     }
1487
1488     mdcDataDebugMessage.debugExitMessage(null, null);
1489     return serviceTemplatesMap;
1490   }
1491
1492 }