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.google.gerrit.server.schema.Schema_57.java

License:Apache License

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
    SystemConfig sc = db.systemConfig().get(new SystemConfig.Key());
    Project.NameKey allProjects = sc.wildProjectName;

    FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config, FS.DETECTED);
    boolean cfgDirty = false;
    try {//from w ww.  j a  v a  2 s  .  c  o  m
        cfg.load();
    } catch (ConfigInvalidException err) {
        throw new OrmException("Cannot read " + site.gerrit_config, err);
    } catch (IOException err) {
        throw new OrmException("Cannot read " + site.gerrit_config, err);
    }

    if (!allProjects.get().equals(AllProjectsNameProvider.DEFAULT)) {
        ui.message("Setting gerrit.allProjects = " + allProjects.get());
        cfg.setString("gerrit", null, "allProjects", allProjects.get());
        cfgDirty = true;
    }

    try {
        Repository git = mgr.openRepository(allProjects);
        try {
            MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
            md.getCommitBuilder().setAuthor(serverUser);
            md.getCommitBuilder().setCommitter(serverUser);

            ProjectConfig config = ProjectConfig.read(md);
            AccessSection cap = config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true);

            // Move the Administrators group reference to All-Projects.
            cap.getPermission(GlobalCapability.ADMINISTRATE_SERVER, true)
                    .add(new PermissionRule(config.resolve(db.accountGroups().get(sc.adminGroupId))));

            // Move the repository.*.createGroup to Create Project.
            String[] createGroupList = cfg.getStringList("repository", "*", "createGroup");

            // Prepare the account_group_includes query
            PreparedStatement stmt = ((JdbcSchema) db).getConnection()
                    .prepareStatement("SELECT * FROM account_group_includes WHERE group_id = ?");

            for (String name : createGroupList) {
                AccountGroup.NameKey key = new AccountGroup.NameKey(name);
                AccountGroupName groupName = db.accountGroupNames().get(key);
                if (groupName == null) {
                    continue;
                }

                AccountGroup group = db.accountGroups().get(groupName.getId());
                if (group == null) {
                    continue;
                }

                cap.getPermission(GlobalCapability.CREATE_PROJECT, true)
                        .add(new PermissionRule(config.resolve(group)));
            }
            if (createGroupList.length != 0) {
                ui.message("Moved repository.*.createGroup to 'Create Project' capability");
                cfg.unset("repository", "*", "createGroup");
                cfgDirty = true;
            }

            AccountGroup batch = db.accountGroups().get(sc.batchUsersGroupId);
            stmt.setInt(1, sc.batchUsersGroupId.get());
            if (batch != null && db.accountGroupMembers().byGroup(sc.batchUsersGroupId).toList().isEmpty()
                    && stmt.executeQuery().first() != false) {
                // If the batch user group is not used, delete it.
                //
                db.accountGroups().delete(Collections.singleton(batch));

                AccountGroupName name = db.accountGroupNames().get(batch.getNameKey());
                if (name != null) {
                    db.accountGroupNames().delete(Collections.singleton(name));
                }
            } else if (batch != null) {
                cap.getPermission(GlobalCapability.PRIORITY, true).getRule(config.resolve(batch), true)
                        .setAction(Action.BATCH);
            }

            md.setMessage("Upgrade to Gerrit Code Review schema 57\n");
            config.commit(md);
        } catch (SQLException err) {
            throw new OrmException("Cannot read account_group_includes", err);
        } finally {
            git.close();
        }
    } catch (ConfigInvalidException err) {
        throw new OrmException("Cannot read " + allProjects, err);
    } catch (IOException err) {
        throw new OrmException("Cannot update " + allProjects, err);
    }

    if (cfgDirty) {
        try {
            cfg.save();
        } catch (IOException err) {
            throw new OrmException("Cannot update " + site.gerrit_config, err);
        }
    }

    // We cannot set the columns to NULL, so use 0 and a DELETED tag.
    sc.adminGroupId = new AccountGroup.Id(0);
    sc.adminGroupUUID = new AccountGroup.UUID("DELETED");
    sc.anonymousGroupId = new AccountGroup.Id(0);
    sc.registeredGroupId = new AccountGroup.Id(0);
    sc.wildProjectName = new Project.NameKey("DELETED");
    sc.ownerGroupId = new AccountGroup.Id(0);
    sc.batchUsersGroupId = new AccountGroup.Id(0);
    sc.batchUsersGroupUUID = new AccountGroup.UUID("DELETED");
    sc.registerEmailPrivateKey = "DELETED";

    db.systemConfig().update(Collections.singleton(sc));
}

