James Moger
2012-07-10 3fb41fdec5712b792da05e8549c2c0a31f112ca0
commit | author | age
f13c4c 1 /*
JM 2  * Copyright 2011 gitblit.com.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
fc948c 16 package com.gitblit;
JM 17
b75734 18 import java.io.BufferedReader;
fc948c 19 import java.io.File;
831469 20 import java.io.FileFilter;
f97bf0 21 import java.io.IOException;
b75734 22 import java.io.InputStream;
JM 23 import java.io.InputStreamReader;
dd6f08 24 import java.lang.reflect.Field;
166e6a 25 import java.text.MessageFormat;
6c6e7d 26 import java.text.SimpleDateFormat;
fc948c 27 import java.util.ArrayList;
8f73a7 28 import java.util.Arrays;
0b9119 29 import java.util.Collection;
00afd7 30 import java.util.Collections;
6c6e7d 31 import java.util.Date;
8c9a20 32 import java.util.HashMap;
7c1cdc 33 import java.util.LinkedHashMap;
d7905a 34 import java.util.LinkedHashSet;
fc948c 35 import java.util.List;
8c9a20 36 import java.util.Map;
JM 37 import java.util.Map.Entry;
6cc1d4 38 import java.util.Set;
6c6e7d 39 import java.util.TimeZone;
d7905a 40 import java.util.TreeSet;
831469 41 import java.util.concurrent.ConcurrentHashMap;
JM 42 import java.util.concurrent.Executors;
43 import java.util.concurrent.ScheduledExecutorService;
44 import java.util.concurrent.TimeUnit;
dd6f08 45 import java.util.concurrent.atomic.AtomicInteger;
fc948c 46
831469 47 import javax.mail.Message;
JM 48 import javax.mail.MessagingException;
b75734 49 import javax.servlet.ServletContext;
87cc1e 50 import javax.servlet.ServletContextEvent;
JM 51 import javax.servlet.ServletContextListener;
85c2e6 52 import javax.servlet.http.Cookie;
fc948c 53
85c2e6 54 import org.apache.wicket.protocol.http.WebResponse;
fc948c 55 import org.eclipse.jgit.errors.RepositoryNotFoundException;
JM 56 import org.eclipse.jgit.lib.Repository;
5c2841 57 import org.eclipse.jgit.lib.RepositoryCache.FileKey;
f97bf0 58 import org.eclipse.jgit.lib.StoredConfig;
478678 59 import org.eclipse.jgit.storage.file.WindowCache;
JM 60 import org.eclipse.jgit.storage.file.WindowCacheConfig;
f5d0ad 61 import org.eclipse.jgit.transport.resolver.FileResolver;
892570 62 import org.eclipse.jgit.transport.resolver.RepositoryResolver;
JM 63 import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;
f5d0ad 64 import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException;
5c2841 65 import org.eclipse.jgit.util.FS;
8a2e9c 66 import org.eclipse.jgit.util.FileUtils;
fc948c 67 import org.slf4j.Logger;
JM 68 import org.slf4j.LoggerFactory;
69
dfb889 70 import com.gitblit.Constants.AccessRestrictionType;
831469 71 import com.gitblit.Constants.FederationRequest;
JM 72 import com.gitblit.Constants.FederationStrategy;
73 import com.gitblit.Constants.FederationToken;
74 import com.gitblit.models.FederationModel;
75 import com.gitblit.models.FederationProposal;
31abc2 76 import com.gitblit.models.FederationSet;
4d44cf 77 import com.gitblit.models.Metric;
1f9dae 78 import com.gitblit.models.RepositoryModel;
d896e6 79 import com.gitblit.models.SearchResult;
d03aff 80 import com.gitblit.models.ServerSettings;
b75734 81 import com.gitblit.models.ServerStatus;
JM 82 import com.gitblit.models.SettingModel;
fe24a0 83 import com.gitblit.models.TeamModel;
1f9dae 84 import com.gitblit.models.UserModel;
0db5c4 85 import com.gitblit.utils.ArrayUtils;
72633d 86 import com.gitblit.utils.ByteFormat;
f6740d 87 import com.gitblit.utils.FederationUtils;
fc948c 88 import com.gitblit.utils.JGitUtils;
93f0b1 89 import com.gitblit.utils.JsonUtils;
4d44cf 90 import com.gitblit.utils.MetricUtils;
9275bd 91 import com.gitblit.utils.ObjectCache;
00afd7 92 import com.gitblit.utils.StringUtils;
fc948c 93
892570 94 /**
JM 95  * GitBlit is the servlet context listener singleton that acts as the core for
96  * the web ui and the servlets. This class is either directly instantiated by
97  * the GitBlitServer class (Gitblit GO) or is reflectively instantiated from the
98  * definition in the web.xml file (Gitblit WAR).
99  * 
100  * This class is the central logic processor for Gitblit. All settings, user
101  * object, and repository object operations pass through this class.
102  * 
103  * Repository Resolution. There are two pathways for finding repositories. One
104  * pathway, for web ui display and repository authentication & authorization, is
105  * within this class. The other pathway is through the standard GitServlet.
106  * 
107  * @author James Moger
108  * 
109  */
87cc1e 110 public class GitBlit implements ServletContextListener {
fc948c 111
5450d0 112     private static GitBlit gitblit;
6c6e7d 113     
fc948c 114     private final Logger logger = LoggerFactory.getLogger(GitBlit.class);
JM 115
831469 116     private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
JM 117
118     private final List<FederationModel> federationRegistrations = Collections
119             .synchronizedList(new ArrayList<FederationModel>());
120
121     private final Map<String, FederationModel> federationPullResults = new ConcurrentHashMap<String, FederationModel>();
4d44cf 122
JM 123     private final ObjectCache<Long> repositorySizeCache = new ObjectCache<Long>();
124
125     private final ObjectCache<List<Metric>> repositoryMetricsCache = new ObjectCache<List<Metric>>();
831469 126
892570 127     private RepositoryResolver<Void> repositoryResolver;
fc948c 128
b75734 129     private ServletContext servletContext;
JM 130
166e6a 131     private File repositoriesFolder;
fc948c 132
85c2e6 133     private IUserService userService;
fc948c 134
892570 135     private IStoredSettings settings;
b75734 136
84c1d5 137     private ServerSettings settingsModel;
b75734 138
JM 139     private ServerStatus serverStatus;
831469 140
JM 141     private MailExecutor mailExecutor;
6c6e7d 142     
e31da0 143     private LuceneExecutor luceneExecutor;
JM 144     
6c6e7d 145     private TimeZone timezone;
87cc1e 146
5450d0 147     public GitBlit() {
JM 148         if (gitblit == null) {
892570 149             // set the static singleton reference
5450d0 150             gitblit = this;
JM 151         }
87cc1e 152     }
JM 153
892570 154     /**
JM 155      * Returns the Gitblit singleton.
156      * 
157      * @return gitblit singleton
158      */
2a7306 159     public static GitBlit self() {
5450d0 160         if (gitblit == null) {
892570 161             new GitBlit();
5450d0 162         }
JM 163         return gitblit;
831469 164     }
JM 165
166     /**
167      * Determine if this is the GO variant of Gitblit.
168      * 
169      * @return true if this is the GO variant of Gitblit.
170      */
171     public static boolean isGO() {
172         return self().settings instanceof FileSettings;
6c6e7d 173     }
JM 174     
175     /**
176      * Returns the preferred timezone for the Gitblit instance.
177      * 
178      * @return a timezone
179      */
180     public static TimeZone getTimezone() {
181         if (self().timezone == null) {
182             String tzid = getString("web.timezone", null);
183             if (StringUtils.isEmpty(tzid)) {
184                 self().timezone = TimeZone.getDefault();
185                 return self().timezone;
186             }
187             self().timezone = TimeZone.getTimeZone(tzid);
188         }
189         return self().timezone;
2a7306 190     }
3d0494 191     
ae9e15 192     /**
JM 193      * Returns the user-defined blob encodings.
194      * 
195      * @return an array of encodings, may be empty
196      */
197     public static String [] getEncodings() {
198         return getStrings(Keys.web.blobEncodings).toArray(new String[0]);
199     }
200     
2a7306 201
892570 202     /**
JM 203      * Returns the boolean value for the specified key. If the key does not
204      * exist or the value for the key can not be interpreted as a boolean, the
205      * defaultValue is returned.
206      * 
207      * @see IStoredSettings.getBoolean(String, boolean)
208      * @param key
209      * @param defaultValue
210      * @return key value or defaultValue
211      */
2a7306 212     public static boolean getBoolean(String key, boolean defaultValue) {
892570 213         return self().settings.getBoolean(key, defaultValue);
2a7306 214     }
JM 215
892570 216     /**
JM 217      * Returns the integer value for the specified key. If the key does not
218      * exist or the value for the key can not be interpreted as an integer, the
219      * defaultValue is returned.
220      * 
221      * @see IStoredSettings.getInteger(String key, int defaultValue)
222      * @param key
223      * @param defaultValue
224      * @return key value or defaultValue
225      */
2a7306 226     public static int getInteger(String key, int defaultValue) {
892570 227         return self().settings.getInteger(key, defaultValue);
2a7306 228     }
JM 229
892570 230     /**
7e5ee5 231      * Returns the char value for the specified key. If the key does not exist
JM 232      * or the value for the key can not be interpreted as a character, the
233      * defaultValue is returned.
234      * 
235      * @see IStoredSettings.getChar(String key, char defaultValue)
236      * @param key
237      * @param defaultValue
238      * @return key value or defaultValue
239      */
240     public static char getChar(String key, char defaultValue) {
241         return self().settings.getChar(key, defaultValue);
242     }
dd6f08 243
7e5ee5 244     /**
892570 245      * Returns the string value for the specified key. If the key does not exist
JM 246      * or the value for the key can not be interpreted as a string, the
247      * defaultValue is returned.
248      * 
249      * @see IStoredSettings.getString(String key, String defaultValue)
250      * @param key
251      * @param defaultValue
252      * @return key value or defaultValue
253      */
2a7306 254     public static String getString(String key, String defaultValue) {
892570 255         return self().settings.getString(key, defaultValue);
2a7306 256     }
JM 257
892570 258     /**
JM 259      * Returns a list of space-separated strings from the specified key.
260      * 
261      * @see IStoredSettings.getStrings(String key)
262      * @param name
263      * @return list of strings
264      */
2a7306 265     public static List<String> getStrings(String key) {
892570 266         return self().settings.getStrings(key);
7c1cdc 267     }
JM 268
269     /**
270      * Returns a map of space-separated key-value pairs from the specified key.
271      * 
272      * @see IStoredSettings.getStrings(String key)
273      * @param name
274      * @return map of string, string
275      */
276     public static Map<String, String> getMap(String key) {
277         return self().settings.getMap(key);
2a7306 278     }
892570 279
JM 280     /**
281      * Returns the list of keys whose name starts with the specified prefix. If
282      * the prefix is null or empty, all key names are returned.
283      * 
284      * @see IStoredSettings.getAllKeys(String key)
285      * @param startingWith
286      * @return list of keys
287      */
2a7306 288
JM 289     public static List<String> getAllKeys(String startingWith) {
892570 290         return self().settings.getAllKeys(startingWith);
fc948c 291     }
155bf7 292
892570 293     /**
JM 294      * Is Gitblit running in debug mode?
295      * 
296      * @return true if Gitblit is running in debug mode
297      */
8c9a20 298     public static boolean isDebugMode() {
892570 299         return self().settings.getBoolean(Keys.web.debugMode, false);
d03aff 300     }
JM 301
302     /**
b774de 303      * Returns the file object for the specified configuration key.
JM 304      * 
305      * @return the file
306      */
307     public static File getFileOrFolder(String key, String defaultFileOrFolder) {
308         String fileOrFolder = GitBlit.getString(key, defaultFileOrFolder);
309         return getFileOrFolder(fileOrFolder);
310     }
311
312     /**
313      * Returns the file object which may have it's base-path determined by
314      * environment variables for running on a cloud hosting service. All Gitblit
315      * file or folder retrievals are (at least initially) funneled through this
316      * method so it is the correct point to globally override/alter filesystem
317      * access based on environment or some other indicator.
318      * 
319      * @return the file
320      */
321     public static File getFileOrFolder(String fileOrFolder) {
322         String openShift = System.getenv("OPENSHIFT_DATA_DIR");
323         if (!StringUtils.isEmpty(openShift)) {
324             // running on RedHat OpenShift
325             return new File(openShift, fileOrFolder);
326         }
327         return new File(fileOrFolder);
328     }
329
330     /**
331      * Returns the path of the repositories folder. This method checks to see if
332      * Gitblit is running on a cloud service and may return an adjusted path.
333      * 
334      * @return the repositories folder path
335      */
336     public static File getRepositoriesFolder() {
337         return getFileOrFolder(Keys.git.repositoriesFolder, "git");
338     }
339
340     /**
341      * Returns the path of the proposals folder. This method checks to see if
342      * Gitblit is running on a cloud service and may return an adjusted path.
343      * 
344      * @return the proposals folder path
345      */
346     public static File getProposalsFolder() {
347         return getFileOrFolder(Keys.federation.proposalsFolder, "proposals");
6cc1d4 348     }
JM 349
350     /**
351      * Returns the path of the Groovy folder. This method checks to see if
352      * Gitblit is running on a cloud service and may return an adjusted path.
353      * 
354      * @return the Groovy scripts folder path
355      */
356     public static File getGroovyScriptsFolder() {
357         return getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
b774de 358     }
JM 359
360     /**
d03aff 361      * Updates the list of server settings.
JM 362      * 
363      * @param settings
364      * @return true if the update succeeded
365      */
97a20e 366     public boolean updateSettings(Map<String, String> updatedSettings) {
486ee1 367         return settings.saveSettings(updatedSettings);
b75734 368     }
JM 369
370     public ServerStatus getStatus() {
371         // update heap memory status
372         serverStatus.heapAllocated = Runtime.getRuntime().totalMemory();
373         serverStatus.heapFree = Runtime.getRuntime().freeMemory();
374         return serverStatus;
87cc1e 375     }
JM 376
892570 377     /**
JM 378      * Returns the list of non-Gitblit clone urls. This allows Gitblit to
379      * advertise alternative urls for Git client repository access.
380      * 
381      * @param repositoryName
382      * @return list of non-gitblit clone urls
383      */
8a2e9c 384     public List<String> getOtherCloneUrls(String repositoryName) {
JM 385         List<String> cloneUrls = new ArrayList<String>();
892570 386         for (String url : settings.getStrings(Keys.web.otherUrls)) {
8a2e9c 387             cloneUrls.add(MessageFormat.format(url, repositoryName));
JM 388         }
389         return cloneUrls;
fc948c 390     }
JM 391
892570 392     /**
JM 393      * Set the user service. The user service authenticates all users and is
394      * responsible for managing user permissions.
395      * 
396      * @param userService
397      */
85c2e6 398     public void setUserService(IUserService userService) {
JM 399         logger.info("Setting up user service " + userService.toString());
400         this.userService = userService;
63ee41 401         this.userService.setup(settings);
fc948c 402     }
6cca86 403     
JM 404     /**
405      * 
406      * @return true if the user service supports credential changes
407      */
408     public boolean supportsCredentialChanges() {
409         return userService.supportsCredentialChanges();
410     }
411
412     /**
413      * 
0aa8cf 414      * @return true if the user service supports display name changes
JM 415      */
416     public boolean supportsDisplayNameChanges() {
417         return userService.supportsDisplayNameChanges();
418     }
419
420     /**
421      * 
422      * @return true if the user service supports email address changes
423      */
424     public boolean supportsEmailAddressChanges() {
425         return userService.supportsEmailAddressChanges();
426     }
427
428     /**
429      * 
6cca86 430      * @return true if the user service supports team membership changes
JM 431      */
432     public boolean supportsTeamMembershipChanges() {
433         return userService.supportsTeamMembershipChanges();
434     }
fc948c 435
892570 436     /**
JM 437      * Authenticate a user based on a username and password.
438      * 
439      * @see IUserService.authenticate(String, char[])
440      * @param username
441      * @param password
442      * @return a user object or null
443      */
511554 444     public UserModel authenticate(String username, char[] password) {
831469 445         if (StringUtils.isEmpty(username)) {
JM 446             // can not authenticate empty username
447             return null;
448         }
449         String pw = new String(password);
450         if (StringUtils.isEmpty(pw)) {
451             // can not authenticate empty password
452             return null;
453         }
454
455         // check to see if this is the federation user
456         if (canFederate()) {
457             if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
458                 List<String> tokens = getFederationTokens();
459                 if (tokens.contains(pw)) {
460                     // the federation user is an administrator
461                     UserModel federationUser = new UserModel(Constants.FEDERATION_USER);
462                     federationUser.canAdmin = true;
463                     return federationUser;
464                 }
465             }
466         }
467
468         // delegate authentication to the user service
85c2e6 469         if (userService == null) {
fc948c 470             return null;
JM 471         }
85c2e6 472         return userService.authenticate(username, password);
JM 473     }
474
892570 475     /**
JM 476      * Authenticate a user based on their cookie.
477      * 
478      * @param cookies
479      * @return a user object or null
480      */
85c2e6 481     public UserModel authenticate(Cookie[] cookies) {
JM 482         if (userService == null) {
483             return null;
484         }
485         if (userService.supportsCookies()) {
486             if (cookies != null && cookies.length > 0) {
487                 for (Cookie cookie : cookies) {
488                     if (cookie.getName().equals(Constants.NAME)) {
489                         String value = cookie.getValue();
490                         return userService.authenticate(value.toCharArray());
491                     }
492                 }
493             }
494         }
495         return null;
496     }
497
892570 498     /**
JM 499      * Sets a cookie for the specified user.
500      * 
501      * @param response
502      * @param user
503      */
85c2e6 504     public void setCookie(WebResponse response, UserModel user) {
JM 505         if (userService == null) {
506             return;
507         }
508         if (userService.supportsCookies()) {
509             Cookie userCookie;
510             if (user == null) {
511                 // clear cookie for logout
512                 userCookie = new Cookie(Constants.NAME, "");
513             } else {
514                 // set cookie for login
515                 char[] cookie = userService.getCookie(user);
516                 userCookie = new Cookie(Constants.NAME, new String(cookie));
517                 userCookie.setMaxAge(Integer.MAX_VALUE);
518             }
519             userCookie.setPath("/");
520             response.addCookie(userCookie);
521         }
fc948c 522     }
ea094a 523     
JM 524     /**
525      * Logout a user.
526      * 
527      * @param user
528      */
529     public void logout(UserModel user) {
530         if (userService == null) {
531             return;
532         }
533         userService.logout(user);
534     }
fc948c 535
892570 536     /**
JM 537      * Returns the list of all users available to the login service.
538      * 
539      * @see IUserService.getAllUsernames()
540      * @return list of all usernames
541      */
f98825 542     public List<String> getAllUsernames() {
85c2e6 543         List<String> names = new ArrayList<String>(userService.getAllUsernames());
00afd7 544         return names;
abeaaf 545     }
e36d4d 546
abeaaf 547     /**
JM 548      * Returns the list of all users available to the login service.
549      * 
550      * @see IUserService.getAllUsernames()
551      * @return list of all usernames
552      */
553     public List<UserModel> getAllUsers() {
554         List<UserModel> users = userService.getAllUsers();
555         return users;
8a2e9c 556     }
JM 557
892570 558     /**
JM 559      * Delete the user object with the specified username
560      * 
561      * @see IUserService.deleteUser(String)
562      * @param username
563      * @return true if successful
564      */
8a2e9c 565     public boolean deleteUser(String username) {
85c2e6 566         return userService.deleteUser(username);
f98825 567     }
dfb889 568
892570 569     /**
JM 570      * Retrieve the user object for the specified username.
571      * 
572      * @see IUserService.getUserModel(String)
573      * @param username
574      * @return a user object or null
575      */
f98825 576     public UserModel getUserModel(String username) {
85c2e6 577         UserModel user = userService.getUserModel(username);
dfb889 578         return user;
f98825 579     }
8a2e9c 580
892570 581     /**
JM 582      * Returns the list of all users who are allowed to bypass the access
583      * restriction placed on the specified repository.
584      * 
585      * @see IUserService.getUsernamesForRepositoryRole(String)
586      * @param repository
587      * @return list of all usernames that can bypass the access restriction
588      */
f98825 589     public List<String> getRepositoryUsers(RepositoryModel repository) {
892570 590         return userService.getUsernamesForRepositoryRole(repository.name);
f98825 591     }
8a2e9c 592
892570 593     /**
JM 594      * Sets the list of all uses who are allowed to bypass the access
595      * restriction placed on the specified repository.
596      * 
597      * @see IUserService.setUsernamesForRepositoryRole(String, List<String>)
598      * @param repository
599      * @param usernames
600      * @return true if successful
601      */
f98825 602     public boolean setRepositoryUsers(RepositoryModel repository, List<String> repositoryUsers) {
892570 603         return userService.setUsernamesForRepositoryRole(repository.name, repositoryUsers);
dfb889 604     }
JM 605
892570 606     /**
JM 607      * Adds/updates a complete user object keyed by username. This method allows
608      * for renaming a user.
609      * 
610      * @see IUserService.updateUserModel(String, UserModel)
611      * @param username
612      * @param user
613      * @param isCreate
614      * @throws GitBlitException
615      */
616     public void updateUserModel(String username, UserModel user, boolean isCreate)
2a7306 617             throws GitBlitException {
16038c 618         if (!username.equalsIgnoreCase(user.username)) {
JM 619             if (userService.getUserModel(user.username) != null) {
d03aff 620                 throw new GitBlitException(MessageFormat.format(
JM 621                         "Failed to rename ''{0}'' because ''{1}'' already exists.", username,
622                         user.username));
16038c 623             }
JM 624         }
85c2e6 625         if (!userService.updateUserModel(username, user)) {
dfb889 626             throw new GitBlitException(isCreate ? "Failed to add user!" : "Failed to update user!");
JM 627         }
fe24a0 628     }
JM 629
630     /**
631      * Returns the list of available teams that a user or repository may be
632      * assigned to.
633      * 
634      * @return the list of teams
635      */
636     public List<String> getAllTeamnames() {
637         List<String> teams = new ArrayList<String>(userService.getAllTeamNames());
abeaaf 638         return teams;
JM 639     }
e36d4d 640
abeaaf 641     /**
JM 642      * Returns the list of available teams that a user or repository may be
643      * assigned to.
644      * 
645      * @return the list of teams
646      */
647     public List<TeamModel> getAllTeams() {
648         List<TeamModel> teams = userService.getAllTeams();
fe24a0 649         return teams;
JM 650     }
651
652     /**
653      * Returns the TeamModel object for the specified name.
654      * 
655      * @param teamname
656      * @return a TeamModel object or null
657      */
658     public TeamModel getTeamModel(String teamname) {
659         return userService.getTeamModel(teamname);
660     }
661
662     /**
663      * Returns the list of all teams who are allowed to bypass the access
664      * restriction placed on the specified repository.
665      * 
666      * @see IUserService.getTeamnamesForRepositoryRole(String)
667      * @param repository
668      * @return list of all teamnames that can bypass the access restriction
669      */
670     public List<String> getRepositoryTeams(RepositoryModel repository) {
671         return userService.getTeamnamesForRepositoryRole(repository.name);
672     }
673
674     /**
675      * Sets the list of all uses who are allowed to bypass the access
676      * restriction placed on the specified repository.
677      * 
678      * @see IUserService.setTeamnamesForRepositoryRole(String, List<String>)
679      * @param repository
680      * @param teamnames
681      * @return true if successful
682      */
683     public boolean setRepositoryTeams(RepositoryModel repository, List<String> repositoryTeams) {
684         return userService.setTeamnamesForRepositoryRole(repository.name, repositoryTeams);
685     }
fa54be 686
fe24a0 687     /**
JM 688      * Updates the TeamModel object for the specified name.
689      * 
690      * @param teamname
691      * @param team
692      * @param isCreate
693      */
fa54be 694     public void updateTeamModel(String teamname, TeamModel team, boolean isCreate)
JM 695             throws GitBlitException {
fe24a0 696         if (!teamname.equalsIgnoreCase(team.name)) {
JM 697             if (userService.getTeamModel(team.name) != null) {
698                 throw new GitBlitException(MessageFormat.format(
699                         "Failed to rename ''{0}'' because ''{1}'' already exists.", teamname,
700                         team.name));
701             }
702         }
703         if (!userService.updateTeamModel(teamname, team)) {
704             throw new GitBlitException(isCreate ? "Failed to add team!" : "Failed to update team!");
705         }
706     }
fa54be 707
fe24a0 708     /**
JM 709      * Delete the team object with the specified teamname
710      * 
711      * @see IUserService.deleteTeam(String)
712      * @param teamname
713      * @return true if successful
714      */
715     public boolean deleteTeam(String teamname) {
716         return userService.deleteTeam(teamname);
dfb889 717     }
JM 718
892570 719     /**
4d44cf 720      * Clears all the cached data for the specified repository.
JM 721      * 
722      * @param repositoryName
723      */
724     public void clearRepositoryCache(String repositoryName) {
725         repositorySizeCache.remove(repositoryName);
726         repositoryMetricsCache.remove(repositoryName);
727     }
728
729     /**
892570 730      * Returns the list of all repositories available to Gitblit. This method
JM 731      * does not consider user access permissions.
732      * 
733      * @return list of all repositories
734      */
166e6a 735     public List<String> getRepositoryList() {
b86562 736         return JGitUtils.getRepositoryList(repositoriesFolder, 
JM 737                 settings.getBoolean(Keys.git.onlyAccessBareRepositories, false),
892570 738                 settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true));
166e6a 739     }
155bf7 740
892570 741     /**
JM 742      * Returns the JGit repository for the specified name.
743      * 
744      * @param repositoryName
745      * @return repository or null
746      */
166e6a 747     public Repository getRepository(String repositoryName) {
11924d 748         return getRepository(repositoryName, true);
JM 749     }
750
751     /**
752      * Returns the JGit repository for the specified name.
753      * 
754      * @param repositoryName
755      * @param logError
756      * @return repository or null
757      */
758     public Repository getRepository(String repositoryName, boolean logError) {
166e6a 759         Repository r = null;
JM 760         try {
761             r = repositoryResolver.open(null, repositoryName);
762         } catch (RepositoryNotFoundException e) {
763             r = null;
11924d 764             if (logError) {
JM 765                 logger.error("GitBlit.getRepository(String) failed to find "
766                         + new File(repositoriesFolder, repositoryName).getAbsolutePath());
767             }
892570 768         } catch (ServiceNotAuthorizedException e) {
JM 769             r = null;
11924d 770             if (logError) {
JM 771                 logger.error("GitBlit.getRepository(String) failed to find "
772                         + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
773             }
166e6a 774         } catch (ServiceNotEnabledException e) {
JM 775             r = null;
11924d 776             if (logError) {
JM 777                 logger.error("GitBlit.getRepository(String) failed to find "
778                         + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
779             }
166e6a 780         }
JM 781         return r;
782     }
dfb889 783
892570 784     /**
JM 785      * Returns the list of repository models that are accessible to the user.
786      * 
787      * @param user
788      * @return list of repository models accessible to user
789      */
511554 790     public List<RepositoryModel> getRepositoryModels(UserModel user) {
166e6a 791         List<String> list = getRepositoryList();
JM 792         List<RepositoryModel> repositories = new ArrayList<RepositoryModel>();
793         for (String repo : list) {
dfb889 794             RepositoryModel model = getRepositoryModel(user, repo);
JM 795             if (model != null) {
796                 repositories.add(model);
797             }
166e6a 798         }
3d293a 799         if (getBoolean(Keys.web.showRepositorySizes, true)) {
JM 800             int repoCount = 0;
801             long startTime = System.currentTimeMillis();
802             ByteFormat byteFormat = new ByteFormat();
803             for (RepositoryModel model : repositories) {
804                 if (!model.skipSizeCalculation) {
805                     repoCount++;
806                     model.size = byteFormat.format(calculateSize(model));
807                 }
808             }
809             long duration = System.currentTimeMillis() - startTime;
810             logger.info(MessageFormat.format("{0} repository sizes calculated in {1} msecs",
811                     repoCount, duration));
812         }
166e6a 813         return repositories;
JM 814     }
8a2e9c 815
892570 816     /**
JM 817      * Returns a repository model if the repository exists and the user may
818      * access the repository.
819      * 
820      * @param user
821      * @param repositoryName
822      * @return repository model or null
823      */
511554 824     public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
dfb889 825         RepositoryModel model = getRepositoryModel(repositoryName);
85c2e6 826         if (model == null) {
JM 827             return null;
828         }
dfb889 829         if (model.accessRestriction.atLeast(AccessRestrictionType.VIEW)) {
efe8ec 830             if (user != null && user.canAccessRepository(model)) {
dfb889 831                 return model;
JM 832             }
833             return null;
834         } else {
835             return model;
836         }
837     }
838
892570 839     /**
JM 840      * Returns the repository model for the specified repository. This method
841      * does not consider user access permissions.
842      * 
843      * @param repositoryName
844      * @return repository model or null
845      */
166e6a 846     public RepositoryModel getRepositoryModel(String repositoryName) {
JM 847         Repository r = getRepository(repositoryName);
1f9dae 848         if (r == null) {
JM 849             return null;
850         }
166e6a 851         RepositoryModel model = new RepositoryModel();
JM 852         model.name = repositoryName;
bc9d4a 853         model.hasCommits = JGitUtils.hasCommits(r);
4fea45 854         model.lastChange = JGitUtils.getLastChange(r);
b74031 855         model.isBare = r.isBare();
166e6a 856         StoredConfig config = JGitUtils.readConfig(r);
JM 857         if (config != null) {
00afd7 858             model.description = getConfig(config, "description", "");
JM 859             model.owner = getConfig(config, "owner", "");
860             model.useTickets = getConfig(config, "useTickets", false);
861             model.useDocs = getConfig(config, "useDocs", false);
2a7306 862             model.accessRestriction = AccessRestrictionType.fromName(getConfig(config,
94dcbd 863                     "accessRestriction", settings.getString(Keys.git.defaultAccessRestriction, null)));
00afd7 864             model.showRemoteBranches = getConfig(config, "showRemoteBranches", false);
JM 865             model.isFrozen = getConfig(config, "isFrozen", false);
a1ea87 866             model.showReadme = getConfig(config, "showReadme", false);
3d293a 867             model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
fe3262 868             model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
831469 869             model.federationStrategy = FederationStrategy.fromName(getConfig(config,
JM 870                     "federationStrategy", null));
8f73a7 871             model.federationSets = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 872                     Constants.CONFIG_GITBLIT, null, "federationSets")));
831469 873             model.isFederated = getConfig(config, "isFederated", false);
JM 874             model.origin = config.getString("remote", "origin", "url");
fa54be 875             model.preReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 876                     Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
fa54be 877             model.postReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 878                     Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
eb96ea 879             model.mailingLists = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 880                     Constants.CONFIG_GITBLIT, null, "mailingList")));
40ca5c 881             model.indexedBranches = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 882                     Constants.CONFIG_GITBLIT, null, "indexBranch")));
4a5a55 883             
JC 884             // Custom defined properties
7c1cdc 885             model.customFields = new LinkedHashMap<String, String>();
380afa 886             for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
JM 887                 model.customFields.put(aProperty, config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
4a5a55 888             }
166e6a 889         }
90b8d7 890         model.HEAD = JGitUtils.getHEADRef(r);
JM 891         model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
166e6a 892         r.close();
JM 893         return model;
00afd7 894     }
8a2e9c 895
892570 896     /**
4d44cf 897      * Returns the size in bytes of the repository. Gitblit caches the
JM 898      * repository sizes to reduce the performance penalty of recursive
899      * calculation. The cache is updated if the repository has been changed
900      * since the last calculation.
5c2841 901      * 
JM 902      * @param model
903      * @return size in bytes
904      */
905     public long calculateSize(RepositoryModel model) {
4d44cf 906         if (repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
JM 907             return repositorySizeCache.getObject(model.name);
908         }
5c2841 909         File gitDir = FileKey.resolve(new File(repositoriesFolder, model.name), FS.DETECTED);
4d44cf 910         long size = com.gitblit.utils.FileUtils.folderSize(gitDir);
JM 911         repositorySizeCache.updateObject(model.name, model.lastChange, size);
912         return size;
5c2841 913     }
JM 914
915     /**
dd6f08 916      * Ensure that a cached repository is completely closed and its resources
JM 917      * are properly released.
918      * 
919      * @param repositoryName
920      */
921     private void closeRepository(String repositoryName) {
922         Repository repository = getRepository(repositoryName);
923         // assume 2 uses in case reflection fails
924         int uses = 2;
925         try {
926             // The FileResolver caches repositories which is very useful
927             // for performance until you want to delete a repository.
928             // I have to use reflection to call close() the correct
929             // number of times to ensure that the object and ref databases
930             // are properly closed before I can delete the repository from
931             // the filesystem.
932             Field useCnt = Repository.class.getDeclaredField("useCnt");
933             useCnt.setAccessible(true);
934             uses = ((AtomicInteger) useCnt.get(repository)).get();
935         } catch (Exception e) {
936             logger.warn(MessageFormat
937                     .format("Failed to reflectively determine use count for repository {0}",
938                             repositoryName), e);
939         }
940         if (uses > 0) {
941             logger.info(MessageFormat
942                     .format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases",
943                             repositoryName, uses, uses));
944             for (int i = 0; i < uses; i++) {
945                 repository.close();
946             }
947         }
e6637c 948         
JM 949         // close any open index writer/searcher in the Lucene executor
950         luceneExecutor.close(repositoryName);
dd6f08 951     }
JM 952
953     /**
4d44cf 954      * Returns the metrics for the default branch of the specified repository.
JM 955      * This method builds a metrics cache. The cache is updated if the
956      * repository is updated. A new copy of the metrics list is returned on each
957      * call so that modifications to the list are non-destructive.
958      * 
959      * @param model
960      * @param repository
961      * @return a new array list of metrics
962      */
963     public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
964         if (repositoryMetricsCache.hasCurrent(model.name, model.lastChange)) {
965             return new ArrayList<Metric>(repositoryMetricsCache.getObject(model.name));
966         }
40538c 967         List<Metric> metrics = MetricUtils.getDateMetrics(repository, null, true, null, getTimezone());
4d44cf 968         repositoryMetricsCache.updateObject(model.name, model.lastChange, metrics);
JM 969         return new ArrayList<Metric>(metrics);
970     }
971
972     /**
973      * Returns the gitblit string value for the specified key. If key is not
892570 974      * set, returns defaultValue.
JM 975      * 
976      * @param config
977      * @param field
978      * @param defaultValue
979      * @return field value or defaultValue
980      */
00afd7 981     private String getConfig(StoredConfig config, String field, String defaultValue) {
380afa 982         String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
00afd7 983         if (StringUtils.isEmpty(value)) {
JM 984             return defaultValue;
985         }
986         return value;
987     }
8a2e9c 988
892570 989     /**
380afa 990      * Returns the gitblit boolean value for the specified key. If key is not
892570 991      * set, returns defaultValue.
JM 992      * 
993      * @param config
994      * @param field
995      * @param defaultValue
996      * @return field value or defaultValue
997      */
00afd7 998     private boolean getConfig(StoredConfig config, String field, boolean defaultValue) {
380afa 999         return config.getBoolean(Constants.CONFIG_GITBLIT, field, defaultValue);
166e6a 1000     }
JM 1001
892570 1002     /**
JM 1003      * Creates/updates the repository model keyed by reopsitoryName. Saves all
1004      * repository settings in .git/config. This method allows for renaming
1005      * repositories and will update user access permissions accordingly.
1006      * 
1007      * All repositories created by this method are bare and automatically have
1008      * .git appended to their names, which is the standard convention for bare
1009      * repositories.
1010      * 
1011      * @param repositoryName
1012      * @param repository
1013      * @param isCreate
1014      * @throws GitBlitException
1015      */
1016     public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
2a7306 1017             boolean isCreate) throws GitBlitException {
f5d0ad 1018         Repository r = null;
JM 1019         if (isCreate) {
a3bde6 1020             // ensure created repository name ends with .git
168566 1021             if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
a3bde6 1022                 repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
JM 1023             }
166e6a 1024             if (new File(repositoriesFolder, repository.name).exists()) {
2a7306 1025                 throw new GitBlitException(MessageFormat.format(
JM 1026                         "Can not create repository ''{0}'' because it already exists.",
1027                         repository.name));
166e6a 1028             }
dfb889 1029             // create repository
f5d0ad 1030             logger.info("create repository " + repository.name);
168566 1031             r = JGitUtils.createRepository(repositoriesFolder, repository.name);
f5d0ad 1032         } else {
8a2e9c 1033             // rename repository
JM 1034             if (!repositoryName.equalsIgnoreCase(repository.name)) {
16038c 1035                 if (!repository.name.toLowerCase().endsWith(
JM 1036                         org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
1037                     repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
1038                 }
1039                 if (new File(repositoriesFolder, repository.name).exists()) {
d03aff 1040                     throw new GitBlitException(MessageFormat.format(
JM 1041                             "Failed to rename ''{0}'' because ''{1}'' already exists.",
1042                             repositoryName, repository.name));
16038c 1043                 }
dd6f08 1044                 closeRepository(repositoryName);
8a2e9c 1045                 File folder = new File(repositoriesFolder, repositoryName);
JM 1046                 File destFolder = new File(repositoriesFolder, repository.name);
1047                 if (destFolder.exists()) {
2a7306 1048                     throw new GitBlitException(
JM 1049                             MessageFormat
1050                                     .format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
1051                                             repositoryName, repository.name));
8a2e9c 1052                 }
c1a4cc 1053                 File parentFile = destFolder.getParentFile();
JM 1054                 if (!parentFile.exists() && !parentFile.mkdirs()) {
1055                     throw new GitBlitException(MessageFormat.format(
1056                             "Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
1057                 }
8a2e9c 1058                 if (!folder.renameTo(destFolder)) {
2a7306 1059                     throw new GitBlitException(MessageFormat.format(
JM 1060                             "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
1061                             repository.name));
8a2e9c 1062                 }
JM 1063                 // rename the roles
85c2e6 1064                 if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
2a7306 1065                     throw new GitBlitException(MessageFormat.format(
JM 1066                             "Failed to rename repository permissions ''{0}'' to ''{1}''.",
1067                             repositoryName, repository.name));
8a2e9c 1068                 }
4d44cf 1069
JM 1070                 // clear the cache
1071                 clearRepositoryCache(repositoryName);
8a2e9c 1072             }
JM 1073
f5d0ad 1074             // load repository
JM 1075             logger.info("edit repository " + repository.name);
1076             try {
1077                 r = repositoryResolver.open(null, repository.name);
1078             } catch (RepositoryNotFoundException e) {
1079                 logger.error("Repository not found", e);
892570 1080             } catch (ServiceNotAuthorizedException e) {
JM 1081                 logger.error("Service not authorized", e);
f5d0ad 1082             } catch (ServiceNotEnabledException e) {
JM 1083                 logger.error("Service not enabled", e);
1084             }
f97bf0 1085         }
JM 1086
f5d0ad 1087         // update settings
2a7306 1088         if (r != null) {
831469 1089             updateConfiguration(r, repository);
2cdb73 1090             // only update symbolic head if it changes
90b8d7 1091             String currentRef = JGitUtils.getHEADRef(r);
JM 1092             if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
d394d9 1093                 logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", 
90b8d7 1094                         repository.name, currentRef, repository.HEAD));
JM 1095                 if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
1096                     // clear the cache
1097                     clearRepositoryCache(repository.name);
1098                 }
912938 1099             }
d394d9 1100
JM 1101             // close the repository object
2a7306 1102             r.close();
831469 1103         }
JM 1104     }
1105
1106     /**
1107      * Updates the Gitblit configuration for the specified repository.
1108      * 
1109      * @param r
1110      *            the Git repository
1111      * @param repository
1112      *            the Gitblit repository model
1113      */
1114     public void updateConfiguration(Repository r, RepositoryModel repository) {
1115         StoredConfig config = JGitUtils.readConfig(r);
380afa 1116         config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
JM 1117         config.setString(Constants.CONFIG_GITBLIT, null, "owner", repository.owner);
1118         config.setBoolean(Constants.CONFIG_GITBLIT, null, "useTickets", repository.useTickets);
1119         config.setBoolean(Constants.CONFIG_GITBLIT, null, "useDocs", repository.useDocs);
1120         config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
1121         config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
1122         config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
1123         config.setBoolean(Constants.CONFIG_GITBLIT, null, "showReadme", repository.showReadme);
1124         config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
1125         config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
1126         config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
831469 1127                 repository.federationStrategy.name());
380afa 1128         config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);
a21fc5 1129
5efafa 1130         updateList(config, "federationSets", repository.federationSets);
JM 1131         updateList(config, "preReceiveScript", repository.preReceiveScripts);
1132         updateList(config, "postReceiveScript", repository.postReceiveScripts);
1133         updateList(config, "mailingList", repository.mailingLists);
1134         updateList(config, "indexBranch", repository.indexedBranches);
4a5a55 1135         
JC 1136         // User Defined Properties
380afa 1137         if (repository.customFields != null) {
JM 1138             if (repository.customFields.size() == 0) {
1139                 // clear section
1140                 config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
1141             } else {
1142                 for (Entry<String, String> property : repository.customFields.entrySet()) {
1143                     // set field
1144                     String key = property.getKey();
1145                     String value = property.getValue();
1146                     config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
1147                 }
1148             }
4a5a55 1149         }
a21fc5 1150
831469 1151         try {
JM 1152             config.save();
1153         } catch (IOException e) {
1154             logger.error("Failed to save repository config!", e);
f97bf0 1155         }
f5d0ad 1156     }
5efafa 1157     
JM 1158     private void updateList(StoredConfig config, String field, List<String> list) {
1159         // a null list is skipped, not cleared
1160         // this is for RPC administration where an older manager might be used
1161         if (list == null) {
1162             return;
1163         }
1164         if (ArrayUtils.isEmpty(list)) {
380afa 1165             config.unset(Constants.CONFIG_GITBLIT, null, field);
5efafa 1166         } else {
380afa 1167             config.setStringList(Constants.CONFIG_GITBLIT, null, field, list);
5efafa 1168         }
JM 1169     }
f5d0ad 1170
892570 1171     /**
JM 1172      * Deletes the repository from the file system and removes the repository
1173      * permission from all repository users.
1174      * 
1175      * @param model
1176      * @return true if successful
1177      */
8a2e9c 1178     public boolean deleteRepositoryModel(RepositoryModel model) {
JM 1179         return deleteRepository(model.name);
1180     }
1181
892570 1182     /**
JM 1183      * Deletes the repository from the file system and removes the repository
1184      * permission from all repository users.
1185      * 
1186      * @param repositoryName
1187      * @return true if successful
1188      */
8a2e9c 1189     public boolean deleteRepository(String repositoryName) {
JM 1190         try {
dd6f08 1191             closeRepository(repositoryName);
8a2e9c 1192             File folder = new File(repositoriesFolder, repositoryName);
JM 1193             if (folder.exists() && folder.isDirectory()) {
892570 1194                 FileUtils.delete(folder, FileUtils.RECURSIVE | FileUtils.RETRY);
85c2e6 1195                 if (userService.deleteRepositoryRole(repositoryName)) {
8a2e9c 1196                     return true;
JM 1197                 }
1198             }
4d44cf 1199
JM 1200             // clear the repository cache
1201             clearRepositoryCache(repositoryName);
8a2e9c 1202         } catch (Throwable t) {
JM 1203             logger.error(MessageFormat.format("Failed to delete repository {0}", repositoryName), t);
1204         }
1205         return false;
1206     }
1207
892570 1208     /**
JM 1209      * Returns an html version of the commit message with any global or
1210      * repository-specific regular expression substitution applied.
1211      * 
1212      * @param repositoryName
1213      * @param text
1214      * @return html version of the commit message
1215      */
8c9a20 1216     public String processCommitMessage(String repositoryName, String text) {
JM 1217         String html = StringUtils.breakLinesForHtml(text);
1218         Map<String, String> map = new HashMap<String, String>();
1219         // global regex keys
892570 1220         if (settings.getBoolean(Keys.regex.global, false)) {
JM 1221             for (String key : settings.getAllKeys(Keys.regex.global)) {
8c9a20 1222                 if (!key.equals(Keys.regex.global)) {
JM 1223                     String subKey = key.substring(key.lastIndexOf('.') + 1);
892570 1224                     map.put(subKey, settings.getString(key, ""));
8c9a20 1225                 }
JM 1226             }
1227         }
1228
1229         // repository-specific regex keys
892570 1230         List<String> keys = settings.getAllKeys(Keys.regex._ROOT + "."
8c9a20 1231                 + repositoryName.toLowerCase());
JM 1232         for (String key : keys) {
1233             String subKey = key.substring(key.lastIndexOf('.') + 1);
892570 1234             map.put(subKey, settings.getString(key, ""));
8c9a20 1235         }
JM 1236
1237         for (Entry<String, String> entry : map.entrySet()) {
1238             String definition = entry.getValue().trim();
1239             String[] chunks = definition.split("!!!");
1240             if (chunks.length == 2) {
1241                 html = html.replaceAll(chunks[0], chunks[1]);
1242             } else {
1243                 logger.warn(entry.getKey()
1244                         + " improperly formatted.  Use !!! to separate match from replacement: "
1245                         + definition);
1246             }
1247         }
1248         return html;
1249     }
1250
892570 1251     /**
831469 1252      * Returns Gitblit's scheduled executor service for scheduling tasks.
JM 1253      * 
1254      * @return scheduledExecutor
1255      */
1256     public ScheduledExecutorService executor() {
1257         return scheduledExecutor;
1258     }
1259
1260     public static boolean canFederate() {
2c32fd 1261         String passphrase = getString(Keys.federation.passphrase, "");
JM 1262         return !StringUtils.isEmpty(passphrase);
831469 1263     }
JM 1264
1265     /**
1266      * Configures this Gitblit instance to pull any registered federated gitblit
1267      * instances.
1268      */
1269     private void configureFederation() {
2c32fd 1270         boolean validPassphrase = true;
JM 1271         String passphrase = settings.getString(Keys.federation.passphrase, "");
1272         if (StringUtils.isEmpty(passphrase)) {
1273             logger.warn("Federation passphrase is blank! This server can not be PULLED from.");
1274             validPassphrase = false;
831469 1275         }
2c32fd 1276         if (validPassphrase) {
8f73a7 1277             // standard tokens
831469 1278             for (FederationToken tokenType : FederationToken.values()) {
JM 1279                 logger.info(MessageFormat.format("Federation {0} token = {1}", tokenType.name(),
1280                         getFederationToken(tokenType)));
8f73a7 1281             }
JM 1282
1283             // federation set tokens
1284             for (String set : settings.getStrings(Keys.federation.sets)) {
1285                 logger.info(MessageFormat.format("Federation Set {0} token = {1}", set,
1286                         getFederationToken(set)));
831469 1287             }
JM 1288         }
1289
1290         // Schedule the federation executor
1291         List<FederationModel> registrations = getFederationRegistrations();
1292         if (registrations.size() > 0) {
f6740d 1293             FederationPullExecutor executor = new FederationPullExecutor(registrations, true);
JM 1294             scheduledExecutor.schedule(executor, 1, TimeUnit.MINUTES);
831469 1295         }
JM 1296     }
1297
1298     /**
1299      * Returns the list of federated gitblit instances that this instance will
1300      * try to pull.
1301      * 
1302      * @return list of registered gitblit instances
1303      */
1304     public List<FederationModel> getFederationRegistrations() {
1305         if (federationRegistrations.isEmpty()) {
f6740d 1306             federationRegistrations.addAll(FederationUtils.getFederationRegistrations(settings));
831469 1307         }
JM 1308         return federationRegistrations;
1309     }
1310
1311     /**
1312      * Retrieve the specified federation registration.
1313      * 
1314      * @param name
1315      *            the name of the registration
1316      * @return a federation registration
1317      */
1318     public FederationModel getFederationRegistration(String url, String name) {
1319         // check registrations
1320         for (FederationModel r : getFederationRegistrations()) {
1321             if (r.name.equals(name) && r.url.equals(url)) {
1322                 return r;
1323             }
1324         }
1325
1326         // check the results
1327         for (FederationModel r : getFederationResultRegistrations()) {
1328             if (r.name.equals(name) && r.url.equals(url)) {
1329                 return r;
1330             }
1331         }
1332         return null;
1333     }
1334
1335     /**
31abc2 1336      * Returns the list of federation sets.
JM 1337      * 
1338      * @return list of federation sets
1339      */
1340     public List<FederationSet> getFederationSets(String gitblitUrl) {
1341         List<FederationSet> list = new ArrayList<FederationSet>();
1342         // generate standard tokens
1343         for (FederationToken type : FederationToken.values()) {
1344             FederationSet fset = new FederationSet(type.toString(), type, getFederationToken(type));
1345             fset.repositories = getRepositories(gitblitUrl, fset.token);
1346             list.add(fset);
1347         }
1348         // generate tokens for federation sets
1349         for (String set : settings.getStrings(Keys.federation.sets)) {
1350             FederationSet fset = new FederationSet(set, FederationToken.REPOSITORIES,
1351                     getFederationToken(set));
1352             fset.repositories = getRepositories(gitblitUrl, fset.token);
1353             list.add(fset);
1354         }
1355         return list;
1356     }
1357
1358     /**
831469 1359      * Returns the list of possible federation tokens for this Gitblit instance.
JM 1360      * 
1361      * @return list of federation tokens
1362      */
1363     public List<String> getFederationTokens() {
1364         List<String> tokens = new ArrayList<String>();
8f73a7 1365         // generate standard tokens
831469 1366         for (FederationToken type : FederationToken.values()) {
JM 1367             tokens.add(getFederationToken(type));
8f73a7 1368         }
JM 1369         // generate tokens for federation sets
1370         for (String set : settings.getStrings(Keys.federation.sets)) {
1371             tokens.add(getFederationToken(set));
831469 1372         }
JM 1373         return tokens;
1374     }
1375
1376     /**
1377      * Returns the specified federation token for this Gitblit instance.
1378      * 
1379      * @param type
1380      * @return a federation token
1381      */
1382     public String getFederationToken(FederationToken type) {
8f73a7 1383         return getFederationToken(type.name());
JM 1384     }
1385
1386     /**
1387      * Returns the specified federation token for this Gitblit instance.
1388      * 
1389      * @param value
1390      * @return a federation token
1391      */
1392     public String getFederationToken(String value) {
2c32fd 1393         String passphrase = settings.getString(Keys.federation.passphrase, "");
8f73a7 1394         return StringUtils.getSHA1(passphrase + "-" + value);
831469 1395     }
JM 1396
1397     /**
1398      * Compares the provided token with this Gitblit instance's tokens and
1399      * determines if the requested permission may be granted to the token.
1400      * 
1401      * @param req
1402      * @param token
1403      * @return true if the request can be executed
1404      */
1405     public boolean validateFederationRequest(FederationRequest req, String token) {
1406         String all = getFederationToken(FederationToken.ALL);
1407         String unr = getFederationToken(FederationToken.USERS_AND_REPOSITORIES);
1408         String jur = getFederationToken(FederationToken.REPOSITORIES);
1409         switch (req) {
1410         case PULL_REPOSITORIES:
1411             return token.equals(all) || token.equals(unr) || token.equals(jur);
1412         case PULL_USERS:
fe24a0 1413         case PULL_TEAMS:
831469 1414             return token.equals(all) || token.equals(unr);
JM 1415         case PULL_SETTINGS:
df162c 1416         case PULL_SCRIPTS:
831469 1417             return token.equals(all);
JM 1418         }
1419         return false;
1420     }
1421
1422     /**
1423      * Acknowledge and cache the status of a remote Gitblit instance.
1424      * 
1425      * @param identification
1426      *            the identification of the pulling Gitblit instance
1427      * @param registration
1428      *            the registration from the pulling Gitblit instance
1429      * @return true if acknowledged
1430      */
1431     public boolean acknowledgeFederationStatus(String identification, FederationModel registration) {
1432         // reset the url to the identification of the pulling Gitblit instance
1433         registration.url = identification;
1434         String id = identification;
1435         if (!StringUtils.isEmpty(registration.folder)) {
1436             id += "-" + registration.folder;
1437         }
1438         federationPullResults.put(id, registration);
1439         return true;
1440     }
1441
1442     /**
1443      * Returns the list of registration results.
1444      * 
1445      * @return the list of registration results
1446      */
1447     public List<FederationModel> getFederationResultRegistrations() {
1448         return new ArrayList<FederationModel>(federationPullResults.values());
1449     }
1450
1451     /**
1452      * Submit a federation proposal. The proposal is cached locally and the
1453      * Gitblit administrator(s) are notified via email.
1454      * 
1455      * @param proposal
1456      *            the proposal
1457      * @param gitblitUrl
4aafd4 1458      *            the url of your gitblit instance to send an email to
JM 1459      *            administrators
831469 1460      * @return true if the proposal was submitted
JM 1461      */
1462     public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {
1463         // convert proposal to json
93f0b1 1464         String json = JsonUtils.toJsonString(proposal);
831469 1465
JM 1466         try {
1467             // make the proposals folder
b774de 1468             File proposalsFolder = getProposalsFolder();
831469 1469             proposalsFolder.mkdirs();
JM 1470
1471             // cache json to a file
1472             File file = new File(proposalsFolder, proposal.token + Constants.PROPOSAL_EXT);
1473             com.gitblit.utils.FileUtils.writeContent(file, json);
1474         } catch (Exception e) {
1475             logger.error(MessageFormat.format("Failed to cache proposal from {0}", proposal.url), e);
1476         }
1477
1478         // send an email, if possible
1479         try {
1480             Message message = mailExecutor.createMessageForAdministrators();
1481             if (message != null) {
1482                 message.setSubject("Federation proposal from " + proposal.url);
1483                 message.setText("Please review the proposal @ " + gitblitUrl + "/proposal/"
1484                         + proposal.token);
1485                 mailExecutor.queue(message);
1486             }
1487         } catch (Throwable t) {
1488             logger.error("Failed to notify administrators of proposal", t);
1489         }
1490         return true;
1491     }
1492
1493     /**
1494      * Returns the list of pending federation proposals
1495      * 
1496      * @return list of federation proposals
1497      */
1498     public List<FederationProposal> getPendingFederationProposals() {
1499         List<FederationProposal> list = new ArrayList<FederationProposal>();
b774de 1500         File folder = getProposalsFolder();
831469 1501         if (folder.exists()) {
JM 1502             File[] files = folder.listFiles(new FileFilter() {
1503                 @Override
1504                 public boolean accept(File file) {
1505                     return file.isFile()
1506                             && file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);
1507                 }
1508             });
1509             for (File file : files) {
1510                 String json = com.gitblit.utils.FileUtils.readContent(file, null);
31abc2 1511                 FederationProposal proposal = JsonUtils.fromJsonString(json,
JM 1512                         FederationProposal.class);
831469 1513                 list.add(proposal);
JM 1514             }
1515         }
1516         return list;
1517     }
1518
1519     /**
dd9ae7 1520      * Get repositories for the specified token.
JM 1521      * 
1522      * @param gitblitUrl
1523      *            the base url of this gitblit instance
1524      * @param token
1525      *            the federation token
1526      * @return a map of <cloneurl, RepositoryModel>
1527      */
1528     public Map<String, RepositoryModel> getRepositories(String gitblitUrl, String token) {
1529         Map<String, String> federationSets = new HashMap<String, String>();
1530         for (String set : getStrings(Keys.federation.sets)) {
1531             federationSets.put(getFederationToken(set), set);
1532         }
1533
1534         // Determine the Gitblit clone url
1535         StringBuilder sb = new StringBuilder();
1536         sb.append(gitblitUrl);
1537         sb.append(Constants.GIT_PATH);
1538         sb.append("{0}");
1539         String cloneUrl = sb.toString();
1540
1541         // Retrieve all available repositories
1542         UserModel user = new UserModel(Constants.FEDERATION_USER);
1543         user.canAdmin = true;
1544         List<RepositoryModel> list = getRepositoryModels(user);
1545
1546         // create the [cloneurl, repositoryModel] map
1547         Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();
1548         for (RepositoryModel model : list) {
1549             // by default, setup the url for THIS repository
1550             String url = MessageFormat.format(cloneUrl, model.name);
1551             switch (model.federationStrategy) {
1552             case EXCLUDE:
1553                 // skip this repository
1554                 continue;
1555             case FEDERATE_ORIGIN:
1556                 // federate the origin, if it is defined
1557                 if (!StringUtils.isEmpty(model.origin)) {
1558                     url = model.origin;
1559                 }
1560                 break;
1561             }
1562
1563             if (federationSets.containsKey(token)) {
1564                 // include repositories only for federation set
1565                 String set = federationSets.get(token);
1566                 if (model.federationSets.contains(set)) {
1567                     repositories.put(url, model);
1568                 }
1569             } else {
1570                 // standard federation token for ALL
1571                 repositories.put(url, model);
1572             }
1573         }
1574         return repositories;
1575     }
1576
1577     /**
1578      * Creates a proposal from the token.
1579      * 
1580      * @param gitblitUrl
1581      *            the url of this Gitblit instance
1582      * @param token
1583      * @return a potential proposal
1584      */
1585     public FederationProposal createFederationProposal(String gitblitUrl, String token) {
1586         FederationToken tokenType = FederationToken.REPOSITORIES;
1587         for (FederationToken type : FederationToken.values()) {
1588             if (token.equals(getFederationToken(type))) {
1589                 tokenType = type;
1590                 break;
1591             }
1592         }
1593         Map<String, RepositoryModel> repositories = getRepositories(gitblitUrl, token);
1594         FederationProposal proposal = new FederationProposal(gitblitUrl, tokenType, token,
1595                 repositories);
1596         return proposal;
1597     }
1598
1599     /**
831469 1600      * Returns the proposal identified by the supplied token.
JM 1601      * 
1602      * @param token
1603      * @return the specified proposal or null
1604      */
1605     public FederationProposal getPendingFederationProposal(String token) {
1606         List<FederationProposal> list = getPendingFederationProposals();
1607         for (FederationProposal proposal : list) {
1608             if (proposal.token.equals(token)) {
1609                 return proposal;
1610             }
1611         }
1612         return null;
1613     }
1614
1615     /**
1616      * Deletes a pending federation proposal.
1617      * 
1618      * @param a
1619      *            proposal
1620      * @return true if the proposal was deleted
1621      */
1622     public boolean deletePendingFederationProposal(FederationProposal proposal) {
b774de 1623         File folder = getProposalsFolder();
831469 1624         File file = new File(folder, proposal.token + Constants.PROPOSAL_EXT);
JM 1625         return file.delete();
1626     }
1627
1628     /**
d7905a 1629      * Returns the list of all Groovy push hook scripts. Script files must have
6cc1d4 1630      * .groovy extension
JM 1631      * 
1632      * @return list of available hook scripts
1633      */
d7905a 1634     public List<String> getAllScripts() {
6cc1d4 1635         File groovyFolder = getGroovyScriptsFolder();
JM 1636         File[] files = groovyFolder.listFiles(new FileFilter() {
1637             @Override
1638             public boolean accept(File pathname) {
1639                 return pathname.isFile() && pathname.getName().endsWith(".groovy");
1640             }
1641         });
1642         List<String> scripts = new ArrayList<String>();
1643         if (files != null) {
1644             for (File file : files) {
1645                 String script = file.getName().substring(0, file.getName().lastIndexOf('.'));
d7905a 1646                 scripts.add(script);
6cc1d4 1647             }
JM 1648         }
1649         return scripts;
1650     }
d7905a 1651
JM 1652     /**
1653      * Returns the list of pre-receive scripts the repository inherited from the
1654      * global settings and team affiliations.
1655      * 
1656      * @param repository
1657      *            if null only the globally specified scripts are returned
1658      * @return a list of scripts
1659      */
1660     public List<String> getPreReceiveScriptsInherited(RepositoryModel repository) {
1661         Set<String> scripts = new LinkedHashSet<String>();
1662         // Globals
0d013a 1663         for (String script : getStrings(Keys.groovy.preReceiveScripts)) {
JM 1664             if (script.endsWith(".groovy")) {
d7905a 1665                 scripts.add(script.substring(0, script.lastIndexOf('.')));
0d013a 1666             } else {
d7905a 1667                 scripts.add(script);
0d013a 1668             }
JM 1669         }
d7905a 1670
JM 1671         // Team Scripts
1672         if (repository != null) {
1673             for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
1674                 TeamModel team = userService.getTeamModel(teamname);
1675                 scripts.addAll(team.preReceiveScripts);
1676             }
1677         }
1678         return new ArrayList<String>(scripts);
0d013a 1679     }
d7905a 1680
JM 1681     /**
1682      * Returns the list of all available Groovy pre-receive push hook scripts
1683      * that are not already inherited by the repository. Script files must have
1684      * .groovy extension
1685      * 
1686      * @param repository
1687      *            optional parameter
1688      * @return list of available hook scripts
1689      */
1690     public List<String> getPreReceiveScriptsUnused(RepositoryModel repository) {
1691         Set<String> inherited = new TreeSet<String>(getPreReceiveScriptsInherited(repository));
1692
1693         // create list of available scripts by excluding inherited scripts
1694         List<String> scripts = new ArrayList<String>();
1695         for (String script : getAllScripts()) {
1696             if (!inherited.contains(script)) {
1697                 scripts.add(script);
1698             }
1699         }
1700         return scripts;
1701     }
1702
1703     /**
1704      * Returns the list of post-receive scripts the repository inherited from
1705      * the global settings and team affiliations.
1706      * 
1707      * @param repository
1708      *            if null only the globally specified scripts are returned
1709      * @return a list of scripts
1710      */
1711     public List<String> getPostReceiveScriptsInherited(RepositoryModel repository) {
1712         Set<String> scripts = new LinkedHashSet<String>();
1713         // Global Scripts
0d013a 1714         for (String script : getStrings(Keys.groovy.postReceiveScripts)) {
JM 1715             if (script.endsWith(".groovy")) {
d7905a 1716                 scripts.add(script.substring(0, script.lastIndexOf('.')));
0d013a 1717             } else {
d7905a 1718                 scripts.add(script);
0d013a 1719             }
JM 1720         }
d7905a 1721         // Team Scripts
JM 1722         if (repository != null) {
1723             for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
1724                 TeamModel team = userService.getTeamModel(teamname);
1725                 scripts.addAll(team.postReceiveScripts);
1726             }
1727         }
1728         return new ArrayList<String>(scripts);
1729     }
1730
1731     /**
1732      * Returns the list of unused Groovy post-receive push hook scripts that are
1733      * not already inherited by the repository. Script files must have .groovy
1734      * extension
1735      * 
1736      * @param repository
1737      *            optional parameter
1738      * @return list of available hook scripts
1739      */
1740     public List<String> getPostReceiveScriptsUnused(RepositoryModel repository) {
1741         Set<String> inherited = new TreeSet<String>(getPostReceiveScriptsInherited(repository));
1742
1743         // create list of available scripts by excluding inherited scripts
1744         List<String> scripts = new ArrayList<String>();
1745         for (String script : getAllScripts()) {
1746             if (!inherited.contains(script)) {
1747                 scripts.add(script);
1748             }
1749         }
1750         return scripts;
0d013a 1751     }
d896e6 1752     
JM 1753     /**
1754      * Search the specified repositories using the Lucene query.
1755      * 
1756      * @param query
d04009 1757      * @param page
JM 1758      * @param pageSize
d896e6 1759      * @param repositories
JM 1760      * @return
1761      */
d04009 1762     public List<SearchResult> search(String query, int page, int pageSize, List<String> repositories) {        
JM 1763         List<SearchResult> srs = luceneExecutor.search(query, page, pageSize, repositories);
d896e6 1764         return srs;
JM 1765     }
0d013a 1766
6cc1d4 1767     /**
831469 1768      * Notify the administrators by email.
JM 1769      * 
1770      * @param subject
1771      * @param message
1772      */
eb96ea 1773     public void sendMailToAdministrators(String subject, String message) {
831469 1774         try {
JM 1775             Message mail = mailExecutor.createMessageForAdministrators();
1776             if (mail != null) {
1777                 mail.setSubject(subject);
1778                 mail.setText(message);
1779                 mailExecutor.queue(mail);
1780             }
1781         } catch (MessagingException e) {
1782             logger.error("Messaging error", e);
1783         }
1784     }
1785
1786     /**
fa54be 1787      * Notify users by email of something.
JM 1788      * 
1789      * @param subject
1790      * @param message
1791      * @param toAddresses
1792      */
0b9119 1793     public void sendMail(String subject, String message, Collection<String> toAddresses) {
eb96ea 1794         this.sendMail(subject, message, toAddresses.toArray(new String[0]));
fa54be 1795     }
JM 1796
1797     /**
1798      * Notify users by email of something.
1799      * 
1800      * @param subject
1801      * @param message
1802      * @param toAddresses
1803      */
eb96ea 1804     public void sendMail(String subject, String message, String... toAddresses) {
fa54be 1805         try {
JM 1806             Message mail = mailExecutor.createMessage(toAddresses);
1807             if (mail != null) {
1808                 mail.setSubject(subject);
1809                 mail.setText(message);
1810                 mailExecutor.queue(mail);
1811             }
1812         } catch (MessagingException e) {
1813             logger.error("Messaging error", e);
1814         }
b938ae 1815     }
JM 1816
1817     /**
b75734 1818      * Returns the descriptions/comments of the Gitblit config settings.
JM 1819      * 
84c1d5 1820      * @return SettingsModel
b75734 1821      */
84c1d5 1822     public ServerSettings getSettingsModel() {
b75734 1823         // ensure that the current values are updated in the setting models
773bb6 1824         for (String key : settings.getAllKeys(null)) {
JM 1825             SettingModel setting = settingsModel.get(key);
e09d4b 1826             if (setting == null) {
JM 1827                 // unreferenced setting, create a setting model
1828                 setting = new SettingModel();
1829                 setting.name = key;
1830                 settingsModel.add(setting);
773bb6 1831             }
e09d4b 1832             setting.currentValue = settings.getString(key, "");            
773bb6 1833         }
d7905a 1834         settingsModel.pushScripts = getAllScripts();
84c1d5 1835         return settingsModel;
b75734 1836     }
JM 1837
1838     /**
1839      * Parse the properties file and aggregate all the comments by the setting
1840      * key. A setting model tracks the current value, the default value, the
1841      * description of the setting and and directives about the setting.
1842      * 
1843      * @return Map<String, SettingModel>
1844      */
84c1d5 1845     private ServerSettings loadSettingModels() {
JM 1846         ServerSettings settingsModel = new ServerSettings();
0aa8cf 1847         settingsModel.supportsCredentialChanges = userService.supportsCredentialChanges();
JM 1848         settingsModel.supportsDisplayNameChanges = userService.supportsDisplayNameChanges();
1849         settingsModel.supportsEmailAddressChanges = userService.supportsEmailAddressChanges();
1850         settingsModel.supportsTeamMembershipChanges = userService.supportsTeamMembershipChanges();
b75734 1851         try {
JM 1852             // Read bundled Gitblit properties to extract setting descriptions.
1853             // This copy is pristine and only used for populating the setting
1854             // models map.
97a20e 1855             InputStream is = servletContext.getResourceAsStream("/WEB-INF/reference.properties");
b75734 1856             BufferedReader propertiesReader = new BufferedReader(new InputStreamReader(is));
JM 1857             StringBuilder description = new StringBuilder();
1858             SettingModel setting = new SettingModel();
1859             String line = null;
1860             while ((line = propertiesReader.readLine()) != null) {
1861                 if (line.length() == 0) {
1862                     description.setLength(0);
1863                     setting = new SettingModel();
1864                 } else {
1865                     if (line.charAt(0) == '#') {
1866                         if (line.length() > 1) {
1867                             String text = line.substring(1).trim();
1868                             if (SettingModel.CASE_SENSITIVE.equals(text)) {
1869                                 setting.caseSensitive = true;
1870                             } else if (SettingModel.RESTART_REQUIRED.equals(text)) {
1871                                 setting.restartRequired = true;
1872                             } else if (SettingModel.SPACE_DELIMITED.equals(text)) {
1873                                 setting.spaceDelimited = true;
1874                             } else if (text.startsWith(SettingModel.SINCE)) {
1875                                 try {
1876                                     setting.since = text.split(" ")[1];
1877                                 } catch (Exception e) {
1878                                     setting.since = text;
1879                                 }
1880                             } else {
1881                                 description.append(text);
1882                                 description.append('\n');
1883                             }
1884                         }
1885                     } else {
1886                         String[] kvp = line.split("=", 2);
1887                         String key = kvp[0].trim();
1888                         setting.name = key;
1889                         setting.defaultValue = kvp[1].trim();
1890                         setting.currentValue = setting.defaultValue;
1891                         setting.description = description.toString().trim();
84c1d5 1892                         settingsModel.add(setting);
b75734 1893                         description.setLength(0);
JM 1894                         setting = new SettingModel();
1895                     }
1896                 }
1897             }
1898             propertiesReader.close();
1899         } catch (NullPointerException e) {
1900             logger.error("Failed to find resource copy of gitblit.properties");
1901         } catch (IOException e) {
1902             logger.error("Failed to load resource copy of gitblit.properties");
1903         }
84c1d5 1904         return settingsModel;
b75734 1905     }
JM 1906
1907     /**
892570 1908      * Configure the Gitblit singleton with the specified settings source. This
JM 1909      * source may be file settings (Gitblit GO) or may be web.xml settings
1910      * (Gitblit WAR).
1911      * 
1912      * @param settings
1913      */
f6740d 1914     public void configureContext(IStoredSettings settings, boolean startFederation) {
1f9dae 1915         logger.info("Reading configuration from " + settings.toString());
892570 1916         this.settings = settings;
b774de 1917         repositoriesFolder = getRepositoriesFolder();
5450d0 1918         logger.info("Git repositories folder " + repositoriesFolder.getAbsolutePath());
b86562 1919         repositoryResolver = new FileResolver<Void>(repositoriesFolder, true);
6c6e7d 1920         
JM 1921         logTimezone("JVM", TimeZone.getDefault());
1922         logTimezone(Constants.NAME, getTimezone());
1923
486ee1 1924         serverStatus = new ServerStatus(isGO());
85c2e6 1925         String realm = settings.getString(Keys.realm.userService, "users.properties");
JM 1926         IUserService loginService = null;
5450d0 1927         try {
892570 1928             // check to see if this "file" is a login service class
5450d0 1929             Class<?> realmClass = Class.forName(realm);
d25c59 1930             loginService = (IUserService) realmClass.newInstance();
5450d0 1931         } catch (Throwable t) {
eb96ea 1932             loginService = new GitblitUserService();
5450d0 1933         }
85c2e6 1934         setUserService(loginService);
831469 1935         mailExecutor = new MailExecutor(settings);
JM 1936         if (mailExecutor.isReady()) {
e31da0 1937             logger.info("Mail executor is scheduled to process the message queue every 2 minutes.");
831469 1938             scheduledExecutor.scheduleAtFixedRate(mailExecutor, 1, 2, TimeUnit.MINUTES);
JM 1939         } else {
1940             logger.warn("Mail server is not properly configured.  Mail services disabled.");
f6740d 1941         }
d896e6 1942         luceneExecutor = new LuceneExecutor(settings, repositoriesFolder);
273cb9 1943         logger.info("Lucene executor is scheduled to process indexed branches every 2 minutes.");
JM 1944         scheduledExecutor.scheduleAtFixedRate(luceneExecutor, 1, 2, TimeUnit.MINUTES);
f6740d 1945         if (startFederation) {
JM 1946             configureFederation();
478678 1947         }
JM 1948         
1949         // Configure JGit
1950         WindowCacheConfig cfg = new WindowCacheConfig();
1951         
1952         cfg.setPackedGitWindowSize(settings.getFilesize(Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
1953         cfg.setPackedGitLimit(settings.getFilesize(Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
1954         cfg.setDeltaBaseCacheLimit(settings.getFilesize(Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
1955         cfg.setPackedGitOpenFiles(settings.getFilesize(Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
1956         cfg.setStreamFileThreshold(settings.getFilesize(Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
1957         cfg.setPackedGitMMAP(settings.getBoolean(Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
1958         
1959         try {
1960             WindowCache.reconfigure(cfg);
1961             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
1962             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
1963             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
1964             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
1965             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
1966             logger.debug(MessageFormat.format("{0} = {1}", Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
1967         } catch (IllegalArgumentException e) {
1968             logger.error("Failed to configure JGit parameters!", e);
1969         }
6c6e7d 1970     }
JM 1971     
1972     private void logTimezone(String type, TimeZone zone) {
1973         SimpleDateFormat df = new SimpleDateFormat("z Z");
1974         df.setTimeZone(zone);
1975         String offset = df.format(new Date());
1976         logger.info(type + " timezone is " + zone.getID() + " (" + offset + ")");
87cc1e 1977     }
JM 1978
892570 1979     /**
JM 1980      * Configure Gitblit from the web.xml, if no configuration has already been
1981      * specified.
1982      * 
1983      * @see ServletContextListener.contextInitialize(ServletContextEvent)
1984      */
87cc1e 1985     @Override
JM 1986     public void contextInitialized(ServletContextEvent contextEvent) {
b75734 1987         servletContext = contextEvent.getServletContext();
892570 1988         if (settings == null) {
JM 1989             // Gitblit WAR is running in a servlet container
b774de 1990             ServletContext context = contextEvent.getServletContext();
JM 1991             WebXmlSettings webxmlSettings = new WebXmlSettings(context);
1992
1993             // 0.7.0 web.properties in the deployed war folder
7a1889 1994             String webProps = context.getRealPath("/WEB-INF/web.properties");
JM 1995             if (!StringUtils.isEmpty(webProps)) {
1996                 File overrideFile = new File(webProps);
1997                 if (overrideFile.exists()) {
1998                     webxmlSettings.applyOverrides(overrideFile);
1999                 }
b774de 2000             }
7a1889 2001             
b774de 2002
JM 2003             // 0.8.0 gitblit.properties file located outside the deployed war
2004             // folder lie, for example, on RedHat OpenShift.
7a1889 2005             File overrideFile = getFileOrFolder("gitblit.properties");
b774de 2006             if (!overrideFile.getPath().equals("gitblit.properties")) {
JM 2007                 webxmlSettings.applyOverrides(overrideFile);
2008             }
f6740d 2009             configureContext(webxmlSettings, true);
e36d4d 2010
JM 2011             // Copy the included scripts to the configured groovy folder
2012             File localScripts = getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
2013             if (!localScripts.exists()) {
2014                 File includedScripts = new File(context.getRealPath("/WEB-INF/groovy"));
2015                 if (!includedScripts.equals(localScripts)) {
2016                     try {
2017                         com.gitblit.utils.FileUtils.copy(localScripts, includedScripts.listFiles());
2018                     } catch (IOException e) {
2019                         logger.error(MessageFormat.format(
2020                                 "Failed to copy included Groovy scripts from {0} to {1}",
2021                                 includedScripts, localScripts));
2022                     }
2023                 }
2024             }
87cc1e 2025         }
b6db0d 2026         
JM 2027         settingsModel = loadSettingModels();
486ee1 2028         serverStatus.servletContainer = servletContext.getServerInfo();
87cc1e 2029     }
JM 2030
892570 2031     /**
JM 2032      * Gitblit is being shutdown either because the servlet container is
2033      * shutting down or because the servlet container is re-deploying Gitblit.
2034      */
87cc1e 2035     @Override
JM 2036     public void contextDestroyed(ServletContextEvent contextEvent) {
f339f5 2037         logger.info("Gitblit context destroyed by servlet container.");
831469 2038         scheduledExecutor.shutdownNow();
b938ae 2039         luceneExecutor.close();
87cc1e 2040     }
fc948c 2041 }