Fixed the test cases,added sonar config
[portal.git] / portal-FE-os / src / app / pages / application-onboarding / application-details-dialog / application-details-dialog.component.ts
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  *
37  */
38
39 import { Component, OnInit, Input, Output, EventEmitter, PLATFORM_ID, Inject, Injector} from '@angular/core';
40 import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
41 import { IApplications } from 'src/app/shared/model/applications-onboarding/applications';
42 import { ApplicationsService } from 'src/app/shared/services';
43 import { ConfirmationModalComponent } from 'src/app/modals/confirmation-modal/confirmation-modal.component';
44 import { InformationModalComponent } from 'src/app/modals/information-modal/information-modal.component';
45 import { isPlatformBrowser } from '@angular/common';
46
47 @Component({
48   selector: 'app-application-details-dialog',
49   templateUrl: './application-details-dialog.component.html',
50   styleUrls: ['./application-details-dialog.component.scss'],
51 })
52 export class ApplicationDetailsDialogComponent implements OnInit {
53
54   emptyImg = null;
55   emptyImgForPreview:string;
56   conflictMessages = {};
57   result: any;
58   isEditMode: boolean = false;
59   appImageTypeError: boolean = false;
60   isSaving: boolean = false;
61   originalImage: any;
62   ECOMP_URL_REGEX = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
63   private ngbModal:NgbModal;
64
65   constructor(public activeModal: NgbActiveModal,
66     public applicationsService : ApplicationsService,@Inject(PLATFORM_ID)private platformId:Object,private injector:Injector) {
67       if(isPlatformBrowser(this.platformId))
68       {
69         this.ngbModal = this.injector.get(NgbModal);
70       }
71      }
72
73   @Input() applicationObj: IApplications;
74   @Output() passEntry: EventEmitter<any> = new EventEmitter();
75
76   newAppModel = {
77     'id': null,
78     'name': null,
79     'imageUrl': null,
80     'description': null,
81     'notes': null,
82     'url': null,
83     'alternateUrl': null,
84     'restUrl': null,
85     'isOpen': false,
86     'username': null,
87     'appPassword': null,
88     'thumbnail': this.emptyImg,
89     'isEnabled': false,
90     'restrictedApp': false,
91     'nameSpace':null,
92     'isCentralAuth': false,
93     'uebTopicName':null,
94     'uebKey': null,
95     'uebSecret': null,
96     'imageLink': null
97   };
98
99
100   ngOnInit() {
101     if(this.applicationObj.id){
102       this.isEditMode = true;
103     }else{
104       this.isEditMode = false;
105     }
106     //console.log("isEditMode :: ",this.isEditMode);
107     this.originalImage = null
108     this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
109   }
110
111   appImageHandler(event: any){
112     var reader = new FileReader();
113     if(event.target.files && event.target.files[0]){
114       reader.readAsDataURL(event.target.files[0]); // read file as data url
115       var fileName = event.target.files[0].name;
116       var validFormats = ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
117       //Get file extension
118       var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
119       //console.log("fileName::>>",fileName ,ext)
120       //console.log("fileExtetion::>>",ext)
121       //Check for valid format
122       if(validFormats.indexOf(ext) == -1){
123           this.newAppModel.thumbnail = this.emptyImg;
124           this.originalImage = null;
125           this.applicationObj.imageUrl = null;
126           this.applicationObj.imageLink = null;
127           this.applicationObj.thumbnail = null;
128           if(!this.isEditMode){
129             this.newAppModel.imageUrl = null;
130             this.newAppModel.imageLink = null;
131             this.newAppModel.thumbnail = null;
132           }
133           this.appImageTypeError=true;
134       }else{
135         reader.onload = (event: any) => { // called once readAsDataURL is completed
136           this.applicationObj.imageLink = event.target.result;
137           this.applicationObj.imageUrl = event.target.result;
138           this.applicationObj.thumbnail = event.target.result;
139           this.originalImage =  event.target.result;
140           if(!this.isEditMode){
141             this.newAppModel.imageLink = event.target.result;
142             this.newAppModel.imageUrl = event.target.result;
143             this.newAppModel.thumbnail = event.target.result;
144             this.originalImage =  event.target.result;
145           }
146         }
147       }
148     }
149   }
150
151   removeImage(){
152     let confirmationMsg = 'Are you sure you want to remove the image?';
153     this.openInformationModal("Confirmation",confirmationMsg).result.then((result) => {
154       if (result === 'Ok') {
155         //this.imageApi.clearFile();
156         this.applicationObj.thumbnail = this.emptyImg;
157         this.originalImage = null;
158         this.applicationObj.imageUrl = null;
159         this.applicationObj.imageLink = null;
160         this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
161       }
162     }, (resut) => {
163       return;
164     })
165   }
166
167   /** Add/Edit Application Method*/
168   saveChanges() {
169     //console.log("addNewApplication getting called..");
170     if(this.applicationObj.isCentralAuth){
171         //if valid.
172         if(!this.applicationObj.isEnabled){
173           if(((this.applicationObj.name == 'undefined' || !this.applicationObj.name)||(this.applicationObj.nameSpace == 'undefined'
174           || !this.applicationObj.nameSpace) ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username))) {
175             this.openConfirmationModal('','Please fill in all required fields(*) for centralized application');
176             return;
177           }
178         }
179         if(this.applicationObj.isEnabled){
180           if(((this.applicationObj.name == 'undefined' || !this.applicationObj.name)
181           ||(this.applicationObj.url == 'undefined'|| !this.applicationObj.url)
182           ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username)||(this.applicationObj.nameSpace == 'undefined'
183           || !this.applicationObj.nameSpace))) {
184
185             this.openConfirmationModal('','Please fill in all required fields(*) for centralized active application');
186             return;
187           }
188         }
189     }else{
190         if(!this.applicationObj.isEnabled) {
191             if((this.applicationObj.name == 'undefined' || !this.applicationObj.name)){
192                 this.openConfirmationModal('','Please fill in all required field(*) ApplicationName to Save the applictaion');
193                 return;
194             }
195         }else if(this.applicationObj.isEnabled && !this.applicationObj.restrictedApp){
196           if((this.applicationObj.name == 'undefined' || !this.applicationObj.name)
197             ||(this.applicationObj.url == 'undefined'|| !this.applicationObj.url)
198             ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username)||
199             (this.applicationObj.appPassword== 'undefined' || !this.applicationObj.appPassword)) {
200
201               this.openConfirmationModal('','Please fill in all required fields(*) along with password as the app is not centralized');
202               return;
203           }
204         }else if(this.applicationObj.isEnabled && this.applicationObj.restrictedApp){
205             if((this.applicationObj.name == 'undefined' || !this.applicationObj.name) ||(this.applicationObj.url == 'undefined'
206             || !this.applicationObj.url)){
207                 this.openConfirmationModal('','Please fill in all required fields(*)');
208                 return;
209             }
210         }
211     }
212
213     //URL Validation
214     if(this.applicationObj.isEnabled){
215       if(this.applicationObj.url && this.applicationObj.url !='undefined' && this.applicationObj.url != ''){
216         let isValidURL = this.isUrlValid(this.applicationObj.url);
217         if(!isValidURL){
218           this.openConfirmationModal('Error','Application URL must be a valid URL.');
219           return;
220         }
221       }else{
222         this.openConfirmationModal('Error','Application URL is required.');
223         return;
224       }
225     }
226
227
228     this.isSaving = true;
229     // For a restricted app, null out all irrelevant fields
230     if(this.applicationObj.restrictedApp) {
231       this.newAppModel.restUrl = null;
232       this.newAppModel.isOpen = true;
233       this.newAppModel.username = null;
234       this.newAppModel.appPassword = null;
235       this.newAppModel.uebTopicName = null;
236       this.newAppModel.uebKey = null;
237       this.newAppModel.uebSecret = null;
238
239       /**Need to set below fields values based on input provided in the dialog */
240       this.newAppModel.restrictedApp = this.applicationObj.restrictedApp;
241       this.newAppModel.name = this.applicationObj.name;
242       this.newAppModel.url = this.applicationObj.url;
243       if(this.applicationObj.isEnabled){
244         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
245       }else{
246         this.newAppModel.isEnabled = false;
247       }
248
249     }else{
250
251        /**Need to set below fields values based on input provided in the dialog */
252        this.newAppModel.restrictedApp = false;
253        this.newAppModel.name = this.applicationObj.name;
254        this.newAppModel.url = this.applicationObj.url;
255        this.newAppModel.restUrl = this.applicationObj.restUrl;
256        this.newAppModel.username = this.applicationObj.username;
257        this.newAppModel.appPassword = this.applicationObj.appPassword;
258
259        if(this.applicationObj.isEnabled){
260         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
261        }else{
262         this.newAppModel.isEnabled = false;
263        }
264
265        if(this.applicationObj.isOpen){
266         this.newAppModel.isOpen = this.applicationObj.isOpen;
267        }else{
268         this.newAppModel.isOpen = false;
269        }
270        //console.log("this.applicationObj.isOpen",this.applicationObj.isOpen);
271
272        if(this.applicationObj.isCentralAuth){
273         this.newAppModel.isCentralAuth = this.applicationObj.isCentralAuth;
274        }else{
275         this.newAppModel.isCentralAuth = false;
276        }
277
278     }
279
280     if (this.applicationObj.nameSpace=="") {
281       this.newAppModel.nameSpace = null;
282     }
283
284     if(this.isEditMode){
285       this.applicationsService.updateOnboardingApp(this.applicationObj)
286         .subscribe( _data => {
287           this.result = _data;
288           //console.log("update application response :: ",this.result);
289           if(this.result !=null && this.result.httpStatusCode ==200){
290             this.passEntry.emit(this.result);
291             this.ngbModal.dismissAll();
292           }else{
293             this.openConfirmationModal('Error','There was a problem updating the application changes. Please try again. If the problem persists, then try again later. Error: '+this.result);
294             return
295           }
296         }, error => {
297           console.log(error);
298           if(error.status == 409){
299             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
300             'The Application Name and URL should  be unique.  Error: ' +
301             error.status);
302             return;
303           }else if(error.status == 500){
304             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
305             'Please try again later. Error: ' +error.status);
306             return;
307           }else if(error.status == 404 || error.status == 403){
308             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
309             'Invalid namespace. Error: ' +error.status);
310             return;
311           }else if(error.status == 401){
312             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
313             'Portal Mechid is unauthorized to access the given namespace. Error: ' +error.status);
314             return;
315           }else if(error.status == 400){
316             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
317             return;
318           } else{
319             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
320             'Please try again. If the problem persists, then try again later. Error: ' +
321             error.status);
322             return;
323           }
324       });
325
326     }else{
327       //console.log("Coming inside add application",this.newAppModel);
328
329       this.applicationsService.addOnboardingApp(this.newAppModel)
330         .subscribe( _data => {
331           this.result = _data;
332           //console.log("Add application response :: ",this.result);
333           if(this.result !=null && this.result.httpStatusCode ==200){
334             this.passEntry.emit(this.result);
335             this.ngbModal.dismissAll();
336           }else{
337             this.openConfirmationModal('Error','There was a problem adding the application changes. Please try again. If the problem persists, then try again later. Error: '+this.result);
338             return
339           }
340         }, error => {
341           console.log(error);
342           if(error.status == 409){
343             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
344             'The Application Name and URL should  be unique.  Error: ' +
345             error.status);
346             return;
347           } else if(error.status == 500){
348             this.openConfirmationModal('Error', 'There was a problem adding the application information. ' +
349             'Please try again later. Error: ' +error.status);
350             return;
351           }else if(error.status == 400){
352             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
353             return;
354           } else{
355             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
356             'Please try again. If the problem persists, then try again later. Error: ' +
357             error.status);
358             return;
359           }
360       });
361     }
362   }
363
364   isUrlValid(userInput){
365     //let  regexQuery = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
366     let  regexQuery = "https?://.+";
367     let res = userInput.match(regexQuery);
368     if(res == null){
369       return false;
370     }else{
371       return true;
372     }
373   }
374
375   openConfirmationModal(_title: string, _message: string) {
376     const modalInfoRef = this.ngbModal.open(ConfirmationModalComponent);
377     modalInfoRef.componentInstance.title = _title;
378     modalInfoRef.componentInstance.message = _message;
379   }
380
381   openInformationModal(_title: string, _message: string){
382     const modalInfoRef = this.ngbModal.open(InformationModalComponent);
383     modalInfoRef.componentInstance.title = _title;
384     modalInfoRef.componentInstance.message = _message;
385     return modalInfoRef;
386   }
387 }