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 ===================================================================
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
14 http://www.apache.org/licenses/LICENSE-2.0
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.
22 ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 ============LICENSE_END============================================
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';
51 selector: 'app-golden-configuration-mapping',
52 templateUrl: './param-name-value.component.html',
53 styleUrls: ['./param-name-value.component.css']
55 export class GoldenConfigurationMappingComponent implements OnInit, OnDestroy {
56 enableMappingSave: boolean = false;
58 fileName: string = '';
61 configMappingEditorContent: any;
66 downloadedFileName: any;
67 enableSaveToAppc: boolean = false;
68 versionNo: any = '0.0.1';
69 showVersionDiv: boolean = false;
73 enableMappingBrowse: boolean = true;
74 enableDownload: boolean = false;
75 showMappingDownloadDiv: boolean = false;
76 mapppingDownloadType: any;
78 artifactName: any = '';
79 enableMerge: boolean = false;
80 apiToken = localStorage['apiToken'];
81 userId = localStorage['userId'];
84 public uploadTypes = [
86 value: 'Mapping Data',
87 display: 'Sample Json Param File'
90 selectedUploadType: string = this.uploadTypes[0].value;
93 showProgressBar: true,
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 = {};
110 public paramsContent = localStorage['paramsContent'];
111 nameValueSubscription: Subscription;
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,
127 this.artifactRequest.action = '';
128 this.artifactRequest.version = '';
129 this.artifactRequest.paramKeysContent = '';
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;
141 this.artifactRequest.paramsContent = '{}';
144 // refObj = refObj[refObj.length - 1];
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;
162 'scope': { 'vnf-type': '', 'vnfc-type': '' },
165 'download-dg-reference': '',
169 'deviceTemplate': '',
173 this.initialAction = this.item.action;
174 this.subscription = this.activeRoutes.url.subscribe(UrlSegment => {
175 this.actionType = UrlSegment[0].path;
178 if (this.actionType === 'myTemplates') {
179 this.mappingEditorService.fromScreen = 'MappingScreen';
181 this.mappingEditorService.paramData = [];
182 this.identifier = this.mappingEditorService.identifier;
187 //========================== End of ngOnInit() Method============================================
189 $('#filesparam').trigger('click');
192 //========================== End of browseOption() Method============================================
195 this.prepareFileName();
196 if( this.subscription ) { this.subscription.unsubscribe(); }
197 if( this.nameValueSubscription ) { this.nameValueSubscription.unsubscribe(); }
200 //========================== End of ngOnDestroy() Method============================================
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);
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;
216 this.scopeName = this.vnfType;
220 this.enableMappingBrowse = false;
224 //========================== End of ngAfterViewInit() Method============================================
227 public fileParamChange(input) {
228 if (input.files && input.files[0]) {
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;
244 this.enableMerge = true;
245 this.initialData = result;
247 /** spinner ends after 3.5 seconds */
253 this.nService.error("Error", "Incorrect File Format")
254 this.artifactRequest.paramsContent = ''
258 this.nService.error("Error", "Failed to read file");
260 this.myInputParam.nativeElement.value = '';
263 //========================== End of fileParamChange() Method============================================
264 validateUploadedFile(fileExtension) {
266 if (fileExtension.toUpperCase() === 'json'.toUpperCase()) {
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);
281 this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
283 reader.readAsText(file, 'UTF-8');
286 //========================== End of readFile() Method============================================
287 public onParamChanges(data) {
288 this.artifactRequest.paramsContent = data;
289 localStorage['paramsContent'] = this.artifactRequest.paramsContent;
292 //========================== End of onParamChanges() Method============================================
294 updateFileName(action: any, scopeName: any, versionNo: any) {
295 let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
296 this.downloadedFileName = fileName;
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;
306 //========================== End of updateFileNameForConfigScaleOut() Method============================================
307 prepareFileName(): any {
308 let fileNameObject: any = this.mappingEditorService.latestAction;
309 return fileNameObject;
312 //========================== End of prepareFileName() Method============================================
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, '');
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);
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,
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';
343 for (var index in newStringArr) {
344 resultStr = resultStr + newStringArr[index];
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;
353 this.nService.info('Information', 'There are no name value pairs saved in APPC for the selected action!');
355 this.ngProgress.done();
357 error => this.nService.error('Error', 'Error in connecting to APPC Server'));
360 this.ngProgress.done();
364 //========================== End of retrieveNameValueFromAppc() Method============================================
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';
374 for (var index in newStringArr) {
375 resultStr = resultStr + newStringArr[index];
377 resultStr = resultStr.substring(0, resultStr.length - 3) + '\r\n}';
381 //========================== End of formatNameValuePairs() Method============================================
384 var paramNameValuesStr = localStorage['paramsContent'];
385 var pdData = this.paramShareService.getSessionParamData();
386 var paramNameValues = [];
387 var pdDataArrayForParamShare = [];
388 var pdDataArrayForSession = [];
390 paramNameValues = JSON.parse(paramNameValuesStr);
391 if (paramNameValues && paramNameValues != undefined) {
392 for (var index in paramNameValues) {
395 'paramValue': paramNameValues[index]
397 pdDataArrayForParamShare.push(json);
399 pdDataArrayForSession.push({
433 'ruleTypeValues': [null]
438 this.paramShareService.setTemplateData(pdDataArrayForParamShare);
440 if (pdData && pdData != undefined) {
441 for (var i = 0; i < pdDataArrayForSession.length; i++) {
443 pdData.forEach(function (arr2item) {
444 if (pdDataArrayForSession[i].name === arr2item.name) {
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
458 pdDataArrayForSession.splice(i, 1, json);
467 this.paramShareService.setSessionParamData(pdDataArrayForSession);
469 this.router.navigate(['../../../vnfs/design/parameterDefinitions/create']);
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');