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