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