9ba89da4dda3b652595c16817015230ed677f7f3
[osm/NG-UI.git] / src / app / packages / instantiate-ns / InstantiateNsComponent.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 Instantiate NS Modal Component.
20  */
21 import { Component, ElementRef, Injector, OnInit, ViewChild } from '@angular/core';
22 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
23 import { Router } from '@angular/router';
24 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
25 import { TranslateService } from '@ngx-translate/core';
26 import { NotifierService } from 'angular-notifier';
27 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA } from 'CommonModel';
28 import { DataService } from 'DataService';
29 import { environment } from 'environment';
30 import * as jsyaml from 'js-yaml';
31 import { NSCREATEPARAMS, NSData, NSDDetails } from 'NSDModel';
32 import { RestService } from 'RestService';
33 import { SharedService, isNullOrUndefined } from 'SharedService';
34 import { VimAccountDetails } from 'VimAccountModel';
35
36 /**
37  * Creating component
38  * @Component takes InstantiateNsComponent.html as template url
39  */
40 @Component({
41   selector: 'app-instantiate-ns',
42   templateUrl: './InstantiateNsComponent.html',
43   styleUrls: ['./InstantiateNsComponent.scss']
44 })
45 /** Exporting a class @exports InstantiateNsComponent */
46 export class InstantiateNsComponent implements OnInit {
47   /** To inject services @public */
48   public injector: Injector;
49
50   /** Contains all the nsd data collections */
51   public nsdSelect: NSDDetails;
52
53   /** FormGroup instance added to the form @ html @public */
54   public instantiateForm: FormGroup;
55
56   /** Contains all vim account collections */
57   public vimAccountSelect: VimAccountDetails;
58
59   /** Instance for active modal service @public */
60   public activeModal: NgbActiveModal;
61
62   /** Variable set for twoway binding @public */
63   public nsdId: string;
64
65   /** Variable set for twoway bindng @public  */
66   public vimAccountId: string;
67
68   /** Form submission Add */
69   public submitted: boolean = false;
70
71   /** Check the loading results @public */
72   public isLoadingResults: boolean = false;
73
74   /** Give the message for the loading @public */
75   public message: string = 'PLEASEWAIT';
76
77   /** Contains Selected VIM Details @public */
78   public selectedVIMDetails: VimAccountDetails = null;
79
80   /** Element ref for fileInputConfig @public */
81   @ViewChild('fileInputConfig', { static: true }) public fileInputConfig: ElementRef;
82
83   /** Element ref for fileInputConfigLabel @public */
84   @ViewChild('fileInputConfigLabel', { static: true }) public fileInputConfigLabel: ElementRef;
85
86   /** Element ref for fileInputSSH @public */
87   @ViewChild('fileInputSSH', { static: true }) public fileInputSSH: ElementRef;
88
89   /** Element ref for fileInputSSHLabel @public */
90   @ViewChild('fileInputSSHLabel', { static: true }) public fileInputSSHLabel: ElementRef;
91
92   /** Holds teh instance of AuthService class of type AuthService @private */
93   private router: Router;
94
95   /** FormBuilder instance added to the formBuilder @private */
96   private formBuilder: FormBuilder;
97
98   /** Utilizes rest service for any CRUD operations @private */
99   private restService: RestService;
100
101   /** Utilizes data service for any communication @private */
102   private dataService: DataService;
103
104   /** Notifier service to popup notification @private */
105   private notifierService: NotifierService;
106
107   /** Contains tranlsate instance @private */
108   private translateService: TranslateService;
109
110   /** Contains all methods related to shared @private */
111   private sharedService: SharedService;
112
113   /** Contains the ssh key to be hosted in dom @private */
114   private copySSHKey: string;
115
116   constructor(injector: Injector) {
117     this.injector = injector;
118     this.restService = this.injector.get(RestService);
119     this.activeModal = this.injector.get(NgbActiveModal);
120     this.formBuilder = this.injector.get(FormBuilder);
121     this.dataService = this.injector.get(DataService);
122     this.notifierService = this.injector.get(NotifierService);
123     this.router = this.injector.get(Router);
124     this.translateService = this.injector.get(TranslateService);
125     this.sharedService = this.injector.get(SharedService);
126   }
127
128   public ngOnInit(): void {
129     /** Setting up initial value for NSD */
130     this.dataService.currentMessage.subscribe((event: NSData) => {
131       if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
132         this.nsdId = event.identifier;
133       }
134     });
135     /** On Initializing call the methods */
136     this.instantiateFormAction();
137     this.getDetailsnsd();
138     this.getDetailsvimAccount();
139   }
140
141   /** On modal initializing forms  @public */
142   public instantiateFormAction(): void {
143     this.instantiateForm = this.formBuilder.group({
144       nsName: ['', [Validators.required]],
145       nsDescription: ['', [Validators.required]],
146       nsdId: ['', [Validators.required]],
147       vimAccountId: ['', [Validators.required]],
148       ssh_keys: [null],
149       config: [null]
150     });
151   }
152
153   /** Convenience getter for easy access to form fields */
154   get f(): FormGroup['controls'] { return this.instantiateForm.controls; }
155
156   /** Call the nsd details in the selection options @public */
157   public getDetailsnsd(): void {
158     this.restService.getResource(environment.NSDESCRIPTORSCONTENT_URL).subscribe((nsPackages: NSDDetails) => {
159       this.nsdSelect = nsPackages;
160     }, (error: ERRORDATA) => {
161       this.restService.handleError(error, 'get');
162     });
163   }
164
165   /** Call the vimAccount details in the selection options @public */
166   public getDetailsvimAccount(): void {
167     this.restService.getResource(environment.VIMACCOUNTS_URL).subscribe((vimAccounts: VimAccountDetails) => {
168       this.vimAccountSelect = vimAccounts;
169     }, (error: ERRORDATA) => {
170       this.restService.handleError(error, 'get');
171     });
172   }
173
174   /** On modal submit instantiateNsSubmit will called @public */
175   public instantiateNsSubmit(): void {
176     this.submitted = true;
177     this.sharedService.cleanForm(this.instantiateForm);
178     if (this.instantiateForm.invalid) {
179       return;
180     }
181     const modalData: MODALCLOSERESPONSEDATA = {
182       message: 'Done'
183     };
184     if (isNullOrUndefined(this.instantiateForm.value.ssh_keys) || this.instantiateForm.value.ssh_keys === '') {
185       delete this.instantiateForm.value.ssh_keys;
186     } else {
187       this.copySSHKey = JSON.parse(JSON.stringify(this.instantiateForm.value.ssh_keys));
188       this.instantiateForm.get('ssh_keys').setValue([this.copySSHKey]);
189     }
190     if (isNullOrUndefined(this.instantiateForm.value.config) || this.instantiateForm.value.config === '') {
191       delete this.instantiateForm.value.config;
192     } else {
193       const validJSON: boolean = this.sharedService.checkJson(this.instantiateForm.value.config);
194       if (validJSON) {
195         this.instantiateForm.value.config = JSON.parse(this.instantiateForm.value.config);
196         Object.keys(this.instantiateForm.value.config).forEach((item: string) => {
197           // eslint-disable-next-line security/detect-object-injection
198           this.instantiateForm.value[item] = this.instantiateForm.value.config[item];
199         });
200         delete this.instantiateForm.value.config;
201       } else {
202         const getConfigJson: string = jsyaml.load(this.instantiateForm.value.config, { json: true });
203         Object.keys(getConfigJson).forEach((item: string) => {
204           // eslint-disable-next-line security/detect-object-injection
205           this.instantiateForm.value[item] = getConfigJson[item];
206         });
207         delete this.instantiateForm.value.config;
208       }
209     }
210     const apiURLHeader: APIURLHEADER = {
211       url: environment.NSINSTANCESCONTENT_URL
212     };
213     this.isLoadingResults = true;
214     this.restService.postResource(apiURLHeader, this.instantiateForm.value).subscribe((result: {}) => {
215       this.activeModal.close(modalData);
216       this.notifierService.notify('success', this.instantiateForm.value.nsName +
217         this.translateService.instant('PAGE.NSINSTANCE.CREATEDSUCCESSFULLY'));
218       this.router.navigate(['/instances/ns']).catch((): void => {
219         // Catch Navigation Error
220     });
221     }, (error: ERRORDATA) => {
222       this.isLoadingResults = false;
223       this.restService.handleError(error, 'post');
224       if (!isNullOrUndefined(this.copySSHKey)) {
225         this.instantiateForm.get('ssh_keys').setValue(this.copySSHKey);
226       }
227     });
228   }
229
230   /** ssh file process @private */
231   public sshFile(files: FileList): void {
232     if (files && files.length === 1) {
233       this.sharedService.getFileString(files, 'pub').then((fileContent: string): void => {
234         const getSSHJson: string = jsyaml.load(fileContent, { json: true });
235         this.instantiateForm.get('ssh_keys').setValue(getSSHJson);
236       }).catch((err: string): void => {
237         if (err === 'typeError') {
238           this.notifierService.notify('error', this.translateService.instant('PUBFILETYPEERRROR'));
239         } else {
240           this.notifierService.notify('error', this.translateService.instant('ERROR'));
241         }
242         this.fileInputSSHLabel.nativeElement.innerText = this.translateService.instant('CHOOSEFILE');
243         this.fileInputSSH.nativeElement.value = null;
244       });
245     } else if (files && files.length > 1) {
246       this.notifierService.notify('error', this.translateService.instant('DROPFILESVALIDATION'));
247     }
248     this.fileInputSSHLabel.nativeElement.innerText = files[0].name;
249     this.fileInputSSH.nativeElement.value = null;
250   }
251
252   /** Config file process @private */
253   public configFile(files: FileList): void {
254     if (files && files.length === 1) {
255       const fileFormat: string = this.sharedService.fetchFileExtension(files).toLocaleLowerCase();
256       if (fileFormat === 'yaml' || fileFormat === 'yml') {
257         this.sharedService.getFileString(files, 'yaml').then((fileContent: string): void => {
258           this.instantiateForm.get('config').setValue(fileContent);
259         }).catch((err: string): void => {
260           if (err === 'typeError') {
261             this.notifierService.notify('error', this.translateService.instant('YAMLFILETYPEERRROR'));
262           } else {
263             this.notifierService.notify('error', this.translateService.instant('ERROR'));
264           }
265           this.fileInputConfigLabel.nativeElement.innerText = this.translateService.instant('CHOOSEFILE');
266           this.fileInputConfig.nativeElement.value = null;
267         });
268       } else if (fileFormat === 'json') {
269         this.sharedService.getFileString(files, 'json').then((fileContent: string): void => {
270           const getConfigJson: string = jsyaml.load(fileContent, { json: true });
271           this.instantiateForm.get('config').setValue(JSON.stringify(getConfigJson));
272         }).catch((err: string): void => {
273           if (err === 'typeError') {
274             this.notifierService.notify('error', this.translateService.instant('JSONFILETYPEERRROR'));
275           } else {
276             this.notifierService.notify('error', this.translateService.instant('ERROR'));
277           }
278           this.fileInputConfigLabel.nativeElement.innerText = this.translateService.instant('CHOOSEFILE');
279           this.fileInputConfig.nativeElement.value = null;
280         });
281       }
282     } else if (files && files.length > 1) {
283       this.notifierService.notify('error', this.translateService.instant('DROPFILESVALIDATION'));
284     }
285     this.fileInputConfigLabel.nativeElement.innerText = files[0].name;
286     this.fileInputConfig.nativeElement.value = null;
287   }
288
289   /** Get Selected VIM details @public */
290   public getSelectedVIMDetails(vimDetails: VimAccountDetails): void {
291     if (!isNullOrUndefined(vimDetails.resources)) {
292       this.selectedVIMDetails = vimDetails;
293     }
294   }
295 }