Bug 1383 Error when consulting NS instance's topology
[osm/NG-UI.git] / src / app / packages / vnf-packages / VNFPackagesComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17 */
18 /**
19  * @file VNF Package details Component.
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, ElementRef, Injector, OnInit, ViewChild } from '@angular/core';
23 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
24 import { TranslateService } from '@ngx-translate/core';
25 import { NotifierService } from 'angular-notifier';
26 import { APIURLHEADER, ERRORDATA } from 'CommonModel';
27 import { ComposePackages } from 'ComposePackages';
28 import { DataService } from 'DataService';
29 import { environment } from 'environment';
30 import { LocalDataSource } from 'ng2-smart-table';
31 import { RestService } from 'RestService';
32 import { Subscription } from 'rxjs';
33 import { SharedService } from 'SharedService';
34 import { VNFD, VNFData } from 'VNFDModel';
35 import { VNFPackagesActionComponent } from 'VNFPackagesAction';
36
37 /**
38  * Creating component
39  * @Component takes VNFPackagesComponent.html as template url
40  */
41 @Component({
42     selector: 'app-vnf-packages',
43     templateUrl: './VNFPackagesComponent.html',
44     styleUrls: ['./VNFPackagesComponent.scss']
45 })
46 /** Exporting a class @exports VNFPackagesComponent */
47 export class VNFPackagesComponent implements OnInit {
48     /** To inject services @public */
49     public injector: Injector;
50
51     /** Data of smarttable populate through LocalDataSource @public */
52     public dataSource: LocalDataSource = new LocalDataSource();
53
54     /** handle translate @public */
55     public translateService: TranslateService;
56
57     /** Columns list of the smart table @public */
58     public columnLists: object = {};
59
60     /** Settings for smarttable to populate the table with columns @public */
61     public settings: object = {};
62
63     /** Check the loading results @public */
64     public isLoadingResults: boolean = true;
65
66     /** Give the message for the loading @public */
67     public message: string = 'PLEASEWAIT';
68
69     /** Class for empty and present data @public */
70     public checkDataClass: string;
71
72     /** Element ref for fileInput @public */
73     @ViewChild('fileInput', { static: true }) public fileInput: ElementRef;
74
75     /** Instance of the rest service @private */
76     private restService: RestService;
77
78     /** dataService to pass the data from one component to another @private */
79     private dataService: DataService;
80
81     /** Formation of appropriate Data for LocalDatasource @private */
82     private vnfData: VNFData[] = [];
83
84     /** Contains all methods related to shared @private */
85     private sharedService: SharedService;
86
87     /** variables contains file information */
88     private fileData: string | ArrayBuffer;
89
90     /** Controls the header form @private */
91     private headers: HttpHeaders;
92
93     /** Notifier service to popup notification @private */
94     private notifierService: NotifierService;
95
96     /** Instance of the modal service @private */
97     private modalService: NgbModal;
98
99     /** Instance of subscriptions @private */
100     private generateDataSub: Subscription;
101
102     constructor(injector: Injector) {
103         this.injector = injector;
104         this.restService = this.injector.get(RestService);
105         this.dataService = this.injector.get(DataService);
106         this.sharedService = this.injector.get(SharedService);
107         this.translateService = this.injector.get(TranslateService);
108         this.notifierService = this.injector.get(NotifierService);
109         this.modalService = this.injector.get(NgbModal);
110     }
111
112     /**
113      * Lifecyle Hooks the trigger before component is instantiate
114      */
115     public ngOnInit(): void {
116         this.generateColumns();
117         this.generateSettings();
118         this.generateData();
119         this.headers = new HttpHeaders({
120             'Content-Type': 'application/gzip',
121             Accept: 'application/json',
122             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
123         });
124         this.generateDataSub = this.sharedService.dataEvent.subscribe((): void => { this.generateData(); });
125     }
126
127     /** smart table Header Colums @public */
128     public generateColumns(): void {
129         this.columnLists = {
130             productName: { title: this.translateService.instant('PRODUCTNAME'), width: '15%', sortDirection: 'asc' },
131             identifier: { title: this.translateService.instant('IDENTIFIER'), width: '15%' },
132             version: { title: this.translateService.instant('VERSION'), width: '10%' },
133             provider: { title: this.translateService.instant('PROVIDER'), width: '10%' },
134             type: {
135                 title: this.translateService.instant('TYPE'),
136                 filter: {
137                     type: 'list',
138                     config: {
139                         selectText: 'Select',
140                         list: [
141                             { value: 'vnfd', title: 'VNF' },
142                             { value: 'pnfd', title: 'PNF' },
143                             { value: 'hnfd', title: 'HNF' }
144                         ]
145                     }
146                 },
147                 width: '10%'
148             },
149             description: { title: this.translateService.instant('DESCRIPTION'), width: '25%' },
150             Actions: {
151                 name: 'Action', width: '15%', filter: false, sort: false, type: 'custom',
152                 title: this.translateService.instant('ACTIONS'),
153                 valuePrepareFunction: (cell: VNFData, row: VNFData): VNFData => row, renderComponent: VNFPackagesActionComponent
154             }
155         };
156     }
157
158     /** smart table Data Settings @public */
159     public generateSettings(): void {
160         this.settings = {
161             edit: {
162                 editButtonContent: '<i class="fa fa-edit" title="Edit"></i>',
163                 confirmSave: true
164             },
165             delete: {
166                 deleteButtonContent: '<i class="far fa-trash-alt" title="delete"></i>',
167                 confirmDelete: true
168             },
169             columns: this.columnLists,
170             actions: {
171                 add: false,
172                 edit: false,
173                 delete: false,
174                 position: 'right'
175             },
176             attr: this.sharedService.tableClassConfig(),
177             pager: this.sharedService.paginationPagerConfig(),
178             noDataMessage: this.translateService.instant('NODATAMSG')
179         };
180     }
181
182     /** smart table listing manipulation @public */
183     public onChange(perPageValue: number): void {
184         this.dataSource.setPaging(1, perPageValue, true);
185     }
186
187     /** OnUserRowSelect Function @public */
188     public onUserRowSelect(event: MessageEvent): void {
189         Object.assign(event.data, { page: 'vnf-package' });
190         this.dataService.changeMessage(event.data);
191     }
192
193     /** Drag and drop feature and fetchind the details of files  @public */
194     public filesDropped(files: FileList): void {
195         if (files && files.length === 1) {
196             this.isLoadingResults = true;
197             this.sharedService.getFileString(files, 'gz').then((fileContent: ArrayBuffer): void => {
198                 const apiURLHeader: APIURLHEADER = {
199                     url: environment.VNFPACKAGESCONTENT_URL,
200                     httpOptions: { headers: this.headers }
201                 };
202                 this.saveFileData(apiURLHeader, fileContent);
203             }).catch((err: string): void => {
204                 this.isLoadingResults = false;
205                 if (err === 'typeError') {
206                     this.notifierService.notify('error', this.translateService.instant('GZFILETYPEERRROR'));
207                 } else {
208                     this.notifierService.notify('error', this.translateService.instant('ERROR'));
209                 }
210             });
211         } else if (files && files.length > 1) {
212             this.notifierService.notify('error', this.translateService.instant('DROPFILESVALIDATION'));
213         }
214     }
215
216     /** Post the droped files and reload the page @public */
217     public saveFileData(urlHeader: APIURLHEADER, fileData: {}): void {
218         this.fileInput.nativeElement.value = null;
219         this.restService.postResource(urlHeader, fileData).subscribe((result: {}): void => {
220             this.notifierService.notify('success', this.translateService.instant('PAGE.VNFPACKAGE.CREATEDSUCCESSFULLY'));
221             this.generateData();
222         }, (error: ERRORDATA): void => {
223             this.restService.handleError(error, 'post');
224             this.isLoadingResults = false;
225         });
226     }
227
228     /** Generate nsData object from loop and return for the datasource @public */
229     public generatevnfdData(vnfdpackagedata: VNFD): VNFData {
230         return {
231             productName: vnfdpackagedata['product-name'],
232             identifier: vnfdpackagedata._id,
233             type: vnfdpackagedata._admin.type,
234             description: vnfdpackagedata.description,
235             version: vnfdpackagedata.version,
236             provider: vnfdpackagedata.provider !== undefined ? vnfdpackagedata.provider : '-'
237         };
238     }
239     /** Handle compose new ns package method  @public */
240     public composeVNFPackage(): void {
241         this.modalService.open(ComposePackages, { backdrop: 'static' }).componentInstance.params = { page: 'vnf-package' };
242     }
243
244     /**
245      * Lifecyle hook which get trigger on component destruction
246      */
247     public ngOnDestroy(): void {
248         this.generateDataSub.unsubscribe();
249     }
250
251     /** Fetching the data from server to Load in the smarttable @protected */
252     protected generateData(): void {
253         this.isLoadingResults = true;
254         this.restService.getResource(environment.VNFPACKAGESCONTENT_URL).subscribe((vnfdPackageData: VNFD[]): void => {
255             this.vnfData = [];
256             vnfdPackageData.forEach((vnfdpackagedata: VNFD): void => {
257                 const vnfDataObj: VNFData = this.generatevnfdData(vnfdpackagedata);
258                 this.vnfData.push(vnfDataObj);
259             });
260             if (this.vnfData.length > 0) {
261                 this.checkDataClass = 'dataTables_present';
262             } else {
263                 this.checkDataClass = 'dataTables_empty';
264             }
265             this.dataSource.load(this.vnfData).then((data: boolean): void => {
266                 this.isLoadingResults = false;
267             }).catch((): void => {
268                 this.isLoadingResults = false;
269             });
270         }, (error: ERRORDATA): void => {
271             this.restService.handleError(error, 'get');
272             this.isLoadingResults = false;
273         });
274     }
275 }