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