From source file:com.google.gerrit.server.schema.Schema_64.java

License:Apache License

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    List<GroupReference> groups = Lists.newArrayList();
    Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
    try {/*from   ww w  .ja  v  a2s  . c o m*/
        ResultSet rs = stmt
                .executeQuery("SELECT group_uuid, name FROM account_groups WHERE email_only_authors = 'Y'");
        try {
            while (rs.next()) {
                AccountGroup.UUID uuid = new AccountGroup.UUID(rs.getString(1));
                GroupReference group = new GroupReference(uuid, rs.getString(2));
                groups.add(group);
            }
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }

    if (groups.isEmpty()) {
        return;
    }
    ui.message("Moved account_groups.email_only_authors to 'Email Reviewers' capability");

    Repository git;
    try {
        git = mgr.openRepository(allProjects);
    } catch (IOException e) {
        throw new OrmException(e);
    }
    try {
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
        md.getCommitBuilder().setAuthor(serverUser);
        md.getCommitBuilder().setCommitter(serverUser);

        ProjectConfig config = ProjectConfig.read(md);
        AccessSection section = config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true);
        Permission capability = section.getPermission(GlobalCapability.EMAIL_REVIEWERS, true);
        for (GroupReference group : groups) {
            capability.getRule(config.resolve(group), true).setDeny();
        }

        md.setMessage("Upgrade to Gerrit Code Review schema 64\n");
        config.commit(md);
    } catch (IOException e) {
        throw new OrmException(e);
    } catch (ConfigInvalidException e) {
        throw new OrmException(e);
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.server.schema.Schema_65.java

License:Apache License

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    Repository git;
    try {/*from ww w.  ja v  a  2 s  .  c o  m*/
        git = mgr.openRepository(allProjects);
    } catch (IOException e) {
        throw new OrmException(e);
    }
    try {
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
        ProjectConfig config = ProjectConfig.read(md);
        Map<Integer, ContributorAgreement> agreements = getAgreementToAdd(db, config);
        if (agreements.isEmpty()) {
            return;
        }
        ui.message("Moved contributor agreements to project.config");

        // Create the auto verify groups.
        List<AccountGroup.UUID> adminGroupUUIDs = getAdministrateServerGroups(db, config);
        for (ContributorAgreement agreement : agreements.values()) {
            if (agreement.getAutoVerify() != null) {
                getOrCreateGroupForIndividuals(db, config, adminGroupUUIDs, agreement);
            }
        }

        // Scan AccountAgreement
        long minTime = addAccountAgreements(db, config, adminGroupUUIDs, agreements);

        ProjectConfig base = ProjectConfig.read(md, null);
        for (ContributorAgreement agreement : agreements.values()) {
            base.replace(agreement);
        }
        base.getAccountsSection().setSameGroupVisibility(config.getAccountsSection().getSameGroupVisibility());

        BatchMetaDataUpdate batch = base.openUpdate(md);
        try {
            // Scan AccountGroupAgreement
            List<AccountGroupAgreement> groupAgreements = getAccountGroupAgreements(db, agreements);

            // Find the earliest change
            for (AccountGroupAgreement aga : groupAgreements) {
                minTime = Math.min(minTime, aga.getTime());
            }
            minTime -= 60 * 1000; // 1 Minute

            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(new PersonIdent(serverUser, new Date(minTime)));
            commit.setCommitter(new PersonIdent(serverUser, new Date(minTime)));
            commit.setMessage("Add the ContributorAgreements for upgrade to Gerrit Code Review schema 65\n");
            batch.write(commit);

            for (AccountGroupAgreement aga : groupAgreements) {
                AccountGroup group = db.accountGroups().get(aga.groupId);
                if (group == null) {
                    continue;
                }

                ContributorAgreement agreement = agreements.get(aga.claId);
                agreement.getAccepted().add(new PermissionRule(config.resolve(group)));
                base.replace(agreement);

                PersonIdent ident = null;
                if (aga.reviewedBy != null) {
                    Account ua = db.accounts().get(aga.reviewedBy);
                    if (ua != null) {
                        String name = ua.getFullName();
                        String email = ua.getPreferredEmail();

                        if (email == null || email.isEmpty()) {
                            // No preferred email is configured. Use a generic identity so we
                            // don't leak an address the user may have given us, but doesn't
                            // necessarily want to publish through Git records.
                            //
                            String user = ua.getUserName();
                            if (user == null || user.isEmpty()) {
                                user = "account-" + ua.getId().toString();
                            }

                            String host = SystemReader.getInstance().getHostname();
                            email = user + "@" + host;
                        }

                        if (name == null || name.isEmpty()) {
                            final int at = email.indexOf('@');
                            if (0 < at) {
                                name = email.substring(0, at);
                            } else {
                                name = anonymousCowardName;
                            }
                        }

                        ident = new PersonIdent(name, email, new Date(aga.getTime()), TimeZone.getDefault());
                    }
                }
                if (ident == null) {
                    ident = new PersonIdent(serverUser, new Date(aga.getTime()));
                }

                // Build the commits such that it keeps track of the date added and
                // who added it.
                commit = new CommitBuilder();
                commit.setAuthor(ident);
                commit.setCommitter(new PersonIdent(serverUser, new Date(aga.getTime())));

                String msg = String.format("Accept %s contributor agreement for %s\n", agreement.getName(),
                        group.getName());
                if (!Strings.isNullOrEmpty(aga.reviewComments)) {
                    msg += "\n" + aga.reviewComments + "\n";
                }
                commit.setMessage(msg);
                batch.write(commit);
            }

            // Merge the agreements with the other data in project.config.
            commit = new CommitBuilder();
            commit.setAuthor(serverUser);
            commit.setCommitter(serverUser);
            commit.setMessage("Upgrade to Gerrit Code Review schema 65\n");
            commit.addParentId(config.getRevision());
            batch.write(config, commit);

            // Save the the final metadata.
            batch.commitAt(config.getRevision());
        } finally {
            batch.close();
        }
    } catch (IOException e) {
        throw new OrmException(e);
    } catch (ConfigInvalidException e) {
        throw new OrmException(e);
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.server.schema.Schema_69.java

License:Apache License

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {

    // Find all groups that have an LDAP type.
    Map<AccountGroup.UUID, GroupReference> ldapUUIDMap = Maps.newHashMap();
    Set<AccountGroup.UUID> toResolve = Sets.newHashSet();
    List<AccountGroup.Id> toDelete = Lists.newArrayList();
    List<AccountGroup.NameKey> namesToDelete = Lists.newArrayList();
    Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
    try {/*  w ww. j  ava  2  s .c  o  m*/
        ResultSet rs = stmt.executeQuery("SELECT group_id, group_uuid, external_name, name FROM account_groups"
                + " WHERE group_type ='LDAP'");
        try {
            while (rs.next()) {
                AccountGroup.Id groupId = new AccountGroup.Id(rs.getInt(1));
                AccountGroup.UUID groupUUID = new AccountGroup.UUID(rs.getString(2));
                AccountGroup.NameKey name = new AccountGroup.NameKey(rs.getString(4));
                String dn = rs.getString(3);

                if (isNullOrEmpty(dn)) {
                    // The LDAP group does not have a DN. Determine if the UUID is used.
                    toResolve.add(groupUUID);
                } else {
                    toDelete.add(groupId);
                    namesToDelete.add(name);
                    GroupReference ref = groupReference(dn);
                    ldapUUIDMap.put(groupUUID, ref);
                }
            }
        } catch (NamingException e) {
            throw new RuntimeException(e);
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
    if (toDelete.isEmpty() && toResolve.isEmpty()) {
        return; // No ldap groups. Nothing to do.
    }

    ui.message("Update LDAP groups to be GroupReferences.");

    // Update the groupOwnerUUID for LDAP groups to point to the new UUID.
    List<AccountGroup> toUpdate = Lists.newArrayList();
    Set<AccountGroup.UUID> resolveToUpdate = Sets.newHashSet();
    Map<AccountGroup.UUID, AccountGroup> resolveGroups = Maps.newHashMap();
    for (AccountGroup g : db.accountGroups().all()) {
        if (ldapUUIDMap.containsKey(g.getGroupUUID())) {
            continue; // Ignore the LDAP groups with a valid DN.
        } else if (toResolve.contains(g.getGroupUUID())) {
            resolveGroups.put(g.getGroupUUID(), g); // Keep the ones to resolve.
            continue;
        }

        GroupReference ref = ldapUUIDMap.get(g.getOwnerGroupUUID());
        if (ref != null) {
            // Update the owner group UUID to the new ldap UUID scheme.
            g.setOwnerGroupUUID(ref.getUUID());
            toUpdate.add(g);
        } else if (toResolve.contains(g.getOwnerGroupUUID())) {
            // The unresolved group is used as an owner.
            // Add to the list of LDAP groups to be made INTERNAL.
            resolveToUpdate.add(g.getOwnerGroupUUID());
        }
    }

    toResolve.removeAll(resolveToUpdate);

    // Update project.config group references to use the new LDAP GroupReference
    for (Project.NameKey name : mgr.list()) {
        Repository git;
        try {
            git = mgr.openRepository(name);
        } catch (RepositoryNotFoundException e) {
            throw new OrmException(e);
        } catch (IOException e) {
            throw new OrmException(e);
        }

        try {
            MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, name, git);
            md.getCommitBuilder().setAuthor(serverUser);
            md.getCommitBuilder().setCommitter(serverUser);

            ProjectConfig config = ProjectConfig.read(md);

            // Update the existing refences to the new reference.
            boolean updated = false;
            for (Map.Entry<AccountGroup.UUID, GroupReference> entry : ldapUUIDMap.entrySet()) {
                GroupReference ref = config.getGroup(entry.getKey());
                if (ref != null) {
                    updated = true;
                    ref.setName(entry.getValue().getName());
                    ref.setUUID(entry.getValue().getUUID());
                    config.resolve(ref);
                }
            }

            // Determine if a toResolve group is used and should be made INTERNAL.
            Iterator<AccountGroup.UUID> iter = toResolve.iterator();
            while (iter.hasNext()) {
                AccountGroup.UUID uuid = iter.next();
                if (config.getGroup(uuid) != null) {
                    resolveToUpdate.add(uuid);
                    iter.remove();
                }
            }

            if (!updated) {
                continue;
            }

            md.setMessage("Switch LDAP group UUIDs to DNs\n");
            config.commit(md);
        } catch (IOException e) {
            throw new OrmException(e);
        } catch (ConfigInvalidException e) {
            throw new OrmException(e);
        } finally {
            git.close();
        }
    }

    for (AccountGroup.UUID uuid : resolveToUpdate) {
        AccountGroup group = resolveGroups.get(uuid);
        group.setType(AccountGroup.Type.INTERNAL);
        toUpdate.add(group);

        ui.message(
                String.format("*** Group has no DN and is inuse. Updated to be INTERNAL: %s", group.getName()));
    }

    for (AccountGroup.UUID uuid : toResolve) {
        AccountGroup group = resolveGroups.get(uuid);
        toDelete.add(group.getId());
        namesToDelete.add(group.getNameKey());
    }

    // Update group owners
    db.accountGroups().update(toUpdate);
    // Delete existing LDAP groups
    db.accountGroupNames().deleteKeys(namesToDelete);
    db.accountGroups().deleteKeys(toDelete);
}

From source file:com.google.gerrit.server.schema.Schema_77.java

License:Apache License

private void migrateLabelsToAllProjects(ReviewDb db, LegacyLabelTypes labelTypes)
        throws SQLException, RepositoryNotFoundException, IOException, ConfigInvalidException {
    Repository git = mgr.openRepository(allProjects);

    try {/*from ww w.  ja  va  2s.co m*/
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
        md.getCommitBuilder().setAuthor(serverUser);
        md.getCommitBuilder().setCommitter(serverUser);

        ProjectConfig config = ProjectConfig.read(md);
        Map<String, LabelType> configTypes = config.getLabelSections();
        List<LabelType> newTypes = Lists.newArrayList();
        for (LegacyLabelType type : labelTypes.getLegacyLabelTypes()) {
            if (!configTypes.containsKey(type.getName())) {
                newTypes.add(type);
            }
        }
        newTypes.addAll(configTypes.values());
        configTypes.clear();
        for (LabelType type : newTypes) {
            configTypes.put(type.getName(), type);
        }
        md.setMessage("Upgrade to Gerrit Code Review schema 77\n");
        config.commit(md);
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.server.schema.Schema_81.java

License:Apache License

private void migrateStartReplicationCapability(ReviewDb db, Description d)
        throws SQLException, RepositoryNotFoundException, IOException, ConfigInvalidException {
    Repository git = mgr.openRepository(allProjects);
    try {//from www  .ja v  a  2 s.  com
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
        md.getCommitBuilder().setAuthor(serverUser);
        md.getCommitBuilder().setCommitter(serverUser);
        ProjectConfig config = ProjectConfig.read(md);
        AccessSection capabilities = config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES);
        Permission startReplication = capabilities.getPermission("startReplication");
        if (startReplication == null) {
            return;
        }
        String msg = null;
        switch (d.what) {
        case REMOVE:
            capabilities.remove(startReplication);
            msg = "Remove startReplication capability, plugin not installed\n";
            break;
        case RENAME:
            capabilities.remove(startReplication);
            Permission pluginStartReplication = capabilities
                    .getPermission(String.format("%s-startReplication", d.prefix), true);
            pluginStartReplication.setRules(startReplication.getRules());
            msg = "Rename startReplication capability to match updated plugin\n";
            break;
        }
        config.replace(capabilities);
        md.setMessage(msg);
        config.commit(md);
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.server.util.Git.java

License:Apache License

public ObjectId getObjectId(Branch.NameKey branch)
        throws IOException, NoSuchRefException, RepositoryNotFoundException {
    Repository repo = repos.openRepository(branch.getParentKey());
    try {// w w  w. ja v  a  2 s.  c o  m
        return repo.getRef(branch.get()).getObjectId();
    } finally {
        repo.close();
    }
}

From source file:com.google.gerrit.sshd.commands.CreateProject.java

License:Apache License

@Override
public void start(final Environment env) {
    startThread(new CommandRunnable() {
        @Override/*from w  ww.ja v a 2s.  c om*/
        public void run() throws Exception {
            PrintWriter p = toPrintWriter(out);

            parseCommandLine();

            try {
                validateParameters();
                nameKey = new Project.NameKey(projectName);

                final Repository repo = repoManager.createRepository(nameKey);
                try {
                    RefUpdate u = repo.updateRef(Constants.HEAD);
                    u.disableRefLog();
                    u.link(branch);

                    createProject();
                    repoManager.setProjectDescription(nameKey, projectDescription);

                    if (createEmptyCommit) {
                        createEmptyCommit(repo, nameKey, branch);
                    }

                    rq.replicateNewProject(nameKey, branch);
                } finally {
                    repo.close();
                }
            } catch (Exception e) {
                p.print("Error when trying to create project: " + e.getMessage() + "\n");
                p.flush();
            }
        }
    });
}

From source file:com.google.gerrit.sshd.commands.ListProjects.java

License:Apache License

private List<Ref> getBranchRefs(Project.NameKey projectName) {
    try {/*from w  ww  . java2 s  .c  o  m*/
        final Repository r = repoManager.openRepository(projectName);
        try {
            final List<Ref> result = new ArrayList<Ref>(showBranch.size());
            for (String branch : showBranch) {
                result.add(r.getRef(branch));
            }
            return result;
        } finally {
            r.close();
        }
    } catch (IOException ioe) {
        return null;
    }
}

From source file:com.google.gitiles.DefaultAccess.java

License:Open Source License

@Override
public Map<String, RepositoryDescription> listRepositories(Set<String> branches) throws IOException {
    Map<String, RepositoryDescription> repos = Maps.newTreeMap();
    for (Repository repo : scanRepositories(basePath, req)) {
        repos.put(getRepositoryName(repo), buildDescription(repo, branches));
        repo.close();
    }/* w w w  .j a  v a 2s . c o m*/
    return repos;
}