Update tomcat to 8.5
[portal.git] / ecomp-portal-FE-os / client / src / views / applications / application-details-dialog / application-details.controller.js
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 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 'use strict';
39 (function () {
40     class AppDetailsModalCtrl {
41         constructor($scope, $log, $timeout, applicationsService, errorMessageByCode,
42                     ECOMP_URL_REGEX,userProfileService, $cookies, confirmBoxService,items) {
43 //            let emptyImg = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
44             // empty image should really be empty, or it causes problems for the back end
45             let emptyImg = null;
46             this.emptyImgForPreview = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
47             $scope.ngDialogData=items;
48             let newAppModel = {
49                 'id': null,
50                 'name': null,
51                 'imageUrl': null,
52                 'description': null,
53                 'notes': null,
54                 'url': null,
55                 'alternateUrl': null,
56                 'restUrl': null,
57                 'isOpen': false,
58                 'username': null,
59                 'appPassword': null,
60                 'thumbnail': emptyImg,
61                 'isEnabled': false,
62                 'restrictedApp': false,
63                 'nameSpace': null,
64                 'isCentralAuth': false                
65             };
66
67             let init = () => {
68                 $log.info('AppDetailsModalCtrl::init');
69                 this.isSaving = false;
70                 if($scope.ngDialogData && $scope.ngDialogData.app){
71                     $log.debug('AppDetailsModalCtrl:init:: Edit app mode for', $scope.ngDialogData.app);
72                     this.isEditMode = true;
73                     this.app = _.clone($scope.ngDialogData.app);
74                 }else{
75                     $log.debug('AppDetailsModalCtrl:init:: New app mode');
76                     this.isEditMode = false;
77                     this.app = _.clone(newAppModel);
78                 }
79                 this.originalImage = null
80             };
81
82             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
83
84             this.imageApi = {};
85             this.removeImage = () => {
86                 $log.debug('AppDetailsModalCtrl:removeImage:: entering removeImage');
87
88                 confirmBoxService.confirm("Are you sure you want to remove the image?").then(isConfirmed => {
89                     if(isConfirmed){
90                         this.imageApi.clearFile();
91                         this.app.thumbnail = emptyImg;
92                         this.originalImage = null;
93                         this.app.imageUrl = null;
94                         this.app.imageLink = null;
95                     }
96                 }).catch(err => {
97                     $log.error('AppDetailsModalCtrl:removeImage error:: ',err);
98                 });
99             };
100
101             //This part handles conflict errors (409)
102             this.conflictMessages = {};
103             this.scrollApi = {};
104             let handleConflictErrors = err => {
105                 if(!err.data){
106                     return;
107                 }
108                 if(!err.data.length){ //support objects
109                     err.data = [err.data]
110                 }
111                 _.forEach(err.data, item => {
112                     _.forEach(item.fields, field => {
113                         //set conflict message
114                         this.conflictMessages[field.name] = errorMessageByCode[item.errorCode];
115                         //set field as invalid
116                         $scope.appForm[field.name].$setValidity('conflict', false);
117                         //set watch once to clear error after user correction
118                         watchOnce[field.name]();
119                     });
120                 });
121                 this.scrollApi.scrollTop();
122             };
123
124             let resetConflict = fieldName => {
125                 delete this.conflictMessages[fieldName];
126                 if($scope.appForm[fieldName]){
127                     $scope.appForm[fieldName].$setValidity('conflict', true);
128                 }
129             };
130
131
132             let emptyCookies = () => {
133                 $log.debug('AppDetailsModalCtrl:emptyCookies:: entering emptyCookies');
134                 userProfileService.getUserProfile()
135                     .then(profile=> {
136                         // $log.info(profile);
137                         $scope.orgUserId = profile.orgUserId;
138                         $log.debug('AppDetailsModalCtrl:emptyCookies for the following orgUserId: ' + profile.orgUserId);
139                         if ($cookies.getObject($scope.orgUserId + '_apps') != undefined && $cookies.getObject($scope.orgUserId + '_apps') != null) {
140                             $cookies.remove($scope.orgUserId + '_apps');
141                             $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_apps');
142                         }
143                         if ($cookies.getObject($scope.orgUserId + '_widget') != undefined && $cookies.getObject($scope.orgUserId + '_widget') != null) {
144                             $cookies.remove($scope.orgUserId + '_widget');
145                             $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_widget');
146                         }
147                     }).catch(err => {
148                         $log.error('AppDetailsModalCtrl:emptyCookies error:: '+ JSON.stringify(err));
149                     });
150             };
151
152
153             let watchOnce = {
154                 name: () => {
155                     let unregisterName = $scope.$watch('appDetails.app.name', (newVal, oldVal) => {
156                         // $log.debug('newVal, oldVal = ' + newVal.toLowerCase() + " | " + oldVal.toLowerCase())
157                         if(newVal.toLowerCase() !== oldVal.toLowerCase()){
158                             resetConflict('name');
159                             unregisterName();
160                         }
161                     });
162                 },
163                 url: () => {
164                     let unregisterUrl = $scope.$watch('appDetails.app.url', (newVal, oldVal) => {
165                         if(newVal.toLowerCase() !== oldVal.toLowerCase()) {
166                             resetConflict('url');
167                             unregisterUrl();
168                         }
169                     });
170                 }
171             };
172             //***************************
173
174             this.saveChanges = () => {
175                  //if valid..
176                 if(this.app.isCentralAuth){
177                     //if valid.
178                         if(!this.app.isEnabled)
179                                 {
180                                 if(((angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.nameSpace) || !this.app.nameSpace)
181                                          ||(angular.isUndefined(this.app.username) || !this.app.username))) {
182                                     confirmBoxService.showInformation('Please fill in all required fields for centralized application').then(isConfirmed => {});
183                             return;
184                            }
185                                 }
186                         if(this.app.isEnabled){
187                                 if(((angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
188                                          ||(angular.isUndefined(this.app.username) || !this.app.username)||(angular.isUndefined(this.app.nameSpace) || !this.app.nameSpace))) {
189                                  confirmBoxService.showInformation('Please fill in all required fields for centralized active application').then(isConfirmed => {});
190                             return;
191                         }
192                    }
193                         }else{
194                                 
195                                 if(!this.app.isEnabled)
196                                         {
197                                          if((angular.isUndefined(this.app.name) || !this.app.name)){
198                                                  confirmBoxService.showInformation('Please fill in all required field ApplicationName to Save the applictaion').then(isConfirmed => {});
199                                  return; 
200                                          }
201                                         }else if(this.app.isEnabled && !this.app.restrictedApp){
202                                     if(((angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
203                                          ||(angular.isUndefined(this.app.username) || !this.app.username)||(angular.isUndefined(this.app.appPassword) || !this.app.appPassword))) {
204                                     confirmBoxService.showInformation('Please fill in all required fields along with password as the app is not centralized').then(isConfirmed => {});
205                                  return;
206                                     } }else if(this.app.isEnabled && this.app.restrictedApp){
207                                 if((angular.isUndefined(this.app.name) || !this.app.name) ||(angular.isUndefined(this.app.url) || !this.app.url)){
208                                     confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
209                              return;
210                          
211                          }
212                            }
213                         }
214                 this.isSaving = true;
215                 // For a restricted app, null out all irrelevant fields
216                 if (this.app.restrictedApp) {
217                     this.app.restUrl = null;
218                     this.app.isOpen = true;
219                     this.app.username = null;
220                     this.app.appPassword = null;
221                     this.app.uebTopicName = null;
222                     this.app.uebKey = null;
223                     this.app.uebSecret = null;
224                 }
225                 if(this.isEditMode){
226                     if (this.app.nameSpace=="") {this.app.nameSpace = null;}
227                     applicationsService.updateOnboardingApp(this.app)
228                         .then(() => {
229                             $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: App update succeeded!');
230                           //  $scope.closeThisDialog(true);
231                             $scope.$dismiss('cancel');
232                             emptyCookies();
233                         }).catch(err => {
234                             switch (err.status) {
235                                 case '409':         // Conflict
236                                     handleConflictErrors(err);
237                                     break;
238                                 case '500':         // Internal Server Error
239                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
240                                         'Please try again later. Error: ' + err.status).then(isConfirmed => {});
241                                     break;
242                                 case '403':         // Forbidden... possible webjunction error to try again
243                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
244                                         'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
245                                     break;
246                                 default:
247                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
248                                         'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
249                             }
250                             $log.error('applicationsService:updateOnboardingApp error:: '+ JSON.stringify(err));
251                         }).finally(()=>{
252                             this.isSaving = false;
253                             // for bug in IE 11
254                             var objOffsetVersion = objAgent.indexOf("MSIE");
255                             if (objOffsetVersion != -1) {
256                                 $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh');
257                                 $window.location.reload();            // for bug in IE 11
258                             }
259                             // for bug in IE 11
260                         });
261                 }else{
262                     applicationsService.addOnboardingApp(this.app)
263                         .then(() => {
264                             $log.debug('App creation succeeded!');
265                             //$scope.closeThisDialog(true);
266                             $scope.$dismiss('cancel');
267                             emptyCookies();
268                         }).catch(err => {
269                             switch (err.status) {
270                                 case '409':         // Conflict
271                                     handleConflictErrors(err);
272                                     break;
273                                 case '500':         // Internal Server Error
274                                     confirmBoxService.showInformation('There was a problem adding the application information. ' +
275                                         'Please try again later. Error: ' + err.status).then(isConfirmed => {});
276                                     break;
277                                 default:
278                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
279                                         'Please try again. If the problem persists, then try again later. Error: ' +
280                                         err.status).then(isConfirmed => {});
281                             }
282                             $log.error('applicationsService:addOnboardingApp error:: '+ JSON.stringify(err));
283                         }).finally(()=>{
284                             this.isSaving = false;
285                             // for bug in IE 11
286                             var objOffsetVersion = objAgent.indexOf("MSIE");
287                             if (objOffsetVersion != -1) {
288                                 $log.debug('applicationsService:addOnboardingApp:: Browser is IE, forcing Refresh');
289                                 $window.location.reload();            // for bug in IE 11
290                             }
291                             // for bug in IE 11
292                         });
293                 }
294                 
295             };
296             
297          // Caches the file name supplied by the event handler.
298                 $scope.appImageHandler = (event, files) => {
299                         if(files[0]){
300                                 var fileName = files[0].name;
301                     var validFormats = ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
302                     //Get file extension
303                     var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); 
304                     //Check for valid format
305                     if(validFormats.indexOf(ext) == -1){
306                         $scope.appImageTypeError=true;
307                         $timeout(function(){
308                                 $scope.appImageTypeError=false;
309                         }, 5000);
310                     }
311                         }
312                 }; // file change handler
313
314
315             init();
316
317             $scope.$watch('appDetails.originalImage', (newVal, oldVal) => {
318               if((!newVal || !newVal.resized) && !this.app.imageUrl){
319                   if (!newVal) {
320                       $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is null');
321                   } else {
322                       $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is not resized and no imageUrl');
323                   }
324                   this.app.imageUrl = null;
325                   this.app.thumbnail = emptyImg;
326                   return;
327               }
328
329                 if(!(_.isEqual(newVal, oldVal))){
330                     $log.debug('applicationsService:$scope.$watch:: thumbnail updated!');
331                     this.app.imageUrl = null;
332                     this.app.imageLink = null;
333                     this.app.thumbnail = newVal.resized.dataURL;
334                 }
335             });
336
337             $scope.$on('$stateChangeStart', e => {
338                 //Disable navigation when modal is opened
339                 e.preventDefault();
340             });
341         }
342     }
343     AppDetailsModalCtrl.$inject = ['$scope', '$log', '$timeout', 'applicationsService', 'errorMessageByCode',
344         'ECOMP_URL_REGEX','userProfileService','$cookies', 'confirmBoxService','items'];
345     angular.module('ecompApp').controller('AppDetailsModalCtrl', AppDetailsModalCtrl);
346 })();