[sdc] - latest code changes
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / openecomp-sdc-translator-core / src / main / java / org / openecomp / sdc / translator / datatypes / heattotosca / TranslationContext.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.datatypes.heattotosca;
22
23 import org.openecomp.config.api.Configuration;
24 import org.openecomp.config.api.ConfigurationManager;
25 import org.openecomp.core.utilities.CommonMethods;
26 import org.openecomp.core.utilities.file.FileContentHandler;
27 import org.openecomp.sdc.common.utils.SdcCommon;
28 import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration;
29 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
30 import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile;
31 import org.openecomp.sdc.heat.datatypes.model.Resource;
32 import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate;
33 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
34 import org.openecomp.sdc.tosca.services.ToscaUtil;
35 import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource;
36 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity;
37 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedSubstitutionData;
38 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData;
39 import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants;
40 import org.openecomp.sdc.translator.services.heattotosca.Constants;
41 import org.openecomp.sdc.translator.services.heattotosca.NameExtractor;
42 import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator;
43
44 import java.io.InputStream;
45 import java.util.HashMap;
46 import java.util.HashSet;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Objects;
50 import java.util.Optional;
51 import java.util.Set;
52
53
54 public class TranslationContext {
55
56
57   private static Map<String, Map<String, Map<String, String>>> translationMapping;
58   private static Map<String, ServiceTemplate> globalServiceTemplates;
59   private static Map<String, ImplementationConfiguration> nameExtractorImplMap;
60   private static Map<String, ImplementationConfiguration> supportedConsolidationComputeResources;
61   private static Map<String, ImplementationConfiguration> supportedConsolidationPortResources;
62   private static List enrichPortResourceProperties;
63
64   static {
65     Configuration config = ConfigurationManager.lookup();
66     String propertyFileName = SdcCommon.HEAT_TO_TOSCA_MAPPING_CONF;
67     translationMapping =
68         config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY);
69     try {
70       globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate();
71     } catch (Exception e) {
72       throw new RuntimeException("Failed to load GlobalTypes", e);
73     }
74     nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE,
75         ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, ImplementationConfiguration.class);
76     supportedConsolidationComputeResources = config.populateMap(ConfigConstants
77         .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants
78         .SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, ImplementationConfiguration.class);
79     supportedConsolidationPortResources = config.populateMap(ConfigConstants
80         .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants
81         .SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, ImplementationConfiguration.class);
82     enrichPortResourceProperties = config.getAsStringValues(ConfigConstants
83         .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants
84         .ENRICH_PORT_RESOURCE_PROP);
85
86   }
87
88   private Map<String, UnifiedSubstitutionData> unifiedSubstitutionData = new HashMap<>();
89   private ManifestFile manifest;
90
91   public static List getEnrichPortResourceProperties() {
92     return enrichPortResourceProperties;
93   }
94
95   private FileContentHandler files = new FileContentHandler();
96   private Map<String, FileData.Type> manifestFiles = new HashMap<>();
97   //Key - file name, value - file type
98   private Set<String> nestedHeatsFiles = new HashSet<>();
99   private FileContentHandler externalArtifacts = new FileContentHandler();
100   // Key - heat file name,value - set of heat resource ids which were translated
101   private Map<String, Set<String>> translatedResources = new HashMap<>();
102   // Key - heat file name, value - translated Node template id
103   private Map<String, Set<String>> heatStackGroupMembers = new HashMap<>();
104   // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id
105   private Map<String, Map<String, String>> translatedIds = new HashMap<>();
106   // key - service template type, value - translated service templates
107   private Map<String, ServiceTemplate> translatedServiceTemplates = new HashMap<>();
108   //key - heat param name, value - shared resource data
109   private Map<String, TranslatedHeatResource> heatSharedResourcesByParam = new HashMap<>();
110   //key - translated substitute service template file name, value - source nested heat file name
111   private Map<String, String> nestedHeatFileName = new HashMap<>();
112   //Key - heat file name,value - Map eith key - heat pseudo param name,
113   // value - translated tosca parameter name
114   private Map<String, Map<String, String>> usedHeatPseudoParams = new HashMap<>();
115   //Consolidation data gathered for Unified TOSCA model
116   private ConsolidationData consolidationData = new ConsolidationData();
117
118   public static Map<String, ImplementationConfiguration>
119   getSupportedConsolidationComputeResources() {
120     return supportedConsolidationComputeResources;
121   }
122
123   public static void setSupportedConsolidationComputeResources(
124       Map<String, ImplementationConfiguration> supportedConsolidationComputeResources) {
125     TranslationContext.supportedConsolidationComputeResources =
126         supportedConsolidationComputeResources;
127   }
128
129   public static Map<String, ImplementationConfiguration> getSupportedConsolidationPortResources() {
130     return supportedConsolidationPortResources;
131   }
132
133   public static void setSupportedConsolidationPortResources(
134       Map<String, ImplementationConfiguration> supportedConsolidationPortResources) {
135     TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources;
136   }
137
138   /**
139    * Get nameExtractor implemetation class instance.
140    *
141    * @param extractorImplKey configuration key for the implementation class
142    * @return implemetation class instance
143    */
144   public static NameExtractor getNameExtractorImpl(String extractorImplKey) {
145     String nameExtractorImplClassName =
146         nameExtractorImplMap.get(extractorImplKey).getImplementationClass();
147
148     return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class);
149   }
150
151   public Map<String, UnifiedSubstitutionData> getUnifiedSubstitutionData() {
152     return unifiedSubstitutionData;
153   }
154
155   public void setUnifiedSubstitutionData(
156       Map<String, UnifiedSubstitutionData> unifiedSubstitutionData) {
157     this.unifiedSubstitutionData = unifiedSubstitutionData;
158   }
159
160   public void addCleanedNodeTemplate(String serviceTemplateName,
161                                      String nodeTemplateId,
162                                      UnifiedCompositionEntity unifiedCompositionEntity,
163                                      NodeTemplate nodeTemplate) {
164     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
165     this.unifiedSubstitutionData
166         .get(serviceTemplateName)
167         .addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate);
168   }
169
170   public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName,
171                                              String nodeTemplateId) {
172     return this.unifiedSubstitutionData.get(serviceTemplateName)
173         .getCleanedNodeTemplate(nodeTemplateId);
174   }
175
176   public void addUnifiedNestedNodeTemplateId(String serviceTemplateName,
177                                              String nestedNodeTemplateId,
178                                              String unifiedNestedNodeTemplateId) {
179     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
180     this.unifiedSubstitutionData.get(serviceTemplateName)
181         .addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId);
182   }
183
184   public Optional<String> getUnifiedNestedNodeTemplateId(String serviceTemplateName,
185                                                          String nestedNodeTemplateId) {
186     return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty()
187             :this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId);
188   }
189
190   public void addUnifiedNestedNodeTypeId(String serviceTemplateName,
191                                              String nestedNodeTypeId,
192                                              String unifiedNestedNodeTypeId){
193     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
194     this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId);
195   }
196
197   public Optional<String> getUnifiedNestedNodeTypeId(String serviceTemplateName,
198                                                      String nestedNodeTemplateId) {
199     return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty()
200             : this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTypeId(nestedNodeTemplateId);
201   }
202
203   public ConsolidationData getConsolidationData() {
204     return consolidationData;
205   }
206
207   public void setConsolidationData(ConsolidationData consolidationData) {
208     this.consolidationData = consolidationData;
209   }
210
211   public void addManifestFile(String fileName, FileData.Type fileType) {
212     this.manifestFiles.put(fileName, fileType);
213   }
214
215   public Set<String> getNestedHeatsFiles() {
216     return nestedHeatsFiles;
217   }
218
219   public Map<String, Set<String>> getHeatStackGroupMembers() {
220     return heatStackGroupMembers;
221   }
222
223   public FileContentHandler getFiles() {
224     return files;
225   }
226
227   public void setFiles(Map<String, byte[]> files) {
228     this.files.putAll(files);
229   }
230
231   public InputStream getFileContent(String fileName) {
232     return files.getFileContent(fileName);
233   }
234
235   public void addFile(String name, byte[] content) {
236     files.addFile(name, content);
237   }
238
239   public ManifestFile getManifest() {
240     return manifest;
241   }
242
243   public void setManifest(ManifestFile manifest) {
244     this.manifest = manifest;
245   }
246
247   public Map<String, Set<String>> getTranslatedResources() {
248     return translatedResources;
249   }
250
251   public Map<String, Map<String, String>> getTranslatedIds() {
252     return translatedIds;
253   }
254
255   public Set<String> getAllTranslatedResourceIdsFromDiffNestedFiles(String
256                                                                         nestedHeatFileNameToSkip){
257     Set<String> allTranslatedResourceIds = new HashSet<>();
258
259     this.translatedIds.entrySet().stream().filter(
260         heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey()
261             .equals(nestedHeatFileNameToSkip)).forEach(heatFileNameToTranslatedIdsEntry -> {
262       allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet());
263     });
264
265     return allTranslatedResourceIds;
266   }
267
268   // get tosca name from mapping configuration file
269   //element type - parameter/attribute
270   // element name - heat parameter/attribute name
271   //return value - tosca parameter/attribute name
272   public String getElementMapping(String resourceType, String elementType, String elementName) {
273     if (Objects.isNull(translationMapping.get(resourceType))) {
274       return null;
275     }
276     if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) {
277       return null;
278     }
279     return translationMapping.get(resourceType).get(elementType).get(elementName);
280   }
281
282   public Map<String, String> getElementMapping(String resourceType, String elementType) {
283     if (Objects.isNull(translationMapping.get(resourceType))) {
284       return null;
285     }
286     return translationMapping.get(resourceType).get(elementType);
287   }
288
289   public Set<String> getElementSet(String resourceType, String elementType) {
290     if (Objects.isNull(translationMapping.get(resourceType))) {
291       return new HashSet<>();
292     }
293     if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) {
294       return new HashSet<>();
295     }
296     return translationMapping.get(resourceType).get(elementType).keySet();
297   }
298
299   public Map<String, ServiceTemplate> getTranslatedServiceTemplates() {
300     return translatedServiceTemplates;
301   }
302
303   public ServiceTemplate getGlobalSubstitutionServiceTemplate() {
304     return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
305   }
306
307   public FileContentHandler getExternalArtifacts() {
308     return externalArtifacts;
309   }
310
311   public void addExternalArtifacts(String name, byte[] content) {
312     this.externalArtifacts.addFile(name, content);
313   }
314
315   public Map<String, TranslatedHeatResource> getHeatSharedResourcesByParam() {
316     return heatSharedResourcesByParam;
317   }
318
319   public void addHeatSharedResourcesByParam(String parameterName, String resourceId,
320                                             Resource resource) {
321     this.addHeatSharedResourcesByParam(parameterName,
322         new TranslatedHeatResource(resourceId, resource));
323   }
324
325   private void addHeatSharedResourcesByParam(String parameterName,
326                                             TranslatedHeatResource translatedHeatResource) {
327     this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource);
328   }
329
330   public Map<String, ServiceTemplate> getGlobalServiceTemplates() {
331     return globalServiceTemplates;
332   }
333
334   public Map<String, String> getNestedHeatFileName() {
335     return nestedHeatFileName;
336   }
337
338   public void addNestedHeatFileName(String substituteServiceTempalteName,
339                                     String nestedHeatFileName) {
340     this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName);
341   }
342
343   public Map<String, Map<String, String>> getUsedHeatPseudoParams() {
344     return usedHeatPseudoParams;
345   }
346
347   public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String
348       translatedToscaParam) {
349     if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) {
350       this.usedHeatPseudoParams.put(heatFileName, new HashMap<>());
351     }
352     this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam);
353   }
354
355   /**
356    * Add the unified substitution data info in context. Contains a mapping of original node
357    * template id and the new node template id in the abstract substitute
358    *
359    * @param serviceTemplateFileName the service template file name
360    * @param originalNodeTemplateId  the original node template id
361    * @param abstractNodeTemplateId  the node template id in the abstract substitute
362    */
363   public void addUnifiedSubstitutionData(String serviceTemplateFileName,
364                                          String originalNodeTemplateId,
365                                          String abstractNodeTemplateId) {
366
367     Map<String, String> nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData()
368         .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData())
369         .getNodesRelatedAbstractNode();
370
371     if (nodeAbstractNodeTemplateIdMap == null) {
372       nodeAbstractNodeTemplateIdMap = new HashMap<>();
373     }
374     nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId);
375     this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode(
376         nodeAbstractNodeTemplateIdMap);
377   }
378
379   /**
380    * Add the unified substitution data info in context. Contains a mapping of original node
381    * template id and the new node template id in the abstract substitute
382    *
383    * @param serviceTemplateFileName                   the service template file name
384    * @param originalNodeTemplateId                    the original node template id
385    * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution
386    *                                                  service template
387    */
388   public void addSubstitutionServiceTemplateUnifiedSubstitutionData(String serviceTemplateFileName,
389                                                 String originalNodeTemplateId,
390                                                 String substitutionServiceTemplateNodeTemplateId) {
391
392     Map<String, String> nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this
393         .getUnifiedSubstitutionData()
394         .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData())
395         .getNodesRelatedSubstitutionServiceTemplateNode();
396
397     if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) {
398       nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>();
399     }
400     nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId,
401         substitutionServiceTemplateNodeTemplateId);
402     this.getUnifiedSubstitutionData().get(serviceTemplateFileName)
403         .setNodesRelatedSubstitutionServiceTemplateNode(
404             nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap);
405   }
406
407   /**
408    * Get unified abstract node template which is mapped to the input node template id.
409    *
410    * @param serviceTemplate the service template
411    * @param nodeTemplateId  the node template id
412    */
413   public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate,
414                                                  String nodeTemplateId) {
415     UnifiedSubstitutionData unifiedSubstitutionData =
416         this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
417     return unifiedSubstitutionData.getNodesRelatedAbstractNode().get(nodeTemplateId);
418   }
419
420   /**
421    * Get unified node template in the substitution service template which is mapped to the
422    * original input node template id.
423    *
424    * @param serviceTemplate the service template
425    * @param nodeTemplateId  the node template id
426    */
427   public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate,
428                                                      String nodeTemplateId) {
429     UnifiedSubstitutionData unifiedSubstitutionData =
430         this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
431     return unifiedSubstitutionData.getNodesRelatedSubstitutionServiceTemplateNode()
432         .get(nodeTemplateId);
433   }
434
435   public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName,
436                                                       String computeType){
437     return this.unifiedSubstitutionData.get(serviceTemplateName)
438         .getHandledNestedComputeNodeTemplateIndex(computeType);
439   }
440
441   public void updateHandledComputeType(String serviceTemplateName,
442                                        String nestedServiceTemplateFileName,
443                                        String handledComputeType){
444     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
445     this.unifiedSubstitutionData.get(serviceTemplateName)
446         .addHandledComputeType(nestedServiceTemplateFileName, handledComputeType);
447   }
448
449   public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName,
450                                                    String nestedServiceTemplateFileName){
451     if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){
452       return false;
453     }
454     return this.unifiedSubstitutionData.get(serviceTemplateName)
455         .isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName);
456   }
457
458   public void addNestedFileToUsedNestedComputeType(String serviceTemplateName,
459                                                    String nestedServiceTemplateFileName,
460                                                    String computeType){
461     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
462
463     this.unifiedSubstitutionData.get(serviceTemplateName).addNestedFileToUsedNestedComputeType
464         (computeType, nestedServiceTemplateFileName);
465   }
466
467   public int getGlobalNodeTypeIndex(String serviceTemplateName,
468                                     String computeType){
469     if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){
470       return 0;
471     }
472     return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex
473         (computeType);
474   }
475
476   public void addNewPropertyIdToNodeTemplate(String serviceTemplateName,
477                                              String newPropertyId,
478                                              Object origPropertyValue){
479     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
480     this.unifiedSubstitutionData.get(serviceTemplateName).addNewPropertyIdToNodeTemplate(
481         newPropertyId, origPropertyValue);
482   }
483
484   public Optional<Object> getNewPropertyInputParamId(String serviceTemplateName,
485                                                      String newPropertyId){
486     if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){
487       return Optional.empty();
488     }
489
490     return this.unifiedSubstitutionData.get(serviceTemplateName).getNewPropertyInputParam
491         (newPropertyId);
492   }
493
494   public Map<String, Object> getAllNewPropertyInputParamIdsPerNodeTenplateId(String serviceTemplateName){
495     if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){
496       return new HashMap<>();
497     }
498
499     return this.unifiedSubstitutionData.get(serviceTemplateName).getAllNewPropertyInputParamIds();
500
501   }
502
503
504 }