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 ===================================================================
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 ============LICENSE_END============================================
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";
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 = sessionStorage['apiToken'];
81 userId = sessionStorage['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: any;
105 public item: any = {};
110 public paramsContent:any;
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
128 this.artifactRequest.action = '';
129 this.artifactRequest.version = '';
130 this.artifactRequest.paramKeysContent = '';
134 var refObj = this.refObj = this.prepareFileName();
135 if (refObj && refObj != undefined) {
137 this.paramsContent=JSON.stringify(JSON.parse(localStorage['paramsContent']))
141 console.log("error parsing param values");
143 if (this.paramsContent && this.paramsContent != undefined && this.paramsContent !== '{}') {
144 this.artifactRequest.paramsContent = this.formatNameValuePairs(this.paramsContent);
148 this.artifactRequest.paramsContent = '{}';
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'];
161 'scope': { 'vnf-type': '', 'vnfc-type': '' },
164 'download-dg-reference': '',
168 'deviceTemplate': '',
172 this.mappingEditorService.paramData = [];
173 this.identifier = this.mappingEditorService.identifier;
177 //========================== End of ngOnInit() Method============================================
179 $('#filesparam').trigger('click');
182 //========================== End of browseOption() Method============================================
184 this.prepareFileName();
185 if( this.subscription ) { this.subscription.unsubscribe(); }
186 // if( this.nameValueSubscription ) { this.nameValueSubscription.unsubscribe(); }
189 //========================== End of ngOnDestroy() Method============================================
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);
197 if (this.vnfcType && this.vnfcType.length != 0) {
198 this.scopeName = this.vnfcType;
201 this.scopeName = this.vnfType;
205 this.enableMappingBrowse = false;
209 //========================== End of ngAfterViewInit() Method============================================
212 public fileParamChange(input) {
213 if (input.files && input.files[0]) {
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;
230 /** spinner ends after 3.5 seconds */
236 this.nService.error("Error", "Incorrect File Format")
237 this.artifactRequest.paramsContent = ''
241 this.nService.error("Error", "Failed to read file");
243 this.myInputParam.nativeElement.value = '';
246 //========================== End of fileParamChange() Method============================================
247 validateUploadedFile(fileExtension) {
249 if (fileExtension.toUpperCase() === 'json'.toUpperCase()) {
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);
265 reader.readAsText(file, 'UTF-8');
268 //========================== End of readFile() Method============================================
269 public onParamChanges(data) {
270 this.artifactRequest.paramsContent = data;
271 localStorage['paramsContent'] = this.artifactRequest.paramsContent;
274 //========================== End of onParamChanges() Method============================================
275 prepareFileName(): any {
276 let fileNameObject: any = this.mappingEditorService.newObject;
277 return fileNameObject;
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, '');
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';
304 for (var index in newStringArr) {
305 resultStr = resultStr + newStringArr[index];
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;
314 this.nService.info('Information', 'There are no name value pairs saved in APPC for the selected action!');
316 this.ngProgress.done();
318 error => this.nService.error('Error', 'Error in connecting to APPC Server'));
321 this.ngProgress.done();
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';
334 for (var index in newStringArr) {
335 resultStr = resultStr + newStringArr[index];
337 resultStr = resultStr.substring(0, resultStr.length - 3) + '\r\n}';
341 //========================== End of formatNameValuePairs() Method============================================
344 var paramNameValuesStr = localStorage['paramsContent'];
345 var pdData = this.paramShareService.getSessionParamData();
346 var paramNameValues = [];
347 var pdDataArrayForParamShare = [];
348 var pdDataArrayForSession = [];
350 paramNameValues = JSON.parse(paramNameValuesStr);
351 if (paramNameValues && paramNameValues != undefined) {
352 for (var index in paramNameValues) {
355 'paramValue': paramNameValues[index]
357 pdDataArrayForParamShare.push(json);
359 pdDataArrayForSession.push({
393 'ruleTypeValues': [null]
398 this.paramShareService.setTemplateData(pdDataArrayForParamShare);
400 if (pdData && pdData != undefined) {
401 for (var i = 0; i < pdDataArrayForSession.length; i++) {
403 pdData.forEach(function (arr2item) {
404 if (pdDataArrayForSession[i].name === arr2item.name) {
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
418 pdDataArrayForSession.splice(i, 1, json);
427 this.paramShareService.setSessionParamData(pdDataArrayForSession);
429 this.router.navigate(['../../../vnfs/design/parameterDefinitions/create']);
434 this.nService.error('Error', 'Error synchronising with name values. Please check the format of json uploaded/ retrieved');