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