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