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