6cae746fd5989df8a1831a26408f0105ee0b0c23
[appc/cdt.git] / src / app / vnfs / build-artifacts / template-holder / template-configuration / template-configuration.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
5 ===================================================================
6 Copyright (C) 2018 IBM.
7 ===================================================================
8
9 Unless otherwise specified, all software contained herein is licensed
10 under the Apache License, Version 2.0 (the License);
11 you may not use this software except in compliance with the License.
12 You may obtain a copy of the License at
13
14     http://www.apache.org/licenses/LICENSE-2.0
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22 ============LICENSE_END============================================
23 */
24
25 import { Component, Input, OnInit, ViewChild } from '@angular/core';
26 import { Subscription } from 'rxjs/Subscription';
27 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
28 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
29 import { ArtifactRequest } from '../../../../shared/models/index';
30 import { ActivatedRoute, Router } from '@angular/router';
31 import { saveAs } from 'file-saver';
32 import { NotificationService } from '../../../../shared/services/notification.service';
33 import { NotificationsService } from 'angular2-notifications';
34 import { ParamShareService } from '../../../../shared/services/paramShare.service';
35 import { DialogService } from 'ng2-bootstrap-modal';
36 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
37 import { BuildDesignComponent } from '../../build-artifacts.component';
38 import { environment } from '../../../../../environments/environment';
39 import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
40 import { NgProgress } from 'ngx-progressbar';
41 import { NgxSpinnerService } from 'ngx-spinner';
42 import { UtilityService } from '../../../../shared/services/utilityService/utility.service';
43 declare var $: any
44 const PARAM_DATA:string="param_data";
45 const TEMPLATE_DATA:string="template_data";
46 @Component({ selector: 'app-golden-configuration', templateUrl: './template-configuration.component.html', styleUrls: ['./template-configuration.component.css'] })
47 export class GoldenConfigurationComponent implements OnInit {
48   @ViewChild('templateeditor') templateeditor;
49   @Input() configMappingEditorContent: string;
50   @Input() isMappingComp: boolean;
51   @ViewChild('myInput') myInputVariable: any;
52   @ViewChild('myModal') modal: ModalComponent;
53   aceText: string = ""
54   fileName: string = ""
55   showTemplateVersionDiv: any;
56   downloadedTemplateFileName: any;
57   downloadedParamFileName: any;
58   templateVersionNo: any = '0.0.1';
59   saveToGuiCacheFlag = 'false';
60   initialAction: any;
61   public referenceData: Array<Object> = [];
62   public scopeName: any;
63   public subscription: Subscription;
64   public templateSubscription : Subscription;
65   public item: any = {};
66   public goldenActions: Array<string> = [];
67   public refNameObj = {};
68   public action = '';
69   public artifactName = '';
70   public type;
71   public showError: boolean = false;
72   public tempretrieveFlag: boolean = false;
73   public fileNameForTempSave;
74   initialData: any;
75   showDownloadDiv: boolean = false;
76   downloadType: any;
77   enableBrowse: boolean = true;
78   enableMerge: boolean = false;
79   uploadValidationSuccess: boolean = false;
80   fileExtension: any = "xml";
81   apiToken = localStorage['apiToken'];
82   public appDataObject: any;
83   public downloadDataObject: any;
84   public checkNameEntered: boolean = true;
85   public selectedWord: any = this.mappingEditorService.getSelectedWord();
86   public Actions = [
87     { action: "ConfigBackup", value: "ConfigBackup" },
88     { action: "ConfigModify", value: "ConfigModify" },
89     { action: "ConfigRestore", value: "ConfigRestore" },
90     { action: "Configure", value: "Configure" },
91     { action: "GetRunningConfig", value: "GetRunningConfig" },
92     { action: "HealthCheck", value: "HealthCheck" },
93     { action: "StartApplication", value: "StartApplication" },
94     { action: "StopApplication", value: "StopApplication" }
95   ];
96   options = {
97     timeOut: 1000,
98     showProgressBar: true,
99     pauseOnHover: true,
100     clickToClose: true,
101     maxLength: 200
102   }
103   public replaceWord;
104   public enableDownloadButtons: boolean = false;
105    
106   constructor(
107     private buildDesignComponent: BuildDesignComponent, 
108     private paramShareService: ParamShareService, 
109     private dialogService: DialogService, 
110     private notificationService: NotificationService, 
111     private httpUtil: HttpUtilService, 
112     private mappingEditorService: MappingEditorService, 
113     private activeRoutes: ActivatedRoute, 
114     private router: Router, 
115     private nService: NotificationsService, 
116     private ngProgress: NgProgress,
117     private spinner: NgxSpinnerService,
118     private utilityService: UtilityService) {
119     this.artifactRequest.action = '';
120     this.artifactRequest.version = '';
121     this.artifactRequest.paramsContent = '{}';
122     this.artifactRequest.paramKeysContent = '';
123   }
124   public templateEditor: any;
125   public fileType: any = '';
126   public actionType: any;
127   public myfileName: any;
128   userId = localStorage['userId'];
129   public artifactRequest: ArtifactRequest = new ArtifactRequest();
130   public showUploadStatus: boolean = false;
131   public uploadStatus: boolean = false;
132   public uploadTypes = [
133     {
134       value: 'Generated Template',
135       display: 'Sample Json Param File'
136     },
137     {
138       value: 'Mapping Data',
139       display: 'Sample Json Param File'
140     }
141   ];
142   vnfType: any = '';
143   vnfcType: any = '';
144   protocol: any = '';
145   refObj: any;
146   editor: any;
147   editorContent: any;
148   tempName: any;
149   enableValidateTemplate: boolean = false;;
150   public selectedUploadType: string = this.uploadTypes[0].value;
151   identifier: any;
152   public tempRetrievalResponse: any;
153   public mergeStatus: boolean = false;
154
155   //======================================Start of ngOnInit() Method============================================
156   ngOnInit() {
157     var refObj = this.refObj = this.prepareFileName();
158     if (refObj && refObj != undefined) {
159       this.item = refObj;
160
161       this.vnfType = this.item.scope["vnf-type"];
162       this.vnfcType = this.item.scope["vnfc-type"];
163       this.protocol = this.item['device-protocol'];
164       this.action = this.item.action;
165       this.artifactRequest.action = this.item.action;
166       this.artifactRequest.vnfType = this.vnfType;
167       if (this.vnfcType != undefined && this.vnfcType.length != 0) {
168         this.scopeName = this.vnfcType;
169       }
170       else {
171         this.scopeName = this.vnfType;
172       }
173     }
174     else {
175       this.item = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
176     }
177     this.initialAction = this.item.action;
178     this.subscription = this.activeRoutes.url.subscribe(UrlSegment => {
179       this.actionType = UrlSegment[0].path
180     })
181     this.mappingEditorService.fromScreen = 'MappingScreen';
182     this.identifier = this.mappingEditorService.identifier;
183   }
184   //========================== End of ngOnInit() Method============================================
185   ngOnDestroy() {
186     if (this.refObj && this.refObj != undefined) {
187       if (this.configMappingEditorContent && this.configMappingEditorContent != undefined) {
188         this.saveTemplate();
189         this.prepareAppData();
190         this.prepareDownloadData();
191         this.mappingEditorService.changeNavAppData(this.appDataObject);
192         this.mappingEditorService.changeNavDownloadData(this.downloadDataObject);
193       }
194     }
195
196     if(this.subscription) { this.subscription.unsubscribe(); }
197     if(this.templateSubscription) { this.templateSubscription.unsubscribe(); }
198   }
199   //========================== End of ngOnDestroy() Method============================================
200   ngAfterViewInit() {
201     if (this.mappingEditorService.latestAction) {
202       this.refNameObj = this.mappingEditorService.latestAction;
203       if (this.vnfcType !== 'null') {
204         this.type = this.vnfcType;
205       }
206       else {
207         this.type = this.vnfType;
208       }
209       for (let i = 0; i < this.refNameObj['artifact-list'].length; i++) {
210         let artifactList = this.refNameObj['artifact-list'];
211         if (artifactList[i]['artifact-type'] === 'config_template') {
212           var artifactName = artifactList[i]['artifact-name'];
213           var artifactNameWithoutExtension = '';
214                     if (artifactName) {
215             artifactNameWithoutExtension = artifactName.substring(0, artifactName.lastIndexOf("."));
216           }
217           if(this.mappingEditorService.identifier) {
218             if(artifactNameWithoutExtension.endsWith(this.mappingEditorService.identifier)) {
219                 this.artifactName = artifactName;
220             }
221           }
222           else {
223             this.artifactName = artifactName;
224           }
225
226         }
227       }
228     }
229     let self = this;
230     this.templateEditor = self.templateeditor.getEditor();
231     this.templateeditor.getEditor().commands.addCommand({
232       name: 'annotateCommandAlternate',
233       bindKey: { win: 'CTRL-4', mac: 'Command-4' },
234       exec: (editor: any) => {
235         this.handleAnnotation(this.modal);
236       }
237     });
238     this.templateeditor.getEditor().$enableBlockSelect = false;
239     this.templateeditor.getEditor().$enableMultiselect = false;
240     if (this.mappingEditorService.fromScreen === 'MappingScreen') {
241       this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
242       this.fileType = sessionStorage.getItem('fileType');
243     }
244     if (this.configMappingEditorContent) {
245       this.artifactRequest.templateContent = this.configMappingEditorContent;
246       this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
247     }
248     if (this.refObj) {
249       if (this.mappingEditorService.getTemplateMappingDataFromStore() && this.mappingEditorService.getTemplateMappingDataFromStore() != undefined) {
250         this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
251       }
252       else {
253         if (this.artifactName) this.retrieveTemplateFromAppc();
254       }
255     }
256     else {
257       this.Actions = [];
258       this.enableBrowse = false;
259       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
260     }
261   }
262
263   //========================== End of ngAfterViewInit() Method============================================
264   browseOption() {
265     $("#inputFile").trigger('click');
266   }
267   //========================== End of browseOption() Method============================================
268   //save to GUI
269   public saveTemplate() {
270     this.saveToGuiCacheFlag = 'true';
271     this.mappingEditorService.paramData = [];
272     if (this.configMappingEditorContent) {
273       this.initialData = this.configMappingEditorContent;
274       this.mappingEditorService.refreshEditor();
275       let paramArr: any = []
276       if (this.mappingEditorService.paramData && this.mappingEditorService.paramData != undefined) {
277         if (this.mappingEditorService.paramData.length === 0 && this.mappingEditorService.hasErrorCode === true) {
278           this.nService.error("Error", 'Special characters error', 'Error')
279           return;
280         }
281         else {
282           this.showError = false;
283         }
284       }
285       this.showTemplateVersionDiv = true;
286
287       if (this.mappingEditorService.fromScreen === 'MappingScreen') {
288         this.mappingEditorService.setTemplateMappingDataFromStore(this.configMappingEditorContent);
289       }
290       if (this.fileType === 'text/xml') {
291         sessionStorage.setItem('fileType', 'text/xml');
292       }
293       if (this.fileType === '') {
294         sessionStorage.setItem('fileType', '');
295       }
296     }
297   }
298   //========================== End of saveTemplate() Method============================================
299   retrieveTemplateFromAppc() {
300     let refObj = this.refObj;
301     if (refObj && refObj != undefined) {
302
303       let fileName = this.artifactName;
304       let input = this.utilityService.createPayloadForRetrieve(false, this.item.action, this.vnfType, fileName);
305       let artifactContent: any;
306       this.ngProgress.start();
307       this.templateSubscription = this.httpUtil.post({
308         url: environment.getDesigns,
309         data: input
310       }).subscribe(resp => {
311         if (resp.output.status.code === '400' && resp.output.status.message === "success") {
312           this.nService.success("Success", "Template retrieved successfully from APPC");
313           this.tempRetrievalResponse = resp;
314           let result = JSON.parse(resp.output.data.block).artifactInfo[0];
315           result = result['artifact-content'];
316           if ('Generated Template' === this.selectedUploadType) {
317             this.configMappingEditorContent = result
318             this.artifactRequest.templateContent = this.configMappingEditorContent;
319             this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
320             if (this.artifactRequest.templateContent) {
321               this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
322             }
323           }
324           this.tempretrieveFlag = true;
325           this.fileNameForTempSave = fileName;
326           this.enableDownloadButtons = true;
327           this.initialData = result;
328           this.saveTemplate();
329         }
330         else {
331           this.nService.info("Information", "There is no template saved in APPC for the selected action!");
332         }
333         this.ngProgress.done();
334       },
335         error => this.nService.error("Error", "Error in connecting to APPC Server"));
336       setTimeout(() => {
337         this.ngProgress.done();
338       }, 3500);
339     }
340   }
341   //========================== End of retrieveTemplateFromAppc() Method============================================
342   prepareAppData() {
343     let refObj = this.refObj;
344     if (refObj && refObj != undefined) {
345       let paramsKeyValueFromEditor: JSON;
346       try {
347         paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
348       }
349       catch (error) {
350         console.log("Could not parse name value pairs==" + error);
351       }
352       if (paramsKeyValueFromEditor) {
353         this.showTemplateVersionDiv = true;
354         let action = this.item.action;
355         var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
356         var fileName = '';
357         let id = this.mappingEditorService.identifier;
358         if (id) fileName = this.updateFileNameForConfigScaleOut(this.item.action, scopeName, this.templateVersionNo, id);
359         else fileName = this.updateParamFileName(this.item.action, scopeName, this.templateVersionNo);
360
361         let vnfType = this.vnfType;
362         let Json = [paramsKeyValueFromEditor];
363         let slashedPayload = this.appendSlashes(JSON.stringify(Json));
364         let data = this.utilityService.createPayLoadForSave(PARAM_DATA, this.vnfType, action, fileName, this.templateVersionNo, slashedPayload);
365         this.appDataObject.template.nameValueData = data;
366       }
367       if (this.configMappingEditorContent) {
368         let actualContent = this.configMappingEditorContent;
369         this.mappingEditorService.generateTemplate(this.templateEditor);
370         this.showTemplateVersionDiv = true;
371         let action = this.item.action;
372         let versionandFileType: any;
373         if (this.fileType === "text/xml") {
374
375           versionandFileType = this.templateVersionNo + 'V.xml'
376         } else {
377
378           versionandFileType = this.templateVersionNo + 'V.json'
379         }
380         let fileName: any;
381         if (this.tempretrieveFlag) {
382           fileName = this.fileNameForTempSave;
383         }
384         else {
385           fileName = this.artifactName;
386         }
387         let vnfType = this.vnfType;
388         let data = this.utilityService.createPayLoadForSave(TEMPLATE_DATA, this.vnfType, action, fileName, this.templateVersionNo, this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}'));
389         this.appDataObject.template.templateData = data;
390         this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
391       }
392     }
393   }
394   //========================== End of prepareAppData() Method============================================
395   prepareFileName(): any {
396     let fileNameObject: any = this.mappingEditorService.latestAction;
397     this.appDataObject = this.mappingEditorService.appDataObject;
398     this.downloadDataObject = this.mappingEditorService.downloadDataObject;
399     this.referenceData = fileNameObject;
400     return fileNameObject;
401   }
402   //========================== End of prepareFileName() Method============================================
403   onDownloadParameter() {
404     let refObj = this.refObj;
405     if (refObj) {
406       let paramsKeyValueFromEditor: JSON;
407       try {
408         paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
409       }
410       catch (error) {
411         console.log("Could not parse name value pairs==" + error);
412       }
413       let theJSON = JSON.stringify(paramsKeyValueFromEditor, null, "\t")
414       var blob = new Blob([theJSON], {
415         type: "text/json"
416       });
417       this.showTemplateVersionDiv = true;
418       let fileName: any;
419       var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
420       let id = this.mappingEditorService.identifier;
421       if (id) fileName = this.updateFileNameForConfigScaleOut(this.item.action, scopeName, this.templateVersionNo, id);
422       else fileName = this.updateParamFileName(this.item.action, scopeName, this.templateVersionNo);
423
424       this.downloadDataObject.template.nameValueData = theJSON;
425       this.downloadDataObject.template.nameValueFileName = fileName;
426     }
427     else {
428       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
429     }
430
431   }
432   //========================== End of onDownloadParameter() Method============================================
433   updateParamFileName(action: any, scopeName: any, versionNo: any) {
434     let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
435     this.downloadedParamFileName = fileName;
436     return fileName;
437   }
438   //========================== End of updateParamFileName() Method============================================
439   updateFileNameForConfigScaleOut(action: any, scopeName: any, versionNo: any, id: any) {
440     let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V_' + id + '.json';
441     this.downloadedParamFileName = fileName;
442     return fileName;
443   }
444   //========================== End of updateFileNameForConfigScaleOut() Method============================================
445   public onDownloadTemplate(artifact: string) {
446     let actualContent = this.configMappingEditorContent;
447     var textToSaveAsBlob: any;
448     var config_template_fileName: any
449     let refObj = this.refObj;
450     let versionandFileType: string;
451     if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
452       this.showTemplateVersionDiv = true;
453       if (this.fileType === "text/xml") {
454         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
455           type: "text/xml"
456         });
457         versionandFileType = this.templateVersionNo + 'V.xml'
458       }
459       if (this.fileType === "text/plain") {
460         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
461           type: "text/plain"
462         });
463         versionandFileType = this.templateVersionNo + 'V.txt'
464       }
465       if (this.fileType === "text/json") {
466         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
467           type: "text/json"
468         });
469         versionandFileType = this.templateVersionNo + 'V.json'
470       }
471       if (this.tempretrieveFlag) {
472         config_template_fileName = this.fileNameForTempSave;
473         var filextension = config_template_fileName.substring(config_template_fileName.indexOf("V") + 2, config_template_fileName.length);
474
475         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
476           type: "text/" + filextension
477         });
478       }
479       else {
480         config_template_fileName = this.artifactName;
481       }
482       this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
483       this.downloadDataObject.template.templateData = this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}');
484       this.downloadDataObject.template.templateFileName = config_template_fileName;
485     }
486
487   }
488   //========================== End of onDownloadTemplate() Method============================================
489   fileChange(input) {
490
491     let self = this;
492     let refObj = this.refObj;
493     this.enableValidateTemplate = true;
494
495     if (refObj && refObj != undefined) {
496       if (input.files && input.files[0]) {
497         this.spinner.show();
498         this.myfileName = input.files[0].name;
499         this.fileName = input.files[0].name;
500         this.fileType = input.files[0].type;
501         let reader = new FileReader();
502         this.readFile(input.files[0], reader, (result) => {
503           if (this.fileType === 'text/xml') {
504             sessionStorage.setItem('fileType', 'text/xml');
505           }
506           if (this.fileName.endsWith(".json")) {
507             this.fileType = "text/json";
508             sessionStorage.setItem('fileType', 'text/json');
509           }
510           if (this.fileType === '') {
511             sessionStorage.setItem('fileType', '');
512           }
513
514
515           if ('Generated Template' === this.selectedUploadType) {
516             this.configMappingEditorContent = result
517             this.artifactRequest.templateContent = this.configMappingEditorContent;
518             this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
519             if (this.artifactRequest.templateContent) {
520               this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
521             }
522           }
523           this.enableDownloadButtons = true;
524           this.initialData = result;
525           this.saveTemplate();
526           this.templateeditor.getEditor().$enableBlockSelect = false;
527           this.templateeditor.getEditor().$enableMultiselect = false;
528           setTimeout(() => {
529                         /** spinner ends after 3.5 seconds */
530                         this.spinner.hide();
531           }, 3500);
532         });
533       }
534       else {
535         this.nService.error("Error", "Failed to read file");
536       }
537       this.myInputVariable.nativeElement.value = "";
538     }
539     else {
540       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
541       return false;
542     }
543   }
544   //========================== End of fileChange() Method============================================
545   public readFile(file, reader, callback) {
546     // Set a callback funtion to fire after the file is fully loaded
547     reader.onload = () => {
548       // callback with the results
549       callback(reader.result);
550     }
551     this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
552     // Read the file
553     reader.readAsText(file, "UTF-8");
554   }
555   //========================== End of readFile() Method============================================
556   validateUploadedFile(fileExtension) {
557
558     if (fileExtension.toUpperCase() === 'json'.toUpperCase() || fileExtension.toUpperCase() === 'xml'.toUpperCase()) {
559       return true;
560     }
561     else {
562       return false;
563     }
564
565   }
566   //========================== End of validateUploadedFile() Method============================================
567   appendSlashes(artifactData) {
568     let x = artifactData.replace(new RegExp(',"', "g"), ',\"');
569     let y = x.replace(new RegExp('":', 'g'), '\":');
570     let z = y.replace(new RegExp('{"', 'g'), '{\"')
571     let t = z.replace(new RegExp(':"', 'g'), ':\"')
572     let m = t.replace(new RegExp('",', 'g'), '\",');
573     let n = y.replace(new RegExp('"}', 'g'), '\"}')
574     let nw = n.replace(new RegExp('{"', 'g'), '{\"');
575     let nw1 = nw.replace(new RegExp(':"', 'g'), ':\"');
576     let nw2 = nw1.replace(new RegExp('",', 'g'), '\",');
577     return nw2;
578   }
579   //========================== End of appendSlashes() Method============================================
580   prepareDownloadData() {
581     this.onDownloadParameter();
582     this.onDownloadTemplate('Template');
583   }
584   //========================== End of prepareDownloadData() Method============================================
585   syncTemplate() {
586     this.mappingEditorService.replaceNamesWithBlankValues();
587     this.saveTemplate();
588
589     var templateData = this.mappingEditorService.paramData; //template data array
590     var pdData = this.paramShareService.getSessionParamData(); //PD data array
591     var paramsContent = localStorage["paramsContent"];
592
593     if (paramsContent && paramsContent != undefined) {
594       try {
595         var paramTabData = JSON.parse(paramsContent);
596       }
597       catch (error) {
598         console.log("error is : " + error)
599       }
600     }
601     var resultArr = [];
602     var json = {};
603     var resultParamObj = {};
604     let checkNamesOnlyCondition: boolean = true;
605
606     if (templateData && templateData != undefined) {
607       templateData.forEach(function (item) {
608         if (item.paramValue !== "" && item.paramValue != undefined && item.paramValue != null) {
609           checkNamesOnlyCondition = false;
610         }
611
612       });
613
614       templateData.forEach(function (item) {
615         resultParamObj[item.paramName] = item.paramValue;
616       });
617       if (paramTabData && paramTabData != undefined) {
618         templateData.forEach(function (item) {
619           for (var index in paramTabData) {
620             if (item.paramName === index) {
621               if (checkNamesOnlyCondition) {
622                 resultParamObj[index] = paramTabData[index];
623               }
624               else {
625                 if (item.paramValue === "") {
626                   resultParamObj[index] = paramTabData[index];
627                 }
628                 else {
629                   resultParamObj[index] = item.paramValue;
630                 }
631               }
632             }
633
634           }
635
636         });
637
638       }
639       localStorage["paramsContent"] = JSON.stringify(resultParamObj);
640       templateData = Array.from(new Set(templateData.map((itemInArray) => itemInArray.paramName)))
641
642       //reformatting arr1 to match with PD
643       templateData.forEach(function (item) {
644
645         resultArr.push({
646           "name": item,
647           "type": null,
648           "description": null,
649           "required": null,
650           "default": null,
651           "source": "Manual",
652           "rule-type": null,
653           "request-keys": [{
654             "key-name": null,
655             "key-value": null
656           }, {
657             "key-name": null,
658             "key-value": null
659           }, {
660             "key-name": null,
661             "key-value": null
662           }],
663           "response-keys": [{
664             "key-name": null,
665             "key-value": null
666           }, {
667             "key-name": null,
668             "key-value": null
669           }, {
670             "key-name": null,
671             "key-value": null
672           }, {
673             "key-name": null,
674             "key-value": null
675           }, {
676             "key-name": null,
677             "key-value": null
678           }],
679           "ruleTypeValues": [null]
680
681         })
682       });
683     }
684     if (pdData && pdData != undefined) {
685       for (var i = 0; i < resultArr.length; i++) {
686
687         pdData.forEach(function (arr2item) {
688           if (resultArr[i].name === arr2item.name) {
689
690             var json = {
691               "name": arr2item.name,
692               "type": arr2item.type,
693               "description": arr2item.description,
694               "required": arr2item.required,
695               "default": arr2item.default,
696               "source": arr2item.source,
697               "rule-type": arr2item["rule-type"],
698               "request-keys": arr2item["request-keys"],
699               "response-keys": arr2item["response-keys"],
700               "ruleTypeValues": arr2item.ruleTypeValues
701             };
702             resultArr.splice(i, 1, json)
703           }
704
705         });
706
707       };
708
709     }
710     this.paramShareService.setSessionParamData(resultArr);
711     this.mappingEditorService.paramData = [];
712     //navigate to PD page after sync
713     this
714       .router
715       .navigate(['../../../vnfs/design/parameterDefinitions/create']);
716   }
717
718   //========================== End of syncTemplate() Method============================================
719   mergeParams() {
720     this.mergeStatus = this.mappingEditorService.autoAnnotateDataForParams();
721     if (this.mergeStatus) {
722       this.nService.success("Success", "Merge Successful");
723     }
724     else {
725       this.nService.error("Error", "Merge Unsuccessful");
726     }
727     this.saveTemplate();
728   }
729   //========================== End of mergeParams() Method============================================  
730   public handleAnnotation(modal) {
731
732     this.selectedWord = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
733     if (this.selectedWord && this.selectedWord != undefined) modal.open();
734   }
735   //========================== End of handleAnnotations() Method============================================ 
736   public submitNameValues() {
737     if (this.tempName) {
738       this.checkNameEntered = true;
739
740       if (this.selectedWord) {
741         if (this.selectedWord.startsWith('${(')) {
742           var replaceWord: any = this.replaceWord = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
743           this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
744
745         } else {
746           let mappingKey = this.mappingEditorService.getKeysForValues(this.selectedWord);
747           var replaceWord: any = this.replaceWord = '${(' + this.selectedWord + ')=(' + this.tempName + ')}';
748           this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
749
750         }
751       }
752       this.mappingEditorService.refreshEditor();
753       this.tempName = '';
754       this.modal.close();
755
756     }
757     else {
758       this.checkNameEntered = false;
759     }
760
761   }
762   //========================== End of submitNameValues() Method============================================
763 }