]> source.dussan.org Git - archiva.git/blob
4784224b4a5d628dca49a2d193f9fdee7bc7f184
[archiva.git] /
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 define("archiva/admin/features/generaladmin/main",["jquery","i18n","utils","jquery.tmpl","knockout","knockout.simpleGrid",
20   "knockout.sortable","jquery.ui","jquery.validate","bootstrap","select2","knockout.select2"]
21     , function(jquery,i18n,utils,jqueryTmpl,ko,simpleGrid,sortable,jqueryUi,validate,bootstrap,select2) {
22
23   showMenu = function( administrationMenuItems) {
24         administrationMenuItems.push({  text : $.i18n.prop('menu.repository-scanning')      , order:2000, id: "menu-repository-scanning-list-a"    , href: "#scanningList"         , redback: "{permissions: ['archiva-manage-configuration']}", func: function(){displayRepositoryScanning();}});
25         administrationMenuItems.push({  text : $.i18n.prop('menu.runtime-configuration')    , order:2010, id: "menu-runtime-configuration-list-a"  , href: "#runtimeconfig"        , redback: "{permissions: ['archiva-manage-configuration']}", func: function(){displayRuntimeConfiguration();}});
26         administrationMenuItems.push({  text : $.i18n.prop('menu.system-status')            , order:2020, id: "menu-system-status-list-a"          , href: "#status"               , redback: "{permissions: ['archiva-manage-configuration']}", func: function(){displaySystemStatus();}});
27         administrationMenuItems.push({  text : $.i18n.prop('menu.sirona')                   , order:2030, id: "menu-system-sirona-list-a"          , href: "#sirona"               , redback: "{permissions: ['archiva-manage-configuration']}", func: function(){displaySirona();}});
28         administrationMenuItems.push({  text : $.i18n.prop('menu.ui-configuration')         , order:2040, id: "menu-ui-configuration-list-a"       , href: "#uiconfig"             , redback: "{permissions: ['archiva-manage-configuration']}", func: function(){displayUiConfiguration();}});
29         administrationMenuItems.push({  text : $.i18n.prop('menu.reports')                  , order:2050, id: "menu-report-list-a"                 , href: "#reports"              , redback: "{permissions: ['archiva-manage-configuration']}", func: function(){displayReportsPage();}});
30  
31   };
32  
33   //---------------------------
34   // repository scanning part
35   //---------------------------
36
37   FileType=function(id,patterns){
38     //private String id;
39     this.id=ko.observable(id);
40
41     //private List<String> patterns;
42     this.patterns=ko.observableArray(patterns);
43
44   };
45
46   mapFileType=function(data){
47     return new FileType(data.id,data.patterns);
48   };
49
50   mapFileTypes=function(data){
51     if (data!=null){
52       return $.isArray(data)? $.map(data,function(item){
53         return mapFileType(item)
54       }):[mapFileType(data)];
55     }
56     return [];
57   };
58
59   AdminRepositoryConsumer=function(enabled,id,description){
60     //private boolean enabled = false;
61     this.enabled=ko.observable(enabled);
62
63     //private String id;
64     this.id=ko.observable(id)
65
66     //private String description;
67     this.description=ko.observable(description);
68   }
69
70   mapAdminRepositoryConsumer=function(data){
71     return new AdminRepositoryConsumer(data.enabled,data.id,data.description);
72   }
73
74   mapAdminRepositoryConsumers=function(data){
75     if (data!=null){
76       return $.isArray(data)? $.map(data,function(item){
77         return mapAdminRepositoryConsumer(item)
78       }):[mapAdminRepositoryConsumer(data)];
79     }
80     return [];
81   }
82
83
84
85   RepositoryScanningViewModel=function(){
86     var self=this;
87     this.fileTypes=ko.observableArray([]);
88     this.knownAdminRepositoryConsumers=ko.observableArray([]);
89     this.invalidAdminRepositoryConsumers=ko.observableArray([]);
90
91     this.findFileType=function(id){
92       var fileType=null;
93       for (var i=0;i<self.fileTypes().length;i++){
94         if (id==self.fileTypes()[i].id()){
95           fileType=self.fileTypes()[i];
96         }
97       }
98       return fileType;
99     }
100
101     removeFileTypePattern=function(id,pattern){
102       clearUserMessages();
103       var url="restServices/archivaServices/archivaAdministrationService/removeFileTypePattern?"
104       url+="fileTypeId="+encodeURIComponent(id);
105       url+="&pattern="+encodeURIComponent(pattern);
106       $.ajax(url, {
107           type: "GET",
108           dataType: 'json',
109           success: function(data){
110             self.findFileType(id ).patterns.remove(pattern);
111             displaySuccessMessage( $.i18n.prop("repository-scanning.file-types.removed.pattern",id,pattern));
112
113           }
114       });
115     }
116
117     addFileTypePattern=function(id){
118       var pattern=$("#main-content #pattern-"+id ).val();
119       $.log("addFileTypePattern:"+id+":"+pattern);
120       clearUserMessages();
121       var url="restServices/archivaServices/archivaAdministrationService/addFileTypePattern?"
122       url+="fileTypeId="+encodeURIComponent(id);
123       url+="&pattern="+encodeURIComponent(pattern);
124       $.ajax(url, {
125           type: "GET",
126           dataType: 'json',
127           success: function(data){
128             self.findFileType(id ).patterns.push(pattern);
129             displaySuccessMessage( $.i18n.prop("repository-scanning.file-types.added.pattern",id,pattern));
130
131           }
132       });
133     }
134
135     disableKnowContentConsumer=function(adminRepositoryConsumer){
136       $.log("disableKnowContentConsumer");
137       clearUserMessages();
138       var userMessages=$("#user-messages" )
139       userMessages.html(mediumSpinnerImg());
140       var url="restServices/archivaServices/archivaAdministrationService/disabledKnownContentConsumer/"
141       url+=encodeURIComponent(adminRepositoryConsumer.id());
142       $.ajax(url, {
143           type: "GET",
144           dataType: 'json',
145           success: function(data){
146             adminRepositoryConsumer.enabled(false);
147             displaySuccessMessage( $.i18n.prop("repository-scanning.consumers.know.disabled",adminRepositoryConsumer.id()));
148             removeMediumSpinnerImg(userMessages);
149           }
150       });
151     }
152
153     enableKnowContentConsumer=function(adminRepositoryConsumer){
154       clearUserMessages();
155       var userMessages=$("#user-messages" )
156       userMessages.html(mediumSpinnerImg());
157       var url="restServices/archivaServices/archivaAdministrationService/enabledKnownContentConsumer/"
158       url+=encodeURIComponent(adminRepositoryConsumer.id());
159       $.ajax(url, {
160           type: "GET",
161           dataType: 'json',
162           success: function(data){
163             adminRepositoryConsumer.enabled(true);
164             displaySuccessMessage( $.i18n.prop("repository-scanning.consumers.know.enabled",adminRepositoryConsumer.id()));
165             removeMediumSpinnerImg(userMessages);
166           }
167       });
168     }
169
170     disableInvalidContentConsumer=function(adminRepositoryConsumer){
171       clearUserMessages();
172       var url="restServices/archivaServices/archivaAdministrationService/disabledInvalidContentConsumer/"
173       url+=encodeURIComponent(adminRepositoryConsumer.id());
174       $.ajax(url, {
175           type: "GET",
176           dataType: 'json',
177           success: function(data){
178             adminRepositoryConsumer.enabled(false);
179             displaySuccessMessage( $.i18n.prop("repository-scanning.consumers.invalid.disabled",adminRepositoryConsumer.id()));
180           }
181       });
182     }
183
184     enableInvalidContentConsumer=function(adminRepositoryConsumer){
185       clearUserMessages();
186       var url="restServices/archivaServices/archivaAdministrationService/enabledInvalidContentConsumer/"
187       url+=encodeURIComponent(adminRepositoryConsumer.id());
188       $.ajax(url, {
189           type: "GET",
190           dataType: 'json',
191           success: function(data){
192             adminRepositoryConsumer.enabled(true);
193             displaySuccessMessage( $.i18n.prop("repository-scanning.consumers.invalid.enabled",adminRepositoryConsumer.id()));
194           }
195       });
196     }
197
198   }
199
200   displayRepositoryScanning=function(){
201     screenChange();
202     var mainContent=$("#main-content");
203
204     mainContent.html($("#repository-scanning-main").tmpl());
205     mainContent.find("#file-types-content").html(mediumSpinnerImg());
206     mainContent.find("#consumers-known-content").html(mediumSpinnerImg());
207     mainContent.find("#consumers-invalid-content").html(mediumSpinnerImg());
208
209     var repositoryScanningViewModel=new RepositoryScanningViewModel();
210
211     $.ajax("restServices/archivaServices/archivaAdministrationService/getFileTypes", {
212         type: "GET",
213         dataType: 'json',
214         success: function(data){
215           var fileTypes=mapFileTypes(data);
216           repositoryScanningViewModel.fileTypes(fileTypes);
217           ko.applyBindings(repositoryScanningViewModel,mainContent.find("#file-types-content").get(0));
218         }
219     });
220
221     $.ajax("restServices/archivaServices/archivaAdministrationService/getKnownContentAdminRepositoryConsumers", {
222         type: "GET",
223         dataType: 'json',
224         success: function(data){
225           var knownAdminRepositoryConsumers=mapAdminRepositoryConsumers(data);
226           repositoryScanningViewModel.knownAdminRepositoryConsumers(knownAdminRepositoryConsumers);
227           ko.applyBindings(repositoryScanningViewModel,mainContent.find("#consumers-known-content").get(0));
228         }
229     });
230
231     $.ajax("restServices/archivaServices/archivaAdministrationService/getInvalidContentAdminRepositoryConsumers", {
232         type: "GET",
233         dataType: 'json',
234         success: function(data){
235           var invalidAdminRepositoryConsumers=mapAdminRepositoryConsumers(data);
236           repositoryScanningViewModel.invalidAdminRepositoryConsumers(invalidAdminRepositoryConsumers);
237           ko.applyBindings(repositoryScanningViewModel,mainContent.find("#consumers-invalid-content").get(0));
238         }
239     });
240
241   }
242
243   //---------------------------
244   // network configuration part
245   //---------------------------
246
247   NetworkConfiguration=function(maxTotal,maxTotalPerHost,usePooling){
248     //private int maxTotal = 30;
249     this.maxTotal=ko.observable(maxTotal);
250
251     //private int maxTotalPerHost = 30;
252     this.maxTotalPerHost=ko.observable(maxTotalPerHost);
253
254     //private boolean usePooling = true;
255     this.usePooling=ko.observable(usePooling);
256   }
257
258   NetworkConfigurationViewModel=function(networkConfiguration){
259     var self=this;
260     this.networkConfiguration=ko.observable(networkConfiguration);
261
262     save=function(){
263       var userMessages=$("#user-messages");
264
265       var mainContent=$("#main-content");
266
267       if (!mainContent.find("#network-configuration-edit-form").valid()){
268         return;
269       }
270       userMessages.html(mediumSpinnerImg());
271       mainContent.find("#network-configuration-btn-save" ).button('loading');
272       $.ajax("restServices/archivaServices/archivaAdministrationService/setNetworkConfiguration", {
273         type: "POST",
274         contentType: 'application/json',
275         data: ko.toJSON(self.networkConfiguration),
276         dataType: 'json',
277         success: function(data){
278           displaySuccessMessage( $.i18n.prop("network-configuration.updated"));
279         },
280         complete: function(){
281           removeMediumSpinnerImg(userMessages);
282           mainContent.find("#network-configuration-btn-save" ).button('reset');
283         }
284       });
285     }
286   }
287
288   displayRuntimeConfiguration=function(){
289     screenChange();
290     var mainContent=$("#main-content");
291
292     mainContent.html($("#runtime-configuration-screen").tmpl());
293     mainContent.find("#network-configuration-form" ).html(mediumSpinnerImg());
294     $.ajax("restServices/archivaServices/archivaAdministrationService/getNetworkConfiguration", {
295         type: "GET",
296         dataType: 'json',
297         success: function(data){
298
299           var networkConfiguration=new NetworkConfiguration(data.maxTotal,data.maxTotalPerHost,data.usePooling);
300           var networkConfigurationViewModel=new NetworkConfigurationViewModel(networkConfiguration);
301           ko.applyBindings(networkConfigurationViewModel,mainContent.find("#network-configuration-form-content").get(0));
302           var validator = mainContent.find("#network-configuration-edit-form")
303                   .validate({
304                               showErrors: function(validator, errorMap, errorList) {
305                                 customShowError(mainContent.find("#network-configuration-edit-form" ),validator,errorMap,errorMap);
306                               }
307                             });
308         }
309     });
310
311
312     $.ajax("restServices/archivaServices/archivaRuntimeConfigurationService/archivaRuntimeConfiguration", {
313       type: "GET",
314       dataType: 'json',
315       success: function(data){
316
317         var archivaRuntimeConfiguration=mapArchivaRuntimeConfiguration(data);
318         var archivaRuntimeConfigurationViewModel=new ArchivaRuntimeConfigurationViewModel(archivaRuntimeConfiguration);
319         ko.applyBindings(archivaRuntimeConfigurationViewModel,mainContent.find("#cache-failure-form").get(0));
320         ko.applyBindings(archivaRuntimeConfigurationViewModel,mainContent.find("#filelocking-form").get(0));
321         mainContent.find("#cache-failure-form-id")
322                 .validate({
323                             showErrors: function(validator, errorMap, errorList) {
324                               customShowError(mainContent.find("#cache-failure-form-id" ),validator,errorMap,errorMap);
325                             }
326                           });
327       }
328     });
329
330   }
331
332   ArchivaRuntimeConfigurationViewModel=function(archivaRuntimeConfiguration){
333     var self=this;
334     this.archivaRuntimeConfiguration=ko.observable(archivaRuntimeConfiguration);
335
336     save=function(){
337       var userMessages=$("#user-messages");
338
339       var mainContent=$("#main-content");
340
341       if (!mainContent.find("#cache-failure-form-id").valid()){
342         return;
343       }
344       userMessages.html(mediumSpinnerImg());
345       mainContent.find("#cache-failure-form-btn-save" ).button('loading');
346       $.ajax("restServices/archivaServices/archivaRuntimeConfigurationService/archivaRuntimeConfiguration", {
347         type: "PUT",
348         contentType: 'application/json',
349         data: ko.toJSON(self.archivaRuntimeConfiguration),
350         dataType: 'json',
351         success: function(data){
352           displaySuccessMessage( $.i18n.prop("archiva.runtime-configuration.updated"));
353         },
354         error:function(){
355           displayErrorMessage("error.500");
356         }
357       } ).always(
358           function(){
359             removeMediumSpinnerImg(userMessages);
360             mainContent.find("#cache-failure-form-btn-save" ).button('reset');
361           }
362         );
363     }
364   }
365
366   FileLockConfiguration=function(skipLocking,lockingTimeout){
367     //private boolean skipLocking = true;
368     this.skipLocking=ko.observable(skipLocking);
369     //private int lockingTimeout = 0;
370     this.lockingTimeout=ko.observable(lockingTimeout) ;
371   }
372
373   ArchivaRuntimeConfiguration=function(cacheConfiguration,fileLockConfiguration){
374     this.urlFailureCacheConfiguration=ko.observable(cacheConfiguration);
375     this.fileLockConfiguration=ko.observable(fileLockConfiguration);
376   }
377
378   mapFileLockConfiguration=function(data){
379     if (!data){
380       return null;
381     }
382     return new FileLockConfiguration(data.skipLocking,data.lockingTimeout);
383   }
384
385   mapArchivaRuntimeConfiguration=function(data){
386     if(!data){
387       return null;
388     }
389     return new ArchivaRuntimeConfiguration(data.urlFailureCacheConfiguration?mapCacheConfiguration(data.urlFailureCacheConfiguration):null,
390                                            data.fileLockConfiguration?mapFileLockConfiguration(data.fileLockConfiguration):null);
391   }
392   //---------------------------
393   // organisation/appearance configuration part
394   //---------------------------
395   OrganisationInformation=function(name,url,logoLocation){
396     this.name=ko.observable(name);
397     this.url=ko.observable(url);
398     this.logoLocation=ko.observable(logoLocation);
399   }
400   mapOrganisationInformation=function(data){
401     return new OrganisationInformation(data.name, data.url, data.logoLocation);
402   }
403   mapOrganisationInformations=function(data){
404     if (data!=null){
405       return $.isArray(data)? $.map(data, function(item){
406         return mapOrganisationInformation(item);
407       }):[mapOrganisationInformation(data)];
408     }
409   }
410   activateOrganisationInformationFormValidation=function(){
411     var validate = $("#main-content" ).find("#appearance-configuration-form-id")
412       .validate({
413         rules: {
414           name: {
415             required: true
416           },
417           url: {
418             required:true,
419             url:true
420           },
421           logoLocation: {
422             required:false,
423             url:true
424           }
425         },
426         showErrors: function(validator, errorMap, errorList) {
427           $.log("activateOrganisationInformationFormValidation#customShowError");
428           customShowError($("#main-content" ).find("#appearance-configuration-form-id"), validator, errorMap, errorMap);
429         }
430       });
431   }
432   OrganisationInformationViewModel=function(organisationInformation){
433
434     this.organisationInformation=ko.observable(organisationInformation);
435
436     this.save=function(){
437       $.log("OrganisationInformationViewModel#save");
438       var mainContent=$("#main-content" );
439       if (!mainContent.find("#appearance-configuration-form-id").valid()) {
440         return;
441       }
442       clearUserMessages();
443       var userMessages=$("#user-messages");
444       userMessages.html(mediumSpinnerImg());
445       mainContent.find("#appearance-configuration-btn-save" ).button('loading');
446       $.ajax("restServices/archivaServices/archivaAdministrationService/setOrganisationInformation", {
447         type: "POST",
448         contentType: "application/json",
449         data: ko.toJSON(this.organisationInformation),
450         dataType: "json",
451         success: function(data){
452           displaySuccessMessage($.i18n.prop('appearance-configuration.updated'));
453           updateAppearanceToolBar();
454         },
455         error: function(data){
456           displayErrorMessage($.i18n.prop('appearance-configuration.updating-error'));
457         },
458         complete: function(){
459           removeMediumSpinnerImg(userMessages);
460           mainContent.find("#appearance-configuration-btn-save" ).button('reset');
461         }
462       });
463     }
464   }
465
466
467   //---------------------------
468   // UiConfiguration part
469   //---------------------------
470
471   UiConfiguration=function(showFindArtifacts,appletFindEnabled,disableEasterEggs,applicationUrl,disableRegistration){
472     this.showFindArtifacts = ko.observable(showFindArtifacts);
473
474     this.appletFindEnabled = ko.observable(appletFindEnabled);
475
476     this.disableEasterEggs = ko.observable(disableEasterEggs);
477
478     this.applicationUrl = ko.observable(applicationUrl);
479
480     // default to false
481     this.disableRegistration = ko.observable(disableRegistration?disableRegistration:false);
482   }
483
484   UiConfigurationViewModel=function(uiConfiguration){
485     this.uiConfiguration=ko.observable(uiConfiguration);
486     var self=this;
487     save=function(){
488       var mainContent=$("#main-content" );
489       var userMessages=$("#user-messages");
490       userMessages.html( mediumSpinnerImg());
491       mainContent.find("#ui-configuration-btn-save" ).button('loading');
492       $.ajax("restServices/archivaServices/archivaAdministrationService/setUiConfiguration", {
493         type: "POST",
494         contentType: 'application/json',
495         data: ko.toJSON(self.uiConfiguration),
496         dataType: 'json',
497         success: function(data){
498           displaySuccessMessage( $.i18n.prop("ui-configuration.updated"));
499         },
500         complete: function(){
501           removeMediumSpinnerImg(userMessages);
502           mainContent.find("#ui-configuration-btn-save" ).button('reset');
503         }
504       });
505     }
506   }
507
508   displayUiConfiguration=function(){
509     var mainContent=$("#main-content");
510
511     mainContent.html($("#ui-configuration" ).tmpl());
512
513     mainContent.find("#ui-configuration-form").html(mediumSpinnerImg());
514
515     $.ajax("restServices/archivaServices/archivaAdministrationService/getUiConfiguration", {
516       type: "GET",
517       dataType: 'json',
518       success: function(data){
519         var uiConfiguration=new UiConfiguration(data.showFindArtifacts,data.appletFindEnabled,data.disableEasterEggs,
520                                                 data.applicationUrl,data.disableRegistration);
521         var uiConfigurationViewModel=new UiConfigurationViewModel(uiConfiguration);
522         ko.applyBindings(uiConfigurationViewModel,mainContent.find("#ui-configuration-form").get(0));
523       }
524     });
525
526     $.ajax("restServices/archivaServices/archivaAdministrationService/getOrganisationInformation", {
527       type: "GET",
528       dataType: 'json',
529       success: function(data) {
530         var organisationInformation=new OrganisationInformation(data.name,data.url,data.logoLocation);
531         var organisationInformationViewModel=new OrganisationInformationViewModel(organisationInformation);
532         ko.applyBindings(organisationInformationViewModel, mainContent.find("#change-appearance-form").get(0));
533         activateOrganisationInformationFormValidation();
534       }
535     });
536   }
537
538   //---------------------------
539   // System status part
540   //---------------------------
541
542   QueueEntry=function(key,entriesNumber){
543     this.key=key;
544     this.entriesNumber=entriesNumber;
545   }
546
547
548   mapQueueEntries=function(data){
549     if (data!=null){
550       return $.map(data,function(item){
551         return new QueueEntry(item.key,item.entriesNumber);
552       })
553     }
554     return [];
555   }
556
557   CacheEntry=function(key,size,cacheHits,cacheMiss,cacheHitRate,inMemorySize){
558     this.key=key;
559     this.size=size;
560     this.cacheHits=cacheHits;
561     this.cacheMiss=cacheMiss;
562     this.cacheHitRate=cacheHitRate;
563     this.inMemorySize=inMemorySize;
564   }
565
566   mapCacheEntries=function(data){
567     if(data!=null){
568       return $.map(data,function(item){
569         return new CacheEntry(item.key,item.size,item.cacheHits,item.cacheMiss,item.cacheHitRate,item.inMemorySize);
570       })
571     }
572     return [];
573   }
574
575
576
577   displayCacheEntries=function(){
578     var divContent = $("#main-content" ).find("#status_caches");
579     divContent.html(smallSpinnerImg());
580     $.ajax("restServices/archivaServices/systemStatusService/cacheEntries", {
581         type: "GET",
582         success: function(data){
583           var cacheEntries=mapCacheEntries(data);
584           divContent.html($("#status_caches_tmpl" ).tmpl({cacheEntries: cacheEntries}));
585         }
586     });
587   }
588
589   flushCache=function(key){
590     clearUserMessages();
591     $("#main-content" ).find("#status_caches").html(smallSpinnerImg());
592     $.ajax("restServices/archivaServices/systemStatusService/clearCache/"+encodeURIComponent(key), {
593         type: "GET",
594         success: function(data){
595           displaySuccessMessage( $.i18n.prop("system-status.caches.flushed",key));
596           displayCacheEntries();
597         }
598     });
599   }
600
601   flushAllCaches=function(){
602     clearUserMessages();
603     $("#main-content" ).find("#status_caches").html(smallSpinnerImg());
604     $.ajax("restServices/archivaServices/systemStatusService/clearAllCaches", {
605         type: "GET",
606         success: function(data){
607           displaySuccessMessage( $.i18n.prop("system-status.caches.all.flushed"));
608           displayCacheEntries();
609         }
610     });
611   }
612
613   mapRepositoryScannerStatisticsList=function(data){
614     if(data!=null){
615       return $.isArray(data)? $.map(data,function(item){
616         return mapRepositoryScannerStatistics(item);
617       }):[data];
618     }
619     return [];
620   }
621
622
623   mapRepositoryScannerStatistics=function(data){
624     return new RepositoryScannerStatistics(mapManagedRepository(data.managedRepository),data.totalFileCount,
625                                             data.newFileCount,data.consumerScanningStatistics);
626   }
627
628   RepositoryScannerStatistics=function(managedRepository,totalFileCount,newFileCount,consumerScanningStatisticsList){
629     //private ManagedRepository managedRepository;
630     this.managedRepository=managedRepository
631
632     this.consumerScanningStatisticsList= consumerScanningStatisticsList;
633
634     //private long totalFileCount = 0;
635     this.totalFileCount=totalFileCount;
636
637     //private long newFileCount = 0;
638     this.newFileCount=newFileCount;
639   }
640
641   displayScanningStats=function(){
642     var divContent = $("#main-content" ).find("#status_scanning");
643     divContent.html(smallSpinnerImg());
644     $.ajax("restServices/archivaServices/systemStatusService/repositoryScannerStatistics", {
645         type: "GET",
646         success: function(data){
647           var stats= mapRepositoryScannerStatisticsList(data);
648           $.log("size:"+data.length);
649           divContent.html($("#status_scanning_tmpl").tmpl({repositoryScannerStatisticsList:stats}));
650         }
651     });
652   }
653
654   displayMemoryUsage=function(){
655     var divContent = $("#main-content" ).find("#status_memory_info");
656     divContent.html(smallSpinnerImg());
657     $.ajax("restServices/archivaServices/systemStatusService/memoryStatus", {
658         type: "GET",
659         dataType: "text",
660         success: function(data){
661           var memUsage = data;
662           $.log("memUsage:"+memUsage);
663           divContent.html(memUsage);
664         }
665     });
666   }
667
668   displayQueueEntries=function(){
669     var divContent = $("#main-content" ).find("#status_queues");
670     divContent.html(smallSpinnerImg());
671     $.ajax("restServices/archivaServices/systemStatusService/queueEntries", {
672         type: "GET",
673         success: function(data){
674           var queueEntries=mapQueueEntries(data);
675           divContent.html($("#status_queues_tmpl" ).tmpl({queueEntries: queueEntries}));
676         }
677     });
678   }
679
680   displayServerTime=function(){
681     var divContent = $("#main-content" ).find("#status_current_time");
682     divContent.html(smallSpinnerImg());
683     $.ajax("restServices/archivaServices/systemStatusService/currentServerTime/"+encodeURIComponent(usedLang()), {
684         type: "GET",
685         dataType: "text",
686         success: function(data){
687           var curTime=data;
688           $.log("currentServerTime:"+curTime);
689           divContent.html(curTime);
690         }
691     });
692   }
693
694   displaySystemStatus=function(){
695     screenChange();
696     var mainContent=$("#main-content");
697     mainContent.html($("#system-status-main").tmpl());
698
699     var versionInfo=window.archivaRuntimeInfo.version+" - "
700             +$.i18n.prop('system-status.header.version.buildNumber')+": "+window.archivaRuntimeInfo.buildNumber
701             +" - "+$.i18n.prop('system-status.header.version.timestampStr')+": "+window.archivaRuntimeInfo.timestampStr;
702     mainContent.find("#status_version_info").html(versionInfo);
703
704     displayMemoryUsage();
705
706     displayServerTime();
707
708     displayQueueEntries();
709
710     displayScanningStats();
711
712     displayCacheEntries();
713   }
714
715   displaySirona=function(){
716     window.open("sirona-monitoring/", '_blank');
717     window.focus();
718   }
719
720   refreshSystemStatus=function(){
721     displayCacheEntries();
722     displayScanningStats();
723     displayMemoryUsage();
724     displayQueueEntries();
725     displayServerTime();
726   }
727
728   //---------------------------
729   // report configuration page
730   //---------------------------
731   StatisticsReportRequest=function() {
732     this.repositories = ko.observableArray( [] );
733     this.rowCount = ko.observable(100);
734     this.startDate = ko.observable();
735     this.endDate = ko.observable();
736   }
737
738   reportStatisticsFormValidator=function(){
739     $.log("reportStatisticsFormValidator");
740     var validate = $("#main-content" ).find("#report-statistics-form-id").validate({
741       rules: {
742         rowCountStatistics: {
743           required:true,
744           number: true,
745           min: 10
746         },
747         startDate: {
748           date: true
749         },
750         endDate: {
751           date: true
752         }
753       },
754       showErrors: function(validator, errorMap, errorList) {
755         $.log("showErrors");
756         customShowError("#main-content #report-statistics-form-id", validator, errorMap, errorMap);
757       }
758     })
759   }
760   ReportStatisticsViewModel=function(repositoriesAvailable){
761     var mainContent=$("#main-content");
762     reportStatisticsFormValidator();
763
764     var self=this;
765     this.availableRepositories = ko.observableArray( repositoriesAvailable );
766     this.statisticsReport = ko.observable( new StatisticsReportRequest() );
767
768     mainContent.find("#startDate" ).datepicker();
769     mainContent.find("#endDate" ).datepicker();
770     mainContent.find("#rowcount-info-button" ).popover();
771
772     this.showStatistics=function() {
773       $.log("showStatistics");
774       clearUserMessages( "repositoriesErrorMessage" );
775       if (!mainContent.find("#report-statistics-form-id").valid()) {
776         return;
777       }
778       if(this.statisticsReport().repositories().length==0){
779         displayErrorMessage( $.i18n.prop('report.statistics.repositories.required'), "repositoriesErrorMessage" );
780         return;
781       }
782
783       var resultTabContent = mainContent.find("#report-result");
784
785       url = "restServices/archivaServices/reportServices/getStatisticsReport/?rowCount="
786         + this.statisticsReport().rowCount();
787
788       for(var i=0;i<this.statisticsReport().repositories().length;i++){
789         url += "&repository=" + this.statisticsReport().repositories()[i];
790       }
791
792       if(this.statisticsReport().startDate()!=null){
793         url += "&startDate=" + this.statisticsReport().startDate();
794       }
795       if(this.statisticsReport().endDate()!=null){
796         url += "&endDate=" + this.statisticsReport().endDate();
797       }
798
799       $.ajax(url, {
800         type: "GET",
801         contentType: 'application/json',
802         dataType: 'json',
803         success: function(data){
804           resultTabContent.html( $( "#report-statistics" ).tmpl() );
805           var reportStatistics = new ReportStatisticsResultViewModel( data );
806           ko.applyBindings( reportStatistics, resultTabContent.get( 0 ) );
807           var reportResultTabLi=$( "#report-result-tab-li");
808           reportResultTabLi.removeClass( "hide" );
809           reportResultTabLi.addClass( "active" );
810           $( "#report-stat-tab-li" ).removeClass( "active" );
811           $( "#report-stat-tab-content" ).removeClass( "active" );
812           resultTabContent.addClass( "active" );
813         },
814         error: function(data){
815           var res = $.parseJSON(data.responseText);
816           displayErrorMessage($.i18n.prop(res.errorMessage));
817         }
818       });
819     }
820   }
821   ReportStatisticsResultViewModel=function(report){
822     this.reports = ko.observableArray( report );
823     var self = this;
824
825     this.tableReportViewModel = new ko.simpleGrid.viewModel({
826       data: this.reports,
827       viewModel: this,
828       columns: [
829         { headerText: "Repository ID", rowText: "repositoryId" },
830         { headerText: "Start Date", rowText: function(item){return new Date(item.scanStartTime);}},
831         { headerText: "Total File Count", rowText: "totalFileCount" },
832         { headerText: "Total Size", rowText: "totalArtifactFileSize" },
833         { headerText: "Artifact Count", rowText: "totalArtifactCount" },
834         { headerText: "Group Count", rowText: "totalGroupCount" },
835         { headerText: "Project Count", rowText: "totalProjectCount" },
836         { headerText: "Archetypes", rowText: function (item) { return !item.totalCountForType.pom || item.totalCountForType.pom === "" ? "0" : item.totalCountForType.pom } },
837         { headerText: "Jars", rowText: function (item) { return !item.totalCountForType.war || item.totalCountForType.jar === "" ? "0" : item.totalCountForType.jar } },
838         { headerText: "Wars", rowText: function (item) { return !item.totalCountForType.war || item.totalCountForType.war === "" ? "0" : item.totalCountForType.jar } },
839         { headerText: "Ears", rowText: function (item) { return !item.totalCountForType.ear || item.totalCountForType.ear === "" ? "0" : item.totalCountForType.ear } },
840         { headerText: "Exes", rowText: function (item) { return !item.totalCountForType.exe || item.totalCountForType.exe === "" ? "0" : item.totalCountForType.exe } },
841         { headerText: "Dlls", rowText: function (item) { return !item.totalCountForType.dll || item.totalCountForType.dll === "" ? "0" : item.totalCountForType.dll} },
842         { headerText: "Zips", rowText: function (item) { return !item.totalCountForType.zip || item.totalCountForType.zip === "" ? "0" : item.totalCountForType.zip } }
843       ],
844       pageSize: 10
845     });
846   }
847
848   HealthReportRequest=function(){
849     this.repositoryId = ko.observable();
850     this.rowCount = ko.observable(100);
851     this.groupId = ko.observable();
852   }
853   HealthReportResult=function(repositoryId,namespace,project,version,id,message,problem,name,facetId){
854     this.repositoryId = repositoryId;
855     this.namespace = namespace;
856     this.project = project;
857     this.version = version;
858     this.id = id;
859     this.message = message;
860     this.problem = problem;
861     this.name = name;
862     this.facetId = facetId;
863   }
864   mapHealthReportResult=function(data){
865     if(data==null) return;
866     return new HealthReportResult( data.repositoryId, data.namespace, data.project, data.version, data.id, data.message,
867                                    data.problem, data.name, data.facetId );
868   }
869   mapHealthReportResults=function(data){
870     if (data != null)
871     {
872       return $.isArray(data)? $.map(data, function(item){
873         return mapHealthReportResult(item);
874       }):[mapHealthReportResult(data)];
875     }
876     return [];
877   }
878   ReportHealthResultViewModel=function(report){
879     this.reports = ko.observableArray( report );
880     var self = this;
881     this.tableReportViewModel = new ko.simpleGrid.viewModel({
882       data: this.reports,
883       viewModel: this,
884       columns: [
885         { headerText: "ID", rowText: "id" },
886         { headerText: "Namespace", rowText: "namespace" },
887         { headerText: "Project", rowText: "project" },
888         { headerText: "Version", rowText: "version" },
889         { headerText: "Name", rowText: "name" },
890         { headerText: "Problem", rowText: "problem" },
891         { headerText: "Message", rowText: "message" }
892         ],
893       pageSize: 10
894     });
895   }
896
897   reportHealthFormValidator=function(){
898     var validate = $("#main-content" ).find("#report-health-form-id").validate({
899       rules: {
900         rowCountHealth: {
901           required: true,
902           number: true,
903           min: 10
904         },
905         repositoryId: {
906           required: true
907         }
908       },
909       showErrors: function(validator, errorMap, errorList) {
910         customShowError("#main-content #report-health-form-id", validator, errorMap, errorMap);
911       }
912     })
913   }
914   ReportHealthViewModel=function(){
915     reportHealthFormValidator();
916     this.healthReport = ko.observable(new HealthReportRequest());
917
918     this.showHealth=function() {
919       if (!$("#main-content" ).find("#report-health-form-id").valid()) {
920         return;
921       }
922
923       var resultTabContent = $("#main-content" ).find("#report-result");
924
925       var url =
926         "restServices/archivaServices/reportServices/getHealthReports/" + this.healthReport().repositoryId() + "/"
927           + this.healthReport().rowCount();
928
929       if (this.healthReport().groupId())
930       {
931         url += "?groupId=" + this.healthReport().groupId();
932       }
933
934       $.ajax(url, {
935         type: "GET",
936         contentType: 'application/json',
937         dataType: 'json',
938         success: function(data){
939           var reports = new ReportHealthResultViewModel( mapHealthReportResults( data ) );
940           resultTabContent.html( $( "#report-health" ).tmpl() );
941           ko.applyBindings( reports, resultTabContent.get( 0 ) );
942           var reportResultTabLi=$( "#report-result-tab-li" );
943           reportResultTabLi.removeClass( "hide" );
944           reportResultTabLi.addClass( "active" );
945           $( "#report-health-tab-li" ).removeClass( "active" );
946           $( "#report-health-tab-content" ).removeClass( "active" );
947           resultTabContent.addClass( "active" );
948         },
949         error: function(data){
950             var res = $.parseJSON(data.responseText);
951             displayRestError(res);
952           }
953       });
954     }
955   }
956
957   displayReportsPage=function(){
958     screenChange();
959     clearUserMessages();
960     var mainContent = $("#main-content");
961     mainContent.html(mediumSpinnerImg());
962     $.ajax("restServices/archivaServices/searchService/observableRepoIds", {
963       type: "GET",
964       dataType: 'json',
965       success: function(data) {
966         var repos = mapStringList( data );
967         mainContent.html( $( "#report-base" ).tmpl( {repositoriesList:repos} ) );
968         var statisticsReportViewModel = ReportStatisticsViewModel( repos );
969         var healthReportViewModel = ReportHealthViewModel( );
970         ko.applyBindings( statisticsReportViewModel, mainContent.get( 0 ) );
971         ko.applyBindings( healthReportViewModel, mainContent.get( 0 ) );
972       }
973     });
974   }
975
976
977   RedbackRuntimeConfiguration=function(userManagerImpls,ldapConfiguration,migratedFromRedbackConfiguration,configurationPropertiesEntries
978                                       ,useUsersCache,cacheConfiguration,rbacManagerImpls){
979     $.log("new RedbackRuntimeConfiguration");
980     var self=this;
981     this.modified=ko.observable(false);
982     this.modified.subscribe(function(newValue){$.log("RedbackRuntimeConfiguration modified")});
983
984     this.userManagerImpls=ko.observableArray(userManagerImpls);
985     this.userManagerImpls.subscribe(function(newValue){self.modified(true)});
986
987     this.rbacManagerImpls=ko.observableArray(rbacManagerImpls);
988     this.rbacManagerImpls.subscribe(function(newValue){self.modified(true)});
989
990     this.ldapConfiguration=ko.observable(ldapConfiguration);
991     this.ldapConfiguration.subscribe(function(newValue){self.modified(true)});
992
993     this.migratedFromRedbackConfiguration=ko.observable(migratedFromRedbackConfiguration);
994
995     this.configurationPropertiesEntries=ko.observableArray(configurationPropertiesEntries?configurationPropertiesEntries:[]);
996     this.configurationPropertiesEntries.subscribe(function(newValue){
997       self.modified(true);
998       $.log("configurationPropertiesEntries modified")
999     });
1000
1001     this.findPropertyValue=function(key){
1002       for(var i=0;i<self.configurationPropertiesEntries().length;i++){
1003         if(self.configurationPropertiesEntries()[i].key==key){
1004           var val = self.configurationPropertiesEntries()[i].value;
1005           $.log("findPropertyValue " + key + "->" + val);
1006           return val;
1007         }
1008       }
1009     }
1010
1011     this.useUsersCache=ko.observable(useUsersCache);
1012     this.useUsersCache.subscribe(function(newValue){self.modified(true)});
1013
1014     this.usersCacheConfiguration=ko.observable(cacheConfiguration);
1015     this.usersCacheConfiguration.subscribe(function(newValue){self.modified(true)});
1016
1017     this.ldapGroups=ko.observableArray([]);
1018     this.ldapGroups.subscribe(function(newValue){self.modified(true)});
1019
1020     this.ldapGroupMappings=ko.observableArray([]);
1021     this.ldapGroupMappings.subscribe(function(newValue){
1022       self.modified(true);
1023       $.log('ldapGroupMappings modified:'+newValue.group);
1024     });
1025
1026   }
1027
1028   mapRedbackRuntimeConfiguration=function(data){
1029
1030     var ldapConfiguration=mapLdapConfiguration(data.ldapConfiguration);
1031
1032     var redbackRuntimeConfiguration =
1033             new RedbackRuntimeConfiguration(data.userManagerImpls,ldapConfiguration,data.migratedFromRedbackConfiguration,[]
1034                     ,data.useUsersCache,mapCacheConfiguration(data.usersCacheConfiguration),data.rbacManagerImpls);
1035
1036     $.log("redbackRuntimeConfiguration.rbacManagerImpls:"+redbackRuntimeConfiguration.rbacManagerImpls().length);
1037     var configurationPropertiesEntries = data.configurationPropertiesEntries == null ? []: $.each(data.configurationPropertiesEntries,function(item){
1038       var entry = new Entry(item.key, item.value,function(newValue){
1039         redbackRuntimeConfiguration.modified(true);
1040       });
1041       return entry;
1042     });
1043
1044     if (!$.isArray(configurationPropertiesEntries)){
1045       configurationPropertiesEntries=[];
1046     }
1047
1048     redbackRuntimeConfiguration.configurationPropertiesEntries(configurationPropertiesEntries);
1049     redbackRuntimeConfiguration.modified(false);
1050     return redbackRuntimeConfiguration;
1051
1052   }
1053
1054   LdapConfiguration=function(hostName,port,ssl,baseDn,baseGroupsDn,contextFactory,bindDn,password,authenticationMethod,
1055                              extraPropertiesEntries,writable,useRoleNameAsGroup,bindAuthenticatorEnabled){
1056
1057     var self=this;
1058     this.modified=ko.observable(false);
1059
1060     //private String hostName;
1061     this.hostName=ko.observable(hostName);
1062     this.hostName.subscribe(function(newValue){self.modified(true)});
1063
1064     //private String port;
1065     this.port=ko.observable(port);
1066     this.port.subscribe(function(newValue){self.modified(true)});
1067
1068     //private boolean ssl = false;
1069     this.ssl=ko.observable(ssl);
1070     this.ssl.subscribe(function(newValue){self.modified(true)});
1071
1072     //private String baseDn;
1073     this.baseDn=ko.observable(baseDn);
1074     this.baseDn.subscribe(function(newValue){self.modified(true)});
1075
1076     //private String baseGroupsDn;
1077     this.baseGroupsDn=ko.observable(baseGroupsDn);
1078     this.baseGroupsDn.subscribe(function(newValue){self.modified(true)});
1079
1080     //private String contextFactory;
1081     this.contextFactory=ko.observable(contextFactory);
1082     this.contextFactory.subscribe(function(newValue){self.modified(true)});
1083
1084     //private String bindDn;
1085     this.bindDn=ko.observable(bindDn);
1086     this.bindDn.subscribe(function(newValue){self.modified(true)});
1087
1088     //private String password;
1089     this.password=ko.observable(password);
1090     this.password.subscribe(function(newValue){self.modified(true)});
1091
1092     //private String authenticationMethod;
1093     this.authenticationMethod=ko.observable(authenticationMethod);
1094     this.authenticationMethod.subscribe(function(newValue){self.modified(true)});
1095
1096     this.extraPropertiesEntries=ko.observableArray(extraPropertiesEntries);
1097     this.extraPropertiesEntries.subscribe(function(newValue){self.modified(true)});
1098
1099     //private boolean writable = false;
1100     this.writable=ko.observable(writable);
1101     this.writable.subscribe(function(newValue){self.modified(true)});
1102
1103     // useRoleNameAsGroup
1104     this.useRoleNameAsGroup=ko.observable(useRoleNameAsGroup);
1105     this.useRoleNameAsGroup.subscribe(function(newValue){self.modified(true)});
1106
1107     //bindAuthenticatorEnabled
1108     this.bindAuthenticatorEnabled=ko.observable(bindAuthenticatorEnabled);
1109     this.bindAuthenticatorEnabled.subscribe(function(newValue){self.modified(true)});
1110
1111   }
1112
1113   mapLdapConfiguration=function(data){
1114     $.log("mapLdapConfiguration");
1115       if(data){
1116         var extraPropertiesEntries = data.extraPropertiesEntries == null ? []: $.each(data.extraPropertiesEntries,function(item){
1117             return new Entry(item.key, item.value);
1118         });
1119         if (!$.isArray(extraPropertiesEntries)){
1120             extraPropertiesEntries=[];
1121         }
1122         $.log("mapLdapConfiguration done");
1123         return new LdapConfiguration(data.hostName,data.port,data.ssl,data.baseDn,data.baseGroupsDn,data.contextFactory,data.bindDn,data.password,
1124                                     data.authenticationMethod,extraPropertiesEntries,data.writable,data.useRoleNameAsGroup,data.bindAuthenticatorEnabled);
1125       }
1126       return null;
1127   }
1128
1129   RedbackRuntimeConfigurationViewModel=function(redbackRuntimeConfiguration,userManagerImplementationInformations,rbacManagerImplementationInformations){
1130     var self=this;
1131     this.redbackRuntimeConfiguration=ko.observable(redbackRuntimeConfiguration);
1132     this.userManagerImplementationInformations=ko.observableArray(userManagerImplementationInformations);
1133     this.rbacManagerImplementationInformations=ko.observableArray(rbacManagerImplementationInformations);
1134
1135     this.usedUserManagerImpls=ko.observableArray([]);
1136
1137     this.usedRbacManagerImpls=ko.observableArray([]);
1138
1139     this.modifiesLdapGroupMappings=ko.observableArray([]);
1140
1141     this.availableUserManagerImpls=ko.observableArray([]);
1142     this.availableRbacManagerImpls=ko.observableArray([]);
1143
1144     this.allRoleNames=ko.observableArray([]);
1145
1146     findUserManagerImplementationInformation=function(id){
1147       for(var i= 0;i<self.userManagerImplementationInformations().length;i++){
1148         $.log(id+""+self.userManagerImplementationInformations()[i].beanId);
1149         if(id==self.userManagerImplementationInformations()[i].beanId){
1150           return self.userManagerImplementationInformations()[i];
1151         }
1152       }
1153     }
1154
1155     findRbacManagerImplementationInformation=function(id){
1156       for(var i= 0;i<self.rbacManagerImplementationInformations().length;i++){
1157         $.log(id+""+self.rbacManagerImplementationInformations()[i].beanId);
1158         if(id==self.rbacManagerImplementationInformations()[i].beanId){
1159           return self.rbacManagerImplementationInformations()[i];
1160         }
1161       }
1162     }
1163
1164     checkLdapServerConfiguration=function(){
1165       $.log("checkLdapServerConfiguration");
1166       clearUserMessages();
1167       var btn = $("#ldap-configuration-check-server");
1168       btn.button('loading');
1169       var userMessages=$("#user-messages");
1170       userMessages.html(mediumSpinnerImg());
1171       $.log("checkChangedLdapConfiguration");
1172       $.ajax("restServices/archivaServices/redbackRuntimeConfigurationService/checkLdapConnection",
1173              {
1174                type: "GET",
1175                success: function(data) {
1176                  var message=$.i18n.prop('redback.runtime.ldap.verified');
1177                  displaySuccessMessage(message);
1178                },
1179                error: function(data) {
1180                  try{
1181                    var res = $.parseJSON(data.responseText);
1182                    displayRestError(res);
1183                  }catch (e){
1184                    displayErrorMessage( $.i18n.prop("error.500"));
1185                  }
1186
1187                }
1188              }
1189       ).always(
1190         function(data){
1191           removeMediumSpinnerImg(userMessages);
1192           btn.button('reset');
1193         }
1194       );
1195     }
1196
1197     checkChangedLdapConfiguration=function(){
1198       clearUserMessages();
1199       var btn = $("#ldap-configuration-check-modification");
1200       btn.button('loading');
1201       var userMessages=$("#user-messages");
1202       userMessages.html(mediumSpinnerImg());
1203       $.log("checkChangedLdapConfiguration");
1204       $.ajax("restServices/archivaServices/redbackRuntimeConfigurationService/checkLdapConnection",
1205              {
1206                type: "POST",
1207                contentType: 'application/json',
1208                data:ko.toJSON(self.redbackRuntimeConfiguration().ldapConfiguration),
1209                dataType: 'json',
1210                success: function(data) {
1211                  var message=$.i18n.prop('redback.runtime.ldap.verified');
1212                  displaySuccessMessage(message);
1213                },
1214                error: function(data) {
1215                  try{
1216                    var res = $.parseJSON(data.responseText);
1217                    displayRestError(res);
1218                  }catch (e){
1219                    displayErrorMessage( $.i18n.prop("error.500"));
1220                  }
1221                }
1222              }
1223       ).always(
1224         function(data){
1225           removeMediumSpinnerImg(userMessages);
1226           btn.button('reset');
1227         }
1228       );
1229     }
1230
1231     for(var i= 0;i<redbackRuntimeConfiguration.userManagerImpls().length;i++){
1232       var id=redbackRuntimeConfiguration.userManagerImpls()[i];
1233
1234       var userManagerImplementationInformation=findUserManagerImplementationInformation(id);
1235
1236       if(userManagerImplementationInformation!=null){
1237         this.usedUserManagerImpls.push(userManagerImplementationInformation);
1238       }
1239     }
1240
1241     $.log("init usedUserManagerImpls done");
1242
1243     for(var i= 0;i<redbackRuntimeConfiguration.rbacManagerImpls().length;i++){
1244       var id=redbackRuntimeConfiguration.rbacManagerImpls()[i];
1245
1246       var rbacManagerImplementationInformation=findRbacManagerImplementationInformation(id);
1247
1248       if(rbacManagerImplementationInformation!=null){
1249         this.usedRbacManagerImpls.push(rbacManagerImplementationInformation);
1250       }
1251     }
1252
1253     $.log("init usedUserManagerImpls done");
1254
1255     isUsedUserManagerImpl=function(userManagerImplementationInformation){
1256       for(var i=0;i<self.usedUserManagerImpls().length;i++){
1257         if(self.usedUserManagerImpls()[i].beanId==userManagerImplementationInformation.beanId){
1258           return true;
1259         }
1260       }
1261       return false;
1262     }
1263
1264     for(var i=0;i<self.userManagerImplementationInformations().length;i++){
1265       if(!isUsedUserManagerImpl(self.userManagerImplementationInformations()[i])){
1266         self.availableUserManagerImpls.push(self.userManagerImplementationInformations()[i]);
1267       }
1268     }
1269
1270     userManagerImplMoved=function(arg){
1271       $.log("userManagerImplMoved");
1272       self.redbackRuntimeConfiguration().modified(true);
1273     }
1274
1275     isUsedRbacManagerImpl=function(rbacManagerImplementationInformation){
1276       for(var i=0;i<self.usedRbacManagerImpls().length;i++){
1277         if(self.usedRbacManagerImpls()[i].beanId==rbacManagerImplementationInformation.beanId){
1278           return true;
1279         }
1280       }
1281       return false;
1282     }
1283
1284
1285
1286     for(var i=0;i<self.rbacManagerImplementationInformations().length;i++){
1287       if(!isUsedRbacManagerImpl(self.rbacManagerImplementationInformations()[i])){
1288         self.availableRbacManagerImpls.push(self.rbacManagerImplementationInformations()[i]);
1289       }
1290     }
1291
1292     rbacManagerImplMoved=function(arg){
1293       $.log("rbacManagerImplMoved");
1294       self.redbackRuntimeConfiguration().modified(true);
1295     }
1296
1297     saveRedbackRuntimeConfiguration=function(){
1298
1299       var mainContent=$("#main-content");
1300       var valid = mainContent.find("#redback-runtime-general-form-id").valid();
1301       if (valid==false) {
1302         return;
1303       }
1304       var useLdap = false;
1305       for(var i=0;i<self.usedUserManagerImpls().length;i++){
1306         var beanId=self.usedUserManagerImpls()[i].beanId;
1307         $.log("beanId:"+beanId);
1308         if(beanId=='ldap'){
1309           useLdap=true;
1310         }
1311       }
1312       $.log("useLdap:"+useLdap);
1313       if(useLdap==true) {
1314         valid = mainContent.find("#redback-runtime-ldap-form-id").valid();
1315         $.log("ldap valid:"+valid);
1316         if (valid==false) {
1317           return;
1318         }
1319       }
1320
1321       clearUserMessages();
1322
1323       if (self.usedUserManagerImpls().length<1){
1324         displayErrorMessage( $.i18n.prop("error.redback.runtimeconfiguration.user-managers.empty"));
1325         valid=false;
1326       }
1327
1328       if (self.usedRbacManagerImpls().length<1){
1329         displayErrorMessage( $.i18n.prop("error.redback.runtimeconfiguration.rbac-managers.empty"));
1330         valid=false;
1331       }
1332
1333       if(valid==false){
1334         return;
1335       }
1336
1337       $.log("saveRedbackRuntimeConfiguration");
1338       var saveButton = mainContent.find("#redback-runtime-configuration-save" );
1339       saveButton.button('loading');
1340       clearUserMessages();
1341       var userMessages=$("#user-messages");
1342       userMessages.html(mediumSpinnerImg());
1343
1344       self.redbackRuntimeConfiguration().userManagerImpls=ko.observableArray([]);
1345
1346       for(var i=0;i<self.usedUserManagerImpls().length;i++){
1347         var beanId=self.usedUserManagerImpls()[i].beanId;
1348         $.log("beanId:"+beanId);
1349         self.redbackRuntimeConfiguration().userManagerImpls.push(beanId);
1350       }
1351
1352
1353       self.redbackRuntimeConfiguration().rbacManagerImpls=ko.observableArray([]);
1354
1355       for(var i=0;i<self.usedRbacManagerImpls().length;i++){
1356         var beanId=self.usedRbacManagerImpls()[i].beanId;
1357         $.log("beanId:"+beanId);
1358         self.redbackRuntimeConfiguration().rbacManagerImpls.push(beanId);
1359       }
1360
1361
1362       $.log("rememberme enabled:"+self.redbackRuntimeConfiguration().findPropertyValue("security.rememberme.enabled"));
1363       $.ajax("restServices/archivaServices/redbackRuntimeConfigurationService/redbackRuntimeConfiguration",
1364         {
1365           type: "PUT",
1366           contentType: 'application/json',
1367           data:ko.toJSON(self.redbackRuntimeConfiguration),
1368           dataType: 'json',
1369           success: function(data) {
1370             var message=$.i18n.prop('redback-runtime-configuration.updated');
1371             window.sammyArchivaApplication.runRoute("get","#redbackruntimeconfig");
1372             displaySuccessMessage(message);
1373           },
1374           error: function(data) {
1375             var res = $.parseJSON(data.responseText);
1376             displayRestError(res);
1377           }
1378         }
1379       ).always(
1380         function(){
1381           removeMediumSpinnerImg(userMessages);
1382           saveButton.button('reset');
1383           self.redbackRuntimeConfiguration().modified(false);
1384           self.redbackRuntimeConfiguration().ldapConfiguration().modified(false);
1385           saveModifyLdapGroupMapping();
1386         }
1387       );
1388
1389
1390
1391     }
1392
1393     saveModifyLdapGroupMapping=function(){
1394       //save modified ldap group mappings if any
1395       if(self.modifiesLdapGroupMappings().length>0){
1396         $.log("save modifiesLdapGroupMappings");
1397         var message=$.i18n.prop('redback-runtime-ldap-group-mapping.updated');
1398         var userMessages=$("#user-messages");
1399         var ldapGroupMappings=[];
1400         $.each(self.modifiesLdapGroupMappings(),function(idx,item){
1401
1402           if(!(item.automatic&item.roleNames().length<2)){
1403             $.log("update mapping for group:"+item.group());
1404             ldapGroupMappings.push(item);
1405           }
1406         });
1407
1408         if (ldapGroupMappings.length>0){
1409
1410           var mainContent=$("#main-content");
1411           var saveButton = mainContent.find("#redback-runtime-configuration-save" );
1412           saveButton.button('loading');
1413           userMessages.html(mediumSpinnerImg());
1414           $.ajax("restServices/redbackServices/ldapGroupMappingService",
1415                  {
1416                    type: "POST",
1417                    contentType: 'application/json',
1418                    data:ko.toJSON(new LdapGroupMappingUpdateRequest(ldapGroupMappings)),
1419                    dataType: 'json',
1420                    success: function(data) {
1421                      displaySuccessMessage(message);
1422                    },
1423                    error: function(data) {
1424                      var res = $.parseJSON(data.responseText);
1425                      displayRestError(res);
1426                    },
1427                    complete:function(data){
1428                      removeMediumSpinnerImg(userMessages);
1429                      saveButton.button('reset');
1430                      self.redbackRuntimeConfiguration().modified(false);
1431                      self.redbackRuntimeConfiguration().ldapConfiguration().modified(false);
1432                    }
1433                  }
1434           );
1435         }
1436
1437
1438       } else {
1439         $.log("not save modifiesLdapGroupMappings");
1440       }
1441       self.modifiesLdapGroupMappings=ko.observableArray([]);
1442     }
1443     this.modifiesLdapGroupMappings=ko.observableArray([]);
1444
1445     this.modifyLdapGroupMapping=function(roleNames,ldapGroupMapping){
1446       var toAdd=true;
1447       $.each(self.modifiesLdapGroupMappings(),function(idx,item){
1448         if(item.group()==ldapGroupMapping.group()){
1449           toAdd=false;
1450         }
1451       });
1452       if(toAdd){
1453         self.modifiesLdapGroupMappings().push(ldapGroupMapping);
1454       }
1455       $.log('modifyLdapGroupMapping:'+ldapGroupMapping.group()+','+self.modifiesLdapGroupMappings().length);
1456     };
1457     //olamy could be better but some reason doesn't work and I didn't find enough to understand why :-)
1458     /*self.gridldapMappingsViewModel = new ko.simpleGrid.viewModel({
1459      data: self.redbackRuntimeConfiguration().ldapGroupMappings,
1460      pageSize: 10,
1461      gridUpdateCallBack: function(){
1462        $.log("ldapGroupsMapping: gridUpdateCallBack");
1463        $("#main-content").find("#ldap-group-mappings-div select" ).select2({width: "element"});
1464      }
1465     });*/
1466
1467     self.gridViewModel = new ko.simpleGrid.viewModel({
1468      data: self.redbackRuntimeConfiguration().configurationPropertiesEntries,
1469      columns: [
1470        {
1471          headerText: $.i18n.prop('redback.runtime.properties.key.label'),
1472          rowText: "key"
1473        },
1474        {
1475          headerText: $.i18n.prop('redback.runtime.properties.value.label'),
1476          rowText: "value"
1477        }
1478      ],
1479      pageSize: 10,
1480      gridUpdateCallBack: function(){
1481        activatePopoverDoc();
1482      }
1483     });
1484
1485     this.newLdapGroupMapping=ko.observable(new LdapGroupMapping("",[],false,null));
1486
1487     addLdapGroupMapping=function(){
1488       // FIXME validate datas from ldapGroupMapping
1489       $.log("addLdapGroupMapping:"+self.newLdapGroupMapping().group()+",roles:"+self.newLdapGroupMapping().roleNames().length);
1490       clearUserMessages();
1491
1492       if (self.newLdapGroupMapping().roleNames().length<1){
1493         displayErrorMessage( $.i18n.prop('redback-runtime-ldap-group-mapping.role.mandatory'));
1494         return;
1495       }
1496
1497       var mainContent=$("#main-content");
1498       var saveButton = mainContent.find("#redback-runtime-configuration-save" );
1499       saveButton.button('loading');
1500       clearUserMessages();
1501       var userMessages=$("#user-messages");
1502       userMessages.html(mediumSpinnerImg());
1503       $.ajax("restServices/redbackServices/ldapGroupMappingService",
1504              {
1505                type: "PUT",
1506                contentType: 'application/json',
1507                data:ko.toJSON(new LdapGroupMapping(self.newLdapGroupMapping().group(),self.newLdapGroupMapping().roleNames(),false,null)),
1508                dataType: 'json',
1509                success: function(data) {
1510                  self.redbackRuntimeConfiguration().ldapGroupMappings
1511                          .unshift(new LdapGroupMapping(self.newLdapGroupMapping().group(),self.newLdapGroupMapping().roleNames(),false,self.modifyLdapGroupMapping));
1512                  $.log("addLdapGroupMapping:"+self.redbackRuntimeConfiguration().ldapGroupMappings().length);
1513                  var message=$.i18n.prop('redback-runtime-ldap-group-mapping.added');
1514                  displaySuccessMessage(message);
1515                },
1516                error: function(data) {
1517                  var res = $.parseJSON(data.responseText);
1518                  displayRestError(res);
1519                }
1520              }
1521       ).always(
1522         function(){
1523           removeMediumSpinnerImg(userMessages);
1524           $.log("addLdapGroupMapping#always");
1525           //self.newLdapGroupMapping.group("");
1526           //self.newLdapGroupMapping.roleNames([]);
1527           //self.newLdapGroupMapping(new LdapGroupMapping("",[],false,null));
1528           saveButton.button('reset');
1529         }
1530       );
1531
1532
1533     }
1534
1535     deleteLdapGroupMapping=function(ldapGroupMapping){
1536
1537
1538       var mainContent=$("#main-content");
1539       var saveButton = mainContent.find("#redback-runtime-configuration-save" );
1540       saveButton.button('loading');
1541       clearUserMessages();
1542       var userMessages=$("#user-messages");
1543       userMessages.html(mediumSpinnerImg());
1544       $.ajax("restServices/redbackServices/ldapGroupMappingService/"+ldapGroupMapping.group(),
1545              {
1546                type: "DELETE",
1547                contentType: 'application/json',
1548                dataType: 'json',
1549                success: function(data) {
1550                  $.log("deleteLdapGroupMapping:"+ldapGroupMapping.group());
1551                  self.redbackRuntimeConfiguration().ldapGroupMappings.remove(ldapGroupMapping);
1552                  var message=$.i18n.prop('redback-runtime-ldap-group-mapping.deleted');
1553                  displaySuccessMessage(message);
1554                },
1555                error: function(data) {
1556                  var res = $.parseJSON(data.responseText);
1557                  displayRestError(res);
1558                }
1559              }
1560       ).always(
1561         function(){
1562           removeMediumSpinnerImg(userMessages);
1563           saveButton.button('reset');
1564         }
1565       );
1566     }
1567   }
1568
1569   ManagerImplementationInformation=function(beanId,descriptionKey,readOnly){
1570     this.beanId=beanId;
1571     this.descriptionKey=descriptionKey;
1572     this.description= $.i18n.prop(descriptionKey);
1573     this.readOnly=readOnly;
1574   }
1575
1576   mapManagerImplementationInformations=function(data){
1577     return $.map(data, function(item) {
1578       return mapManagerImplementationInformation(item);
1579     });
1580   }
1581
1582   mapManagerImplementationInformation=function(data){
1583     if(data==null){
1584       return null;
1585     }
1586     return new ManagerImplementationInformation(data.beanId,data.descriptionKey,data.readOnly);
1587   }
1588
1589   activateRedbackRuntimeGeneralFormValidation=function(){
1590     var formSelector=$("#main-content" ).find("#redback-runtime-general-form-id");
1591     var validator = formSelector.validate({
1592       rules: {
1593         usersCacheTimeToLiveSeconds : {
1594          digits: true,
1595          min: 1,
1596          required: true
1597        },
1598         usersCacheTimeToIdleSeconds : {
1599           digits: true,
1600           min: 1,
1601           required: true
1602         },
1603         maxElementsInMemory : {
1604           digits: true,
1605           min: 1,
1606           required: true
1607         },
1608         maxElementsOnDisk : {
1609           digits: true,
1610           min: 1,
1611           required: true
1612         }
1613       },
1614       showErrors: function(validator, errorMap, errorList) {
1615        customShowError(formSelector,validator,errorMap,errorMap);
1616       }
1617       });
1618   }
1619
1620   activateLdapConfigurationFormValidation=function(){
1621     var formSelector=$("#main-content" ).find("#redback-runtime-ldap-form-id");
1622     var validator = formSelector.validate({
1623       rules: {
1624         ldapHost : {
1625           required: true
1626         },
1627         ldapPort : {
1628           digits: true,
1629           min: 1,
1630           required: true
1631         }
1632       },
1633       showErrors: function(validator, errorMap, errorList) {
1634         customShowError(formSelector,validator,errorMap,errorMap);
1635       }
1636     });
1637   }
1638
1639   displayRedbackRuntimeConfiguration=function(){
1640     var jqueryUi = require("jquery.ui");
1641     $.log("displayRuntimeConfiguration");
1642     var mainContent = $("#main-content");
1643     mainContent.html(mediumSpinnerImg());
1644
1645     $.ajax("restServices/archivaServices/redbackRuntimeConfigurationService/redbackImplementationsInformations", {
1646       type: "GET",
1647       dataType: 'json',
1648       success: function(data) {
1649         var userManagerImplementationInformations=data?mapManagerImplementationInformations(data.userManagerImplementationInformations):[];
1650         var rbacManagerImplementationInformations=data?mapManagerImplementationInformations(data.rbacManagerImplementationInformations):[];
1651         $.log("rbacManagerImplementationInformations:"+rbacManagerImplementationInformations.length);
1652         $.ajax("restServices/archivaServices/redbackRuntimeConfigurationService/redbackRuntimeConfiguration", {
1653           type: "GET",
1654           dataType: 'json',
1655           success: function(data) {
1656             var redbackRuntimeConfiguration = mapRedbackRuntimeConfiguration(data);
1657             $.log("before new RedbackRuntimeConfigurationViewModel");
1658             var redbackRuntimeConfigurationViewModel =
1659                 new RedbackRuntimeConfigurationViewModel(redbackRuntimeConfiguration,userManagerImplementationInformations,rbacManagerImplementationInformations);
1660
1661             var groups=[];
1662             $.log("before useLdap:"+$.inArray("ldap",redbackRuntimeConfiguration.userManagerImpls())
1663                           +','+$.inArray("ldap",redbackRuntimeConfiguration.rbacManagerImpls()));
1664             var useLdap = $.inArray("ldap",redbackRuntimeConfiguration.userManagerImpls())>=0
1665                     ||$.inArray("ldap",redbackRuntimeConfiguration.rbacManagerImpls())>=0;
1666             $.log("useLdap:"+useLdap);
1667             if(useLdap){
1668               $.log("in get ldap groups");
1669
1670               // load ldap roles
1671               $.ajax("restServices/redbackServices/ldapGroupMappingService/ldapGroups", {
1672                 type: "GET",
1673                 dataType: 'json',
1674                 success: function(data){
1675                   groups = mapStringList(data);
1676                   $.log("groups number:"+groups.length);
1677                   redbackRuntimeConfiguration.ldapGroups=ko.observableArray(groups);
1678                 }
1679               } )
1680               .always(
1681                 function() {
1682                   $.log("complete");
1683
1684                   // load ldap group mappings if any
1685                   $.ajax("restServices/redbackServices/ldapGroupMappingService", {
1686                     type: "GET",
1687                     dataType: 'json',
1688                     success: function(data) {
1689                       var groupMappings=mapLdapGroupMappings(data,redbackRuntimeConfigurationViewModel.modifyLdapGroupMapping);
1690
1691                       $.ajax("restServices/redbackServices/roleManagementService/allRoles", {
1692                         type: "GET",
1693                         dataType: 'json',
1694                         success: function(data) {
1695                           displayRuntimeConfigurationScreen(redbackRuntimeConfigurationViewModel,data,groupMappings,groups);
1696                         }
1697                       });
1698                     }
1699                   });
1700                 }
1701               );
1702             } else {
1703               $.log("before displayRuntimeConfigurationScreen");
1704               displayRuntimeConfigurationScreen(redbackRuntimeConfigurationViewModel,null,null);
1705             }
1706           }
1707         });
1708
1709       }
1710     });
1711
1712   }
1713
1714   displayRuntimeConfigurationScreen=function(redbackRuntimeConfigurationViewModel,allRoles,groupMappings,groups){
1715     var allRoleNames = $.map(allRoles?allRoles:[], function(item) {
1716       return item.name;
1717     });
1718
1719     redbackRuntimeConfigurationViewModel.allRoleNames=ko.observableArray(allRoleNames);
1720
1721     if (redbackRuntimeConfigurationViewModel.redbackRuntimeConfiguration().ldapConfiguration().useRoleNameAsGroup()&&groups) {
1722       // if using groups == roles add all as mapping except already mapped
1723       $.each(groups,function(idx,item){
1724         var exists=false;
1725         // avoid duplicate if mapping really exists !
1726         $.each(groupMappings,function(idx2,groupMapping){
1727           if(groupMapping.group()==item){
1728             exists=true;
1729           }
1730         });
1731         if(!exists){
1732           groupMappings.push(new LdapGroupMapping(item,[item],true,redbackRuntimeConfigurationViewModel.modifyLdapGroupMapping));
1733         }
1734
1735       });
1736     }
1737
1738     redbackRuntimeConfigurationViewModel.redbackRuntimeConfiguration().ldapGroupMappings=ko.observableArray(groupMappings?groupMappings:[]);
1739     redbackRuntimeConfigurationViewModel.redbackRuntimeConfiguration().modified(false);
1740
1741     $("#main-content").html( $("#redback-runtime-configuration-main" ).tmpl() );
1742     $.log("applyBindings:#redback-runtime-configuration-content:"+redbackRuntimeConfigurationViewModel.redbackRuntimeConfiguration().ldapGroupMappings().length);
1743     ko.applyBindings(redbackRuntimeConfigurationViewModel,$("#redback-runtime-configuration-content" ).get(0));
1744     activateRedbackRuntimeGeneralFormValidation();
1745     activateLdapConfigurationFormValidation();
1746   }
1747
1748   LdapGroupMapping=function(group,roleNames,automatic,subscribeFn){
1749     var self=this;
1750     this.modified=ko.observable(false);
1751     //private String group;
1752     this.group=ko.observable(group);
1753     this.group.subscribe(function(newValue){
1754       self.modified(true);
1755       if(subscribeFn){
1756         subscribeFn(newValue,self)
1757       }
1758     });
1759
1760     //private Collection<String> roleNames;
1761     this.roleNames=ko.observableArray(roleNames);
1762     this.roleNames.subscribe(function(newValue){
1763       self.modified(true);
1764       $.log("roleNames modified");
1765       if(subscribeFn){
1766         subscribeFn(newValue,self);
1767       }
1768     });
1769
1770     this.automatic=automatic?automatic:false;
1771     this.update=true;
1772   }
1773
1774   LdapGroupMappingUpdateRequest=function(ldapGroupMappings){
1775     this.ldapGroupMappings=ko.observableArray(ldapGroupMappings?ldapGroupMappings:[]);
1776   }
1777
1778   mapLdapGroupMappings=function(data,modifyLdapGroupMapping){
1779     if(data!=null){
1780       return $.map(data,function(item){
1781         return new LdapGroupMapping(item.group,item.roleNames?item.roleNames:[],false,modifyLdapGroupMapping);
1782       })
1783     }
1784     return [];
1785   }
1786
1787   CacheConfiguration=function(timeToIdleSeconds,timeToLiveSeconds,maxElementsInMemory,maxElementsOnDisk){
1788     var self=this;
1789     this.modified=ko.observable(false);
1790
1791     this.timeToIdleSeconds=ko.observable(timeToIdleSeconds);
1792     this.timeToIdleSeconds.subscribe(function(newValue){self.modified(true)});
1793
1794     this.timeToLiveSeconds=ko.observable(timeToLiveSeconds);
1795     this.timeToLiveSeconds.subscribe(function(newValue){self.modified(true)});
1796
1797     this.maxElementsInMemory=ko.observable(maxElementsInMemory);
1798     this.maxElementsInMemory.subscribe(function(newValue){self.modified(true)});
1799
1800     this.maxElementsOnDisk=ko.observable(maxElementsOnDisk);
1801     this.maxElementsOnDisk.subscribe(function(newValue){self.modified(true)});
1802
1803   }
1804
1805   mapCacheConfiguration=function(data){
1806     if(!data){
1807       return new CacheConfiguration();
1808     }
1809     return new CacheConfiguration(data.timeToIdleSeconds,data.timeToLiveSeconds,data.maxElementsInMemory,data.maxElementsOnDisk);
1810   }
1811
1812  
1813
1814 });