Example usage for org.eclipse.jgit.lib Repository close

List of usage examples for org.eclipse.jgit.lib Repository close

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository close.

Prototype

@Override
public void close() 

Source Link

Document

Decrement the use count, and maybe close resources.

Usage

From source file:com.gitblit.FederationPullExecutor.java

License:Apache License

/**
 * Mirrors a repository and, optionally, the server's users, and/or
 * configuration settings from a origin Gitblit instance.
 * /*from   w w  w.j  av  a 2s  .  co  m*/
 * @param registration
 * @throws Exception
 */
private void pull(FederationModel registration) throws Exception {
    Map<String, RepositoryModel> repositories = FederationUtils.getRepositories(registration, true);
    String registrationFolder = registration.folder.toLowerCase().trim();
    // confirm valid characters in server alias
    Character c = StringUtils.findInvalidCharacter(registrationFolder);
    if (c != null) {
        logger.error(MessageFormat.format(
                "Illegal character ''{0}'' in folder name ''{1}'' of federation registration {2}!", c,
                registrationFolder, registration.name));
        return;
    }
    File repositoriesFolder = new File(GitBlit.getString(Keys.git.repositoriesFolder, "git"));
    File registrationFolderFile = new File(repositoriesFolder, registrationFolder);
    registrationFolderFile.mkdirs();

    // Clone/Pull the repository
    for (Map.Entry<String, RepositoryModel> entry : repositories.entrySet()) {
        String cloneUrl = entry.getKey();
        RepositoryModel repository = entry.getValue();
        if (!repository.hasCommits) {
            logger.warn(MessageFormat.format(
                    "Skipping federated repository {0} from {1} @ {2}. Repository is EMPTY.", repository.name,
                    registration.name, registration.url));
            registration.updateStatus(repository, FederationPullStatus.SKIPPED);
            continue;
        }

        // Determine local repository name
        String repositoryName;
        if (StringUtils.isEmpty(registrationFolder)) {
            repositoryName = repository.name;
        } else {
            repositoryName = registrationFolder + "/" + repository.name;
        }

        if (registration.bare) {
            // bare repository, ensure .git suffix
            if (!repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {
                repositoryName += DOT_GIT_EXT;
            }
        } else {
            // normal repository, strip .git suffix
            if (repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {
                repositoryName = repositoryName.substring(0, repositoryName.indexOf(DOT_GIT_EXT));
            }
        }

        // confirm that the origin of any pre-existing repository matches
        // the clone url
        String fetchHead = null;
        Repository existingRepository = GitBlit.self().getRepository(repositoryName);
        if (existingRepository != null) {
            StoredConfig config = existingRepository.getConfig();
            config.load();
            String origin = config.getString("remote", "origin", "url");
            RevCommit commit = JGitUtils.getCommit(existingRepository,
                    org.eclipse.jgit.lib.Constants.FETCH_HEAD);
            if (commit != null) {
                fetchHead = commit.getName();
            }
            existingRepository.close();
            if (!origin.startsWith(registration.url)) {
                logger.warn(MessageFormat.format(
                        "Skipping federated repository {0} from {1} @ {2}. Origin does not match, consider EXCLUDING.",
                        repository.name, registration.name, registration.url));
                registration.updateStatus(repository, FederationPullStatus.SKIPPED);
                continue;
            }
        }

        // clone/pull this repository
        CredentialsProvider credentials = new UsernamePasswordCredentialsProvider(Constants.FEDERATION_USER,
                registration.token);
        logger.info(MessageFormat.format("Pulling federated repository {0} from {1} @ {2}", repository.name,
                registration.name, registration.url));

        CloneResult result = JGitUtils.cloneRepository(registrationFolderFile, repository.name, cloneUrl,
                registration.bare, credentials);
        Repository r = GitBlit.self().getRepository(repositoryName);
        RepositoryModel rm = GitBlit.self().getRepositoryModel(repositoryName);
        repository.isFrozen = registration.mirror;
        if (result.createdRepository) {
            // default local settings
            repository.federationStrategy = FederationStrategy.EXCLUDE;
            repository.isFrozen = registration.mirror;
            repository.showRemoteBranches = !registration.mirror;
            logger.info(MessageFormat.format("     cloning {0}", repository.name));
            registration.updateStatus(repository, FederationPullStatus.MIRRORED);
        } else {
            // fetch and update
            boolean fetched = false;
            RevCommit commit = JGitUtils.getCommit(r, org.eclipse.jgit.lib.Constants.FETCH_HEAD);
            String newFetchHead = commit.getName();
            fetched = fetchHead == null || !fetchHead.equals(newFetchHead);

            if (registration.mirror) {
                // mirror
                if (fetched) {
                    // update local branches to match the remote tracking branches
                    for (RefModel ref : JGitUtils.getRemoteBranches(r, false, -1)) {
                        if (ref.displayName.startsWith("origin/")) {
                            String branch = org.eclipse.jgit.lib.Constants.R_HEADS
                                    + ref.displayName.substring(ref.displayName.indexOf('/') + 1);
                            String hash = ref.getReferencedObjectId().getName();

                            JGitUtils.setBranchRef(r, branch, hash);
                            logger.info(MessageFormat.format("     resetting {0} of {1} to {2}", branch,
                                    repository.name, hash));
                        }
                    }

                    String newHead;
                    if (StringUtils.isEmpty(repository.HEAD)) {
                        newHead = newFetchHead;
                    } else {
                        newHead = repository.HEAD;
                    }
                    JGitUtils.setHEADtoRef(r, newHead);
                    logger.info(MessageFormat.format("     resetting HEAD of {0} to {1}", repository.name,
                            newHead));
                    registration.updateStatus(repository, FederationPullStatus.MIRRORED);
                } else {
                    // indicate no commits pulled
                    registration.updateStatus(repository, FederationPullStatus.NOCHANGE);
                }
            } else {
                // non-mirror
                if (fetched) {
                    // indicate commits pulled to origin/master
                    registration.updateStatus(repository, FederationPullStatus.PULLED);
                } else {
                    // indicate no commits pulled
                    registration.updateStatus(repository, FederationPullStatus.NOCHANGE);
                }
            }

            // preserve local settings
            repository.isFrozen = rm.isFrozen;
            repository.federationStrategy = rm.federationStrategy;

            // merge federation sets
            Set<String> federationSets = new HashSet<String>();
            if (rm.federationSets != null) {
                federationSets.addAll(rm.federationSets);
            }
            if (repository.federationSets != null) {
                federationSets.addAll(repository.federationSets);
            }
            repository.federationSets = new ArrayList<String>(federationSets);

            // merge indexed branches
            Set<String> indexedBranches = new HashSet<String>();
            if (rm.indexedBranches != null) {
                indexedBranches.addAll(rm.indexedBranches);
            }
            if (repository.indexedBranches != null) {
                indexedBranches.addAll(repository.indexedBranches);
            }
            repository.indexedBranches = new ArrayList<String>(indexedBranches);

        }
        // only repositories that are actually _cloned_ from the origin
        // Gitblit repository are marked as federated. If the origin
        // is from somewhere else, these repositories are not considered
        // "federated" repositories.
        repository.isFederated = cloneUrl.startsWith(registration.url);

        GitBlit.self().updateConfiguration(r, repository);
        r.close();
    }

    IUserService userService = null;

    try {
        // Pull USERS
        // TeamModels are automatically pulled because they are contained
        // within the UserModel. The UserService creates unknown teams
        // and updates existing teams.
        Collection<UserModel> users = FederationUtils.getUsers(registration);
        if (users != null && users.size() > 0) {
            File realmFile = new File(registrationFolderFile, registration.name + "_users.conf");
            realmFile.delete();
            userService = new ConfigUserService(realmFile);
            for (UserModel user : users) {
                userService.updateUserModel(user.username, user);

                // merge the origin permissions and origin accounts into
                // the user accounts of this Gitblit instance
                if (registration.mergeAccounts) {
                    // reparent all repository permissions if the local
                    // repositories are stored within subfolders
                    if (!StringUtils.isEmpty(registrationFolder)) {
                        List<String> permissions = new ArrayList<String>(user.repositories);
                        user.repositories.clear();
                        for (String permission : permissions) {
                            user.addRepository(registrationFolder + "/" + permission);
                        }
                    }

                    // insert new user or update local user
                    UserModel localUser = GitBlit.self().getUserModel(user.username);
                    if (localUser == null) {
                        // create new local user
                        GitBlit.self().updateUserModel(user.username, user, true);
                    } else {
                        // update repository permissions of local user
                        for (String repository : user.repositories) {
                            localUser.addRepository(repository);
                        }
                        localUser.password = user.password;
                        localUser.canAdmin = user.canAdmin;
                        GitBlit.self().updateUserModel(localUser.username, localUser, false);
                    }

                    for (String teamname : GitBlit.self().getAllTeamnames()) {
                        TeamModel team = GitBlit.self().getTeamModel(teamname);
                        if (user.isTeamMember(teamname) && !team.hasUser(user.username)) {
                            // new team member
                            team.addUser(user.username);
                            GitBlit.self().updateTeamModel(teamname, team, false);
                        } else if (!user.isTeamMember(teamname) && team.hasUser(user.username)) {
                            // remove team member
                            team.removeUser(user.username);
                            GitBlit.self().updateTeamModel(teamname, team, false);
                        }

                        // update team repositories
                        TeamModel remoteTeam = user.getTeam(teamname);
                        if (remoteTeam != null && !ArrayUtils.isEmpty(remoteTeam.repositories)) {
                            int before = team.repositories.size();
                            team.addRepositories(remoteTeam.repositories);
                            int after = team.repositories.size();
                            if (after > before) {
                                // repository count changed, update
                                GitBlit.self().updateTeamModel(teamname, team, false);
                            }
                        }
                    }
                }
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve USERS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull TEAMS
        // We explicitly pull these even though they are embedded in
        // UserModels because it is possible to use teams to specify
        // mailing lists or push scripts without specifying users.
        if (userService != null) {
            Collection<TeamModel> teams = FederationUtils.getTeams(registration);
            if (teams != null && teams.size() > 0) {
                for (TeamModel team : teams) {
                    userService.updateTeamModel(team);
                }
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve TEAMS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull SETTINGS
        Map<String, String> settings = FederationUtils.getSettings(registration);
        if (settings != null && settings.size() > 0) {
            Properties properties = new Properties();
            properties.putAll(settings);
            FileOutputStream os = new FileOutputStream(
                    new File(registrationFolderFile, registration.name + "_" + Constants.PROPERTIES_FILE));
            properties.store(os, null);
            os.close();
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve SETTINGS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull SCRIPTS
        Map<String, String> scripts = FederationUtils.getScripts(registration);
        if (scripts != null && scripts.size() > 0) {
            for (Map.Entry<String, String> script : scripts.entrySet()) {
                String scriptName = script.getKey();
                if (scriptName.endsWith(".groovy")) {
                    scriptName = scriptName.substring(0, scriptName.indexOf(".groovy"));
                }
                File file = new File(registrationFolderFile, registration.name + "_" + scriptName + ".groovy");
                FileUtils.writeContent(file, script.getValue());
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve SCRIPTS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }
}

From source file:com.gitblit.GCExecutor.java

License:Apache License

@Override
public void run() {
    if (!isReady()) {
        return;//from   w  w w  . j ava 2  s.  c o m
    }

    running.set(true);
    Date now = new Date();

    for (String repositoryName : GitBlit.self().getRepositoryList()) {
        if (forceClose.get()) {
            break;
        }
        if (isCollectingGarbage(repositoryName)) {
            logger.warn(MessageFormat.format("Already collecting garbage from {0}?!?", repositoryName));
            continue;
        }
        boolean garbageCollected = false;
        RepositoryModel model = null;
        Repository repository = null;
        try {
            model = GitBlit.self().getRepositoryModel(repositoryName);
            repository = GitBlit.self().getRepository(repositoryName);
            if (repository == null) {
                logger.warn(MessageFormat.format("GCExecutor is missing repository {0}?!?", repositoryName));
                continue;
            }

            if (!isRepositoryIdle(repository)) {
                logger.debug(MessageFormat.format("GCExecutor is skipping {0} because it is not idle",
                        repositoryName));
                continue;
            }

            // By setting the GCStatus to COLLECTING we are
            // disabling *all* access to this repository from Gitblit.
            // Think of this as a clutch in a manual transmission vehicle.
            if (!setGCStatus(repositoryName, GCStatus.COLLECTING)) {
                logger.warn(MessageFormat.format("Can not acquire GC lock for {0}, skipping", repositoryName));
                continue;
            }

            logger.debug(MessageFormat.format("GCExecutor locked idle repository {0}", repositoryName));

            Git git = new Git(repository);
            GarbageCollectCommand gc = git.gc();
            Properties stats = gc.getStatistics();

            // determine if this is a scheduled GC
            Calendar cal = Calendar.getInstance();
            cal.setTime(model.lastGC);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.DATE, model.gcPeriod);
            Date gcDate = cal.getTime();
            boolean shouldCollectGarbage = now.after(gcDate);

            // determine if filesize triggered GC
            long gcThreshold = FileUtils.convertSizeToLong(model.gcThreshold, 500 * 1024L);
            long sizeOfLooseObjects = (Long) stats.get("sizeOfLooseObjects");
            boolean hasEnoughGarbage = sizeOfLooseObjects >= gcThreshold;

            // if we satisfy one of the requirements, GC
            boolean hasGarbage = sizeOfLooseObjects > 0;
            if (hasGarbage && (hasEnoughGarbage || shouldCollectGarbage)) {
                long looseKB = sizeOfLooseObjects / 1024L;
                logger.info(MessageFormat.format("Collecting {1} KB of loose objects from {0}", repositoryName,
                        looseKB));

                // do the deed
                gc.call();

                garbageCollected = true;
            }
        } catch (Exception e) {
            logger.error("Error collecting garbage in " + repositoryName, e);
        } finally {
            // cleanup
            if (repository != null) {
                if (garbageCollected) {
                    // update the last GC date
                    model.lastGC = new Date();
                    GitBlit.self().updateConfiguration(repository, model);
                }

                repository.close();
            }

            // reset the GC lock 
            releaseLock(repositoryName);
            logger.debug(MessageFormat.format("GCExecutor released GC lock for {0}", repositoryName));
        }
    }

    running.set(false);
}

From source file:com.gitblit.git.GitDaemonService.java

License:Eclipse Distribution License

void execute(final GitDaemonClient client, final String commandLine)
        throws IOException, ServiceNotEnabledException, ServiceNotAuthorizedException {
    final String name = commandLine.substring(command.length() + 1);
    Repository db;
    try {//from   w w w . j ava  2 s .  c  o m
        db = client.getDaemon().openRepository(client, name);
    } catch (ServiceMayNotContinueException e) {
        // An error when opening the repo means the client is expecting a ref
        // advertisement, so use that style of error.
        PacketLineOut pktOut = new PacketLineOut(client.getOutputStream());
        pktOut.writeString("ERR " + e.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        db = null;
    }
    if (db == null)
        return;
    try {
        if (isEnabledFor(db))
            execute(client, db);
    } finally {
        db.close();
    }
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Returns the repository model for the specified repository. This method
 * does not consider user access permissions.
 * /*from  w w w.j  a  va 2 s. c om*/
 * @param repositoryName
 * @return repository model or null
 */
public RepositoryModel getRepositoryModel(String repositoryName) {
    if (!repositoryListCache.containsKey(repositoryName)) {
        RepositoryModel model = loadRepositoryModel(repositoryName);
        if (model == null) {
            return null;
        }
        addToCachedRepositoryList(repositoryName, model);
        return model;
    }

    // cached model
    RepositoryModel model = repositoryListCache.get(repositoryName);

    // check for updates
    Repository r = getRepository(repositoryName);
    if (r == null) {
        // repository is missing
        removeFromCachedRepositoryList(repositoryName);
        logger.error(
                MessageFormat.format("Repository \"{0}\" is missing! Removing from cache.", repositoryName));
        return null;
    }

    FileBasedConfig config = (FileBasedConfig) getRepositoryConfig(r);
    if (config.isOutdated()) {
        // reload model
        logger.info(MessageFormat.format("Config for \"{0}\" has changed. Reloading model and updating cache.",
                repositoryName));
        model = loadRepositoryModel(repositoryName);
        removeFromCachedRepositoryList(repositoryName);
        addToCachedRepositoryList(repositoryName, model);
    } else {
        // update a few repository parameters 
        if (!model.hasCommits) {
            // update hasCommits, assume a repository only gains commits :)
            model.hasCommits = JGitUtils.hasCommits(r);
        }

        model.lastChange = JGitUtils.getLastChange(r);
    }
    r.close();

    // return a copy of the cached model
    return DeepCopier.copy(model);
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Create a repository model from the configuration and repository data.
 * //from   w  w w.  ja v  a  2s  .c om
 * @param repositoryName
 * @return a repositoryModel or null if the repository does not exist
 */
private RepositoryModel loadRepositoryModel(String repositoryName) {
    Repository r = getRepository(repositoryName);
    if (r == null) {
        return null;
    }
    RepositoryModel model = new RepositoryModel();
    model.name = repositoryName;
    model.hasCommits = JGitUtils.hasCommits(r);
    model.lastChange = JGitUtils.getLastChange(r);
    model.isBare = r.isBare();
    if (repositoryName.indexOf('/') == -1) {
        model.projectPath = "";
    } else {
        model.projectPath = repositoryName.substring(0, repositoryName.indexOf('/'));
    }

    StoredConfig config = r.getConfig();
    boolean hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));

    if (config != null) {
        model.description = getConfig(config, "description", "");
        model.owner = getConfig(config, "owner", "");
        model.useTickets = getConfig(config, "useTickets", false);
        model.useDocs = getConfig(config, "useDocs", false);
        model.allowForks = getConfig(config, "allowForks", true);
        model.accessRestriction = AccessRestrictionType.fromName(getConfig(config, "accessRestriction",
                settings.getString(Keys.git.defaultAccessRestriction, null)));
        model.authorizationControl = AuthorizationControl.fromName(getConfig(config, "authorizationControl",
                settings.getString(Keys.git.defaultAuthorizationControl, null)));
        model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
        model.isFrozen = getConfig(config, "isFrozen", false);
        model.showReadme = getConfig(config, "showReadme", false);
        model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
        model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
        model.federationStrategy = FederationStrategy.fromName(getConfig(config, "federationStrategy", null));
        model.federationSets = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "federationSets")));
        model.isFederated = getConfig(config, "isFederated", false);
        model.origin = config.getString("remote", "origin", "url");
        model.preReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
        model.postReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
        model.mailingLists = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "mailingList")));
        model.indexedBranches = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "indexBranch")));

        // Custom defined properties
        model.customFields = new LinkedHashMap<String, String>();
        for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
            model.customFields.put(aProperty,
                    config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
        }
    }
    model.HEAD = JGitUtils.getHEADRef(r);
    model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
    r.close();

    if (model.origin != null && model.origin.startsWith("file://")) {
        // repository was cloned locally... perhaps as a fork
        try {
            File folder = new File(new URI(model.origin));
            String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
            if (!StringUtils.isEmpty(originRepo)) {
                // ensure origin still exists
                File repoFolder = new File(getRepositoriesFolder(), originRepo);
                if (repoFolder.exists()) {
                    model.originRepository = originRepo;
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Failed to determine fork for " + model, e);
        }
    }
    return model;
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Determines if this server has the requested repository.
 * /*from www.ja va 2 s. c o  m*/
 * @param name
 * @return true if the repository exists
 */
public boolean hasRepository(String repositoryName) {
    if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
        // if we are caching use the cache to determine availability
        // otherwise we end up adding a phantom repository to the cache
        return repositoryListCache.containsKey(repositoryName);
    }
    Repository r = getRepository(repositoryName, false);
    if (r == null) {
        return false;
    }
    r.close();
    return true;
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Ensure that a cached repository is completely closed and its resources
 * are properly released./*from   w ww. ja  v  a  2 s .  c om*/
 * 
 * @param repositoryName
 */
private void closeRepository(String repositoryName) {
    Repository repository = getRepository(repositoryName);
    // assume 2 uses in case reflection fails
    int uses = 2;
    try {
        // The FileResolver caches repositories which is very useful
        // for performance until you want to delete a repository.
        // I have to use reflection to call close() the correct
        // number of times to ensure that the object and ref databases
        // are properly closed before I can delete the repository from
        // the filesystem.
        Field useCnt = Repository.class.getDeclaredField("useCnt");
        useCnt.setAccessible(true);
        uses = ((AtomicInteger) useCnt.get(repository)).get();
    } catch (Exception e) {
        logger.warn(MessageFormat.format("Failed to reflectively determine use count for repository {0}",
                repositoryName), e);
    }
    if (uses > 0) {
        logger.info(MessageFormat.format(
                "{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases", repositoryName,
                uses, uses));
        for (int i = 0; i < uses; i++) {
            repository.close();
        }
    }

    // close any open index writer/searcher in the Lucene executor
    luceneExecutor.close(repositoryName);
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Creates/updates the repository model keyed by reopsitoryName. Saves all
 * repository settings in .git/config. This method allows for renaming
 * repositories and will update user access permissions accordingly.
 * /*from   ww w.  j  a v a 2s  .c  o m*/
 * All repositories created by this method are bare and automatically have
 * .git appended to their names, which is the standard convention for bare
 * repositories.
 * 
 * @param repositoryName
 * @param repository
 * @param isCreate
 * @throws GitBlitException
 */
public void updateRepositoryModel(String repositoryName, RepositoryModel repository, boolean isCreate)
        throws GitBlitException {
    Repository r = null;
    if (isCreate) {
        // ensure created repository name ends with .git
        if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
            repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
        }
        if (new File(repositoriesFolder, repository.name).exists()) {
            throw new GitBlitException(MessageFormat
                    .format("Can not create repository ''{0}'' because it already exists.", repository.name));
        }
        // create repository
        logger.info("create repository " + repository.name);
        r = JGitUtils.createRepository(repositoriesFolder, repository.name);
    } else {
        // rename repository
        if (!repositoryName.equalsIgnoreCase(repository.name)) {
            if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
                repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
            }
            if (new File(repositoriesFolder, repository.name).exists()) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.",
                                repositoryName, repository.name));
            }
            closeRepository(repositoryName);
            File folder = new File(repositoriesFolder, repositoryName);
            File destFolder = new File(repositoriesFolder, repository.name);
            if (destFolder.exists()) {
                throw new GitBlitException(MessageFormat.format(
                        "Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
                        repositoryName, repository.name));
            }
            File parentFile = destFolder.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
            }
            if (!folder.renameTo(destFolder)) {
                throw new GitBlitException(MessageFormat.format(
                        "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName, repository.name));
            }
            // rename the roles
            if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to rename repository permissions ''{0}'' to ''{1}''.",
                                repositoryName, repository.name));
            }

            // rename fork origins in their configs
            if (!ArrayUtils.isEmpty(repository.forks)) {
                for (String fork : repository.forks) {
                    Repository rf = getRepository(fork);
                    try {
                        StoredConfig config = rf.getConfig();
                        String origin = config.getString("remote", "origin", "url");
                        origin = origin.replace(repositoryName, repository.name);
                        config.setString("remote", "origin", "url", origin);
                        config.save();
                    } catch (Exception e) {
                        logger.error("Failed to update repository fork config for " + fork, e);
                    }
                    rf.close();
                }
            }

            // clear the cache
            clearRepositoryMetadataCache(repositoryName);
            repository.resetDisplayName();
        }

        // load repository
        logger.info("edit repository " + repository.name);
        try {
            r = repositoryResolver.open(null, repository.name);
        } catch (RepositoryNotFoundException e) {
            logger.error("Repository not found", e);
        } catch (ServiceNotAuthorizedException e) {
            logger.error("Service not authorized", e);
        } catch (ServiceNotEnabledException e) {
            logger.error("Service not enabled", e);
        } catch (ServiceMayNotContinueException e) {
            logger.error("Service may not continue", e);
        }
    }

    // update settings
    if (r != null) {
        updateConfiguration(r, repository);
        // only update symbolic head if it changes
        String currentRef = JGitUtils.getHEADRef(r);
        if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
            logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", repository.name, currentRef,
                    repository.HEAD));
            if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
                // clear the cache
                clearRepositoryMetadataCache(repository.name);
            }
        }

        // close the repository object
        r.close();
    }

    // update repository cache
    removeFromCachedRepositoryList(repositoryName);
    // model will actually be replaced on next load because config is stale
    addToCachedRepositoryList(repository.name, repository);
}

