Authentication support for cdt
[appc/cdt.git] / src / app / vnfs / build-artifacts / parameter-definitions / parameter.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
5
6 Copyright (C) 2018 IBM Intellectual Property. All rights reserved.
7 ===================================================================
8 Copyright (C) 2018 IBM.
9 ===================================================================
10
11 Unless otherwise specified, all software contained herein is licensed
12 under the Apache License, Version 2.0 (the License);
13 you may not use this software except in compliance with the License.
14 You may obtain a copy of the License at
15
16     http://www.apache.org/licenses/LICENSE-2.0
17
18 Unless required by applicable law or agreed to in writing, software
19 distributed under the License is distributed on an "AS IS" BASIS,
20 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 See the License for the specific language governing permissions and
22 limitations under the License.
23
24 ============LICENSE_END============================================
25 */
26
27 import { Component, OnInit, ViewChild } from '@angular/core';
28 import { saveAs } from 'file-saver';
29 import { ParamShareService } from '../../../shared/services/paramShare.service';
30 import { MappingEditorService } from '../../../shared/services/mapping-editor.service';
31 import { ModalComponent } from '../../../shared/modal/modal.component';
32 import { HttpUtilService } from '../../../shared/services/httpUtil/http-util.service';
33 import { UtilityService } from '../../../shared/services/utilityService/utility.service';
34 import { environment } from '../../../../environments/environment';
35 import { NotificationsService } from 'angular2-notifications';
36 import { ParameterDefinitionService } from './parameter-definition.service';
37 import 'rxjs/add/operator/map';
38 import { NgProgress } from 'ngx-progressbar';
39 import { NgxSpinnerService } from 'ngx-spinner';
40 import { appConstants } from '../../../../constants/app-constants';
41 import { APIService } from "../../../shared/services/cdt.apicall";
42
43 let YAML = require('yamljs');
44
45 declare var $: any;
46
47 @Component({
48     selector: 'parameter-form',
49     templateUrl: './parameter.component.html',
50     styleUrls: ['../reference-dataform/reference-dataform.component.css'],
51     providers: [ParameterDefinitionService]
52 })
53 export class ParameterComponent implements OnInit {
54     clName= "ParameterCompon";
55     public paramForm: any;
56     public actionType: any;
57     public showFilterFields: boolean;
58     
59     public filterByFieldvalues = appConstants.filterByFieldvalues;
60     public ruleTypeConfiguaration = appConstants.ruleTypeConfiguaration;
61     public requiredValues: boolean[] = appConstants.requiredValues;
62     public sourceValues = appConstants.sourceValues;
63     public ruleTypeValues = appConstants.ruleTypeValues;
64     public typeValues = appConstants.typeValues;
65     public responseKeyNameValues = appConstants.responseKeyNameValues;
66     public responseKeyValues = appConstants.responseKeyValues;
67     public requestKeyNameValues = appConstants.requestKeyNameValues;
68     public requestKeyValues = appConstants.requestKeyValues;
69     public myKeyFileName = null;
70     public myPdFileName = null;
71     public disposable: any;
72     public confirmation: boolean;
73     public showConfirmation: boolean;
74     public test: boolean;
75     apiToken = sessionStorage['apiToken'];
76     userId = sessionStorage['userId'];
77     public initialData: any;
78     public intialData: any;
79     public initialAction: any;
80     public item: any = {};
81     public subscription: any;
82     public Actions = [
83         { action: appConstants.Actions.configBackup, value: appConstants.Actions.configBackup },
84         { action: appConstants.Actions.ConfigModify, value: appConstants.Actions.ConfigModify },
85         { action: appConstants.Actions.configRestore, value: appConstants.Actions.configRestore },
86         { action: appConstants.Actions.configure, value: appConstants.Actions.configure },
87         { action: appConstants.Actions.getRunningConfig, value: appConstants.Actions.getRunningConfig },
88         { action: appConstants.Actions.healthCheck, value: appConstants.Actions.healthCheck },
89         { action: appConstants.Actions.startApplication, value: appConstants.Actions.startApplication },
90         { action: appConstants.Actions.stopApplication, value: appConstants.Actions.stopApplication },
91         { action: appConstants.Actions.distributeTraffic, value: appConstants.Actions.distributeTraffic },
92         { action: appConstants.Actions.distributeTrafficCheck, value: appConstants.Actions.distributeTrafficCheck }
93     ];
94     public uploadTypes = appConstants.uploadTypes;
95
96     options = appConstants.optionsToNotificationComponent;
97     public vnfcTypeData: string = '';
98     public selectedUploadType: string;
99     @ViewChild(ModalComponent) modalComponent: ModalComponent;
100     public title: string;
101     public parameterDefinitionMap: { [index: string]: string; } = {};
102     public parameterNameValues = {};
103     public displayParamObjects;
104     public modelParamDefinitionObjects;
105     public vnfType: any;
106     vnfcType: any;
107     protocol: any;
108     public refNameObj = {};
109     public action;
110     public artifactName;
111     public appDataObject: any;
112     public downloadDataObject: any;
113     public artifact_fileName="";
114     template_id: any;
115     private selectedActionReference: any;
116
117     constructor(private httpService: HttpUtilService,
118         private apiService:APIService,
119         private parameterDefinitionService: ParameterDefinitionService,
120         private paramShareService: ParamShareService,
121         private mappingEditorService: MappingEditorService,
122         private httpUtil: HttpUtilService,
123         private utilService: UtilityService,
124         private nService: NotificationsService,
125         private ngProgress: NgProgress,
126         private spinner: NgxSpinnerService) {
127     }
128
129     ngOnInit() {
130       var methName= "ngOnInit";
131         this.selectedActionReference = this.mappingEditorService.newObject;
132         if (this.selectedActionReference && this.selectedActionReference != undefined) {
133           this.vnfType = this.selectedActionReference.vnf;
134           this.protocol = this.selectedActionReference.protocol;
135           this.action = this.selectedActionReference.action;
136           if( this.utilService.getTracelvl() > 0 )
137             console.log( this.clName+": "+methName+": vnfType:["+this.vnfType+
138               "] action:["+this.action+"] protocol:["+this.protocol+"]");
139             if(this.selectedActionReference.vnfc) {
140                 this.vnfcType = this.selectedActionReference.vnfc;
141               if( this.utilService.getTracelvl() > 0 )
142                 console.log( this.clName+": "+methName+": have vnfcType:["+
143                   this.vnfcType+"]");
144             }
145             if( this.action === 'ConfigScaleOut' || this.action === 'ConfigScaleIn'){
146                 // this.template_id = this.selectedActionReference.templateId;
147                 this.template_id = this.mappingEditorService.identifier;
148             }
149             this.artifact_fileName = this.selectedActionReference.pd_artifact;
150             this.parameterDefinitionService.setValues(this.vnfType, this.vnfcType, this.protocol, this.action, this.artifact_fileName);
151         }
152         else {
153             this.selectedActionReference = {
154                 'action': '',
155                 'scope': { 'vnf-type': '', 'vnfc-type': '' },
156                 'vm': [],
157                 'protocol': '',
158                 'download-dg-reference': '',
159                 'user-name': '',
160                 'port-number': '',
161                 'artifact-list': [],
162                 'deviceTemplate': '',
163                 'scopeType': ''
164             };
165         }
166         //let path = this.location.path
167         /* this.activeRoutes.url.subscribe(UrlSegment => {
168              this.actionType = UrlSegment[0].path
169          })
170          */
171     }
172
173     ngAfterViewInit() {
174         if( this.mappingEditorService.latestAction) {
175             this.displayParamObjects = [];
176             this.modelParamDefinitionObjects = [];
177             this.displayParamObjects= this.paramShareService.getSessionParamData();
178          // if( this.paramShareService.getSessionParamData() != undefined &&
179          //     this.paramShareService.getSessionParamData().length > 0)
180             if( this.displayParamObjects != undefined &&
181                 this.displayParamObjects.length > 0 )
182             {
183               this.parameterDefinitionService.populateDataUponSource( this.displayParamObjects);
184             } else {
185               this.getPD();
186             }
187         } else {
188             this.nService.error(appConstants.errors.error, appConstants.errors["noAction&VNFTypeInRDscreenError"]);
189         }
190         return this.displayParamObjects;
191     }
192
193
194     public getPD() {
195         let result: any;
196         let input=
197           this.utilService.createPayloadForRetrieve( false, this.action, this.vnfType,this.artifact_fileName);
198         let artifactContent: any;
199         this.ngProgress.start();
200         return this.apiService.callGetArtifactsApi(input).subscribe( data => {
201             if( this.utilService.checkResult(data)) {
202               let result: any = JSON.parse(data.output.data.block).artifactInfo[0];
203                 var pdObject = YAML.parse(result['artifact-content']);
204                 let fileModel = pdObject['vnf-parameter-list'];
205                 this.displayParamObjects = this.parameterDefinitionService.populatePD(fileModel);
206             }
207             else {
208             }
209             this.ngProgress.done();
210         },
211
212             error => this.nService.error(appConstants.errors.error, appConstants.errors.connectionError));
213
214     }
215
216     public getPDFromSession() {
217
218       this.ngProgress.start();
219         return this.httpService.get({
220             url: 'testurl',
221         }).subscribe( data => {
222            this.displayParamObjects = this.paramShareService.getSessionParamData();
223            this.ngProgress.done();
224         },
225         error => {
226           this.displayParamObjects = this.paramShareService.getSessionParamData();
227           this.ngProgress.done();
228         });
229     }
230
231     selectedNavItem(item: any) {
232         this.item = item;
233     }
234
235     //========================== End of selectedNavItem() Method============================================
236     browsePdFile() {
237         $('#inputFile1').trigger('click');
238     }
239
240     //========================== End of browsePdFile() Method============================================
241     browseKeyFile() {
242         $('#inputFile2').trigger('click');
243
244     }
245
246     //========================== End of browseKeyFile() Method============================================
247
248
249     //========================== End of appendSlashes() Method============================================
250
251
252     //========================== End of prepareFileName() Method============================================
253     ngOnDestroy() {
254         this.parameterDefinitionService.destroy(this.displayParamObjects);
255     }
256
257     //========================== End of ngOnDestroy() Method============================================
258
259     public showUpload() {
260         this.selectedUploadType = this.uploadTypes[0].value;
261     };
262
263     //========================== End of showUpload() Method============================================
264     //This is called when the user selects new files from the upload button
265     public fileChange(input, uploadType) {
266         if (input.files && input.files[0]) {
267             this.spinner.show();
268             // Create the file reader
269             let reader = new FileReader();
270             this.readFile(input.files[0], reader, (result) => {
271                 if ('keyfile' === uploadType) {
272                     this.myKeyFileName = input.files[0].name;
273                     this.displayParamObjects = this.parameterDefinitionService.processKeyFile(this.myKeyFileName, result);
274                 }
275                 if ('pdfile' === uploadType) {
276                     this.myPdFileName = input.files[0].name;
277                     this.displayParamObjects = this.parameterDefinitionService.processPDfile(this.myPdFileName, result);
278                 }
279             });
280             setTimeout(() => {
281                         /** spinner ends after 3.5 seconds */
282                         this.spinner.hide();
283           }, 3500);
284         }
285     }
286
287     //========================== End of fileChange() Method============================================
288     public readFile(file, reader, callback) {
289         // Set a callback funtion to fire after the file is fully loaded
290         reader.onload = () => {
291             // callback with the results
292             callback(reader.result);
293         };
294         // Read the file
295         reader.readAsText(file, 'UTF-8');
296     }
297
298     //========================== End of readFile() Method============================================
299     fileChangeEvent(fileInput: any) {
300         let obj: any = fileInput.target.files;
301     }
302
303     sourceChanged( data, obj) {
304         if (data == 'A&AI') {
305             obj.ruleTypeValues = appConstants.ruleTypeValues;
306             for (let x = 0; x < 5; x++) {
307                 obj['response-keys'][x]['key-name'] = null;
308                 obj['response-keys'][x]['key-value'] = null;
309             }
310         } else if (data == 'Manual') {
311             obj.ruleTypeValues = [null];
312             obj['rule-type'] = null;
313             obj.showFilterFields = false;
314             for (let x = 0; x < 5; x++) {
315                 obj['response-keys'][x]['key-name'] = null;
316                 obj['response-keys'][x]['key-value'] = null;
317             }
318         }
319         else {
320             obj.ruleTypeValues = [null];
321         }
322     }
323
324     //========================== End of sourceChanged() Method============================================
325     ruleTypeChanged( data, obj) {
326         if (data == null || data == undefined || data == 'null') {
327             obj.showFilterFields = false;
328             obj['rule-type'] = null;
329             for (let x = 0; x < 5; x++) {
330                 obj['response-keys'][x]['key-name'] = null;
331                 obj['response-keys'][x]['key-value'] = null;
332             }
333         } else {
334             let sourceObject = this.ruleTypeConfiguaration[data];
335             if (data == 'vm-name-list' || data == 'vnfc-name-list' || data == 'vnfc-oam-ipv4-address-list') {
336                 this.showFilterFields = false;
337                 obj.showFilterFields = true;
338                 this.filetrByFieldChanged(obj['response-keys'][3]['key-value'], obj);
339             } else {
340                 obj.showFilterFields = false;
341                 obj['response-keys'][3]['key-name'] = null;
342                 obj['response-keys'][3]['key-value'] = null;
343                 obj['response-keys'][4]['key-name'] = null;
344                 obj['response-keys'][4]['key-value'] = null;
345             }
346             for (let x = 0; x < sourceObject.length; x++) {
347                 obj['response-keys'][x]['key-name'] = sourceObject[x]['key-name'];
348                obj['response-keys'][x]['key-value'] = sourceObject[x]['key-value'];
349             }
350         }
351
352     }
353
354     //========================== End of ruleTypeChanged() Method============================================
355     filetrByFieldChanged(data, obj) {
356         if (data == null || data == undefined || data == 'null') {
357             obj.enableFilterByValue = false;
358             obj['response-keys'][4]['key-value'] = null;
359         } else {
360             obj.enableFilterByValue = true;
361         }
362
363     }
364
365
366 }