8514e24edc9d65cee959428100b2b343488c4ed8
[appc/cdt.git] /
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 ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 ============LICENSE_END============================================
22 */
23
24 import { Component, Input, OnInit, ViewChild } from '@angular/core';
25 //import { ModalComponent } from '../../modal/modal.component';
26 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
27 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
28 import { ArtifactRequest } from '../../../../shared/models/index';
29 import { ActivatedRoute, Router } from '@angular/router';
30 import { saveAs } from 'file-saver';
31 import { NotificationService } from '../../../../shared/services/notification.service';
32 import { NotificationsService } from 'angular2-notifications';
33 import { ParamShareService } from '../../../../shared/services/paramShare.service';
34 import { DialogService } from 'ng2-bootstrap-modal';
35 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
36 import { BuildDesignComponent } from '../../build-artifacts.component';
37 import { environment } from '../../../../../environments/environment';
38 import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
39 import { NgProgress } from 'ngx-progressbar';
40 declare var $: any
41
42 @Component({ selector: 'app-golden-configuration', templateUrl: './template-configuration.component.html', styleUrls: ['./template-configuration.component.css'] })
43 export class GoldenConfigurationComponent implements OnInit {
44   @ViewChild('templateeditor') templateeditor;
45   @Input() configMappingEditorContent: string;
46   @Input() isMappingComp: boolean;
47   @ViewChild('myInput') myInputVariable: any;
48   // @ViewChild(ModalComponent) modalComponent: ModalComponent;
49   @ViewChild('myModal') modal: ModalComponent;
50   aceText: string = ""
51   fileName: string = ""
52   showTemplateVersionDiv: any;
53   downloadedTemplateFileName: any;
54   downloadedParamFileName: any;
55   templateVersionNo: any = '0.0.1';
56   saveToGuiCacheFlag = 'false';
57   initialAction: any;
58   public referenceData: Array<Object> = [];
59   public scopeName: any;
60   public subscription: any;
61   public item: any = {};
62   public goldenActions: Array<string> = [];
63   public refNameObj = {};
64   public action = '';
65   public artifactName = '';
66   public type;
67   public showError: boolean = false;
68   public tempretrieveFlag: boolean = false;
69   public fileNameForTempSave;
70   initialData: any;
71   showDownloadDiv: boolean = false;
72   downloadType: any;
73   enableBrowse: boolean = true;
74   enableMerge: boolean = false;
75   uploadValidationSuccess: boolean = false;
76   fileExtension: any = "xml";
77   apiToken = localStorage['apiToken'];
78   public appDataObject: any;
79   public downloadDataObject: any;
80   public checkNameEntered: boolean = true;
81   public selectedWord: any = this.mappingEditorService.getSelectedWord();
82   public Actions = [
83     { action: "ConfigBackup", value: "ConfigBackup" },
84     { action: "ConfigModify", value: "ConfigModify" },
85     { action: "ConfigRestore", value: "ConfigRestore" },
86     { action: "Configure", value: "Configure" },
87     { action: "GetRunningConfig", value: "GetRunningConfig" },
88     { action: "HealthCheck", value: "HealthCheck" },
89     { action: "StartApplication", value: "StartApplication" },
90     { action: "StopApplication", value: "StopApplication" }
91   ];
92   options = {
93     timeOut: 1000,
94     showProgressBar: true,
95     pauseOnHover: true,
96     clickToClose: true,
97     maxLength: 200
98   }
99   public enableDownloadButtons: boolean = false;
100   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) {
101     this.artifactRequest.action = '';
102     this.artifactRequest.version = '';
103     this.artifactRequest.paramsContent = '{}';
104     this.artifactRequest.paramKeysContent = '';
105   }
106   public templateEditor: any;
107   public fileType: any = '';
108   public actionType: any;
109   public myfileName: any;
110   userId = localStorage['userId'];
111   public artifactRequest: ArtifactRequest = new ArtifactRequest();
112   public showUploadStatus: boolean = false;
113   public uploadStatus: boolean = false;
114   public uploadTypes = [
115     {
116       value: 'Generated Template',
117       display: 'Sample Json Param File'
118     },
119     {
120       value: 'Mapping Data',
121       display: 'Sample Json Param File'
122     }
123   ];
124   vnfType: any = '';
125   vnfcType: any = '';
126   protocol: any = '';
127   refObj: any;
128   editor: any;
129   editorContent: any;
130   tempName: any;
131   enableValidateTemplate: boolean = false;;
132   public selectedUploadType: string = this.uploadTypes[0].value;
133   identifier: any;
134   //this.mappingeditorservice.referenceNameObjects = object;PLEASE USE THIS OBJECT TO GET TEMPALLDATA
135   //====================================================
136   ngOnInit() {
137     var refObj = this.refObj = this.prepareFileName();
138     // console.log("Ref object:  " + JSON.stringify(refObj))
139     if (refObj && refObj != undefined) {
140       // refObj = refObj[refObj.length - 1];
141       this.item = refObj;
142
143       this.vnfType = this.item.scope["vnf-type"];
144       this.vnfcType = this.item.scope["vnfc-type"];
145       this.protocol = this.item['device-protocol'];
146       this.action = this.item.action;
147       this.artifactRequest.action = this.item.action;
148       this.artifactRequest.vnfType = this.vnfType;
149       if (this.vnfcType != undefined && this.vnfcType.length != 0) {
150         this.scopeName = this.vnfcType;
151       }
152       else {
153         this.scopeName = this.vnfType;
154       }
155     }
156     else {
157       this.item = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
158     }
159     this.initialAction = this.item.action;
160     this.activeRoutes.url.subscribe(UrlSegment => {
161       this.actionType = UrlSegment[0].path
162     })
163     /*if (this.actionType === 'createTemplate') {
164       this.mappingEditorService.fromScreen = 'TemplateScreen';
165     }
166     if (this.actionType === 'updateTemplate') {*/
167     this.mappingEditorService.fromScreen = 'MappingScreen';
168     // }
169     this.identifier = this.mappingEditorService.identifier;
170   }
171   //========================== End of ngOnInit() Method============================================
172   ngOnDestroy() {
173     //console.log("Reference object =="+ JSON.stringify(this.refObj));
174     if (this.refObj && this.refObj != undefined) {
175       if (this.configMappingEditorContent && this.configMappingEditorContent != undefined) {
176         this.saveTemplate();
177         this.prepareAppData();
178         this.prepareDownloadData();
179         this.mappingEditorService.changeNavAppData(this.appDataObject);
180         this.mappingEditorService.changeNavDownloadData(this.downloadDataObject);
181       }
182     }
183   }
184   //========================== End of ngOnDestroy() Method============================================
185   ngAfterViewInit() {
186     if (this.mappingEditorService.latestAction) {
187       this.refNameObj = this.mappingEditorService.latestAction;
188       if (this.vnfcType !== 'null') {
189         this.type = this.vnfcType;
190       }
191       else {
192         this.type = this.vnfType;
193       }
194       for (let i = 0; i < this.refNameObj['artifact-list'].length; i++) {
195         let artifactList = this.refNameObj['artifact-list'];
196         if (artifactList[i]['artifact-type'] === 'config_template') {
197           this.artifactName = artifactList[i]['artifact-name'];
198         }
199       }
200     }
201     let self = this;
202     this.templateEditor = self.templateeditor.getEditor();
203     /* this.templateeditor.getEditor().commands.addCommand({
204        name: 'annotateCommand',
205        bindKey: { win: 'Ctrl-4', mac: 'Command-4' },
206        exec: function (editor) {
207          self.mappingEditorService.checkMethodCall(this.modal);
208        }
209      });*/
210     this.templateeditor.getEditor().commands.addCommand({
211       name: 'annotateCommand',
212       bindKey: { win: 'ENTER', mac: 'ENTER' },
213       exec: (editor: any) => {
214         this.handleAnnotation(this.modal);
215       }
216     });
217     if (this.mappingEditorService.fromScreen === 'MappingScreen') {
218       this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
219       this.fileType = sessionStorage.getItem('fileType');
220     }
221     /*  else if (this.mappingEditorService.fromScreen === 'TemplateScreen') {
222         this.configMappingEditorContent = this.mappingEditorService.getTemplateDataFromStore();
223         this.fileType = sessionStorage.getItem('fileType');
224       }*/
225     if (this.configMappingEditorContent) {
226       this.artifactRequest.templateContent = this.configMappingEditorContent;
227       this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
228     }
229     if (this.refObj) {
230       if (this.mappingEditorService.getTemplateMappingDataFromStore() && this.mappingEditorService.getTemplateMappingDataFromStore() != undefined) {
231         this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
232       }
233       else {
234         if (this.artifactName) this.retrieveTemplateFromAppc();
235       }
236     }
237     else {
238       this.Actions = [];
239       this.enableBrowse = false;
240       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
241     }
242   }
243
244   //========================== End of ngAfterViewInit() Method============================================
245   browseOption() {
246     $("#inputFile").trigger('click');
247   }
248   //========================== End of browseOption() Method============================================
249   /* openFile(event) {
250      let input = event.target;
251      this.fileName = event.currentTarget.value.replace(/C:\\fakepath\\/i, '');
252      for (let index = 0; index < input.files.length; index++) {
253        let reader = new FileReader();
254        reader.onload = () => {
255          this.configMappingEditorContent = reader.result;
256        }
257        reader.readAsText(input.files[index]);
258      };
259    }
260    //========================== End of openFile() Method============================================*/
261   //save to GUI
262   public saveTemplate() {
263     this.saveToGuiCacheFlag = 'true';
264     this.mappingEditorService.paramData = [];
265     if (this.configMappingEditorContent) {
266       this.initialData = this.configMappingEditorContent;
267       this.mappingEditorService.refreshEditor();
268       let paramArr: any = []
269       if (this.mappingEditorService.paramData && this.mappingEditorService.paramData != undefined) {
270         if (this.mappingEditorService.paramData.length === 0 && this.mappingEditorService.hasErrorCode === true) {
271           this.nService.error("Error", 'Special characters error', 'Error')
272           return;
273         }
274         else {
275           this.showError = false;
276         }
277       }
278       this.showTemplateVersionDiv = true;
279
280       if (this.mappingEditorService.fromScreen === 'MappingScreen') {
281         this.mappingEditorService.setTemplateMappingDataFromStore(this.configMappingEditorContent);
282       }
283       if (this.fileType === 'text/xml') {
284         sessionStorage.setItem('fileType', 'text/xml');
285       }
286       if (this.fileType === '') {
287         sessionStorage.setItem('fileType', '');
288       }
289       // paramArr = this.mappingEditorService.paramData;
290       // this.paramShareService.setTemplateData(paramArr)
291     }
292   }
293   //========================== End of saveTemplate() Method============================================
294   /* clearHighlight() {
295      this.mappingEditorService.removeTheSelectedMarkers();
296    }
297    //========================== End of clearHighlight() Method============================================*/
298   /*validateTemplate() {
299     var fileExtensionArr = this.fileType.split("/");
300     let data = {
301       "input": {
302         "design-request": {
303           "request-id": this.apiToken,
304           "action": "validateTemplate",
305           "data-type": fileExtensionArr[1].toUpperCase(),
306           "payload": this.configMappingEditorContent
307         }
308       }
309     };
310     let url = environment.validateTemplate;
311     this
312       .httpUtil
313       .post(
314       { url: url, data: data })
315       .subscribe(resp => {
316         if (resp.output.status.code === '400' && resp.output.status.message === "success") {
317           this.uploadValidationSuccess = true;
318           this.nService.success("Success", "Template Validated succesfully");
319           return true;
320         }
321         else if (resp.output.status.code === '401') {
322           this.nService.error("Error", resp.output.status.message);
323           return false;
324         }
325       },
326       error => this.nService.error("Error", "Unable to validate the uploaded template. Error in connecting APPC Server"));
327   }
328   //========================== End of validateTemplate() Method============================================*/
329   retrieveTemplateFromAppc() {
330     let refObj = this.refObj;
331     if (refObj && refObj != undefined) {
332
333       let fileName = this.artifactName;
334       let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
335       let input = {
336         "input": {
337           "design-request": {
338             "request-id": this.apiToken,
339             "action": "getArtifact",
340             "payload": payload
341           }
342         }
343       };
344       // console.log("Retrieve artifact payload=="+ payload);
345       let artifactContent: any;
346       this.ngProgress.start();
347       this.httpUtil.post({
348         url: environment.getDesigns,
349         data: input
350       }).subscribe(resp => {
351         if (resp.output.status.code === '400' && resp.output.status.message === "success") {
352           this.nService.success("Success", "Template retrieved successfully from APPC");
353           let result = JSON.parse(resp.output.data.block).artifactInfo[0];
354           result = result['artifact-content'];
355           if ('Generated Template' === this.selectedUploadType) {
356             this.configMappingEditorContent = result
357             this.artifactRequest.templateContent = this.configMappingEditorContent;
358             this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
359             if (this.artifactRequest.templateContent) {
360               this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
361             }
362           }
363           this.tempretrieveFlag = true;
364           this.fileNameForTempSave = fileName;
365           this.enableDownloadButtons = true;
366           this.initialData = result;
367           this.saveTemplate();
368         }
369         else {
370           this.nService.info("Information", "There is no template saved in APPC for the selected action!");
371         }
372         this.ngProgress.done();
373       },
374         /*  (error) => {
375             //  this.showUploadErrorStatus = true;
376             // this.nService.error('Status','Error Connecting to the APPC Network')
377             //this.notificationService.notifyErrorMessage('Configuration Template file successfully uploaded..')
378             //this.uploadStatusError = true;
379             //window.scrollTo(0, 0)
380             // this. nService.error('Status','Error Connecting to the APPC Network')
381             this.openModel(true, "Could not retrieve latest template for given action""Error in connecting to APPC database")
382           });*/
383         error => this.nService.error("Error", "Error in connecting to APPC Server"));
384       setTimeout(() => {
385         this.ngProgress.done();
386       }, 3500);
387     }
388   }
389   //========================== End of retrieveTemplateFromAppc() Method============================================
390   prepareAppData() {
391     let refObj = this.refObj;
392     //console.log("Reference object =="+ JSON.stringify(refObj));
393     if (refObj && refObj != undefined) {
394       // refObj = refObj[refObj.length - 1];
395       let paramsKeyValueFromEditor: JSON;
396       /*  if (this.fileExtension.toUpperCase() === "XML")
397           paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
398         else*/
399       // paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
400       try {
401         paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
402       }
403       catch (error) {
404         console.log("Could not parse name value pairs==" + error);
405       }
406       if (paramsKeyValueFromEditor) {
407         this.showTemplateVersionDiv = true;
408         let action = this.item.action;
409         var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
410         let fileName = this.updateParamFileName(refObj.action, scopeName, this.templateVersionNo);
411         let vnfType = this.vnfType;
412         let Json = [paramsKeyValueFromEditor];
413         let slashedPayload = this.appendSlashes(JSON.stringify(Json));
414         let newPayload =
415           {
416             "userID": this.userId,
417             "vnf-type": this.vnfType,
418             "action": action,
419             "artifact-name": fileName,
420             "artifact-type": "APPC-CONFIG",
421             "artifact-version": this.templateVersionNo,
422             "artifact-contents": slashedPayload
423           }
424         let data =
425           {
426             "input": {
427               "design-request": {
428                 "request-id": this.apiToken,
429                 "action": "uploadArtifact",
430                 "payload": JSON.stringify(newPayload)
431
432               }
433             }
434           }
435         this.appDataObject.template.nameValueData = data;
436       }
437       if (this.configMappingEditorContent) {
438         let actualContent = this.configMappingEditorContent;
439         this.mappingEditorService.generateTemplate(this.templateEditor);
440         this.showTemplateVersionDiv = true;
441         let action = this.item.action;
442         let versionandFileType: any;
443         if (this.fileType === "text/xml") {
444
445           versionandFileType = this.templateVersionNo + 'V.xml'
446         } else {
447
448           versionandFileType = this.templateVersionNo + 'V.json'
449         }
450         let fileName: any;
451         if (this.tempretrieveFlag) {
452           fileName = this.fileNameForTempSave;
453         }
454         else {
455           // fileName = this.updateDownloadTemplateFileName(refObj.action, this.scopeName, versionandFileType);
456           fileName = this.artifactName;
457         }
458         let vnfType = this.vnfType;
459         let newPayload =
460           {
461             "userID": this.userId,
462             "vnf-type": this.vnfType,
463             "action": action,
464             "artifact-name": fileName,
465             "artifact-type": "APPC-CONFIG",
466             "artifact-version": this.templateVersionNo,
467             //"artifact-contents": this.configMappingEditorContent
468             "artifact-contents": this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
469
470           }
471         let data =
472           {
473             "input": {
474               "design-request": {
475                 "request-id": this.apiToken,
476                 "action": "uploadArtifact",
477                 "payload": JSON.stringify(newPayload)
478
479               }
480             }
481           }
482         this.appDataObject.template.templateData = data;
483         this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
484       }
485     }
486   }
487   //========================== End of prepareAppData() Method============================================
488   /*retrieveNameValueFromAppc() {
489     let refObj: any = this.prepareFileName();
490     if (refObj && refObj != undefined) {
491       let fileName = this.updateParamFileName(this.item.action, this.scopeName, this.templateVersionNo);
492       let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
493       let input = {
494         "input": {
495           "design-request": {
496             "request-id": this.apiToken,
497             "action": "getArtifact",
498             "payload": payload
499           }
500         }
501       };
502       
503       let artifactContent: any;
504       this.httpUtil.post({
505         //    url:"https://mtanjv9apdb51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
506         url: environment.getDesigns,
507         data: input
508       }).subscribe(resp => {
509         if (resp.output.status.code === '400' && resp.output.status.message === "success") {
510           this.openModel(true, 'Name/value pairs retrieved successfully from APPC', 'Success');
511           let result = JSON.parse(resp.output.data.block).artifactInfo[0];
512           result = JSON.parse(result['artifact-content']);
513           var jsonString = JSON.stringify(result[0]);
514           var string = jsonString.substring(1, jsonString.length - 1);
515           var stringArr = string.split(",");
516           var newStringArr = [];
517           var resultStr = "{\r\n"
518           for (var index in stringArr) {
519             newStringArr[index] = stringArr[index] + ",\r\n";
520           }
521           for (var index in newStringArr) {
522             resultStr = resultStr + newStringArr[index];
523           }
524           resultStr = resultStr.substring(0, resultStr.length - 3) + "\r\n}"
525           this.configMappingEditorContent = resultStr;
526
527         }
528       },
529         error => this.openModel(true, "Could not retrieve the name value pairs. Error in connecting to APPC Server", "ERROR"));
530     }
531   }*/
532   //========================== End of retrieveNameValueFromAppc() Method============================================
533   prepareFileName(): any {
534     let fileNameObject: any = this.mappingEditorService.latestAction;
535     this.appDataObject = this.mappingEditorService.appDataObject;
536     this.downloadDataObject = this.mappingEditorService.downloadDataObject;
537     this.referenceData = fileNameObject;
538     return fileNameObject;
539   }
540   //========================== End of prepareFileName() Method============================================
541   onDownloadParameter() {
542     let refObj = this.refObj;
543     if (refObj) {
544       // refObj = refObj[refObj.length - 1];
545       let paramsKeyValueFromEditor: JSON;
546       if (this.fileExtension.toUpperCase() === "XML")
547         paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
548       else
549         paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
550
551       try {
552         paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
553       }
554       catch (error) {
555         console.log("Could not parse name value pairs==" + error);
556       }
557       let theJSON = JSON.stringify(paramsKeyValueFromEditor, null, "\t")
558       var blob = new Blob([theJSON], {
559         type: "text/json"
560       });
561       this.showTemplateVersionDiv = true;
562       let fileName: any;
563       var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
564       fileName = this.updateParamFileName(refObj.action, scopeName, this.templateVersionNo);
565       this.downloadDataObject.template.nameValueData = theJSON;
566       this.downloadDataObject.template.nameValueFileName = fileName;
567     }
568     else {
569       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
570     }
571
572   }
573   //========================== End of onDownloadParameter() Method============================================
574   /* JSONToCSVConvertor(JSONData, fileName, ShowLabel) {
575      //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
576      var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
577      var CSV = '';
578      //This condition will generate the Label/Header
579      if (ShowLabel) {
580        var testRow = "";
581        for (var index in arrData[0]) {
582          CSV += index + '\t' + arrData[0][index] + '\r\n';
583        }
584      }
585      if (CSV == '') {
586        return;
587      }
588      //Initialize file format you want csv or xls
589      var uri = 'data:application/vnd.ms-excel,' + encodeURI(CSV);
590      var link = document.createElement("a");
591      link.href = uri;
592      link.download = fileName + ".xls";
593      //this part will append the anchor tag and remove it after automatic click
594      document.body.appendChild(link);
595      link.click();
596      document.body.removeChild(link);
597    }
598    //========================== End of JSONToCSVConvertor() Method============================================
599    updateParamFileNameForXls(action: any, scopeName: any, versionNo: any) {
600      let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V';
601      this.downloadedParamFileName = fileName;
602      return fileName;
603    }
604    //========================== End of updateParamFileNameForXls() Method============================================*/
605   updateParamFileName(action: any, scopeName: any, versionNo: any) {
606     let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
607     this.downloadedParamFileName = fileName;
608     return fileName;
609   }
610   //========================== End of updateParamFileName() Method============================================
611   public onDownloadTemplate(artifact: string) {
612     let actualContent = this.configMappingEditorContent;
613     var textToSaveAsBlob: any;
614     var config_template_fileName: any
615     let refObj = this.refObj;
616     let versionandFileType: string;
617     this.mappingEditorService.generateTemplate(this.templateEditor);
618     if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
619       //  refObj = refObj[refObj.length - 1];
620       this.showTemplateVersionDiv = true;
621       if (this.fileType === "text/xml") {
622         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
623           type: "text/xml"
624         });
625         versionandFileType = this.templateVersionNo + 'V.xml'
626       }
627       if (this.fileType === "text/plain") {
628         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
629           type: "text/plain"
630         });
631         versionandFileType = this.templateVersionNo + 'V.txt'
632       }
633       if (this.fileType === "text/json") {
634         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
635           type: "text/json"
636         });
637         versionandFileType = this.templateVersionNo + 'V.json'
638       }
639       if (this.tempretrieveFlag) {
640         config_template_fileName = this.fileNameForTempSave;
641         var filextension = config_template_fileName.substring(config_template_fileName.indexOf("V") + 2, config_template_fileName.length);
642
643         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
644           type: "text/" + filextension
645         });
646       }
647       else {
648         // config_template_fileName = this.updateDownloadTemplateFileName(refObj.action, this.scopeName, versionandFileType);
649         config_template_fileName = this.artifactName;
650       }
651       // saveAs(textToSaveAsBlob, config_template_fileName);
652       this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
653       //this.downloadDataObject.template.templateData = this.configMappingEditorContent;
654       this.downloadDataObject.template.templateData = this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}');
655       this.downloadDataObject.template.templateFileName = config_template_fileName;
656     }
657
658   }
659   //========================== End of onDownloadTemplate() Method============================================
660   updateDownloadTemplateFileName(action: any, scopeName: any, versionandFileType: any) {
661     let fileName = 'template_' + action + '_' + scopeName + '_' + versionandFileType;
662     this.downloadedTemplateFileName = fileName;
663     return fileName;
664   }
665   //========================== End of updateDownloadTemplateFileName() Method============================================
666   /* openModel(toShow: any, message: any, title: any) {
667      //this.modalComponent.isShow = toShow;
668      //this.modalComponent.message = message;
669      //this.modalComponent.title = title;
670    }
671    //========================== End of openModel() Method============================================*/
672   fileChange(input) {
673
674     let self = this;
675     let refObj = this.refObj;
676     this.enableValidateTemplate = true;
677
678     if (refObj && refObj != undefined) {
679       // refObj = refObj[refObj.length - 1];
680       if (input.files && input.files[0]) {
681         console.log("input files0" + JSON.stringify(input.files[0]))
682         this.myfileName = input.files[0].name;
683         this.fileName = input.files[0].name;
684         this.fileType = input.files[0].type;
685         // var fileExtension = this.myfileName.substr(this.myfileName.lastIndexOf('.') + 1);
686
687         let reader = new FileReader();
688         // if(this.validateUploadedFile(fileExtension))
689         //{
690         this.readFile(input.files[0], reader, (result) => {
691           if (this.fileType === 'text/xml') {
692             sessionStorage.setItem('fileType', 'text/xml');
693           }
694           if (this.fileName.endsWith(".json")) {
695             this.fileType = "text/json";
696             sessionStorage.setItem('fileType', 'text/json');
697           }
698           if (this.fileType === '') {
699             sessionStorage.setItem('fileType', '');
700           }
701
702
703           if ('Generated Template' === this.selectedUploadType) {
704             this.configMappingEditorContent = result
705             this.artifactRequest.templateContent = this.configMappingEditorContent;
706             console.log("editor content==" + JSON.stringify(this.configMappingEditorContent))
707             this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
708             if (this.artifactRequest.templateContent) {
709               this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
710             }
711           }
712           this.enableDownloadButtons = true;
713           this.initialData = result;
714           this.saveTemplate();
715
716         });
717         //  }
718         // else{
719         // this.nService.error("Error", "Incorrect File Format")
720         //this.configMappingEditorContent=''
721         //}
722       }
723       else {
724         this.nService.error("Error", "Failed to read file");
725       }
726       this.myInputVariable.nativeElement.value = "";
727     }
728     else {
729       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
730       return false;
731     }
732   }
733   //========================== End of fileChange() Method============================================
734   public readFile(file, reader, callback) {
735     // Set a callback funtion to fire after the file is fully loaded
736     reader.onload = () => {
737       // callback with the results
738       callback(reader.result);
739     }
740     this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
741     // Read the file
742     reader.readAsText(file, "UTF-8");
743   }
744   //========================== End of readFile() Method============================================
745   validateUploadedFile(fileExtension) {
746
747     if (fileExtension.toUpperCase() === 'json'.toUpperCase() || fileExtension.toUpperCase() === 'xml'.toUpperCase()) {
748       return true;
749     }
750     else {
751       return false;
752     }
753
754   }
755   //========================== End of validateUploadedFile() Method============================================
756   appendSlashes(artifactData) {
757     let x = artifactData.replace(new RegExp(',"', "g"), ',\"');
758     let y = x.replace(new RegExp('":', 'g'), '\":');
759     let z = y.replace(new RegExp('{"', 'g'), '{\"')
760     let t = z.replace(new RegExp(':"', 'g'), ':\"')
761     let m = t.replace(new RegExp('",', 'g'), '\",');
762     let n = y.replace(new RegExp('"}', 'g'), '\"}')
763     let nw = n.replace(new RegExp('{"', 'g'), '{\"');
764     let nw1 = nw.replace(new RegExp(':"', 'g'), ':\"');
765     let nw2 = nw1.replace(new RegExp('",', 'g'), '\",');
766     return nw2;
767   }
768   //========================== End of appendSlashes() Method============================================
769   prepareDownloadData() {
770     this.onDownloadParameter();
771     this.onDownloadTemplate('Template');
772   }
773   //========================== End of prepareDownloadData() Method============================================
774   syncTemplate() {
775     this.mappingEditorService.replaceNamesWithBlankValues();
776     this.saveTemplate();
777
778     var templateData = this.mappingEditorService.paramData; //template data array
779     // this.paramShareService.setTemplateData(templateData);
780
781     //console.log("Template Name value pairs ===" + JSON.stringify(templateData))
782     var pdData = this.paramShareService.getSessionParamData(); //PD data array
783     console.log("PD name value pairs===" + JSON.stringify(pdData))
784
785
786     var paramsContent = localStorage["paramsContent"];
787     console.log("Param content before==" + paramsContent);
788
789     if (paramsContent && paramsContent != undefined) {
790       try {
791         var paramTabData = JSON.parse(paramsContent);
792         //console.log("Param content after==" + paramsContent);
793         //console.log("Param tab data after==" + JSON.stringify(paramTabData))
794       }
795       catch (error) {
796         console.log("error is : " + error)
797       }
798     }
799     var resultArr = [];
800     var json = {};
801     var resultParamObj = {};
802     let checkNamesOnlyCondition: boolean = true;
803
804     if (templateData && templateData != undefined) {
805       templateData.forEach(function (item) {
806         if (item.paramValue !== "" && item.paramValue != undefined && item.paramValue != null) {
807           checkNamesOnlyCondition = false;
808         }
809
810       });
811
812       templateData.forEach(function (item) {
813         resultParamObj[item.paramName] = item.paramValue;
814       });
815       // console.log("pARAM Result array before is " + JSON.stringify(resultParamObj))
816       if (paramTabData && paramTabData != undefined) {
817         templateData.forEach(function (item) {
818           for (var index in paramTabData) {
819             if (item.paramName === index) {
820               if (checkNamesOnlyCondition) {
821                 resultParamObj[index] = paramTabData[index];
822               }
823               else {
824                 if (item.paramValue === "") {
825                   resultParamObj[index] = paramTabData[index];
826                 }
827                 else {
828                   resultParamObj[index] = item.paramValue;
829                 }
830               }
831             }
832
833           }
834
835         });
836
837       }
838       localStorage["paramsContent"] = JSON.stringify(resultParamObj);
839       //console.log("param content after==" +JSON.stringify(resultParamObj));
840
841       //removing duplicate elements from the array
842       templateData = Array.from(new Set(templateData.map((itemInArray) => itemInArray.paramName)))
843
844       //reformatting arr1 to match with PD
845       templateData.forEach(function (item) {
846
847         resultArr.push({
848           "name": item,
849           "type": null,
850           "description": null,
851           "required": null,
852           "default": null,
853           "source": "Manual",
854           "rule-type": null,
855           "request-keys": [{
856             "key-name": null,
857             "key-value": null
858           }, {
859             "key-name": null,
860             "key-value": null
861           }, {
862             "key-name": null,
863             "key-value": null
864           }],
865           "response-keys": [{
866             "key-name": null,
867             "key-value": null
868           }, {
869             "key-name": null,
870             "key-value": null
871           }, {
872             "key-name": null,
873             "key-value": null
874           }, {
875             "key-name": null,
876             "key-value": null
877           }, {
878             "key-name": null,
879             "key-value": null
880           }],
881           "ruleTypeValues": [null]
882
883         })
884       });
885     }
886     //console.log("Result array before is " + JSON.stringify(resultArr))
887     // console.log("Length before is:  " + resultArr.length)
888
889     if (pdData && pdData != undefined) {
890       for (var i = 0; i < resultArr.length; i++) {
891
892         pdData.forEach(function (arr2item) {
893           if (resultArr[i].name === arr2item.name) {
894
895             var json = {
896               "name": arr2item.name,
897               "type": arr2item.type,
898               "description": arr2item.description,
899               "required": arr2item.required,
900               "default": arr2item.default,
901               "source": arr2item.source,
902               "rule-type": arr2item["rule-type"],
903               "request-keys": arr2item["request-keys"],
904               "response-keys": arr2item["response-keys"],
905               "ruleTypeValues": arr2item.ruleTypeValues
906             };
907             resultArr.splice(i, 1, json)
908             //  console.log("Result array index ==" + JSON.stringify(resultArr[i]))
909           }
910
911         });
912
913       };
914
915     }
916     this.paramShareService.setSessionParamData(resultArr);
917     //console.log("Result array after is " + JSON.stringify(resultArr))
918     //console.log("Length after is:  " + resultArr.length)
919     this.mappingEditorService.paramData = [];
920     //navigate to PD page after sync
921     this
922       .router
923       .navigate(['../../../vnfs/design/parameterDefinitions/create']);
924   }
925
926   //========================== End of syncTemplate() Method============================================
927   mergeParams() {
928     var mergeStatus: boolean = this.mappingEditorService.autoAnnotateDataForParams(this.fileType);
929     if (mergeStatus) {
930       this.nService.success("Success", "Merge Successful");
931     }
932     else {
933       this.nService.error("Error", "Merge Unsuccessful");
934     }
935     this.saveTemplate();
936   }
937   //========================== End of mergeParams() Method============================================  
938   public handleAnnotation(modal) {
939
940     let selectedWord: string = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
941     this.selectedWord = selectedWord;
942     modal.open();
943   }
944   //========================== End of handleAnnotations() Method============================================ 
945   public submitNameValues() {
946     /*var editor = this.templateeditor.getEditor()
947     this.editor = editor;
948     this.editor.session = editor.session;
949     this.editor.selection.session.$backMarkers = {};
950     this.editorContent = this.artifactRequest.templateContent;
951     this.editor.$blockScrolling = Infinity;
952     this.editor.$blockSelectEnabled = false;*/
953     if (this.tempName) {
954       this.checkNameEntered = true;
955
956       if (this.selectedWord) {
957         if (this.selectedWord.startsWith('${(')) {
958           var replaceWord: any = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
959           this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
960         } else {
961           let mappingKey = this.mappingEditorService.getKeysForValues(this.selectedWord);
962           var replaceWord: any = '${(' + this.selectedWord + ')=(' + this.tempName + ')}';
963           this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
964         }
965       }
966       this.mappingEditorService.refreshEditor();
967       this.tempName = '';
968       this.modal.close();
969
970     }
971     else {
972       this.checkNameEntered = false;
973     }
974
975   }
976   //========================== End of submitNameValues() Method============================================
977 }