From source file:com.gitblit.LuceneExecutor.java

License:Apache License

/**
 * Run is executed by the Gitblit executor service.  Because this is called 
 * by an executor service, calls will queue - i.e. there can never be
 * concurrent execution of repository index updates.
 *//*from   w  ww . ja  v  a  2  s .c o  m*/
@Override
public void run() {
    if (!storedSettings.getBoolean(Keys.web.allowLuceneIndexing, true)) {
        // Lucene indexing is disabled
        return;
    }
    // reload the excluded extensions
    String exts = storedSettings.getString(Keys.web.luceneIgnoreExtensions, luceneIgnoreExtensions);
    excludedExtensions = new TreeSet<String>(StringUtils.getStringsFromValue(exts));

    for (String repositoryName : GitBlit.self().getRepositoryList()) {
        RepositoryModel model = GitBlit.self().getRepositoryModel(repositoryName);
        if (model.hasCommits && !ArrayUtils.isEmpty(model.indexedBranches)) {
            Repository repository = GitBlit.self().getRepository(model.name);
            index(model, repository);
            repository.close();
            System.gc();
        }
    }
}

From source file:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Returns the most recent change date of any repository served by Gitblit.
 *
 * @return a date/*w ww . j a  va  2s.com*/
 */
@Override
public Date getLastActivityDate() {
    Date date = null;
    for (String name : getRepositoryList()) {
        Repository r = getRepository(name);
        Date lastChange = JGitUtils.getLastChange(r).when;
        r.close();
        if (lastChange != null && (date == null || lastChange.after(date))) {
            date = lastChange;
        }
    }
    return date;
}