f3f6a944f2815645f65b86f3c7b8769085f3eb6a
[appc/cdt.git] / src / app / test / test.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
5 ===================================================================
6 Copyright (C) 2018 IBM.
7 ===================================================================
8 Unless otherwise specified, all software contained herein is licensed
9 under the Apache License, Version 2.0 (the License);
10 you may not use this software except in compliance with the License.
11 You may obtain a copy of the License at
12
13     http://www.apache.org/licenses/LICENSE-2.0
14
15 Unless required by applicable law or agreed to in writing, software
16 distributed under the License is distributed on an "AS IS" BASIS,
17 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 See the License for the specific language governing permissions and
19 limitations under the License.
20 ============LICENSE_END============================================
21 */
22
23 import { Component, OnInit } from '@angular/core';
24 import { NgxSpinnerService } from 'ngx-spinner';
25 import { saveAs } from 'file-saver';
26 import { Location } from '@angular/common';
27 import { ActivatedRoute, Router } from '@angular/router';
28 import { ParamShareService } from '.././shared/services/paramShare.service';
29 import { MappingEditorService } from '.././shared/services/mapping-editor.service';
30 import { NotificationsService } from 'angular2-notifications';
31 import { HttpUtilService } from '.././shared/services/httpUtil/http-util.service';
32 import 'rxjs/add/observable/interval';
33 import { Observable } from 'rxjs/Observable';
34 import { environment } from '../.././environments/environment';
35 import { UtilityService } from '.././shared/services/utilityService/utility.service';
36 import 'rxjs/add/operator/map';
37 import * as XLSX from 'xlsx';
38 import { NgProgress } from 'ngx-progressbar';
39
40
41 let YAML = require('yamljs');
42
43 type AOA = Array<Array<any>>;
44 declare var $: any;
45
46 @Component({ selector: 'test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] })
47 export class TestComponent implements OnInit {
48     public displayParamObjects;
49     options = {
50         timeOut: 1000,
51         showProgressBar: true,
52         pauseOnHover: true,
53         clickToClose: true,
54         maxLength: 200
55     };
56     public action: any;
57     public vnfId: any;
58     public item: any = {};
59
60     public vnfType: any;
61     vnfcType: any;
62     protocol: any;
63     mode: any = 'NORMAL';
64     force: any = 'True';
65     ttl: any;
66     public formattedNameValuePairs = {};
67     public requestId = '';
68     public enableBrowse: boolean = true;
69     public enableSpinner: boolean = false;
70     host: any;
71     public refNameObj = {};
72
73     public artifactName;
74     public type;
75     public transactions = '';
76     public uploadFileName;
77
78     public payload = {};
79     public lastvmJson = {};
80     public vmPayload = [];
81     public subPayload = {};
82     public vmJson = {};
83     public vnfcJson = {};
84     public flag = 1;
85     public oldListName1 = '';
86     public actionIdentifiers = {};
87     public apiRequest = '';
88     public apiResponse = '';
89     public statusResponse;
90     public outputTimeStamp;
91     public status;
92     public statusReason;
93     public errorResponse; 
94     public timer;
95     public subscribe;
96     public enableTestButton: boolean = false;
97     public enableAbort: boolean = false;
98     public showStatusResponseDiv: boolean = false;
99     public enablePollButton: boolean = true;
100     public pollCounter = 0;
101     public enableCounterDiv: boolean = false;
102     public enableDownload: boolean = false;
103     private userId = localStorage['userId'];
104     constructor (
105     private location: Location, 
106     private activeRoutes: ActivatedRoute,
107     private nService: NotificationsService, 
108     private router: Router, 
109     private paramShareService: ParamShareService, 
110     private mappingEditorService: MappingEditorService, 
111     private httpUtil: HttpUtilService,
112     private utiltiy: UtilityService, 
113     private ngProgress: NgProgress,
114     private spinner: NgxSpinnerService
115     ) {
116
117     }
118
119     ngOnInit() {
120
121
122     }
123
124
125     public download() {
126         if (this.apiRequest) {
127             var fileName = 'test_' + this.action + '_' + this.actionIdentifiers['vnf-id'] + '_request';
128             var theJSON = this.apiRequest;
129             if (fileName != null || fileName != '') {
130                 var blob = new Blob([theJSON], {
131                     type: 'text/json'
132                 });
133                 saveAs(blob, fileName);
134             }
135         }
136         else {
137             this.nService.error('Error', 'Please upload spreadsheet to download the request and response');
138         }
139
140         if (this.apiResponse) {
141             var fileName = 'test_' + this.action + '_' + this.actionIdentifiers['vnf-id'] + '_response';
142             var theJSON = this.apiResponse;
143             if (fileName != null || fileName != '') {
144                 var blob = new Blob([theJSON], {
145                     type: 'text/json'
146                 });
147                 saveAs(blob, fileName);
148             }
149         }
150
151     }
152
153
154     public abortTest() {
155         //this.apiResponse = "";
156         this.enableBrowse = true;
157         this.enableTestButton = true;
158         this.enablePollButton = true;
159         if (this.subscribe && this.subscribe != undefined) this.subscribe.unsubscribe();
160         this.nService.info("Information", "Test has been abandoned and polling stopped");
161     }
162
163
164     excelBrowseOption() {
165         $('#excelInputFile').trigger('click');
166     }
167
168
169     upload(evt: any) {
170         /* wire up file reader */
171         $('#filesparam').trigger('click');
172         const target: DataTransfer = <DataTransfer>(evt.target);
173         this.pollCounter = 0;
174         this.uploadFileName = evt.target.files[0].name;
175         var fileExtension = this.uploadFileName.substr(this.uploadFileName.lastIndexOf('.') + 1);
176
177         if (target.files.length != 1) {
178             throw new Error('Cannot upload multiple files on the entry');
179         }
180         if (fileExtension.toUpperCase() === 'XLS' || fileExtension.toUpperCase() === 'XLSX') {
181             this.spinner.show();
182             const reader = new FileReader();
183             reader.onload = (e: any) => {
184                 /* read workbook */
185                 const bstr = e.target.result;
186                 const wb = XLSX.read(bstr, { type: 'binary' });
187                 /* grab first sheet */
188                 const wsname = wb.SheetNames[0];
189                 const ws = wb.Sheets[wsname];
190
191                 /* save data */
192                 this.requestId = ''
193                 this.enableTestButton = true;
194                 this.enableAbort = true;
195                 this.enablePollButton = true;
196
197                 if (this.subscribe && this.subscribe != undefined) {
198                     this.enableCounterDiv = false;
199                     this.subscribe.unsubscribe();
200                 }
201                 this.apiRequest = '';
202                 this.apiResponse = '';
203                 this.showStatusResponseDiv = false;
204                 this.errorResponse = '';
205                 this.statusResponse = '';
206                 this.enableDownload = true;
207                 let arrData = (<AOA>(XLSX.utils.sheet_to_json(ws, { blankrows: false })));
208
209
210
211                 this.vmPayload = [];
212                 this.subPayload = {};
213                 this.vmJson = {};
214                 this.flag = 1;
215                 this.payload = {};
216                 this.oldListName1 = '';
217                 this.actionIdentifiers = {};
218                 // Refactor
219                 this.payload = this.processUploadedFile(arrData);
220                 this.uploadedFileResult();
221             };
222
223             reader.readAsBinaryString(target.files[0]);
224             setTimeout(() => {
225                         /** spinner ends after 2.5 seconds */
226                         this.spinner.hide();
227           }, 2500);
228
229         }
230         else {
231             this.nService.error('Error', 'Incorrect spreadsheet uploaded');
232             this.setValuesOnFileUploadFailure();
233         }
234     }
235
236     processUploadedFile(arrData) {
237         let tempPayload = {};
238         for (var i = 0; i < arrData.length; i++) {
239             var element = arrData[i];
240             if (element['TagName'] === 'action') {
241                 this.action = element['Value'];
242             }
243             if (element['List Name'] === 'action-identifiers') {
244                 this.vnfId = element['Value'];
245                 var key = element['TagName'];
246                 var value = element['Value'];
247                 if (key && value) {
248                     this.actionIdentifiers[key] = value;
249
250                 }
251             }
252
253             if (element['List Name'] === 'payload') {
254                 var listName1 = element['List Name_1'];
255                 var listName2 = element['List Name_2'];
256                 var listName3 = element['List Name_3'];
257                 var key = element['TagName'];
258                 var value = element['Value'];
259                 if (listName1) {
260                     if (this.oldListName1 == '' || (listName1 === this.oldListName1)) {
261                         this.constructTestPayload(listName2, listName3, key, value);
262                         tempPayload[listName1] = this.subPayload;
263                     }
264                     else {
265                         this.subPayload = {};
266                         this.constructTestPayload(listName2, listName3, key, value);
267                         tempPayload[listName1] = this.subPayload;
268                     }
269                     this.oldListName1 = listName1;
270                 }
271                 else {
272                     tempPayload[key] = value;
273                 }
274             }
275         }
276
277         return tempPayload;
278     }
279
280     uploadedFileResult() {
281         if (this.action && this.actionIdentifiers['vnf-id']) {
282             this.nService.success('Success', 'SpreadSheet uploaded successfully');
283         }
284         else {
285             this.setValuesOnFileUploadFailure();
286             this.nService.error("Error", "Please check the contents of the file uploaded")
287         }
288     }
289
290
291
292     constructTestPayload(listName2, listName3, key, value) {
293         if (listName2 == undefined && listName3 == undefined) {
294             this.subPayload[key] = value;
295         }
296         if (listName2) {
297
298             if (!listName3) {
299
300                 //vmPayload.push(vmJson)
301                 this.vmJson = {};
302                 this.vnfcJson = {};
303                 this.vmJson[key] = value;
304                 this.flag = 0;
305             }
306             else {
307                 this.vnfcJson[key] = value;
308                 this.vmJson['vnfc'] = this.vnfcJson;
309                 this.flag = 1;
310             }
311             if (this.vmJson) this.lastvmJson = this.vmJson;
312             if (this.flag == 0) {
313                 this.vmPayload.push(this.lastvmJson);
314                 if (this.vmPayload) this.subPayload['vm'] = this.vmPayload;
315             }
316         }
317     }
318
319     constructRequest() {
320         let timeStamp = new Date().toISOString();
321         let reqId;
322         this.requestId = reqId = new Date().getTime().toString();
323         let data = {
324             'input': {
325                 'common-header': {
326                     'timestamp': timeStamp,
327                     'api-ver': '2.00',
328                     'originator-id': this.userId,
329                     'request-id': this.requestId,
330                     'sub-request-id': this.requestId,
331                     'flags': {
332                         'mode': 'NORMAL',
333                         'force': 'TRUE',
334                         'ttl': 3600
335                     }
336                 },
337                 'action': this.action,
338                 'action-identifiers': this.actionIdentifiers,
339                 'payload': JSON.stringify(this.payload)
340             }
341         };
342
343         return data;
344     }
345
346     testVnf() {
347         this.enableBrowse = false;
348         this.enableTestButton = false;
349         this.enablePollButton = false;
350         this.timer = Observable.interval(10000);
351         this.subscribe = this.timer.subscribe((t) => this.pollTestStatus());
352         this.ngProgress.start();
353         this.apiRequest = JSON.stringify(this.constructRequest());
354
355         this.httpUtil.post(
356             {
357                 url: environment.testVnf + "?urlAction=" + this.getUrlEndPoint(this.action.toLowerCase()),
358                 data: this.apiRequest
359             })
360             .subscribe(resp => {
361                 this.apiResponse = JSON.stringify(resp);
362                 this.enableBrowse = true;
363                 this.enableTestButton = true;
364                 this.ngProgress.done();
365             },
366                 error => {
367                     this.nService.error('Error', 'Error in connecting to APPC Server');
368                     this.enableBrowse = true;
369                     this.enableTestButton = true;
370                     this.enablePollButton = true;
371                     this.enableCounterDiv = false;
372                     if (this.subscribe && this.subscribe != undefined) this.subscribe.unsubscribe();
373
374                 });
375
376         setTimeout(() => {
377             this.ngProgress.done();
378         }, 3500);
379     }
380
381
382     pollTestStatus() {
383         if (this.requestId && this.actionIdentifiers['vnf-id']) {
384             let timeStamp = new Date().toISOString();
385             let reqId = new Date().getTime().toString();
386             let data = {
387                 'input': {
388                     'common-header': {
389                         'timestamp': timeStamp,
390                         'api-ver': '2.00',
391                         'originator-id': this.userId,
392                         'request-id': reqId,
393                         'sub-request-id': reqId,
394                         'flags': {
395                             'mode': 'NORMAL',
396                             'force': 'TRUE',
397                             'ttl': 3600
398                         }
399                     },
400                     'action': 'ActionStatus',
401                     'action-identifiers': {
402                         'vnf-id': this.actionIdentifiers['vnf-id']
403                     },
404                     'payload': '{"request-id":' + this.requestId + '}'
405                 }
406             };
407             this.httpUtil.post(
408                 {
409                     url: environment.checkTestStatus, data: data
410
411                 })
412                 .subscribe(resp => {
413                     this.statusResponse = JSON.stringify(resp);
414                     var status = ''
415                     var statusReason = ''
416                     this.enableCounterDiv = true;
417                     this.pollCounter++;
418                     if (resp.output) var timeStamp = resp.output['common-header'].timestamp;
419                     if (resp.output.payload) {
420                         var payload = resp.output.payload.replace(/\\/g, "")
421                         try {
422                             payload = JSON.parse(payload)
423                             status = payload['status'];
424                             statusReason = payload['status-reason'];
425                         }
426                         catch (err) {
427                             console.log("error" + err)
428                         }
429                     }
430                     if (timeStamp && status && statusReason) {
431                         this.showStatusResponseDiv = true;
432                         this.outputTimeStamp = timeStamp;
433                         this.status = status;
434                         this.statusReason = statusReason;
435                         if (status.toUpperCase() === 'SUCCESS' || status.toUpperCase() === 'SUCCESSFUL') {
436                             if (this.subscribe && this.subscribe != undefined) this.subscribe.unsubscribe();
437                             this.enablePollButton = true;
438                         }
439                         if (status.toUpperCase() === 'FAILED') {
440                             if (this.subscribe && this.subscribe != undefined) this.subscribe.unsubscribe();
441                             this.enablePollButton = true;
442                         }
443                     }
444                     else {
445                         this.showStatusResponseDiv = false;
446                         if (this.subscribe && this.subscribe != undefined) {
447                             this.subscribe.unsubscribe();
448                             this.enablePollButton = true;
449                         }
450
451                     }
452
453                 },
454                     error => {
455                         this.statusResponse = null;
456                         this.showStatusResponseDiv = false;
457                         this.errorResponse = 'Error Connecting to APPC server';
458                         this.enableCounterDiv = false;
459                         if (this.subscribe && this.subscribe != undefined) {
460                             this.subscribe.unsubscribe();
461                             this.enablePollButton = true;
462                         }
463                     });
464         }
465         else {
466             this.nService.error("Error", "Please enter vnf Id & request Id");
467         }
468
469     }
470
471     getUrlEndPoint(action) {
472         switch (action) {
473             case 'configmodify':
474                 return 'config-modify';
475             case 'configbackup':
476                 return 'config-backup';
477             case 'configrestore':
478                 return 'config-restore';
479             case 'healthcheck':
480                 return 'health-check';
481             case 'quiescetraffic':
482                 return 'quiesce-traffic';
483             case 'resumetraffic':
484                 return 'resume-traffic';
485             case 'distributetraffic':
486                 return 'distribute-traffic';
487             case 'startapplication':
488                 return 'start-application';
489             case 'stopapplication':
490                 return 'stop-application';
491             case 'upgradebackout':
492                 return 'upgrade-backout';
493             case 'upgradepostcheck':
494                 return 'upgrade-post-check';
495             case 'upgradeprecheck':
496                 return 'upgrade-pre-check';
497             case 'upgradesoftware':
498                 return 'upgrade-software';
499             case 'upgradebackup':
500                 return 'upgrade-backup';
501             case 'attachvolume':
502                 return 'attach-volume';
503             case 'detachvolume':
504                 return 'detach-volume';
505             default:
506                 return action.toLowerCase();
507         }
508
509     }
510
511     setValuesOnFileUploadFailure() {        
512         this.flag = 1;
513         this.oldListName1 = '';
514         this.vmJson = {};
515         this.vnfcJson = {};
516         this.subPayload = {};
517         this.vmPayload = [];
518         this.payload = {};
519         this.action = '';
520         this.actionIdentifiers = {};
521         this.apiRequest = '';
522         this.apiResponse = '';
523         this.enableCounterDiv = false;
524         this.enableAbort = false;
525         this.enableTestButton = false;
526         this.enableDownload = false;
527     }
528
529 }