40a5291f87bf935721cfc230c77ad543472063f8
[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 ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 ============LICENSE_END============================================
24 */
25
26 import { Component, ContentChildren, OnInit, QueryList, ViewChild, OnDestroy } from '@angular/core';
27 import { ActivatedRoute, Router } from '@angular/router';
28 import { Subscription } from 'rxjs/Subscription';
29 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
30 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
31 import { GoldenConfigurationComponent } from '../template-configuration/template-configuration.component';
32 import { ArtifactRequest } from '../../../../shared/models/index';
33 import { NotificationService } from '../../../../shared/services/notification.service';
34 import { ModalComponent } from '../../../../shared/modal/modal.component';
35 import { saveAs } from 'file-saver';
36 import { DialogService } from 'ng2-bootstrap-modal';
37 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
38 import { BuildDesignComponent } from '../../build-artifacts.component';
39 import { ParamShareService } from '../../../../shared/services/paramShare.service';
40 import { NotificationsService } from 'angular2-notifications';
41 import { Tab } from './tab';
42 import { environment } from '../../../../../environments/environment';
43 import { NgProgress } from 'ngx-progressbar';
44 import * as XLSX from 'xlsx';
45 import { NgxSpinnerService } from 'ngx-spinner';
46 import {UtilityService} from '../../../../shared/services/utilityService/utility.service';
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: Subscription;
105     public item: any = {};
106     vnfType: any = '';
107     vnfcType: any = '';
108     protocol: any = '';
109     refObj: any;
110     public paramsContent = localStorage['paramsContent'];
111     nameValueSubscription: Subscription;
112
113     constructor(
114         private buildDesignComponent: BuildDesignComponent,
115         private paramShareService: ParamShareService,
116         private router: Router,
117         private httpUtil: HttpUtilService,
118         private dialogService: DialogService,
119         private activeRoutes: ActivatedRoute,
120         private mappingEditorService: MappingEditorService,
121         private notificationService: NotificationService,
122         private nService: NotificationsService,
123         private ngProgress: NgProgress,
124         private spinner: NgxSpinnerService,
125         private utilityService: UtilityService,
126     ) {
127         this.artifactRequest.action = '';
128         this.artifactRequest.version = '';
129         this.artifactRequest.paramKeysContent = '';
130     }
131
132     ngOnInit() {
133         var refObj = this.refObj = this.prepareFileName();
134         if (refObj && refObj != undefined) {
135             if (this.paramsContent && this.paramsContent != undefined && this.paramsContent !== '{}') {
136                 this.artifactRequest.paramsContent = this.formatNameValuePairs(this.paramsContent);
137                 // this.artifactRequest.paramsContent = this.paramsContent;
138
139             }
140             else {
141                 this.artifactRequest.paramsContent = '{}';
142             }
143
144             //  refObj = refObj[refObj.length - 1];
145             this.item = refObj;
146             this.vnfType = this.item.scope['vnf-type'];
147             this.vnfcType = this.item.scope['vnfc-type'];
148             this.protocol = this.item['device-protocol'];
149             this.action = this.item.action;
150             var artifactList = this.item['artifact-list'];
151             for (var i = 0; i < artifactList.length; i++) {
152                 var artifactName = artifactList[i]['artifact-name'];
153                 var array = artifactName.split('_');
154                 if (array[0].toUpperCase() === 'TEMPLATE') {
155                     this.artifactName = artifactName;
156                 }
157             }
158         }
159         else {
160             this.item = {
161                 'action': '',
162                 'scope': { 'vnf-type': '', 'vnfc-type': '' },
163                 'vm': [],
164                 'protocol': '',
165                 'download-dg-reference': '',
166                 'user-name': '',
167                 'port-number': '',
168                 'artifact-list': [],
169                 'deviceTemplate': '',
170                 'scopeType': ''
171             };
172         }
173         this.initialAction = this.item.action;
174         this.subscription = this.activeRoutes.url.subscribe(UrlSegment => {
175             this.actionType = UrlSegment[0].path;
176         });
177
178         if (this.actionType === 'myTemplates') {
179             this.mappingEditorService.fromScreen = 'MappingScreen';
180         }
181         this.mappingEditorService.paramData = [];
182         this.identifier = this.mappingEditorService.identifier;
183
184
185     }
186
187     //========================== End of ngOnInit() Method============================================
188     browseOption() {
189         $('#filesparam').trigger('click');
190     }
191
192     //========================== End of browseOption() Method============================================
193
194     ngOnDestroy() {
195         this.prepareFileName();
196         if( this.subscription ) { this.subscription.unsubscribe(); }
197         if( this.nameValueSubscription ) { this.nameValueSubscription.unsubscribe(); }
198     }
199
200     //========================== End of ngOnDestroy() Method============================================
201     ngAfterViewInit() {
202         if (this.mappingEditorService.fromScreen === 'MappingScreen') {
203             this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
204             this.fileType = sessionStorage.getItem('fileType');
205             if (this.configMappingEditorContent)
206                 this.mappingEditorService.initialise(this.mappingComponent.templateeditor.getEditor(), this.configMappingEditorContent, this.modal);
207         }
208         if (this.refObj) {
209
210             this.artifactRequest.action = this.item.action;
211             this.artifactRequest.vnfType = this.vnfType;
212             if (this.vnfcType && this.vnfcType.length != 0) {
213                 this.scopeName = this.vnfcType;
214             }
215             else {
216                 this.scopeName = this.vnfType;
217             }
218         }
219         else {
220             this.enableMappingBrowse = false;
221         }
222     }
223
224     //========================== End of ngAfterViewInit() Method============================================
225
226
227     public fileParamChange(input) {
228         if (input.files && input.files[0]) {
229             this.spinner.show();
230             this.enableMappingSave = true;
231             this.myfileName = input.files[0].name;
232             var fileExtension = this.myfileName.substr(this.myfileName.lastIndexOf('.') + 1);
233             if (this.validateUploadedFile(fileExtension)) {
234                 // Create the file reader
235                 let reader = new FileReader();
236                 this.readFile(input.files[0], reader, (result) => {
237                     if ('Mapping Data' === this.selectedUploadType) {
238                         var jsonObject = JSON.parse(result);
239                         this.artifactRequest.paramsContent = JSON.stringify(jsonObject, null, 1);
240                         this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
241                         this.mappingEditorService.setParamContent(this.artifactRequest.paramsContent);
242                         localStorage['paramsContent'] = this.artifactRequest.paramsContent;
243                     }
244                     this.enableMerge = true;
245                     this.initialData = result;
246                     setTimeout(() => {
247                         /** spinner ends after 3.5 seconds */
248                         this.spinner.hide();
249                     }, 3500);
250                 });
251             }
252             else {
253                 this.nService.error("Error", "Incorrect File Format")
254                 this.artifactRequest.paramsContent = ''
255             }
256         }
257         else {
258             this.nService.error("Error", "Failed to read file");
259         }
260         this.myInputParam.nativeElement.value = '';
261     }
262
263     //========================== End of fileParamChange() Method============================================
264     validateUploadedFile(fileExtension) {
265
266         if (fileExtension.toUpperCase() === 'json'.toUpperCase()) {
267             return true;
268         }
269         else {
270             return false;
271         }
272
273     }
274     //========================== End of validateUploadedFile() Method============================================
275     public readFile(file, reader, callback) {
276         // Set a callback funtion to fire after the file is fully loaded
277         reader.onload = () => {
278             // callback with the results
279             callback(reader.result);
280         };
281         this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
282         // Read the file
283         reader.readAsText(file, 'UTF-8');
284     }
285
286     //========================== End of readFile() Method============================================
287     public onParamChanges(data) {
288         this.artifactRequest.paramsContent = data;
289         localStorage['paramsContent'] = this.artifactRequest.paramsContent;
290     }
291
292     //========================== End of onParamChanges() Method============================================
293
294     updateFileName(action: any, scopeName: any, versionNo: any) {
295         let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
296         this.downloadedFileName = fileName;
297         return fileName;
298     }
299
300     //========================== End of updateFileName() Method============================================
301     updateFileNameForConfigScaleOut(action: any, scopeName: any, versionNo: any, id: any) {
302         let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V_' + id + '.json';
303         this.downloadedFileName = fileName;
304         return fileName;
305     }
306     //========================== End of updateFileNameForConfigScaleOut() Method============================================
307     prepareFileName(): any {
308         let fileNameObject: any = this.mappingEditorService.latestAction;
309         return fileNameObject;
310     }
311
312     //========================== End of prepareFileName() Method============================================
313
314     retrieveNameValueFromAppc() {
315         let refObj = this.refObj;
316         if (refObj && refObj != undefined) {
317             this.enableMerge = true;
318             var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
319             let fileName = '';
320             let id = this.mappingEditorService.identifier;
321             if (id) fileName = this.updateFileNameForConfigScaleOut(this.item.action, scopeName, this.versionNo, id);
322             else fileName = this.updateFileName(this.item.action, scopeName, this.versionNo);
323
324             let input=this.utilityService.createPayloadForRetrieve(false, this.item.action, this.vnfType, fileName);
325             let artifactContent: any;
326             this.ngProgress.start();
327             this.nameValueSubscription = this.httpUtil.post({
328                 url: environment.getDesigns,
329                 data: input
330             }).subscribe(resp => {
331                 if (resp.output.status.code === '400' && resp.output.status.message === 'success') {
332                     this.nService.success('Success', 'Name/value pairs retrieved successfully from APPC');
333                     this.enableMerge = true;
334                     let result = JSON.parse(resp.output.data.block).artifactInfo[0];
335                     result = result['artifact-content'];
336                     var string = result.substring(2, result.length - 2);
337                     var stringArr = string.split(',');
338                     var newStringArr = [];
339                     var resultStr = '{\r\n';
340                     for (var index in stringArr) {
341                         newStringArr[index] = stringArr[index] + ',\r\n';
342                     }
343                     for (var index in newStringArr) {
344                         resultStr = resultStr + newStringArr[index];
345                     }
346                     resultStr = resultStr.substring(0, resultStr.length - 3) + '\r\n}';
347                     this.artifactRequest.paramsContent = resultStr;
348                     this.mappingEditorService.setParamContent(resultStr);
349                     localStorage['paramsContent'] = resultStr;
350                     this.enableMappingSave = true;
351                 }
352                 else {
353                     this.nService.info('Information', 'There are no name value pairs saved in APPC for the selected action!');
354                 }
355                 this.ngProgress.done();
356             },
357                 error => this.nService.error('Error', 'Error in connecting to APPC Server'));
358         }
359         setTimeout(() => {
360             this.ngProgress.done();
361         }, 3500);
362     }
363
364     //========================== End of retrieveNameValueFromAppc() Method============================================
365
366     formatNameValuePairs(namevaluePairs: string) {
367         var string = namevaluePairs.substring(1, namevaluePairs.length - 1);
368         var stringArr = string.split(',');
369         var newStringArr = [];
370         var resultStr = '{\r\n';
371         for (var index in stringArr) {
372             newStringArr[index] = stringArr[index] + ',\r\n';
373         }
374         for (var index in newStringArr) {
375             resultStr = resultStr + newStringArr[index];
376         }
377         resultStr = resultStr.substring(0, resultStr.length - 3) + '\r\n}';
378         return resultStr;
379     }
380
381     //========================== End of formatNameValuePairs() Method============================================
382
383     public syncParam() {
384         var paramNameValuesStr = localStorage['paramsContent'];
385         var pdData = this.paramShareService.getSessionParamData();
386         var paramNameValues = [];
387         var pdDataArrayForParamShare = [];
388         var pdDataArrayForSession = [];
389         try {
390             paramNameValues = JSON.parse(paramNameValuesStr);
391             if (paramNameValues && paramNameValues != undefined) {
392                 for (var index in paramNameValues) {
393                     var json = {
394                         'paramName': index,
395                         'paramValue': paramNameValues[index]
396                     };
397                     pdDataArrayForParamShare.push(json);
398
399                     pdDataArrayForSession.push({
400                         'name': index,
401                         'type': null,
402                         'description': null,
403                         'required': null,
404                         'default': null,
405                         'source': 'Manual',
406                         'rule-type': null,
407                         'request-keys': [{
408                             'key-name': null,
409                             'key-value': null
410                         }, {
411                             'key-name': null,
412                             'key-value': null
413                         }, {
414                             'key-name': null,
415                             'key-value': null
416                         }],
417                         'response-keys': [{
418                             'key-name': null,
419                             'key-value': null
420                         }, {
421                             'key-name': null,
422                             'key-value': null
423                         }, {
424                             'key-name': null,
425                             'key-value': null
426                         }, {
427                             'key-name': null,
428                             'key-value': null
429                         }, {
430                             'key-name': null,
431                             'key-value': null
432                         }],
433                         'ruleTypeValues': [null]
434
435                     });
436
437                 }
438                 this.paramShareService.setTemplateData(pdDataArrayForParamShare);
439
440                 if (pdData && pdData != undefined) {
441                     for (var i = 0; i < pdDataArrayForSession.length; i++) {
442
443                         pdData.forEach(function (arr2item) {
444                             if (pdDataArrayForSession[i].name === arr2item.name) {
445
446                                 var json = {
447                                     'name': arr2item.name,
448                                     'type': arr2item.type,
449                                     'description': arr2item.description,
450                                     'required': arr2item.required,
451                                     'default': arr2item.default,
452                                     'source': arr2item.source,
453                                     'rule-type': arr2item['rule-type'],
454                                     'request-keys': arr2item['request-keys'],
455                                     'response-keys': arr2item['response-keys'],
456                                     'ruleTypeValues': arr2item.ruleTypeValues
457                                 };
458                                 pdDataArrayForSession.splice(i, 1, json);
459
460                             }
461
462                         });
463
464                     }
465                 }
466
467                 this.paramShareService.setSessionParamData(pdDataArrayForSession);
468
469                 this.router.navigate(['../../../vnfs/design/parameterDefinitions/create']);
470
471             }
472         }
473         catch (error) {
474             console.log('Error occured in syncing param names' + JSON.stringify(error));
475             this.nService.error('Error', 'Error synchronising with name values. Please check the format of json uploaded/ retrieved');
476         }
477     }
478
479 }