9567b43637ff74ae09ff6c60405bb1b609947a4e
[osm/NG-UI.git] / src / app / utilities / compose-packages / ComposePackages.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 Info Compose Package Model
20  */
21 import { HttpClient, HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Router } from '@angular/router';
25 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
26 import { TranslateService } from '@ngx-translate/core';
27 import { NotifierService } from 'angular-notifier';
28 import { APIURLHEADER, ERRORDATA, URLPARAMS } from 'CommonModel';
29 import { DataService } from 'DataService';
30 import { environment } from 'environment';
31 import * as jsyaml from 'js-yaml';
32 import * as pako from 'pako';
33 import { RestService } from 'RestService';
34 import { SharedService } from 'SharedService';
35
36 /** This is added globally by the tar.js library */
37 // tslint:disable-next-line: no-any
38 declare const Tar: any;
39
40 /**
41  * Creating component
42  * @Component takes ComposePackages.html as template url
43  */
44 @Component({
45   templateUrl: './ComposePackages.html',
46   styleUrls: ['./ComposePackages.scss']
47 })
48 /** Exporting a class @exports ComposePackages */
49 export class ComposePackages implements OnInit {
50   /** Invoke service injectors @public */
51   public injector: Injector;
52
53   /** dataService to pass the data from one component to another @public */
54   public dataService: DataService;
55
56   /** Varaibles to hold http client @public */
57   public httpClient: HttpClient;
58
59   /** Instance for active modal service @public */
60   public activeModal: NgbActiveModal;
61
62   /** FormGroup instance added to the form @ html @public */
63   public packagesForm: FormGroup;
64
65   /** Form submission Add */
66   public submitted: boolean = false;
67
68   /** To handle loader status for API call @public */
69   public isLoadingResults: boolean = false;
70
71   /** Give the message for the loading @public */
72   public message: string = 'PLEASEWAIT';
73
74   /** FormBuilder instance added to the formBuilder @private */
75   private formBuilder: FormBuilder;
76
77   /** Instance of the rest service @private */
78   private restService: RestService;
79
80   /** Notifier service to popup notification @private */
81   private notifierService: NotifierService;
82
83   /** Controls the header form @private */
84   private headers: HttpHeaders;
85
86   /** Create URL holds the end point of any packages @private */
87   private createURL: string;
88
89   /** Input contains component objects @private */
90   @Input() private params: URLPARAMS;
91
92   /** Holds the end point @private */
93   private endPoint: string;
94
95   /** Contains all methods related to shared @private */
96   private sharedService: SharedService;
97
98   /** Holds teh instance of AuthService class of type AuthService @private */
99   private router: Router;
100
101   /** Contains tranlsate instance @private */
102   private translateService: TranslateService;
103
104   constructor(injector: Injector) {
105     this.injector = injector;
106     this.dataService = this.injector.get(DataService);
107     this.restService = this.injector.get(RestService);
108     this.activeModal = this.injector.get(NgbActiveModal);
109     this.notifierService = this.injector.get(NotifierService);
110     this.formBuilder = this.injector.get(FormBuilder);
111     this.router = this.injector.get(Router);
112     this.translateService = this.injector.get(TranslateService);
113     this.sharedService = this.injector.get(SharedService);
114   }
115
116   /**
117    * Lifecyle Hooks the trigger before component is instantiate
118    */
119   public ngOnInit(): void {
120     this.headers = new HttpHeaders({
121       'Content-Type': 'application/gzip',
122       Accept: 'application/json',
123       'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
124     });
125     this.initializeForm();
126   }
127
128   /** initialize Forms @public */
129   public initializeForm(): void {
130     this.packagesForm = this.formBuilder.group({
131       name: ['', [Validators.required]]
132     });
133   }
134
135   /** convenience getter for easy access to form fields */
136   get f(): FormGroup['controls'] { return this.packagesForm.controls; }
137
138   /** Create packages @public */
139   public createPackages(): void {
140     this.submitted = true;
141     this.sharedService.cleanForm(this.packagesForm);
142     if (!this.packagesForm.invalid) {
143       this.isLoadingResults = true;
144       if (this.params.page === 'ns-package') {
145         this.endPoint = environment.NSDESCRIPTORSCONTENT_URL;
146       } else if (this.params.page === 'vnf-package') {
147         this.endPoint = environment.VNFPACKAGESCONTENT_URL;
148       }
149       const descriptor: string = this.packageYaml(this.params.page);
150       try {
151         // tslint:disable-next-line: no-any
152         const tar: any = new Tar();
153         const out: Uint8Array = tar.append(this.packagesForm.value.name + '/' + this.packagesForm.value.name + '.yaml',
154           descriptor, { type: '0' });
155         const gzipContent: Uint8Array = pako.gzip(out);
156         this.createPackageApi(gzipContent.buffer);
157       } catch (e) {
158         this.isLoadingResults = false;
159         this.notifierService.notify('error', this.translateService.instant('ERROR'));
160       }
161     }
162   }
163   /** Create packages @public */
164   private createPackageApi(packageContent: ArrayBuffer | SharedArrayBuffer): void {
165     const apiURLHeader: APIURLHEADER = {
166       url: this.endPoint,
167       httpOptions: { headers: this.headers }
168     };
169     this.restService.postResource(apiURLHeader, packageContent).subscribe((result: { id: string }) => {
170       this.isLoadingResults = false;
171       this.activeModal.close();
172       this.composeNSPackages(result.id);
173     }, (error: ERRORDATA) => {
174       this.isLoadingResults = false;
175       this.restService.handleError(error, 'post');
176     });
177   }
178   /** Compose NS Packages @private */
179   private composeNSPackages(id: string): void {
180     let packageUrl: string;
181     if (this.params.page === 'ns-package') {
182       packageUrl = '/packages/ns/compose/';
183       this.notifierService.notify('success', this.packagesForm.value.name + ' ' +
184         this.translateService.instant('PAGE.NSPACKAGE.CREATEDSUCCESSFULLY'));
185     } else if (this.params.page === 'vnf-package') {
186       packageUrl = '/packages/vnf/compose/';
187       this.notifierService.notify('success', this.packagesForm.value.name + ' ' +
188         this.translateService.instant('PAGE.VNFPACKAGE.CREATEDSUCCESSFULLY'));
189     }
190     this.router.navigate([packageUrl, id]).catch(() => {
191       // Catch Navigation Error
192     });
193   }
194   /** Deafult template for NS and VNF Packages @private */
195   private packageYaml(descriptorType: string): string {
196     let packageYaml: {} = {};
197     if (descriptorType === 'ns-package') {
198       packageYaml = {
199         'nsd:nsd-catalog': {
200           nsd: [
201             {
202               'short-name': this.packagesForm.value.name,
203               vendor: 'OSM Composer',
204               description: this.packagesForm.value.name + ' descriptor',
205               vld: [],
206               'constituent-vnfd': [],
207               version: '1.0',
208               id: this.packagesForm.value.name,
209               name: this.packagesForm.value.name
210             }
211           ]
212         }
213       };
214     } else {
215       packageYaml = {
216         'vnfd:vnfd-catalog': {
217           vnfd: [
218             {
219               'short-name': this.packagesForm.value.name,
220               vdu: [],
221               description: '',
222               'mgmt-interface': {
223                 cp: ''
224               },
225               id: this.packagesForm.value.name,
226               version: '1.0',
227               'internal-vld': [],
228               'connection-point': [],
229               name: this.packagesForm.value.name
230             }
231           ]
232         }
233       };
234     }
235     return jsyaml.dump(packageYaml);
236   }
237 }