2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
5 ===================================================================
7 Unless otherwise specified, all software contained herein is licensed
8 under the Apache License, Version 2.0 (the License);
9 you may not use this software except in compliance with the License.
10 You may obtain a copy of the License at
12 http://www.apache.org/licenses/LICENSE-2.0
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
20 ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 ============LICENSE_END============================================
24 import { Component, Input, OnInit, ViewChild } from '@angular/core';
25 //import { ModalComponent } from '../../modal/modal.component';
26 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
27 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
28 import { ArtifactRequest } from '../../../../shared/models/index';
29 import { ActivatedRoute, Router } from '@angular/router';
30 import { saveAs } from 'file-saver';
31 import { NotificationService } from '../../../../shared/services/notification.service';
32 import { NotificationsService } from 'angular2-notifications';
33 import { ParamShareService } from '../../../../shared/services/paramShare.service';
34 import { DialogService } from 'ng2-bootstrap-modal';
35 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
36 import { BuildDesignComponent } from '../../build-artifacts.component';
37 import { environment } from '../../../../../environments/environment';
38 import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
39 import { NgProgress } from 'ngx-progressbar';
42 @Component({ selector: 'app-golden-configuration', templateUrl: './template-configuration.component.html', styleUrls: ['./template-configuration.component.css'] })
43 export class GoldenConfigurationComponent implements OnInit {
44 @ViewChild('templateeditor') templateeditor;
45 @Input() configMappingEditorContent: string;
46 @Input() isMappingComp: boolean;
47 @ViewChild('myInput') myInputVariable: any;
48 // @ViewChild(ModalComponent) modalComponent: ModalComponent;
49 @ViewChild('myModal') modal: ModalComponent;
52 showTemplateVersionDiv: any;
53 downloadedTemplateFileName: any;
54 downloadedParamFileName: any;
55 templateVersionNo: any = '0.0.1';
56 saveToGuiCacheFlag = 'false';
58 public referenceData: Array<Object> = [];
59 public scopeName: any;
60 public subscription: any;
61 public item: any = {};
62 public goldenActions: Array<string> = [];
63 public refNameObj = {};
65 public artifactName = '';
67 public showError: boolean = false;
68 public tempretrieveFlag: boolean = false;
69 public fileNameForTempSave;
71 showDownloadDiv: boolean = false;
73 enableBrowse: boolean = true;
74 enableMerge: boolean = false;
75 uploadValidationSuccess: boolean = false;
76 fileExtension: any = "xml";
77 apiToken = localStorage['apiToken'];
78 public appDataObject: any;
79 public downloadDataObject: any;
80 public checkNameEntered: boolean = true;
81 public selectedWord: any = this.mappingEditorService.getSelectedWord();
83 { action: "ConfigBackup", value: "ConfigBackup" },
84 { action: "ConfigModify", value: "ConfigModify" },
85 { action: "ConfigRestore", value: "ConfigRestore" },
86 { action: "Configure", value: "Configure" },
87 { action: "GetRunningConfig", value: "GetRunningConfig" },
88 { action: "HealthCheck", value: "HealthCheck" },
89 { action: "StartApplication", value: "StartApplication" },
90 { action: "StopApplication", value: "StopApplication" }
94 showProgressBar: true,
99 public enableDownloadButtons: boolean = false;
100 constructor(private buildDesignComponent: BuildDesignComponent, private paramShareService: ParamShareService, private dialogService: DialogService, private notificationService: NotificationService, private httpUtil: HttpUtilService, private mappingEditorService: MappingEditorService, private activeRoutes: ActivatedRoute, private router: Router, private nService: NotificationsService, private ngProgress: NgProgress) {
101 this.artifactRequest.action = '';
102 this.artifactRequest.version = '';
103 this.artifactRequest.paramsContent = '{}';
104 this.artifactRequest.paramKeysContent = '';
106 public templateEditor: any;
107 public fileType: any = '';
108 public actionType: any;
109 public myfileName: any;
110 userId = localStorage['userId'];
111 public artifactRequest: ArtifactRequest = new ArtifactRequest();
112 public showUploadStatus: boolean = false;
113 public uploadStatus: boolean = false;
114 public uploadTypes = [
116 value: 'Generated Template',
117 display: 'Sample Json Param File'
120 value: 'Mapping Data',
121 display: 'Sample Json Param File'
131 enableValidateTemplate: boolean = false;;
132 public selectedUploadType: string = this.uploadTypes[0].value;
134 //this.mappingeditorservice.referenceNameObjects = object;PLEASE USE THIS OBJECT TO GET TEMPALLDATA
135 //====================================================
137 var refObj = this.refObj = this.prepareFileName();
138 // console.log("Ref object: " + JSON.stringify(refObj))
139 if (refObj && refObj != undefined) {
140 // refObj = refObj[refObj.length - 1];
143 this.vnfType = this.item.scope["vnf-type"];
144 this.vnfcType = this.item.scope["vnfc-type"];
145 this.protocol = this.item['device-protocol'];
146 this.action = this.item.action;
147 this.artifactRequest.action = this.item.action;
148 this.artifactRequest.vnfType = this.vnfType;
149 if (this.vnfcType != undefined && this.vnfcType.length != 0) {
150 this.scopeName = this.vnfcType;
153 this.scopeName = this.vnfType;
157 this.item = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
159 this.initialAction = this.item.action;
160 this.activeRoutes.url.subscribe(UrlSegment => {
161 this.actionType = UrlSegment[0].path
163 /*if (this.actionType === 'createTemplate') {
164 this.mappingEditorService.fromScreen = 'TemplateScreen';
166 if (this.actionType === 'updateTemplate') {*/
167 this.mappingEditorService.fromScreen = 'MappingScreen';
169 this.identifier = this.mappingEditorService.identifier;
171 //========================== End of ngOnInit() Method============================================
173 //console.log("Reference object =="+ JSON.stringify(this.refObj));
174 if (this.refObj && this.refObj != undefined) {
175 if (this.configMappingEditorContent && this.configMappingEditorContent != undefined) {
177 this.prepareAppData();
178 this.prepareDownloadData();
179 this.mappingEditorService.changeNavAppData(this.appDataObject);
180 this.mappingEditorService.changeNavDownloadData(this.downloadDataObject);
184 //========================== End of ngOnDestroy() Method============================================
186 if (this.mappingEditorService.latestAction) {
187 this.refNameObj = this.mappingEditorService.latestAction;
188 if (this.vnfcType !== 'null') {
189 this.type = this.vnfcType;
192 this.type = this.vnfType;
194 for (let i = 0; i < this.refNameObj['artifact-list'].length; i++) {
195 let artifactList = this.refNameObj['artifact-list'];
196 if (artifactList[i]['artifact-type'] === 'config_template') {
197 this.artifactName = artifactList[i]['artifact-name'];
202 this.templateEditor = self.templateeditor.getEditor();
203 /* this.templateeditor.getEditor().commands.addCommand({
204 name: 'annotateCommand',
205 bindKey: { win: 'Ctrl-4', mac: 'Command-4' },
206 exec: function (editor) {
207 self.mappingEditorService.checkMethodCall(this.modal);
210 this.templateeditor.getEditor().commands.addCommand({
211 name: 'annotateCommand',
212 bindKey: { win: 'ENTER', mac: 'ENTER' },
213 exec: (editor: any) => {
214 this.handleAnnotation(this.modal);
217 if (this.mappingEditorService.fromScreen === 'MappingScreen') {
218 this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
219 this.fileType = sessionStorage.getItem('fileType');
221 /* else if (this.mappingEditorService.fromScreen === 'TemplateScreen') {
222 this.configMappingEditorContent = this.mappingEditorService.getTemplateDataFromStore();
223 this.fileType = sessionStorage.getItem('fileType');
225 if (this.configMappingEditorContent) {
226 this.artifactRequest.templateContent = this.configMappingEditorContent;
227 this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
230 if (this.mappingEditorService.getTemplateMappingDataFromStore() && this.mappingEditorService.getTemplateMappingDataFromStore() != undefined) {
231 this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
234 if (this.artifactName) this.retrieveTemplateFromAppc();
239 this.enableBrowse = false;
240 this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
244 //========================== End of ngAfterViewInit() Method============================================
246 $("#inputFile").trigger('click');
248 //========================== End of browseOption() Method============================================
250 let input = event.target;
251 this.fileName = event.currentTarget.value.replace(/C:\\fakepath\\/i, '');
252 for (let index = 0; index < input.files.length; index++) {
253 let reader = new FileReader();
254 reader.onload = () => {
255 this.configMappingEditorContent = reader.result;
257 reader.readAsText(input.files[index]);
260 //========================== End of openFile() Method============================================*/
262 public saveTemplate() {
263 this.saveToGuiCacheFlag = 'true';
264 this.mappingEditorService.paramData = [];
265 if (this.configMappingEditorContent) {
266 this.initialData = this.configMappingEditorContent;
267 this.mappingEditorService.refreshEditor();
268 let paramArr: any = []
269 if (this.mappingEditorService.paramData && this.mappingEditorService.paramData != undefined) {
270 if (this.mappingEditorService.paramData.length === 0 && this.mappingEditorService.hasErrorCode === true) {
271 this.nService.error("Error", 'Special characters error', 'Error')
275 this.showError = false;
278 this.showTemplateVersionDiv = true;
280 if (this.mappingEditorService.fromScreen === 'MappingScreen') {
281 this.mappingEditorService.setTemplateMappingDataFromStore(this.configMappingEditorContent);
283 if (this.fileType === 'text/xml') {
284 sessionStorage.setItem('fileType', 'text/xml');
286 if (this.fileType === '') {
287 sessionStorage.setItem('fileType', '');
289 // paramArr = this.mappingEditorService.paramData;
290 // this.paramShareService.setTemplateData(paramArr)
293 //========================== End of saveTemplate() Method============================================
294 /* clearHighlight() {
295 this.mappingEditorService.removeTheSelectedMarkers();
297 //========================== End of clearHighlight() Method============================================*/
298 /*validateTemplate() {
299 var fileExtensionArr = this.fileType.split("/");
303 "request-id": this.apiToken,
304 "action": "validateTemplate",
305 "data-type": fileExtensionArr[1].toUpperCase(),
306 "payload": this.configMappingEditorContent
310 let url = environment.validateTemplate;
314 { url: url, data: data })
316 if (resp.output.status.code === '400' && resp.output.status.message === "success") {
317 this.uploadValidationSuccess = true;
318 this.nService.success("Success", "Template Validated succesfully");
321 else if (resp.output.status.code === '401') {
322 this.nService.error("Error", resp.output.status.message);
326 error => this.nService.error("Error", "Unable to validate the uploaded template. Error in connecting APPC Server"));
328 //========================== End of validateTemplate() Method============================================*/
329 retrieveTemplateFromAppc() {
330 let refObj = this.refObj;
331 if (refObj && refObj != undefined) {
333 let fileName = this.artifactName;
334 let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
338 "request-id": this.apiToken,
339 "action": "getArtifact",
344 // console.log("Retrieve artifact payload=="+ payload);
345 let artifactContent: any;
346 this.ngProgress.start();
348 url: environment.getDesigns,
350 }).subscribe(resp => {
351 if (resp.output.status.code === '400' && resp.output.status.message === "success") {
352 this.nService.success("Success", "Template retrieved successfully from APPC");
353 let result = JSON.parse(resp.output.data.block).artifactInfo[0];
354 result = result['artifact-content'];
355 if ('Generated Template' === this.selectedUploadType) {
356 this.configMappingEditorContent = result
357 this.artifactRequest.templateContent = this.configMappingEditorContent;
358 this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
359 if (this.artifactRequest.templateContent) {
360 this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
363 this.tempretrieveFlag = true;
364 this.fileNameForTempSave = fileName;
365 this.enableDownloadButtons = true;
366 this.initialData = result;
370 this.nService.info("Information", "There is no template saved in APPC for the selected action!");
372 this.ngProgress.done();
375 // this.showUploadErrorStatus = true;
376 // this.nService.error('Status','Error Connecting to the APPC Network')
377 //this.notificationService.notifyErrorMessage('Configuration Template file successfully uploaded..')
378 //this.uploadStatusError = true;
379 //window.scrollTo(0, 0)
380 // this. nService.error('Status','Error Connecting to the APPC Network')
381 this.openModel(true, "Could not retrieve latest template for given action""Error in connecting to APPC database")
383 error => this.nService.error("Error", "Error in connecting to APPC Server"));
385 this.ngProgress.done();
389 //========================== End of retrieveTemplateFromAppc() Method============================================
391 let refObj = this.refObj;
392 //console.log("Reference object =="+ JSON.stringify(refObj));
393 if (refObj && refObj != undefined) {
394 // refObj = refObj[refObj.length - 1];
395 let paramsKeyValueFromEditor: JSON;
396 /* if (this.fileExtension.toUpperCase() === "XML")
397 paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
399 // paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
401 paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
404 console.log("Could not parse name value pairs==" + error);
406 if (paramsKeyValueFromEditor) {
407 this.showTemplateVersionDiv = true;
408 let action = this.item.action;
409 var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
410 let fileName = this.updateParamFileName(refObj.action, scopeName, this.templateVersionNo);
411 let vnfType = this.vnfType;
412 let Json = [paramsKeyValueFromEditor];
413 let slashedPayload = this.appendSlashes(JSON.stringify(Json));
416 "userID": this.userId,
417 "vnf-type": this.vnfType,
419 "artifact-name": fileName,
420 "artifact-type": "APPC-CONFIG",
421 "artifact-version": this.templateVersionNo,
422 "artifact-contents": slashedPayload
428 "request-id": this.apiToken,
429 "action": "uploadArtifact",
430 "payload": JSON.stringify(newPayload)
435 this.appDataObject.template.nameValueData = data;
437 if (this.configMappingEditorContent) {
438 let actualContent = this.configMappingEditorContent;
439 this.mappingEditorService.generateTemplate(this.templateEditor);
440 this.showTemplateVersionDiv = true;
441 let action = this.item.action;
442 let versionandFileType: any;
443 if (this.fileType === "text/xml") {
445 versionandFileType = this.templateVersionNo + 'V.xml'
448 versionandFileType = this.templateVersionNo + 'V.json'
451 if (this.tempretrieveFlag) {
452 fileName = this.fileNameForTempSave;
455 // fileName = this.updateDownloadTemplateFileName(refObj.action, this.scopeName, versionandFileType);
456 fileName = this.artifactName;
458 let vnfType = this.vnfType;
461 "userID": this.userId,
462 "vnf-type": this.vnfType,
464 "artifact-name": fileName,
465 "artifact-type": "APPC-CONFIG",
466 "artifact-version": this.templateVersionNo,
467 //"artifact-contents": this.configMappingEditorContent
468 "artifact-contents": this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
475 "request-id": this.apiToken,
476 "action": "uploadArtifact",
477 "payload": JSON.stringify(newPayload)
482 this.appDataObject.template.templateData = data;
483 this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
487 //========================== End of prepareAppData() Method============================================
488 /*retrieveNameValueFromAppc() {
489 let refObj: any = this.prepareFileName();
490 if (refObj && refObj != undefined) {
491 let fileName = this.updateParamFileName(this.item.action, this.scopeName, this.templateVersionNo);
492 let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
496 "request-id": this.apiToken,
497 "action": "getArtifact",
503 let artifactContent: any;
505 // url:"https://mtanjv9apdb51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
506 url: environment.getDesigns,
508 }).subscribe(resp => {
509 if (resp.output.status.code === '400' && resp.output.status.message === "success") {
510 this.openModel(true, 'Name/value pairs retrieved successfully from APPC', 'Success');
511 let result = JSON.parse(resp.output.data.block).artifactInfo[0];
512 result = JSON.parse(result['artifact-content']);
513 var jsonString = JSON.stringify(result[0]);
514 var string = jsonString.substring(1, jsonString.length - 1);
515 var stringArr = string.split(",");
516 var newStringArr = [];
517 var resultStr = "{\r\n"
518 for (var index in stringArr) {
519 newStringArr[index] = stringArr[index] + ",\r\n";
521 for (var index in newStringArr) {
522 resultStr = resultStr + newStringArr[index];
524 resultStr = resultStr.substring(0, resultStr.length - 3) + "\r\n}"
525 this.configMappingEditorContent = resultStr;
529 error => this.openModel(true, "Could not retrieve the name value pairs. Error in connecting to APPC Server", "ERROR"));
532 //========================== End of retrieveNameValueFromAppc() Method============================================
533 prepareFileName(): any {
534 let fileNameObject: any = this.mappingEditorService.latestAction;
535 this.appDataObject = this.mappingEditorService.appDataObject;
536 this.downloadDataObject = this.mappingEditorService.downloadDataObject;
537 this.referenceData = fileNameObject;
538 return fileNameObject;
540 //========================== End of prepareFileName() Method============================================
541 onDownloadParameter() {
542 let refObj = this.refObj;
544 // refObj = refObj[refObj.length - 1];
545 let paramsKeyValueFromEditor: JSON;
546 if (this.fileExtension.toUpperCase() === "XML")
547 paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
549 paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
552 paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
555 console.log("Could not parse name value pairs==" + error);
557 let theJSON = JSON.stringify(paramsKeyValueFromEditor, null, "\t")
558 var blob = new Blob([theJSON], {
561 this.showTemplateVersionDiv = true;
563 var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
564 fileName = this.updateParamFileName(refObj.action, scopeName, this.templateVersionNo);
565 this.downloadDataObject.template.nameValueData = theJSON;
566 this.downloadDataObject.template.nameValueFileName = fileName;
569 this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
573 //========================== End of onDownloadParameter() Method============================================
574 /* JSONToCSVConvertor(JSONData, fileName, ShowLabel) {
575 //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
576 var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
578 //This condition will generate the Label/Header
581 for (var index in arrData[0]) {
582 CSV += index + '\t' + arrData[0][index] + '\r\n';
588 //Initialize file format you want csv or xls
589 var uri = 'data:application/vnd.ms-excel,' + encodeURI(CSV);
590 var link = document.createElement("a");
592 link.download = fileName + ".xls";
593 //this part will append the anchor tag and remove it after automatic click
594 document.body.appendChild(link);
596 document.body.removeChild(link);
598 //========================== End of JSONToCSVConvertor() Method============================================
599 updateParamFileNameForXls(action: any, scopeName: any, versionNo: any) {
600 let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V';
601 this.downloadedParamFileName = fileName;
604 //========================== End of updateParamFileNameForXls() Method============================================*/
605 updateParamFileName(action: any, scopeName: any, versionNo: any) {
606 let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
607 this.downloadedParamFileName = fileName;
610 //========================== End of updateParamFileName() Method============================================
611 public onDownloadTemplate(artifact: string) {
612 let actualContent = this.configMappingEditorContent;
613 var textToSaveAsBlob: any;
614 var config_template_fileName: any
615 let refObj = this.refObj;
616 let versionandFileType: string;
617 this.mappingEditorService.generateTemplate(this.templateEditor);
618 if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
619 // refObj = refObj[refObj.length - 1];
620 this.showTemplateVersionDiv = true;
621 if (this.fileType === "text/xml") {
622 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
625 versionandFileType = this.templateVersionNo + 'V.xml'
627 if (this.fileType === "text/plain") {
628 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
631 versionandFileType = this.templateVersionNo + 'V.txt'
633 if (this.fileType === "text/json") {
634 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
637 versionandFileType = this.templateVersionNo + 'V.json'
639 if (this.tempretrieveFlag) {
640 config_template_fileName = this.fileNameForTempSave;
641 var filextension = config_template_fileName.substring(config_template_fileName.indexOf("V") + 2, config_template_fileName.length);
643 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
644 type: "text/" + filextension
648 // config_template_fileName = this.updateDownloadTemplateFileName(refObj.action, this.scopeName, versionandFileType);
649 config_template_fileName = this.artifactName;
651 // saveAs(textToSaveAsBlob, config_template_fileName);
652 this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
653 //this.downloadDataObject.template.templateData = this.configMappingEditorContent;
654 this.downloadDataObject.template.templateData = this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}');
655 this.downloadDataObject.template.templateFileName = config_template_fileName;
659 //========================== End of onDownloadTemplate() Method============================================
660 updateDownloadTemplateFileName(action: any, scopeName: any, versionandFileType: any) {
661 let fileName = 'template_' + action + '_' + scopeName + '_' + versionandFileType;
662 this.downloadedTemplateFileName = fileName;
665 //========================== End of updateDownloadTemplateFileName() Method============================================
666 /* openModel(toShow: any, message: any, title: any) {
667 //this.modalComponent.isShow = toShow;
668 //this.modalComponent.message = message;
669 //this.modalComponent.title = title;
671 //========================== End of openModel() Method============================================*/
675 let refObj = this.refObj;
676 this.enableValidateTemplate = true;
678 if (refObj && refObj != undefined) {
679 // refObj = refObj[refObj.length - 1];
680 if (input.files && input.files[0]) {
681 console.log("input files0" + JSON.stringify(input.files[0]))
682 this.myfileName = input.files[0].name;
683 this.fileName = input.files[0].name;
684 this.fileType = input.files[0].type;
685 // var fileExtension = this.myfileName.substr(this.myfileName.lastIndexOf('.') + 1);
687 let reader = new FileReader();
688 // if(this.validateUploadedFile(fileExtension))
690 this.readFile(input.files[0], reader, (result) => {
691 if (this.fileType === 'text/xml') {
692 sessionStorage.setItem('fileType', 'text/xml');
694 if (this.fileName.endsWith(".json")) {
695 this.fileType = "text/json";
696 sessionStorage.setItem('fileType', 'text/json');
698 if (this.fileType === '') {
699 sessionStorage.setItem('fileType', '');
703 if ('Generated Template' === this.selectedUploadType) {
704 this.configMappingEditorContent = result
705 this.artifactRequest.templateContent = this.configMappingEditorContent;
706 console.log("editor content==" + JSON.stringify(this.configMappingEditorContent))
707 this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
708 if (this.artifactRequest.templateContent) {
709 this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
712 this.enableDownloadButtons = true;
713 this.initialData = result;
719 // this.nService.error("Error", "Incorrect File Format")
720 //this.configMappingEditorContent=''
724 this.nService.error("Error", "Failed to read file");
726 this.myInputVariable.nativeElement.value = "";
729 this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
733 //========================== End of fileChange() Method============================================
734 public readFile(file, reader, callback) {
735 // Set a callback funtion to fire after the file is fully loaded
736 reader.onload = () => {
737 // callback with the results
738 callback(reader.result);
740 this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
742 reader.readAsText(file, "UTF-8");
744 //========================== End of readFile() Method============================================
745 validateUploadedFile(fileExtension) {
747 if (fileExtension.toUpperCase() === 'json'.toUpperCase() || fileExtension.toUpperCase() === 'xml'.toUpperCase()) {
755 //========================== End of validateUploadedFile() Method============================================
756 appendSlashes(artifactData) {
757 let x = artifactData.replace(new RegExp(',"', "g"), ',\"');
758 let y = x.replace(new RegExp('":', 'g'), '\":');
759 let z = y.replace(new RegExp('{"', 'g'), '{\"')
760 let t = z.replace(new RegExp(':"', 'g'), ':\"')
761 let m = t.replace(new RegExp('",', 'g'), '\",');
762 let n = y.replace(new RegExp('"}', 'g'), '\"}')
763 let nw = n.replace(new RegExp('{"', 'g'), '{\"');
764 let nw1 = nw.replace(new RegExp(':"', 'g'), ':\"');
765 let nw2 = nw1.replace(new RegExp('",', 'g'), '\",');
768 //========================== End of appendSlashes() Method============================================
769 prepareDownloadData() {
770 this.onDownloadParameter();
771 this.onDownloadTemplate('Template');
773 //========================== End of prepareDownloadData() Method============================================
775 this.mappingEditorService.replaceNamesWithBlankValues();
778 var templateData = this.mappingEditorService.paramData; //template data array
779 // this.paramShareService.setTemplateData(templateData);
781 //console.log("Template Name value pairs ===" + JSON.stringify(templateData))
782 var pdData = this.paramShareService.getSessionParamData(); //PD data array
783 console.log("PD name value pairs===" + JSON.stringify(pdData))
786 var paramsContent = localStorage["paramsContent"];
787 console.log("Param content before==" + paramsContent);
789 if (paramsContent && paramsContent != undefined) {
791 var paramTabData = JSON.parse(paramsContent);
792 //console.log("Param content after==" + paramsContent);
793 //console.log("Param tab data after==" + JSON.stringify(paramTabData))
796 console.log("error is : " + error)
801 var resultParamObj = {};
802 let checkNamesOnlyCondition: boolean = true;
804 if (templateData && templateData != undefined) {
805 templateData.forEach(function (item) {
806 if (item.paramValue !== "" && item.paramValue != undefined && item.paramValue != null) {
807 checkNamesOnlyCondition = false;
812 templateData.forEach(function (item) {
813 resultParamObj[item.paramName] = item.paramValue;
815 // console.log("pARAM Result array before is " + JSON.stringify(resultParamObj))
816 if (paramTabData && paramTabData != undefined) {
817 templateData.forEach(function (item) {
818 for (var index in paramTabData) {
819 if (item.paramName === index) {
820 if (checkNamesOnlyCondition) {
821 resultParamObj[index] = paramTabData[index];
824 if (item.paramValue === "") {
825 resultParamObj[index] = paramTabData[index];
828 resultParamObj[index] = item.paramValue;
838 localStorage["paramsContent"] = JSON.stringify(resultParamObj);
839 //console.log("param content after==" +JSON.stringify(resultParamObj));
841 //removing duplicate elements from the array
842 templateData = Array.from(new Set(templateData.map((itemInArray) => itemInArray.paramName)))
844 //reformatting arr1 to match with PD
845 templateData.forEach(function (item) {
881 "ruleTypeValues": [null]
886 //console.log("Result array before is " + JSON.stringify(resultArr))
887 // console.log("Length before is: " + resultArr.length)
889 if (pdData && pdData != undefined) {
890 for (var i = 0; i < resultArr.length; i++) {
892 pdData.forEach(function (arr2item) {
893 if (resultArr[i].name === arr2item.name) {
896 "name": arr2item.name,
897 "type": arr2item.type,
898 "description": arr2item.description,
899 "required": arr2item.required,
900 "default": arr2item.default,
901 "source": arr2item.source,
902 "rule-type": arr2item["rule-type"],
903 "request-keys": arr2item["request-keys"],
904 "response-keys": arr2item["response-keys"],
905 "ruleTypeValues": arr2item.ruleTypeValues
907 resultArr.splice(i, 1, json)
908 // console.log("Result array index ==" + JSON.stringify(resultArr[i]))
916 this.paramShareService.setSessionParamData(resultArr);
917 //console.log("Result array after is " + JSON.stringify(resultArr))
918 //console.log("Length after is: " + resultArr.length)
919 this.mappingEditorService.paramData = [];
920 //navigate to PD page after sync
923 .navigate(['../../../vnfs/design/parameterDefinitions/create']);
926 //========================== End of syncTemplate() Method============================================
928 var mergeStatus: boolean = this.mappingEditorService.autoAnnotateDataForParams(this.fileType);
930 this.nService.success("Success", "Merge Successful");
933 this.nService.error("Error", "Merge Unsuccessful");
937 //========================== End of mergeParams() Method============================================
938 public handleAnnotation(modal) {
940 let selectedWord: string = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
941 this.selectedWord = selectedWord;
944 //========================== End of handleAnnotations() Method============================================
945 public submitNameValues() {
946 /*var editor = this.templateeditor.getEditor()
947 this.editor = editor;
948 this.editor.session = editor.session;
949 this.editor.selection.session.$backMarkers = {};
950 this.editorContent = this.artifactRequest.templateContent;
951 this.editor.$blockScrolling = Infinity;
952 this.editor.$blockSelectEnabled = false;*/
954 this.checkNameEntered = true;
956 if (this.selectedWord) {
957 if (this.selectedWord.startsWith('${(')) {
958 var replaceWord: any = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
959 this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
961 let mappingKey = this.mappingEditorService.getKeysForValues(this.selectedWord);
962 var replaceWord: any = '${(' + this.selectedWord + ')=(' + this.tempName + ')}';
963 this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
966 this.mappingEditorService.refreshEditor();
972 this.checkNameEntered = false;
976 //========================== End of submitNameValues() Method============================================