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 ============LICENSE_END============================================
23 import { Component, Input, OnInit, ViewChild } from '@angular/core';
24 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
25 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
26 import { ArtifactRequest } from '../../../../shared/models/index';
27 import { ActivatedRoute, Router } from '@angular/router';
28 import { saveAs } from 'file-saver';
29 import { NotificationService } from '../../../../shared/services/notification.service';
30 import { NotificationsService } from 'angular2-notifications';
31 import { ParamShareService } from '../../../../shared/services/paramShare.service';
32 import { DialogService } from 'ng2-bootstrap-modal';
33 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
34 import { BuildDesignComponent } from '../../build-artifacts.component';
35 import { environment } from '../../../../../environments/environment';
36 import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
37 import { NgProgress } from 'ngx-progressbar';
40 @Component({ selector: 'app-golden-configuration', templateUrl: './template-configuration.component.html', styleUrls: ['./template-configuration.component.css'] })
41 export class GoldenConfigurationComponent implements OnInit {
42 @ViewChild('templateeditor') templateeditor;
43 @Input() configMappingEditorContent: string;
44 @Input() isMappingComp: boolean;
45 @ViewChild('myInput') myInputVariable: any;
46 @ViewChild('myModal') modal: ModalComponent;
49 showTemplateVersionDiv: any;
50 downloadedTemplateFileName: any;
51 downloadedParamFileName: any;
52 templateVersionNo: any = '0.0.1';
53 saveToGuiCacheFlag = 'false';
55 public referenceData: Array<Object> = [];
56 public scopeName: any;
57 public subscription: any;
58 public item: any = {};
59 public goldenActions: Array<string> = [];
60 public refNameObj = {};
62 public artifactName = '';
64 public showError: boolean = false;
65 public tempretrieveFlag: boolean = false;
66 public fileNameForTempSave;
68 showDownloadDiv: boolean = false;
70 enableBrowse: boolean = true;
71 enableMerge: boolean = false;
72 uploadValidationSuccess: boolean = false;
73 fileExtension: any = "xml";
74 apiToken = localStorage['apiToken'];
75 public appDataObject: any;
76 public downloadDataObject: any;
77 public checkNameEntered: boolean = true;
78 public selectedWord: any = this.mappingEditorService.getSelectedWord();
80 { action: "ConfigBackup", value: "ConfigBackup" },
81 { action: "ConfigModify", value: "ConfigModify" },
82 { action: "ConfigRestore", value: "ConfigRestore" },
83 { action: "Configure", value: "Configure" },
84 { action: "GetRunningConfig", value: "GetRunningConfig" },
85 { action: "HealthCheck", value: "HealthCheck" },
86 { action: "StartApplication", value: "StartApplication" },
87 { action: "StopApplication", value: "StopApplication" }
91 showProgressBar: true,
97 public enableDownloadButtons: boolean = false;
98 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) {
99 this.artifactRequest.action = '';
100 this.artifactRequest.version = '';
101 this.artifactRequest.paramsContent = '{}';
102 this.artifactRequest.paramKeysContent = '';
104 public templateEditor: any;
105 public fileType: any = '';
106 public actionType: any;
107 public myfileName: any;
108 userId = localStorage['userId'];
109 public artifactRequest: ArtifactRequest = new ArtifactRequest();
110 public showUploadStatus: boolean = false;
111 public uploadStatus: boolean = false;
112 public uploadTypes = [
114 value: 'Generated Template',
115 display: 'Sample Json Param File'
118 value: 'Mapping Data',
119 display: 'Sample Json Param File'
129 enableValidateTemplate: boolean = false;;
130 public selectedUploadType: string = this.uploadTypes[0].value;
132 public tempRetrievalResponse:any;
133 public mergeStatus:boolean=false;
135 //======================================Start of ngOnInit() Method============================================
137 var refObj = this.refObj = this.prepareFileName();
138 if (refObj && refObj != undefined) {
141 this.vnfType = this.item.scope["vnf-type"];
142 this.vnfcType = this.item.scope["vnfc-type"];
143 this.protocol = this.item['device-protocol'];
144 this.action = this.item.action;
145 this.artifactRequest.action = this.item.action;
146 this.artifactRequest.vnfType = this.vnfType;
147 if (this.vnfcType != undefined && this.vnfcType.length != 0) {
148 this.scopeName = this.vnfcType;
151 this.scopeName = this.vnfType;
155 this.item = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
157 this.initialAction = this.item.action;
158 this.activeRoutes.url.subscribe(UrlSegment => {
159 this.actionType = UrlSegment[0].path
161 this.mappingEditorService.fromScreen = 'MappingScreen';
162 this.identifier = this.mappingEditorService.identifier;
164 //========================== End of ngOnInit() Method============================================
166 if (this.refObj && this.refObj != undefined) {
167 if (this.configMappingEditorContent && this.configMappingEditorContent != undefined) {
169 this.prepareAppData();
170 this.prepareDownloadData();
171 this.mappingEditorService.changeNavAppData(this.appDataObject);
172 this.mappingEditorService.changeNavDownloadData(this.downloadDataObject);
176 //========================== End of ngOnDestroy() Method============================================
178 if (this.mappingEditorService.latestAction) {
179 this.refNameObj = this.mappingEditorService.latestAction;
180 if (this.vnfcType !== 'null') {
181 this.type = this.vnfcType;
184 this.type = this.vnfType;
186 for (let i = 0; i < this.refNameObj['artifact-list'].length; i++) {
187 let artifactList = this.refNameObj['artifact-list'];
188 if (artifactList[i]['artifact-type'] === 'config_template') {
189 this.artifactName = artifactList[i]['artifact-name'];
194 this.templateEditor = self.templateeditor.getEditor();
195 this.templateeditor.getEditor().commands.addCommand({
196 name: 'annotateCommandAlternate',
197 bindKey: { win: 'CTRL-4', mac: 'Command-4' },
198 exec: (editor: any) => {
199 this.handleAnnotation(this.modal);
202 if (this.mappingEditorService.fromScreen === 'MappingScreen') {
203 this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
204 this.fileType = sessionStorage.getItem('fileType');
206 if (this.configMappingEditorContent) {
207 this.artifactRequest.templateContent = this.configMappingEditorContent;
208 this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
211 if (this.mappingEditorService.getTemplateMappingDataFromStore() && this.mappingEditorService.getTemplateMappingDataFromStore() != undefined) {
212 this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
215 if (this.artifactName) this.retrieveTemplateFromAppc();
220 this.enableBrowse = false;
221 this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
225 //========================== End of ngAfterViewInit() Method============================================
227 $("#inputFile").trigger('click');
229 //========================== End of browseOption() Method============================================
231 public saveTemplate() {
232 this.saveToGuiCacheFlag = 'true';
233 this.mappingEditorService.paramData = [];
234 if (this.configMappingEditorContent) {
235 this.initialData = this.configMappingEditorContent;
236 this.mappingEditorService.refreshEditor();
237 let paramArr: any = []
238 if (this.mappingEditorService.paramData && this.mappingEditorService.paramData != undefined) {
239 if (this.mappingEditorService.paramData.length === 0 && this.mappingEditorService.hasErrorCode === true) {
240 this.nService.error("Error", 'Special characters error', 'Error')
244 this.showError = false;
247 this.showTemplateVersionDiv = true;
249 if (this.mappingEditorService.fromScreen === 'MappingScreen') {
250 this.mappingEditorService.setTemplateMappingDataFromStore(this.configMappingEditorContent);
252 if (this.fileType === 'text/xml') {
253 sessionStorage.setItem('fileType', 'text/xml');
255 if (this.fileType === '') {
256 sessionStorage.setItem('fileType', '');
260 //========================== End of saveTemplate() Method============================================
261 retrieveTemplateFromAppc() {
262 let refObj = this.refObj;
263 if (refObj && refObj != undefined) {
265 let fileName = this.artifactName;
266 let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
270 "request-id": this.apiToken,
271 "action": "getArtifact",
276 let artifactContent: any;
277 this.ngProgress.start();
279 url: environment.getDesigns,
281 }).subscribe(resp => {
282 if (resp.output.status.code === '400' && resp.output.status.message === "success") {
283 this.nService.success("Success", "Template retrieved successfully from APPC");
284 this.tempRetrievalResponse=resp;
285 let result = JSON.parse(resp.output.data.block).artifactInfo[0];
286 result = result['artifact-content'];
287 if ('Generated Template' === this.selectedUploadType) {
288 this.configMappingEditorContent = result
289 this.artifactRequest.templateContent = this.configMappingEditorContent;
290 this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
291 if (this.artifactRequest.templateContent) {
292 this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
295 this.tempretrieveFlag = true;
296 this.fileNameForTempSave = fileName;
297 this.enableDownloadButtons = true;
298 this.initialData = result;
302 this.nService.info("Information", "There is no template saved in APPC for the selected action!");
304 this.ngProgress.done();
306 error => this.nService.error("Error", "Error in connecting to APPC Server"));
308 this.ngProgress.done();
312 //========================== End of retrieveTemplateFromAppc() Method============================================
314 let refObj = this.refObj;
315 if (refObj && refObj != undefined) {
316 let paramsKeyValueFromEditor: JSON;
318 paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
321 console.log("Could not parse name value pairs==" + error);
323 if (paramsKeyValueFromEditor) {
324 this.showTemplateVersionDiv = true;
325 let action = this.item.action;
326 var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
327 let fileName = this.updateParamFileName(refObj.action, scopeName, this.templateVersionNo);
328 let vnfType = this.vnfType;
329 let Json = [paramsKeyValueFromEditor];
330 let slashedPayload = this.appendSlashes(JSON.stringify(Json));
333 "userID": this.userId,
334 "vnf-type": this.vnfType,
336 "artifact-name": fileName,
337 "artifact-type": "APPC-CONFIG",
338 "artifact-version": this.templateVersionNo,
339 "artifact-contents": slashedPayload
345 "request-id": this.apiToken,
346 "action": "uploadArtifact",
347 "payload": JSON.stringify(newPayload)
352 this.appDataObject.template.nameValueData = data;
354 if (this.configMappingEditorContent) {
355 let actualContent = this.configMappingEditorContent;
356 this.mappingEditorService.generateTemplate(this.templateEditor);
357 this.showTemplateVersionDiv = true;
358 let action = this.item.action;
359 let versionandFileType: any;
360 if (this.fileType === "text/xml") {
362 versionandFileType = this.templateVersionNo + 'V.xml'
365 versionandFileType = this.templateVersionNo + 'V.json'
368 if (this.tempretrieveFlag) {
369 fileName = this.fileNameForTempSave;
372 fileName = this.artifactName;
374 let vnfType = this.vnfType;
377 "userID": this.userId,
378 "vnf-type": this.vnfType,
380 "artifact-name": fileName,
381 "artifact-type": "APPC-CONFIG",
382 "artifact-version": this.templateVersionNo,
383 "artifact-contents": this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
390 "request-id": this.apiToken,
391 "action": "uploadArtifact",
392 "payload": JSON.stringify(newPayload)
397 this.appDataObject.template.templateData = data;
398 this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
402 //========================== End of prepareAppData() Method============================================
403 prepareFileName(): any {
404 let fileNameObject: any = this.mappingEditorService.latestAction;
405 this.appDataObject = this.mappingEditorService.appDataObject;
406 this.downloadDataObject = this.mappingEditorService.downloadDataObject;
407 this.referenceData = fileNameObject;
408 return fileNameObject;
410 //========================== End of prepareFileName() Method============================================
411 onDownloadParameter() {
412 let refObj = this.refObj;
414 let paramsKeyValueFromEditor: JSON;
416 paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
419 console.log("Could not parse name value pairs==" + error);
421 let theJSON = JSON.stringify(paramsKeyValueFromEditor, null, "\t")
422 var blob = new Blob([theJSON], {
425 this.showTemplateVersionDiv = true;
427 var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
428 fileName = this.updateParamFileName(refObj.action, scopeName, this.templateVersionNo);
429 this.downloadDataObject.template.nameValueData = theJSON;
430 this.downloadDataObject.template.nameValueFileName = fileName;
433 this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
437 //========================== End of onDownloadParameter() Method============================================
438 updateParamFileName(action: any, scopeName: any, versionNo: any) {
439 let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
440 this.downloadedParamFileName = fileName;
443 //========================== End of updateParamFileName() Method============================================
444 public onDownloadTemplate(artifact: string) {
445 let actualContent = this.configMappingEditorContent;
446 var textToSaveAsBlob: any;
447 var config_template_fileName: any
448 let refObj = this.refObj;
449 let versionandFileType: string;
450 if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
451 this.showTemplateVersionDiv = true;
452 if (this.fileType === "text/xml") {
453 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
456 versionandFileType = this.templateVersionNo + 'V.xml'
458 if (this.fileType === "text/plain") {
459 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
462 versionandFileType = this.templateVersionNo + 'V.txt'
464 if (this.fileType === "text/json") {
465 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
468 versionandFileType = this.templateVersionNo + 'V.json'
470 if (this.tempretrieveFlag) {
471 config_template_fileName = this.fileNameForTempSave;
472 var filextension = config_template_fileName.substring(config_template_fileName.indexOf("V") + 2, config_template_fileName.length);
474 textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
475 type: "text/" + filextension
479 config_template_fileName = this.artifactName;
481 this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
482 this.downloadDataObject.template.templateData = this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}');
483 this.downloadDataObject.template.templateFileName = config_template_fileName;
487 //========================== End of onDownloadTemplate() Method============================================
491 let refObj = this.refObj;
492 this.enableValidateTemplate = true;
494 if (refObj && refObj != undefined) {
495 if (input.files && input.files[0]) {
496 this.myfileName = input.files[0].name;
497 this.fileName = input.files[0].name;
498 this.fileType = input.files[0].type;
499 let reader = new FileReader();
500 this.readFile(input.files[0], reader, (result) => {
501 if (this.fileType === 'text/xml') {
502 sessionStorage.setItem('fileType', 'text/xml');
504 if (this.fileName.endsWith(".json")) {
505 this.fileType = "text/json";
506 sessionStorage.setItem('fileType', 'text/json');
508 if (this.fileType === '') {
509 sessionStorage.setItem('fileType', '');
513 if ('Generated Template' === this.selectedUploadType) {
514 this.configMappingEditorContent = result
515 this.artifactRequest.templateContent = this.configMappingEditorContent;
516 this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
517 if (this.artifactRequest.templateContent) {
518 this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
521 this.enableDownloadButtons = true;
522 this.initialData = result;
528 this.nService.error("Error", "Failed to read file");
530 this.myInputVariable.nativeElement.value = "";
533 this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
537 //========================== End of fileChange() Method============================================
538 public readFile(file, reader, callback) {
539 // Set a callback funtion to fire after the file is fully loaded
540 reader.onload = () => {
541 // callback with the results
542 callback(reader.result);
544 this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
546 reader.readAsText(file, "UTF-8");
548 //========================== End of readFile() Method============================================
549 validateUploadedFile(fileExtension) {
551 if (fileExtension.toUpperCase() === 'json'.toUpperCase() || fileExtension.toUpperCase() === 'xml'.toUpperCase()) {
559 //========================== End of validateUploadedFile() Method============================================
560 appendSlashes(artifactData) {
561 let x = artifactData.replace(new RegExp(',"', "g"), ',\"');
562 let y = x.replace(new RegExp('":', 'g'), '\":');
563 let z = y.replace(new RegExp('{"', 'g'), '{\"')
564 let t = z.replace(new RegExp(':"', 'g'), ':\"')
565 let m = t.replace(new RegExp('",', 'g'), '\",');
566 let n = y.replace(new RegExp('"}', 'g'), '\"}')
567 let nw = n.replace(new RegExp('{"', 'g'), '{\"');
568 let nw1 = nw.replace(new RegExp(':"', 'g'), ':\"');
569 let nw2 = nw1.replace(new RegExp('",', 'g'), '\",');
572 //========================== End of appendSlashes() Method============================================
573 prepareDownloadData() {
574 this.onDownloadParameter();
575 this.onDownloadTemplate('Template');
577 //========================== End of prepareDownloadData() Method============================================
579 this.mappingEditorService.replaceNamesWithBlankValues();
582 var templateData = this.mappingEditorService.paramData; //template data array
583 var pdData = this.paramShareService.getSessionParamData(); //PD data array
584 var paramsContent = localStorage["paramsContent"];
586 if (paramsContent && paramsContent != undefined) {
588 var paramTabData = JSON.parse(paramsContent);
591 console.log("error is : " + error)
596 var resultParamObj = {};
597 let checkNamesOnlyCondition: boolean = true;
599 if (templateData && templateData != undefined) {
600 templateData.forEach(function (item) {
601 if (item.paramValue !== "" && item.paramValue != undefined && item.paramValue != null) {
602 checkNamesOnlyCondition = false;
607 templateData.forEach(function (item) {
608 resultParamObj[item.paramName] = item.paramValue;
610 if (paramTabData && paramTabData != undefined) {
611 templateData.forEach(function (item) {
612 for (var index in paramTabData) {
613 if (item.paramName === index) {
614 if (checkNamesOnlyCondition) {
615 resultParamObj[index] = paramTabData[index];
618 if (item.paramValue === "") {
619 resultParamObj[index] = paramTabData[index];
622 resultParamObj[index] = item.paramValue;
632 localStorage["paramsContent"] = JSON.stringify(resultParamObj);
633 templateData = Array.from(new Set(templateData.map((itemInArray) => itemInArray.paramName)))
635 //reformatting arr1 to match with PD
636 templateData.forEach(function (item) {
672 "ruleTypeValues": [null]
677 if (pdData && pdData != undefined) {
678 for (var i = 0; i < resultArr.length; i++) {
680 pdData.forEach(function (arr2item) {
681 if (resultArr[i].name === arr2item.name) {
684 "name": arr2item.name,
685 "type": arr2item.type,
686 "description": arr2item.description,
687 "required": arr2item.required,
688 "default": arr2item.default,
689 "source": arr2item.source,
690 "rule-type": arr2item["rule-type"],
691 "request-keys": arr2item["request-keys"],
692 "response-keys": arr2item["response-keys"],
693 "ruleTypeValues": arr2item.ruleTypeValues
695 resultArr.splice(i, 1, json)
703 this.paramShareService.setSessionParamData(resultArr);
704 this.mappingEditorService.paramData = [];
705 //navigate to PD page after sync
708 .navigate(['../../../vnfs/design/parameterDefinitions/create']);
711 //========================== End of syncTemplate() Method============================================
713 this.mergeStatus = this.mappingEditorService.autoAnnotateDataForParams();
714 if (this.mergeStatus) {
715 this.nService.success("Success", "Merge Successful");
718 this.nService.error("Error", "Merge Unsuccessful");
722 //========================== End of mergeParams() Method============================================
723 public handleAnnotation(modal) {
725 this.selectedWord = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
726 if(this.selectedWord && this.selectedWord!=undefined) modal.open();
728 //========================== End of handleAnnotations() Method============================================
729 public submitNameValues() {
731 this.checkNameEntered = true;
733 if (this.selectedWord) {
734 if (this.selectedWord.startsWith('${(')) {
735 var replaceWord: any =this.replaceWord = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
736 this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
739 let mappingKey = this.mappingEditorService.getKeysForValues(this.selectedWord);
740 var replaceWord: any = this.replaceWord='${(' + this.selectedWord + ')=(' + this.tempName + ')}';
741 this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
745 this.mappingEditorService.refreshEditor();
751 this.checkNameEntered = false;
755 //========================== End of submitNameValues() Method============================================