[SDC] Onboarding 1710 rebase.
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / openecomp-sdc-translator-core / src / main / java / org / openecomp / sdc / translator / services / heattotosca / HeatToToscaUtil.java
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.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;
95 import java.util.Map;
96 import java.util.Objects;
97 import java.util.Optional;
98 import java.util.Set;
99 import java.util.stream.Collectors;
100
101 /**
102  * The type Heat to tosca util.
103  */
104 public class HeatToToscaUtil {
105
106   protected static Logger logger = (Logger) LoggerFactory.getLogger(HeatToToscaUtil.class);
107   protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
108
109
110   /**
111    * Load and translate template data translator output.
112    *
113    * @param fileNameContentMap the file name content map
114    * @return the translator output
115    */
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);
122
123     heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
124
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))));
130
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;
136     }
137
138     InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap);
139     heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
140
141     mdcDataDebugMessage.debugExitMessage(null, null);
142     return heatToToscaTranslator.translate();
143   }
144
145
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);
152   }
153
154   /**
155    * Build list of files to search optional.
156    *
157    * @param heatFileName  the heat file name
158    * @param filesDataList the files data list
159    * @param types         the types
160    * @return the optional
161    */
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());
169     }
170     return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
171   }
172
173   /**
174    * Gets filtered list of file data by types.
175    *
176    * @param filesToSearch the files to search
177    * @param types         the types
178    * @return the filtered list of file data by types
179    */
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());
184   }
185
186   /**
187    * Gets file data from the list according to the input heat file name.
188    *
189    * @param heatFileName the heat file name
190    * @param fileDataList the file data list
191    * @return the file data
192    */
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);
198       }
199     }
200     return Optional.empty();
201   }
202
203   /**
204    * Gets file data which is supported by the translator, from the context according the input heat
205    * file name.
206    *
207    * @param heatFileName the heat file name
208    * @param context      the translation context
209    * @return the file data
210    */
211   public static FileData getFileData(String heatFileName, TranslationContext context) {
212
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)) {
217         return fileData;
218       }
219     }
220     return null;
221   }
222
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());
230
231     for (FileData fileData : filteredFiles.values()) {
232       String fileName = fileData.getFile();
233
234       if (FileData.isHeatFile(fileData.getType())) {
235         if (fileData.getBase() != null && fileData.getBase().equals(true)) {
236           fileDataCollection.addBaseFiles(fileData);
237         }
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,
245                   resource.getType());
246             } else if (resource.getType()
247                 .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
248               Object resourceDef =
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,
255                       referenced,
256                       internalResourceType);
257                 }
258               }
259             }
260           }
261         }
262
263       } else {
264         fileDataCollection.addArtifactFiles(fileData);
265         filteredFiles.remove(fileData.getFile());
266       }
267     }
268
269     referenced.forEach(filteredFiles::remove);
270     if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
271       for (FileData fileData : fileDataCollection.getBaseFile()) {
272         filteredFiles.remove(fileData.getFile());
273       }
274     }
275     fileDataCollection.setAddOnFiles(filteredFiles.values());
276     return fileDataCollection;
277   }
278
279   private static void handleNestedFile(TranslationContext translationContext,
280                                        FileDataCollection fileDataCollection,
281                                        Map<String, FileData> filteredFiles, Set<String> referenced,
282                                        String nestedFileName) {
283
284
285     mdcDataDebugMessage.debugEntryMessage(null, null);
286
287     referenced.add(nestedFileName);
288     fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
289     translationContext.getNestedHeatsFiles().add(nestedFileName);
290
291     mdcDataDebugMessage.debugExitMessage(null, null);
292   }
293
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));
299     return filtered;
300   }
301
302   private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
303     return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
304   }
305
306   /**
307    * Extract attached resource id optional.
308    *
309    * @param translateTo  the translate to
310    * @param propertyName the property name
311    * @return the optional
312    */
313   public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo,
314                                                                        String propertyName) {
315
316
317     mdcDataDebugMessage.debugEntryMessage(null, null);
318
319     Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
320     if (propertyValue == null) {
321       return Optional.empty();
322     }
323
324     mdcDataDebugMessage.debugExitMessage(null, null);
325     return extractAttachedResourceId(translateTo.getHeatFileName(),
326         translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue);
327   }
328
329   /**
330    * Extract attached resource id optional.
331    *
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
337    */
338   public static Optional<AttachedResourceId> extractAttachedResourceId(
339       String heatFileName,
340       HeatOrchestrationTemplate heatOrchestrationTemplate,
341       TranslationContext context,
342       Object propertyValue) {
343
344     Object entity;
345     Object translatedId;
346
347     if (Objects.isNull(propertyValue)) {
348       return Optional.empty();
349     }
350
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();
357       switch (key) {
358         case "get_resource":
359           referenceType = ReferenceType.GET_RESOURCE;
360           break;
361         case "get_param":
362           referenceType = ReferenceType.GET_PARAM;
363           break;
364         case "get_attr":
365           referenceType = ReferenceType.GET_ATTR;
366           break;
367         default:
368           referenceType = ReferenceType.OTHER;
369           break;
370       }
371
372       if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
373         translatedId = null;
374       } else {
375         translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get()
376             .translateFunction(null, null, null, entry.getKey(), entry.getValue(), heatFileName,
377                 heatOrchestrationTemplate, null, context);
378       }
379       if (translatedId instanceof String
380           && !FunctionTranslationHelper.isResourceSupported((String) translatedId)) {
381         translatedId = null;
382       }
383
384     } else {
385       translatedId = propertyValue;
386       entity = propertyValue;
387     }
388
389     return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
390   }
391
392   /**
393    * Gets contrail attached heat resource id.
394    *
395    * @param attachedResource the attached resource
396    * @return the contrail attached heat resource id
397    */
398   public static Optional<String> getContrailAttachedHeatResourceId(
399       AttachedResourceId attachedResource) {
400
401
402     mdcDataDebugMessage.debugEntryMessage(null, null);
403
404     if (attachedResource == null) {
405       return Optional.empty();
406     }
407
408     if (attachedResource.isGetResource()) {
409       return Optional.of((String) attachedResource.getEntityId());
410     }
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));
415     }
416
417     mdcDataDebugMessage.debugExitMessage(null, null);
418     return Optional.empty();
419   }
420
421   /**
422    * Extract property optional.
423    *
424    * @param propertyValue the property value
425    * @return the optional
426    */
427   public static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
428
429     mdcDataDebugMessage.debugEntryMessage(null, null);
430     Object attachedPropertyVal;
431     if (Objects.isNull(propertyValue)) {
432       return Optional.empty();
433     }
434
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();
441       switch (key) {
442         case "get_resource":
443           referenceType = ReferenceType.GET_RESOURCE;
444           break;
445         case "get_param":
446           referenceType = ReferenceType.GET_PARAM;
447           break;
448         case "get_attr":
449           referenceType = ReferenceType.GET_ATTR;
450           break;
451         default:
452           break;
453       }
454
455     } else {
456       attachedPropertyVal = propertyValue;
457     }
458
459     mdcDataDebugMessage.debugExitMessage(null, null);
460     return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
461   }
462
463   /**
464    * Map boolean.
465    *
466    * @param nodeTemplate the node template
467    * @param propertyKey  the property key
468    */
469   public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
470     mdcDataDebugMessage.debugEntryMessage(null, null);
471
472     Object value = nodeTemplate.getProperties().get(propertyKey);
473     if (value != null && !(value instanceof Map)) {
474       nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
475     }
476
477     mdcDataDebugMessage.debugExitMessage(null, null);
478   }
479
480   /**
481    * Map boolean list.
482    *
483    * @param nodeTemplate    the node template
484    * @param propertyListKey the property list key
485    */
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));
494         }
495       }
496     }
497   }
498
499
500   /**
501    * Is yml file type boolean.
502    *
503    * @param filename the filename
504    * @return the boolean
505    */
506   public static boolean isYmlFileType(String filename) {
507     return (filename.indexOf("yaml") > 0 || filename.indexOf("yml") > 0);
508   }
509
510   /**
511    * Is nested resource boolean.
512    *
513    * @param resource the resource
514    * @return the boolean
515    */
516   public static boolean isNestedResource(Resource resource) {
517     mdcDataDebugMessage.debugEntryMessage(null, null);
518
519     String resourceType = resource.getType();
520
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
526         return false;
527       }
528       String internalResourceType = (String) ((Map) resourceDef).get("type");
529       if (isYamlFile(internalResourceType)) {
530         return true;
531       }
532     } else if (isYamlFile(resourceType)) {
533       return true;
534     }
535
536     mdcDataDebugMessage.debugExitMessage(null, null);
537     return false;
538   }
539
540   /**
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).
543    *
544    * @param resource the resource
545    * @param context the context
546    * @return true if the resource represents a VFC and false otherwise.
547    */
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)) {
558           return true;
559         }
560       }
561     }
562     mdcDataDebugMessage.debugExitMessage(null, null);
563     return false;
564   }
565
566   /**
567    * Get nested heat file name in case of nested resource.
568    *
569    * @param resource the resource
570    * @return the nested heat file name
571    */
572   public static Optional<String> getNestedHeatFileName(Resource resource) {
573     mdcDataDebugMessage.debugEntryMessage(null, null);
574
575     if (!isNestedResource(resource)) {
576       return Optional.empty();
577     }
578
579     String resourceType = resource.getType();
580
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);
585     }
586
587     mdcDataDebugMessage.debugExitMessage(null, null);
588     return Optional.of(resourceType);
589   }
590
591   /**
592    * Gets nested file.
593    *
594    * @param resource the resource
595    * @return the nested file
596    */
597   public static Optional<String> getNestedFile(Resource resource) {
598
599
600     mdcDataDebugMessage.debugEntryMessage(null, null);
601
602     if (!isNestedResource(resource)) {
603       return Optional.empty();
604     }
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");
609
610       mdcDataDebugMessage.debugExitMessage(null, null);
611       return Optional.of(internalResourceType);
612     } else {
613       mdcDataDebugMessage.debugExitMessage(null, null);
614       return Optional.of(resourceType);
615     }
616   }
617
618   private static boolean isYamlFile(String fileName) {
619     return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
620   }
621
622   /**
623    * Gets resource.
624    *
625    * @param heatOrchestrationTemplate the heat orchestration template
626    * @param resourceId                the resource id
627    * @param heatFileName              the heat file name
628    * @return the resource
629    */
630   public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate,
631                                      String resourceId, String heatFileName) {
632
633
634     mdcDataDebugMessage.debugEntryMessage(null, null);
635
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());
643     }
644
645     mdcDataDebugMessage.debugExitMessage(null, null);
646     return resource;
647   }
648
649
650   /**
651    * Get resource type.
652    *
653    * @param resourceId                the resource id
654    * @param heatOrchestrationTemplate heat orchestration template
655    * @param heatFileName              heat file name
656    * @return resource type
657    */
658   public static String getResourceType(String resourceId,
659                                        HeatOrchestrationTemplate heatOrchestrationTemplate,
660                                        String heatFileName) {
661
662
663     mdcDataDebugMessage.debugEntryMessage(null, null);
664
665     mdcDataDebugMessage.debugExitMessage(null, null);
666     return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName)
667         .getType();
668   }
669
670   /**
671    * Is heat file nested boolean.
672    *
673    * @param translateTo  the translate to
674    * @param heatFileName the heat file name
675    * @return the boolean
676    */
677   public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
678     return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName);
679   }
680
681   /**
682    * Extract contrail get resource attached heat resource id optional.
683    *
684    * @param propertyValue the property value
685    * @return the optional
686    */
687   public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(
688       Object propertyValue) {
689
690
691     mdcDataDebugMessage.debugEntryMessage(null, null);
692
693     if (propertyValue == null) {
694       return Optional.empty();
695     }
696
697     Object value;
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));
705             } else {
706               logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString());
707             }
708           }
709         }
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);
714         } else {
715           logger.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
716         }
717       } else {
718         Collection<Object> valCollection = ((Map) propertyValue).values();
719         for (Object entryValue : valCollection) {
720           Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(entryValue);
721           if (ret.isPresent()) {
722             return ret;
723           }
724
725         }
726       }
727     } else if (propertyValue instanceof List) {
728       for (Object prop : (List) propertyValue) {
729         Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
730         if (ret.isPresent()) {
731           return ret;
732         }
733       }
734     }
735
736     mdcDataDebugMessage.debugExitMessage(null, null);
737     return Optional.empty();
738   }
739
740   /**
741    * Gets tosca service model.
742    *
743    * @param context translation context
744    * @return the tosca service model
745    */
746   public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
747     mdcDataDebugMessage.debugEntryMessage(null, null);
748     mdcDataDebugMessage.debugExitMessage(null, null);
749
750     Map<String, String> metadata = new HashMap<>();
751     metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
752     return getToscaServiceModel(context, metadata);
753   }
754
755   /**
756    * Gets tosca service model.
757    *
758    * @param context                 translation context
759    * @param entryDefinitionMetadata template name of the entry definition servie template
760    * @return the tosca service model
761    */
762   public static ToscaServiceModel getToscaServiceModel(
763       TranslationContext context,
764       Map<String, String> entryDefinitionMetadata) {
765     mdcDataDebugMessage.debugEntryMessage(null, null);
766
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);
773     }
774
775     mdcDataDebugMessage.debugExitMessage(null, null);
776     return new ToscaServiceModel(null, serviceTemplates,
777         ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
778   }
779
780   /**
781    * Gets service template from context.
782    *
783    * @param serviceTemplateFileName the service template file name
784    * @param context                 the context
785    * @return the service template from context
786    */
787   public static Optional<ServiceTemplate> getServiceTemplateFromContext(
788       String serviceTemplateFileName, TranslationContext context) {
789
790
791     mdcDataDebugMessage.debugEntryMessage(null, null);
792
793     for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
794       if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
795         mdcDataDebugMessage.debugExitMessage(null, null);
796         return Optional.of(serviceTemplate);
797       }
798     }
799
800     mdcDataDebugMessage.debugExitMessage(null, null);
801     return Optional.empty();
802   }
803
804   /**
805    * Adding link requerment from port node template to network node template.
806    *
807    * @param portNodeTemplate    port node template
808    * @param networkTranslatedId network node template id
809    */
810   public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
811                                                                   String networkTranslatedId) {
812
813
814     mdcDataDebugMessage.debugEntryMessage(null, null);
815
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);
822
823     mdcDataDebugMessage.debugExitMessage(null, null);
824
825     return requirement;
826   }
827
828   /**
829    * Adding binding requerment from sub interface node template to interface (port) node template.
830    *
831    * @param subInterfaceNodeTemplate sub interface template
832    * @param interfaceTranslatedId    interface node template id
833    */
834   public static void addBindingReqFromSubInterfaceToInterface(
835       NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) {
836
837
838     mdcDataDebugMessage.debugEntryMessage(null, null);
839
840     RequirementAssignment requirement = new RequirementAssignment();
841     requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
842     requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
843     requirement.setNode(interfaceTranslatedId);
844     DataModelUtil
845         .addRequirementAssignment(subInterfaceNodeTemplate,
846             ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
847
848     mdcDataDebugMessage.debugExitMessage(null, null);
849   }
850
851   /**
852    * Get property Parameter Name Value.
853    *
854    * @param property property
855    * @return Parameter name in case the property include "get_param" function
856    */
857   public static Optional<String> getPropertyParameterNameValue(Object property) {
858     if (Objects.isNull(property)) {
859       return Optional.empty();
860     }
861     Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
862     if (extractedProperty.isPresent()) {
863       return getParameterName(extractedProperty.get());
864     }
865     return Optional.empty();
866   }
867
868   private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
869     if (!extractedProperty.isGetParam()) {
870       return Optional.empty();
871     }
872     Object getParamFuncValue = extractedProperty.getPropertyValue();
873     if (getParamFuncValue instanceof String) {
874       return Optional.of((String) getParamFuncValue);
875     } else {
876       return Optional.of((String) ((List) getParamFuncValue).get(0));
877     }
878   }
879
880   public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
881                                             String heatPropertyName) {
882     return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
883   }
884
885   /**
886    * Gets tosca property name.
887    *
888    * @param translateTo      the translate to
889    * @param heatPropertyName the heat property name
890    * @return the tosca property name
891    */
892   public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
893     return translateTo.getContext()
894         .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
895   }
896
897   /**
898    * Gets tosca attribute name.
899    *
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
904    */
905   public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
906                                              String heatAttrName) {
907     return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
908   }
909
910   /**
911    * Gets tosca attribute name.
912    *
913    * @param translateTo  the translate to
914    * @param heatAttrName the heat attr name
915    * @return the tosca attribute name
916    */
917   public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
918     return translateTo.getContext()
919         .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
920   }
921
922   /**
923    * Create init substitution service template service template.
924    *
925    * @param templateName the template name
926    * @return the service template
927    */
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;
942   }
943
944   /**
945    * Create init global substitution service template service template.
946    *
947    * @return the service template
948    */
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;
960   }
961
962   /**
963    * Create substitution node type node type.
964    *
965    * @param substitutionServiceTemplate the substitution service template
966    * @return the node type
967    */
968   public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
969     NodeType substitutionNodeType = new NodeType();
970     substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
971     substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
972     substitutionNodeType
973         .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
974     substitutionNodeType
975         .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
976     return substitutionNodeType;
977   }
978
979   private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
980       ServiceTemplate substitutionServiceTemplate) {
981     mdcDataDebugMessage.debugEntryMessage(null, null);
982
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);
988       return null;
989     }
990
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);
1006     }
1007
1008     mdcDataDebugMessage.debugExitMessage(null, null);
1009     return substitutionNodeTypeProperties;
1010   }
1011
1012   private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
1013       ServiceTemplate substitutionServiceTemplate) {
1014
1015
1016     mdcDataDebugMessage.debugEntryMessage(null, null);
1017
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);
1023       return null;
1024     }
1025     AttributeDefinition attributeDefinition;
1026     String toscaAttributeName;
1027
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());
1035       } else {
1036         attributeDefinition.setType(PropertyType.STRING.getDisplayName());
1037       }
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);
1043     }
1044
1045     mdcDataDebugMessage.debugExitMessage(null, null);
1046     return substitutionNodeTypeAttributes;
1047   }
1048
1049   /**
1050    * .
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
1053    *
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
1058    */
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));
1071   }
1072
1073   /**
1074    * Gets node type with flat hierarchy.
1075    *
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
1080    */
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;
1090   }
1091
1092   /**
1093    * Create substitution node template node template.
1094    *
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
1099    */
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,
1109             templateName));
1110     return substitutionNodeTemplate;
1111   }
1112
1113   /**
1114    * Create abstract substitution node template.
1115    *
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
1120    */
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,
1132             templateName));
1133     return substitutionNodeTemplate;
1134   }
1135
1136
1137   /**
1138    * Checks if the source and target resource is a valid candidate for adding tosca dependency
1139    * relationship.
1140    *
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
1147    */
1148   public static boolean isValidDependsOnCandidate(HeatOrchestrationTemplate
1149                                                       heatOrchestrationTemplate,
1150                                                   Resource sourceResource,
1151                                                   Resource targetResource,
1152                                                   ConsolidationEntityType dependencyEntity,
1153                                                   TranslationContext context) {
1154     dependencyEntity
1155         .setEntityType(heatOrchestrationTemplate, sourceResource, targetResource, context);
1156     ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
1157     ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
1158
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) {
1165         return false;
1166       }
1167     }
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) {
1174         return false;
1175       }
1176     }
1177
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) {
1184         return false;
1185       }
1186     }
1187
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) {
1195         return false;
1196       }
1197     }
1198     return true;
1199   }
1200
1201   private static Map<String, Object> managerSubstitutionNodeTemplateProperties(
1202       TranslateTo translateTo,
1203       Template template,
1204       String templateName) {
1205     mdcDataDebugMessage.debugEntryMessage(null, null);
1206
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);
1217       }
1218     }
1219
1220     mdcDataDebugMessage.debugExitMessage(null, null);
1221     return addAbstractSubstitutionProperty(templateName, substitutionProperties);
1222   }
1223
1224   private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
1225                                                                      Map<String, Object>
1226                                                                          substitutionProperties) {
1227
1228
1229     mdcDataDebugMessage.debugEntryMessage(null, null);
1230
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);
1235
1236     mdcDataDebugMessage.debugExitMessage(null, null);
1237     return substitutionProperties;
1238   }
1239
1240   private static Map<String, Map<String, List<String>>>
1241   getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
1242                                                  ServiceTemplate substitutionServiceTemplate,
1243                                                  TranslationContext context) {
1244     mdcDataDebugMessage.debugEntryMessage(null, null);
1245
1246     Map<String, NodeTemplate> nodeTemplates =
1247         substitutionServiceTemplate.getTopology_template().getNode_templates();
1248     String nodeTemplateId;
1249     NodeTemplate nodeTemplate;
1250     String nodeType;
1251     Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
1252     if (nodeTemplates == null) {
1253       return substitutionMapping;
1254     }
1255
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 =
1264         new HashMap<>();
1265     Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
1266     Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
1267     ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1268
1269     for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
1270       nodeTemplateId = entry.getKey();
1271       nodeTemplate = entry.getValue();
1272       nodeType = nodeTemplate.getType();
1273
1274       // get requirements
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);
1284       DataModelUtil
1285           .addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
1286           nodeTemplateId);
1287
1288       //get capabilities
1289       addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
1290           capabilitySubstitutionMapping, nodeType,
1291           nodeTemplateId, substitutionServiceTemplate, context);
1292     }
1293
1294     exposedCapabilitiesDefinition =
1295         toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
1296         fullFilledRequirementsDefinition);
1297     DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
1298
1299     mdcDataDebugMessage.debugExitMessage(null, null);
1300     return substitutionMapping;
1301   }
1302
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);
1308
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
1315           .getCapabilities()
1316           .entrySet()) {
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);
1323       }
1324     }
1325     mdcDataDebugMessage.debugExitMessage(null, null);
1326   }
1327
1328   private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(
1329       String type,
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;
1339
1340     if (flatNodeType.getRequirements() != null) {
1341       for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
1342         for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
1343             .entrySet()) {
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});
1350           }
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});
1361           }
1362         }
1363       }
1364     }
1365
1366     mdcDataDebugMessage.debugExitMessage(null, null);
1367     return requirementList;
1368   }
1369
1370   /**
1371    * Fetch global substitution service template service template.
1372    *
1373    * @param serviceTemplate the service template
1374    * @param context         the context
1375    * @return the service template
1376    */
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);
1389     }
1390     boolean isImportAddedToServiceTemplate =
1391         DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants
1392             .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1393     if (!isImportAddedToServiceTemplate) {
1394       serviceTemplate.getImports()
1395           .addAll(
1396               HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
1397     }
1398     return globalSubstitutionServiceTemplate;
1399   }
1400
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);
1406     return imports;
1407   }
1408
1409   /**
1410    * Create service template import import.
1411    *
1412    * @param serviceTemplate the service template
1413    * @return the import
1414    */
1415   public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
1416     Import serviceTemplateImport = new Import();
1417     serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
1418     return serviceTemplateImport;
1419   }
1420
1421   /**
1422    * Create service template import import.
1423    *
1424    * @param metadataTemplateName the service template name
1425    * @return the import
1426    */
1427   public static Import createServiceTemplateImport(String metadataTemplateName) {
1428     Import serviceTemplateImport = new Import();
1429     serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
1430     return serviceTemplateImport;
1431   }
1432
1433   public static ToscaServiceModel createToscaServiceModel(ServiceTemplate
1434                                                               entryDefinitionServiceTemplate,
1435                                                           TranslationContext translationContext) {
1436
1437
1438     mdcDataDebugMessage.debugEntryMessage(null, null);
1439
1440     mdcDataDebugMessage.debugExitMessage(null, null);
1441     return new ToscaServiceModel(getCsarArtifactFiles(translationContext),
1442         getServiceTemplates(translationContext),
1443         ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
1444   }
1445
1446   private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
1447
1448     mdcDataDebugMessage.debugEntryMessage(null, null);
1449
1450     FileContentHandler artifactFiles = new FileContentHandler();
1451     artifactFiles.setFiles(translationContext.getFiles());
1452     artifactFiles.setFiles(translationContext.getExternalArtifacts());
1453
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);
1462
1463     mdcDataDebugMessage.debugExitMessage(null, null);
1464     return artifactFiles;
1465   }
1466
1467
1468   private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext
1469                                                                       translationContext) {
1470
1471
1472     mdcDataDebugMessage.debugEntryMessage(null, null);
1473
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<>();
1478
1479     for (ServiceTemplate template : serviceTemplates) {
1480       serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
1481     }
1482
1483     mdcDataDebugMessage.debugExitMessage(null, null);
1484     return serviceTemplatesMap;
1485   }
1486
1487 }