added ansible server functionality
[appc/cdt.git] / src / app / vnfs / build-artifacts / template-holder / param-name-value / param-name-value.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
9 Unless otherwise specified, all software contained herein is licensed
10 under the Apache License, Version 2.0 (the License);
11 you may not use this software except in compliance with the License.
12 You may obtain a copy of the License at
13
14     http://www.apache.org/licenses/LICENSE-2.0
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22 ============LICENSE_END============================================
23 */
24
25 import { Component, ContentChildren, OnInit, QueryList, ViewChild, OnDestroy } from '@angular/core';
26 import { ActivatedRoute, Router } from '@angular/router';
27 import { Subscription } from 'rxjs/Subscription';
28 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
29 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
30 import { GoldenConfigurationComponent } from '../template-configuration/template-configuration.component';
31 import { ArtifactRequest } from '../../../../shared/models/index';
32 import { NotificationService } from '../../../../shared/services/notification.service';
33 import { ModalComponent } from '../../../../shared/modal/modal.component';
34 import { saveAs } from 'file-saver';
35 import { DialogService } from 'ng2-bootstrap-modal';
36 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
37 import { BuildDesignComponent } from '../../build-artifacts.component';
38 import { ParamShareService } from '../../../../shared/services/paramShare.service';
39 import { NotificationsService } from 'angular2-notifications';
40 import { Tab } from './tab';
41 import { environment } from '../../../../../environments/environment';
42 import { NgProgress } from 'ngx-progressbar';
43 import * as XLSX from 'xlsx';
44 import { NgxSpinnerService } from 'ngx-spinner';
45 import {UtilityService} from '../../../../shared/services/utilityService/utility.service';
46 import { APIService } from "../../../../shared/services/cdt.apicall";
47
48 declare var $: any;
49
50 @Component({
51     selector: 'app-golden-configuration-mapping',
52     templateUrl: './param-name-value.component.html',
53     styleUrls: ['./param-name-value.component.css']
54 })
55 export class GoldenConfigurationMappingComponent implements OnInit, OnDestroy {
56     enableMappingSave: boolean = false;
57     aceText: string = '';
58     fileName: string = '';
59     actionType: any = '';
60     modal: any;
61     configMappingEditorContent: any;
62     fileType: any = '';
63     myfileName: any;
64     initialData: any;
65     scopeName: any;
66     downloadedFileName: any;
67     enableSaveToAppc: boolean = false;
68     versionNo: any = '0.0.1';
69     showVersionDiv: boolean = false;
70     initialAction: any;
71     title: any;
72     message: any;
73     enableMappingBrowse: boolean = true;
74     enableDownload: boolean = false;
75     showMappingDownloadDiv: boolean = false;
76     mapppingDownloadType: any;
77     action: any = '';
78     artifactName: any = '';
79     enableMerge: boolean = false;
80     apiToken = localStorage['apiToken'];
81     userId = localStorage['userId'];
82     identifier: any;
83
84     public uploadTypes = [
85         {
86             value: 'Mapping Data',
87             display: 'Sample Json Param File'
88         }
89     ];
90     selectedUploadType: string = this.uploadTypes[0].value;
91     options = {
92         timeOut: 1000,
93         showProgressBar: true,
94         pauseOnHover: true,
95         clickToClose: true,
96         maxLength: 200
97     };
98     artifactRequest: ArtifactRequest = new ArtifactRequest();
99     @ViewChild(GoldenConfigurationComponent) mappingComponent: GoldenConfigurationComponent;
100     @ViewChild('templateeditor') templateeditor;
101     @ViewChild('myInputParam') myInputParam: any;
102     @ViewChild(ModalComponent) modalComponent: ModalComponent;
103     @ContentChildren(Tab) tabs: QueryList<Tab>;
104     public subscription: any;
105     public item: any = {};
106     vnfType: any = '';
107     vnfcType: any = '';
108     protocol: any = '';
109     refObj: any;
110     public paramsContent:any;
111
112     constructor(
113         private buildDesignComponent: BuildDesignComponent,
114         private paramShareService: ParamShareService,
115         private router: Router,
116         private httpUtil: HttpUtilService,
117         private dialogService: DialogService,
118         private activeRoutes: ActivatedRoute,
119         private mappingEditorService: MappingEditorService,
120         private notificationService: NotificationService,
121         private nService: NotificationsService,
122         private ngProgress: NgProgress,
123         private spinner: NgxSpinnerService,
124         private apiService:APIService, 
125         private utilityService: UtilityService
126         
127     ) {
128         this.artifactRequest.action = '';
129         this.artifactRequest.version = '';
130         this.artifactRequest.paramKeysContent = '';
131     }
132
133     ngOnInit() {
134         var refObj = this.refObj = this.prepareFileName();
135         if (refObj && refObj != undefined) {
136             try{
137                 this.paramsContent=JSON.stringify(JSON.parse(localStorage['paramsContent']))
138             }
139             catch(e)
140             {
141                 console.log("error parsing param values");
142             }
143             if (this.paramsContent && this.paramsContent != undefined && this.paramsContent !== '{}') {
144                 this.artifactRequest.paramsContent = this.formatNameValuePairs(this.paramsContent);
145                 
146             }
147             else {
148                 this.artifactRequest.paramsContent = '{}';
149             }
150
151             this.item = refObj;
152             this.vnfType = this.item.vnf;
153             this.vnfcType = this.item.vnfc;
154             this.protocol = this.item.protocol;
155             this.action = this.item.action;
156             var artifactList = this.item['artifact-list'];
157         }
158         else {
159             this.item = {
160                 'action': '',
161                 'scope': { 'vnf-type': '', 'vnfc-type': '' },
162                 'vm': [],
163                 'protocol': '',
164                 'download-dg-reference': '',
165                 'user-name': '',
166                 'port-number': '',
167                 'artifact-list': [],
168                 'deviceTemplate': '',
169                 'scopeType': ''
170             };
171         }
172         this.mappingEditorService.paramData = [];
173         this.identifier = this.mappingEditorService.identifier;
174
175     }
176
177     //========================== End of ngOnInit() Method============================================
178     browseOption() {
179         $('#filesparam').trigger('click');
180     }
181
182     //========================== End of browseOption() Method============================================
183     ngOnDestroy() {
184         this.prepareFileName();
185         if( this.subscription ) { this.subscription.unsubscribe(); }
186        // if( this.nameValueSubscription ) { this.nameValueSubscription.unsubscribe(); }
187     }
188
189     //========================== End of ngOnDestroy() Method============================================
190     ngAfterViewInit() {
191         this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
192         this.fileType = sessionStorage.getItem('fileType');
193         if (this.configMappingEditorContent)
194           this.mappingEditorService.initialise(this.mappingComponent.templateeditor.getEditor(), this.configMappingEditorContent);
195         
196         if (this.refObj) {
197             if (this.vnfcType && this.vnfcType.length != 0) {
198                 this.scopeName = this.vnfcType;
199             }
200             else {
201                 this.scopeName = this.vnfType;
202             }
203         }
204         else {
205             this.enableMappingBrowse = false;
206         }
207     }
208
209     //========================== End of ngAfterViewInit() Method============================================
210
211
212     public fileParamChange(input) {
213         if (input.files && input.files[0]) {
214             this.spinner.show();
215             this.enableMappingSave = true;
216             this.myfileName = input.files[0].name;
217             var fileExtension = this.myfileName.substr(this.myfileName.lastIndexOf('.') + 1);
218             if (this.validateUploadedFile(fileExtension)) {
219                 // Create the file reader
220                 let reader = new FileReader();
221                 this.readFile(input.files[0], reader, (result) => {
222                     var jsonObject = JSON.parse(result);
223                     this.artifactRequest.paramsContent = JSON.stringify(jsonObject, null, 1);
224                     this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
225                     this.mappingEditorService.setParamContent(this.artifactRequest.paramsContent);
226                     localStorage['paramsContent'] = this.artifactRequest.paramsContent;
227                     this.enableMerge = true;
228                     this.initialData = result;
229                     setTimeout(() => {
230                         /** spinner ends after 3.5 seconds */
231                         this.spinner.hide();
232                     }, 3500);
233                 });
234             }
235             else {
236                 this.nService.error("Error", "Incorrect File Format")
237                 this.artifactRequest.paramsContent = ''
238             }
239         }
240         else {
241             this.nService.error("Error", "Failed to read file");
242         }
243         this.myInputParam.nativeElement.value = '';
244     }
245
246     //========================== End of fileParamChange() Method============================================
247     validateUploadedFile(fileExtension) {
248
249         if (fileExtension.toUpperCase() === 'json'.toUpperCase()) {
250             return true;
251         }
252         else {
253             return false;
254         }
255
256     }
257     //========================== End of validateUploadedFile() Method============================================
258     public readFile(file, reader, callback) {
259         // Set a callback funtion to fire after the file is fully loaded
260         reader.onload = () => {
261             // callback with the results
262             callback(reader.result);
263         };
264         // Read the file
265         reader.readAsText(file, 'UTF-8');
266     }
267
268     //========================== End of readFile() Method============================================
269     public onParamChanges(data) {
270         this.artifactRequest.paramsContent = data;
271         localStorage['paramsContent'] = this.artifactRequest.paramsContent;
272     }
273
274     //========================== End of onParamChanges() Method============================================
275     prepareFileName(): any {
276         let fileNameObject: any = this.mappingEditorService.newObject;
277         return fileNameObject;
278     }
279
280     //========================== End of prepareFileName() Method============================================
281     retrieveNameValueFromAppc() {
282         let refObj = this.refObj;
283         if (refObj && refObj != undefined) {
284             this.enableMerge = true;
285             var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
286             let fileName = '';
287             fileName=refObj["param_artifact"]
288             let input=this.utilityService.createPayloadForRetrieve(false, this.item.action, this.vnfType, fileName);
289             let artifactContent: any;
290             this.ngProgress.start();
291             this.apiService.callGetArtifactsApi(input).subscribe(resp => {
292                 if (resp.output.status.code === '400' && resp.output.status.message === 'success') {
293                     this.nService.success('Success', 'Name/value pairs retrieved successfully from APPC');
294                     this.enableMerge = true;
295                     let result = JSON.parse(resp.output.data.block).artifactInfo[0];
296                     result = result['artifact-content'];
297                     var string = result.substring(2, result.length - 2);
298                     var stringArr = string.split(',');
299                     var newStringArr = [];
300                     var resultStr = '{\r\n';
301                     for (var index in stringArr) {
302                         newStringArr[index] = stringArr[index] + ',\r\n';
303                     }
304                     for (var index in newStringArr) {
305                         resultStr = resultStr + newStringArr[index];
306                     }
307                     resultStr = resultStr.substring(0, resultStr.length - 3) + '\r\n}';
308                     this.artifactRequest.paramsContent = resultStr;
309                     this.mappingEditorService.setParamContent(resultStr);
310                     localStorage['paramsContent'] = resultStr;
311                     this.enableMappingSave = true;
312                 }
313                 else {
314                     this.nService.info('Information', 'There are no name value pairs saved in APPC for the selected action!');
315                 }
316                 this.ngProgress.done();
317             },
318                 error => this.nService.error('Error', 'Error in connecting to APPC Server'));
319         }
320         setTimeout(() => {
321             this.ngProgress.done();
322         }, 3500);
323     }
324
325     //========================== End of retrieveNameValueFromAppc() Method============================================
326     formatNameValuePairs(namevaluePairs: string) {
327         var string = namevaluePairs.substring(1, namevaluePairs.length - 1);
328         var stringArr = string.split(',');
329         var newStringArr = [];
330         var resultStr = '{\r\n';
331         for (var index in stringArr) {
332             newStringArr[index] = stringArr[index] + ',\r\n';
333         }
334         for (var index in newStringArr) {
335             resultStr = resultStr + newStringArr[index];
336         }
337         resultStr = resultStr.substring(0, resultStr.length - 3) + '\r\n}';
338         return resultStr;
339     }
340
341     //========================== End of formatNameValuePairs() Method============================================
342
343     public syncParam() {
344         var paramNameValuesStr = localStorage['paramsContent'];
345         var pdData = this.paramShareService.getSessionParamData();
346         var paramNameValues = [];
347         var pdDataArrayForParamShare = [];
348         var pdDataArrayForSession = [];
349         try {
350             paramNameValues = JSON.parse(paramNameValuesStr);
351             if (paramNameValues && paramNameValues != undefined) {
352                 for (var index in paramNameValues) {
353                     var json = {
354                         'paramName': index,
355                         'paramValue': paramNameValues[index]
356                     };
357                     pdDataArrayForParamShare.push(json);
358
359                     pdDataArrayForSession.push({
360                         'name': index,
361                         'type': null,
362                         'description': null,
363                         'required': null,
364                         'default': null,
365                         'source': 'Manual',
366                         'rule-type': null,
367                         'request-keys': [{
368                             'key-name': null,
369                             'key-value': null
370                         }, {
371                             'key-name': null,
372                             'key-value': null
373                         }, {
374                             'key-name': null,
375                             'key-value': null
376                         }],
377                         'response-keys': [{
378                             'key-name': null,
379                             'key-value': null
380                         }, {
381                             'key-name': null,
382                             'key-value': null
383                         }, {
384                             'key-name': null,
385                             'key-value': null
386                         }, {
387                             'key-name': null,
388                             'key-value': null
389                         }, {
390                             'key-name': null,
391                             'key-value': null
392                         }],
393                         'ruleTypeValues': [null]
394
395                     });
396
397                 }
398                 this.paramShareService.setTemplateData(pdDataArrayForParamShare);
399
400                 if (pdData && pdData != undefined) {
401                     for (var i = 0; i < pdDataArrayForSession.length; i++) {
402
403                         pdData.forEach(function (arr2item) {
404                             if (pdDataArrayForSession[i].name === arr2item.name) {
405
406                                 var json = {
407                                     'name': arr2item.name,
408                                     'type': arr2item.type,
409                                     'description': arr2item.description,
410                                     'required': arr2item.required,
411                                     'default': arr2item.default,
412                                     'source': arr2item.source,
413                                     'rule-type': arr2item['rule-type'],
414                                     'request-keys': arr2item['request-keys'],
415                                     'response-keys': arr2item['response-keys'],
416                                     'ruleTypeValues': arr2item.ruleTypeValues
417                                 };
418                                 pdDataArrayForSession.splice(i, 1, json);
419                                 
420                             }
421
422                         });
423
424                     }
425                 }
426
427                 this.paramShareService.setSessionParamData(pdDataArrayForSession);
428
429                 this.router.navigate(['../../../vnfs/design/parameterDefinitions/create']);
430
431             }
432         }
433         catch (error) {
434             this.nService.error('Error', 'Error synchronising with name values. Please check the format of json uploaded/ retrieved');
435         }
436     }
437
438 }