added ansible server functionality
[appc/cdt.git] / src / app / vnfs / build-artifacts / parameter-definitions / parameter.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 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 = localStorage['apiToken'];
76     userId = localStorage['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     ];
93     public uploadTypes = appConstants.uploadTypes;
94
95     options = appConstants.optionsToNotificationComponent;
96     public vnfcTypeData: string = '';
97     public selectedUploadType: string;
98     @ViewChild(ModalComponent) modalComponent: ModalComponent;
99     public title: string;
100     public parameterDefinitionMap: { [index: string]: string; } = {};
101     public parameterNameValues = {};
102     public displayParamObjects;
103     public modelParamDefinitionObjects;
104     public vnfType: any;
105     vnfcType: any;
106     protocol: any;
107     public refNameObj = {};
108     public action;
109     public artifactName;
110     public appDataObject: any;
111     public downloadDataObject: any;
112     public artifact_fileName="";
113     template_id: any;
114     private selectedActionReference: any;
115
116     constructor(private httpService: HttpUtilService,
117         private apiService:APIService,
118         private parameterDefinitionService: ParameterDefinitionService,
119         private paramShareService: ParamShareService,
120         private mappingEditorService: MappingEditorService,
121         private httpUtil: HttpUtilService,
122         private utilService: UtilityService,
123         private nService: NotificationsService,
124         private ngProgress: NgProgress,
125         private spinner: NgxSpinnerService) {
126     }
127
128     ngOnInit() {
129       var methName= "ngOnInit";
130         this.selectedActionReference = this.mappingEditorService.newObject;
131         if (this.selectedActionReference && this.selectedActionReference != undefined) {
132           this.vnfType = this.selectedActionReference.vnf;
133           this.protocol = this.selectedActionReference.protocol;
134           this.action = this.selectedActionReference.action;
135           if( this.utilService.getTracelvl() > 0 )
136             console.log( this.clName+": "+methName+": vnfType:["+this.vnfType+
137               "] action:["+this.action+"] protocol:["+this.protocol+"]");
138             if(this.selectedActionReference.vnfc) {
139                 this.vnfcType = this.selectedActionReference.vnfc;
140               if( this.utilService.getTracelvl() > 0 )
141                 console.log( this.clName+": "+methName+": have vnfcType:["+
142                   this.vnfcType+"]");
143             }
144             if( this.action === 'ConfigScaleOut'){
145                 // this.template_id = this.selectedActionReference.templateId;
146                 this.template_id = this.mappingEditorService.identifier;
147             }
148             this.artifact_fileName = this.selectedActionReference.pd_artifact;
149             this.parameterDefinitionService.setValues(this.vnfType, this.vnfcType, this.protocol, this.action, this.artifact_fileName);
150         }
151         else {
152             this.selectedActionReference = {
153                 'action': '',
154                 'scope': { 'vnf-type': '', 'vnfc-type': '' },
155                 'vm': [],
156                 'protocol': '',
157                 'download-dg-reference': '',
158                 'user-name': '',
159                 'port-number': '',
160                 'artifact-list': [],
161                 'deviceTemplate': '',
162                 'scopeType': ''
163             };
164         }
165         //let path = this.location.path
166         /* this.activeRoutes.url.subscribe(UrlSegment => {
167              this.actionType = UrlSegment[0].path
168          })
169          */
170     }
171
172     ngAfterViewInit() {
173         if( this.mappingEditorService.latestAction) {
174             this.displayParamObjects = [];
175             this.modelParamDefinitionObjects = [];
176             this.displayParamObjects= this.paramShareService.getSessionParamData();
177          // if( this.paramShareService.getSessionParamData() != undefined &&
178          //     this.paramShareService.getSessionParamData().length > 0)
179             if( this.displayParamObjects != undefined &&
180                 this.displayParamObjects.length > 0 )
181             {
182               this.parameterDefinitionService.populateDataUponSource( this.displayParamObjects);
183             } else {
184               this.getPD();
185             }
186         } else {
187             this.nService.error(appConstants.errors.error, appConstants.errors["noAction&VNFTypeInRDscreenError"]);
188         }
189         return this.displayParamObjects;
190     }
191
192
193     public getPD() {
194         let result: any;
195         let input=
196           this.utilService.createPayloadForRetrieve( false, this.action, this.vnfType,this.artifact_fileName);
197         let artifactContent: any;
198         this.ngProgress.start();
199         return this.apiService.callGetArtifactsApi(input).subscribe( data => {
200             if( this.utilService.checkResult(data)) {
201               let result: any = JSON.parse(data.output.data.block).artifactInfo[0];
202                 var pdObject = YAML.parse(result['artifact-content']);
203                 let fileModel = pdObject['vnf-parameter-list'];
204                 this.displayParamObjects = this.parameterDefinitionService.populatePD(fileModel);
205             }
206             else {
207             }
208             this.ngProgress.done();
209         },
210
211             error => this.nService.error(appConstants.errors.error, appConstants.errors.connectionError));
212
213     }
214
215     public getPDFromSession() {
216
217       this.ngProgress.start();
218         return this.httpService.get({
219             url: 'testurl',
220         }).subscribe( data => {
221            this.displayParamObjects = this.paramShareService.getSessionParamData();
222            this.ngProgress.done();
223         },
224         error => {
225           this.displayParamObjects = this.paramShareService.getSessionParamData();
226           this.ngProgress.done();
227         });
228     }
229
230     selectedNavItem(item: any) {
231         this.item = item;
232     }
233
234     //========================== End of selectedNavItem() Method============================================
235     browsePdFile() {
236         $('#inputFile1').trigger('click');
237     }
238
239     //========================== End of browsePdFile() Method============================================
240     browseKeyFile() {
241         $('#inputFile2').trigger('click');
242
243     }
244
245     //========================== End of browseKeyFile() Method============================================
246
247
248     //========================== End of appendSlashes() Method============================================
249
250
251     //========================== End of prepareFileName() Method============================================
252     ngOnDestroy() {
253         this.parameterDefinitionService.destroy(this.displayParamObjects);
254     }
255
256     //========================== End of ngOnDestroy() Method============================================
257
258     public showUpload() {
259         this.selectedUploadType = this.uploadTypes[0].value;
260     };
261
262     //========================== End of showUpload() Method============================================
263     //This is called when the user selects new files from the upload button
264     public fileChange(input, uploadType) {
265         if (input.files && input.files[0]) {
266             this.spinner.show();
267             // Create the file reader
268             let reader = new FileReader();
269             this.readFile(input.files[0], reader, (result) => {
270                 if ('keyfile' === uploadType) {
271                     this.myKeyFileName = input.files[0].name;
272                     this.displayParamObjects = this.parameterDefinitionService.processKeyFile(this.myKeyFileName, result);
273                 }
274                 if ('pdfile' === uploadType) {
275                     this.myPdFileName = input.files[0].name;
276                     this.displayParamObjects = this.parameterDefinitionService.processPDfile(this.myPdFileName, result);
277                 }
278             });
279             setTimeout(() => {
280                         /** spinner ends after 3.5 seconds */
281                         this.spinner.hide();
282           }, 3500);
283         }
284     }
285
286     //========================== End of fileChange() Method============================================
287     public readFile(file, reader, callback) {
288         // Set a callback funtion to fire after the file is fully loaded
289         reader.onload = () => {
290             // callback with the results
291             callback(reader.result);
292         };
293         // Read the file
294         reader.readAsText(file, 'UTF-8');
295     }
296
297     //========================== End of readFile() Method============================================
298     fileChangeEvent(fileInput: any) {
299         let obj: any = fileInput.target.files;
300     }
301
302     sourceChanged( data, obj) {
303         if (data == 'A&AI') {
304             obj.ruleTypeValues = appConstants.ruleTypeValues;
305             for (let x = 0; x < 5; x++) {
306                 obj['response-keys'][x]['key-name'] = null;
307                 obj['response-keys'][x]['key-value'] = null;
308             }
309         } else if (data == 'Manual') {
310             obj.ruleTypeValues = [null];
311             obj['rule-type'] = null;
312             obj.showFilterFields = false;
313             for (let x = 0; x < 5; x++) {
314                 obj['response-keys'][x]['key-name'] = null;
315                 obj['response-keys'][x]['key-value'] = null;
316             }
317         }
318         else {
319             obj.ruleTypeValues = [null];
320         }
321     }
322
323     //========================== End of sourceChanged() Method============================================
324     ruleTypeChanged( data, obj) {
325         if (data == null || data == undefined || data == 'null') {
326             obj.showFilterFields = false;
327             obj['rule-type'] = null;
328             for (let x = 0; x < 5; x++) {
329                 obj['response-keys'][x]['key-name'] = null;
330                 obj['response-keys'][x]['key-value'] = null;
331             }
332         } else {
333             let sourceObject = this.ruleTypeConfiguaration[data];
334             if (data == 'vm-name-list' || data == 'vnfc-name-list' || data == 'vnfc-oam-ipv4-address-list') {
335                 this.showFilterFields = false;
336                 obj.showFilterFields = true;
337                 this.filetrByFieldChanged(obj['response-keys'][3]['key-value'], obj);
338             } else {
339                 obj.showFilterFields = false;
340                 obj['response-keys'][3]['key-name'] = null;
341                 obj['response-keys'][3]['key-value'] = null;
342                 obj['response-keys'][4]['key-name'] = null;
343                 obj['response-keys'][4]['key-value'] = null;
344             }
345             for (let x = 0; x < sourceObject.length; x++) {
346                 obj['response-keys'][x]['key-name'] = sourceObject[x]['key-name'];
347                obj['response-keys'][x]['key-value'] = sourceObject[x]['key-value'];
348             }
349         }
350
351     }
352
353     //========================== End of ruleTypeChanged() Method============================================
354     filetrByFieldChanged(data, obj) {
355         if (data == null || data == undefined || data == 'null') {
356             obj.enableFilterByValue = false;
357             obj['response-keys'][4]['key-value'] = null;
358         } else {
359             obj.enableFilterByValue = true;
360         }
361
362     }
363
364
365 }