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.googlesource.gerrit.plugins.smartreviewers.ChangeUpdatedListener.java

License:Apache License

@Override
public void onChangeEvent(ChangeEvent event) {
    if (!(event instanceof PatchSetCreatedEvent)) {
        return;//from  w  w  w.j  a v  a 2s.c om
    }
    PatchSetCreatedEvent e = (PatchSetCreatedEvent) event;
    Project.NameKey projectName = new Project.NameKey(e.change.project);

    int maxReviewers, weightBlame, weightLastReviews, weightWorkload;
    try {
        maxReviewers = cfg.getFromProjectConfigWithInheritance(projectName, pluginName).getInt("maxReviewers",
                3);
        weightBlame = cfg.getFromProjectConfigWithInheritance(projectName, pluginName).getInt("weightBlame", 1);
        weightLastReviews = cfg.getFromProjectConfigWithInheritance(projectName, pluginName)
                .getInt("weightLastReviews", 1);
        weightWorkload = cfg.getFromProjectConfigWithInheritance(projectName, pluginName)
                .getInt("weightWorkload", -1);
    } catch (NoSuchProjectException x) {
        log.error(x.getMessage(), x);
        return;
    }
    if (maxReviewers <= 0) {
        return;
    }

    Repository git;
    try {
        git = repoManager.openRepository(projectName);
    } catch (RepositoryNotFoundException x) {
        log.error(x.getMessage(), x);
        return;
    } catch (IOException x) {
        log.error(x.getMessage(), x);
        return;
    }

    final ReviewDb reviewDb;
    final RevWalk rw = new RevWalk(git);

    try {
        reviewDb = schemaFactory.open();
        try {
            Change.Id changeId = new Change.Id(Integer.parseInt(e.change.number));
            PatchSet.Id psId = new PatchSet.Id(changeId, Integer.parseInt(e.patchSet.number));
            PatchSet ps = reviewDb.patchSets().get(psId);
            if (ps == null) {
                log.warn("Patch set " + psId.get() + " not found.");
                return;
            }

            final Change change = reviewDb.changes().get(psId.getParentKey());
            if (change == null) {
                log.warn("Change " + changeId.get() + " not found.");
                return;
            }

            final RevCommit commit = rw.parseCommit(ObjectId.fromString(e.patchSet.revision));

            final Runnable task = smartReviewersFactory.create(commit, change, ps, maxReviewers, weightBlame,
                    weightLastReviews, weightWorkload, git, reviewDb);

            workQueue.getDefaultQueue().submit(new Runnable() {
                public void run() {
                    RequestContext old = tl.setContext(new RequestContext() {

                        @Override
                        public CurrentUser getCurrentUser() {
                            return identifiedUserFactory.create(change.getOwner());
                        }

                        @Override
                        public Provider<ReviewDb> getReviewDbProvider() {
                            return new Provider<ReviewDb>() {
                                @Override
                                public ReviewDb get() {
                                    if (db == null) {
                                        try {
                                            db = schemaFactory.open();
                                        } catch (OrmException e) {
                                            throw new ProvisionException("Cannot open ReviewDb", e);
                                        }
                                    }
                                    return db;
                                }
                            };
                        }
                    });
                    try {
                        task.run();
                    } finally {
                        tl.setContext(old);
                        if (db != null) {
                            db.close();
                            db = null;
                        }
                    }
                }
            });
        } catch (OrmException x) {
            log.error(x.getMessage(), x);
        } catch (MissingObjectException x) {
            log.error(x.getMessage(), x);
        } catch (IncorrectObjectTypeException x) {
            log.error(x.getMessage(), x);
        } catch (IOException x) {
            log.error(x.getMessage(), x);
        }
    } catch (OrmException x) {
        log.error(x.getMessage(), x);
    } finally {
        rw.release();
        git.close();
    }
}

From source file:com.googlesource.gerrit.plugins.task.TaskConfigFactory.java

License:Apache License

public TaskConfig getTaskConfig(Branch.NameKey branch, String fileName)
        throws ConfigInvalidException, IOException {
    TaskConfig cfg = new TaskConfig(branch, fileName);
    Project.NameKey project = branch.getParentKey();
    try {// w  w  w.j  a  v a2s.  c  o m
        Repository git = gitMgr.openRepository(project);
        try {
            cfg.load(git);
        } finally {
            git.close();
        }
    } catch (IOException e) {
        log.warn("Failed to load " + fileName + " for " + project.get(), e);
        throw e;
    } catch (ConfigInvalidException e) {
        throw e;
    }
    return cfg;
}

From source file:com.googlesrouce.gerrit.plugins.github.git.PullRequestCreateChange.java

License:Apache License

public Change.Id addCommitToChange(final ReviewDb db, final Project project, final Repository git,
        final String destinationBranch, final Account.Id pullRequestOwner, final RevCommit pullRequestCommit,
        final String pullRequestMesage, final String topic, boolean doValidation) throws NoSuchChangeException,
        EmailException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException,
        InvalidChangeOperationException, MergeException, NoSuchProjectException {
    Id newChange = null;//from  w  ww  .j a  v  a  2  s . c o m
    if (destinationBranch == null || destinationBranch.length() == 0) {
        throw new InvalidChangeOperationException("Destination branch cannot be null or empty");
    }

    RefControl refControl = projectControlFactor.controlFor(project.getNameKey())
            .controlForRef(destinationBranch);

    try {
        RevWalk revWalk = new RevWalk(git);
        try {
            Ref destRef = git.getRef(destinationBranch);
            if (destRef == null) {
                throw new InvalidChangeOperationException("Branch " + destinationBranch + " does not exist.");
            }

            String pullRequestSha1 = pullRequestCommit.getId().getName();
            ResultSet<PatchSet> existingPatchSet = db.patchSets().byRevision(new RevId(pullRequestSha1));
            Iterator<PatchSet> patchSetIterator = existingPatchSet.iterator();
            if (patchSetIterator.hasNext()) {
                PatchSet patchSet = patchSetIterator.next();
                LOG.debug("Pull request commit ID " + pullRequestSha1
                        + " has been already uploaded as PatchSetID=" + patchSet.getPatchSetId()
                        + " in ChangeID=" + patchSet.getId());
                return null;
            }

            Change.Key changeKey;
            final List<String> idList = pullRequestCommit.getFooterLines(CHANGE_ID);
            if (!idList.isEmpty()) {
                final String idStr = idList.get(idList.size() - 1).trim();
                changeKey = new Change.Key(idStr);
            } else {
                final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(pullRequestCommit.getTree(),
                        pullRequestCommit, pullRequestCommit.getAuthorIdent(),
                        pullRequestCommit.getCommitterIdent(), pullRequestMesage);

                changeKey = new Change.Key("I" + computedChangeId.name());
            }

            List<Change> destChanges = db.changes()
                    .byBranchKey(new Branch.NameKey(project.getNameKey(), destRef.getName()), changeKey)
                    .toList();

            if (destChanges.size() > 1) {
                throw new InvalidChangeOperationException("Multiple Changes with Change-ID " + changeKey
                        + " already exist on the target branch: cannot add a new patch-set "
                        + destinationBranch);
            } else if (destChanges.size() == 1) {
                // The change key exists on the destination branch: adding a new
                // patch-set
                Change destChange = destChanges.get(0);

                ChangeControl changeControl = projectControlFactor.controlFor(project.getNameKey())
                        .controlFor(destChange);

                return insertPatchSet(git, revWalk, destChange, pullRequestCommit, changeControl,
                        pullRequestOwner, pullRequestMesage, doValidation);
            } else {
                // Change key not found on destination branch. We can create a new
                // change.
                return (newChange = createNewChange(db, git, revWalk, changeKey, project.getNameKey(), destRef,
                        pullRequestOwner, pullRequestCommit, refControl, pullRequestMesage, topic,
                        doValidation));
            }
        } finally {
            revWalk.release();
            if (newChange == null) {
                db.rollback();
            }
        }
    } finally {
        git.close();
    }
}

From source file:com.googlesrouce.gerrit.plugins.github.git.PullRequestImportJob.java

License:Apache License

@Override
public void run() {
    ReviewDb db = schema.get();//from  w  w  w  .  j  av  a  2s.c  o m
    try {
        status.update(GitJobStatus.Code.SYNC);
        exitWhenCancelled();
        GHPullRequest pr = fetchGitHubPullRequestInfo();

        exitWhenCancelled();
        Repository gitRepo = repoMgr.openRepository(new Project.NameKey(organisation + "/" + repoName));
        try {
            exitWhenCancelled();
            fetchGitHubPullRequest(gitRepo, pr);

            exitWhenCancelled();
            List<Id> changeIds = addPullRequestToChange(db, pr, gitRepo);
            status.update(GitJobStatus.Code.COMPLETE, "Imported",
                    "PullRequest imported as Changes " + changeIds);
        } finally {
            gitRepo.close();
        }
        db.commit();
    } catch (JobCancelledException e) {
        status.update(GitJobStatus.Code.CANCELLED);
        try {
            db.rollback();
        } catch (OrmException e1) {
            LOG.error("Error rolling back transation", e1);
        }
    } catch (Exception e) {
        LOG.error("Pull request " + prId + " into repository " + organisation + "/" + repoName + " was failed",
                e);
        status.update(GitJobStatus.Code.FAILED, "Failed", getErrorDescription(e));
        try {
            db.rollback();
        } catch (OrmException e1) {
            LOG.error("Error rolling back transation", e1);
        }
    } finally {
        db.close();
    }
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public static GitService init(String site, String dir) throws Exception {
    String repoPath = dir + "/" + site;
    log.debug("Repository Path :" + repoPath);
    Repository repo = new FileRepository(repoPath + "/.git");
    Git git = null;/*  w ww.jav  a2 s.c  o m*/
    try {
        repo.create();
        git = new Git(repo);

        File localGitRepo = new File(repoPath);
        localGitRepo.mkdirs();
        new File(localGitRepo, "delete.me").createNewFile();

        git.add().addFilepattern("delete.me").call();
        git.commit().setMessage("initial commit").call();
        return new GitService(git);
    } catch (IllegalStateException e) {
        log.debug("Repo Already exists locally");
        if (repo != null) {
            repo.close();
        }
    }
    return null;
}

From source file:com.microsoft.gittf.client.clc.commands.CloneCommand.java

License:Open Source License

@Override
public int run() throws Exception {
    // Parse arguments
    final String collection = ((FreeArgument) getArguments().getArgument("projectcollection")).getValue(); //$NON-NLS-1$
    String tfsPath = ((FreeArgument) getArguments().getArgument("serverpath")).getValue(); //$NON-NLS-1$

    String repositoryPath = getArguments().contains("directory") ? //$NON-NLS-1$
            ((FreeArgument) getArguments().getArgument("directory")).getValue() : null; //$NON-NLS-1$

    final VersionSpec versionSpec = getArguments().contains("version") ? //$NON-NLS-1$
            VersionSpecUtil.parseVersionSpec(((ValueArgument) getArguments().getArgument("version")).getValue()) //$NON-NLS-1$
            : LatestVersionSpec.INSTANCE;

    verifyVersionSpec(versionSpec);/*w  w  w  .j av  a  2 s. c  o m*/

    final boolean bare = getArguments().contains("bare"); //$NON-NLS-1$
    final int depth = getDepthFromArguments();

    final boolean mentions = getArguments().contains("mentions"); //$NON-NLS-1$
    if (mentions && depth < 2) {
        throw new Exception(Messages.getString("Command.MentionsOnlyAvailableWithDeep")); //$NON-NLS-1$
    }

    final boolean tag = getTagFromArguments();

    final URI serverURI = URIUtil.getServerURI(collection);
    tfsPath = ServerPath.canonicalize(tfsPath);

    /*
     * Build repository path
     */
    if (repositoryPath == null) {
        repositoryPath = ServerPath.getFileName(tfsPath);
    }
    repositoryPath = LocalPath.canonicalize(repositoryPath);

    final File repositoryLocation = new File(repositoryPath);
    File parentLocationCreated = null;

    if (!repositoryLocation.exists()) {
        parentLocationCreated = DirectoryUtil.createDirectory(repositoryLocation);
        if (parentLocationCreated == null) {
            throw new Exception(Messages.formatString("CloneCommnad.InvalidPathFormat", repositoryPath)); //$NON-NLS-1$
        }
    }

    final Repository repository = RepositoryUtil.createNewRepository(repositoryPath, bare);

    /*
     * Connect to the server
     */
    try {
        final TFSTeamProjectCollection connection = getConnection(serverURI, repository);

        Check.notNull(connection, "connection"); //$NON-NLS-1$

        final WorkItemClient witClient = mentions ? connection.getWorkItemClient() : null;
        final CloneTask cloneTask = new CloneTask(serverURI, getVersionControlService(), tfsPath, repository,
                witClient);

        cloneTask.setBare(bare);
        cloneTask.setDepth(depth);
        cloneTask.setVersionSpec(versionSpec);
        cloneTask.setTag(tag);

        final TaskStatus cloneStatus = new CommandTaskExecutor(getProgressMonitor()).execute(cloneTask);

        if (!cloneStatus.isOK()) {
            FileHelpers.deleteDirectory(bare ? repository.getDirectory() : repository.getWorkTree());

            if (parentLocationCreated != null) {
                FileHelpers.deleteDirectory(parentLocationCreated);
            }

            return ExitCode.FAILURE;
        }
    } finally {
        repository.close();
    }

    return ExitCode.SUCCESS;
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

License:Apache License

public static void updateProjectRef(ObjectId treeId, ObjectInserter objectInserter, Repository repository,
        CurrentUser currentUser) throws IOException, NoFilepatternException, GitAPIException {
    // Create a branch
    Ref gerritCiRef = repository.getRef("refs/meta/gerrit-ci");
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(treeId);/*from  ww w .ja  v a2 s  .  c  o m*/
    logger.info("treeId: " + treeId);

    if (gerritCiRef != null) {
        ObjectId prevCommit = gerritCiRef.getObjectId();
        logger.info("prevCommit: " + prevCommit);
        commitBuilder.setParentId(prevCommit);
    }
    // build commit
    logger.info("Adding git tree : " + treeId);
    commitBuilder.setMessage("Modify project build rules.");
    final IdentifiedUser iUser = (IdentifiedUser) currentUser;
    PersonIdent user = new PersonIdent(currentUser.getUserName(), iUser.getEmailAddresses().iterator().next());
    commitBuilder.setAuthor(user);
    commitBuilder.setCommitter(user);
    ObjectId commitId = objectInserter.insert(commitBuilder);
    objectInserter.flush();
    logger.info(" Making new commit: " + commitId);
    RefUpdate newRef = repository.updateRef("refs/meta/gerrit-ci");
    newRef.setNewObjectId(commitId);
    newRef.update();
    repository.close();
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public List<String> getSvnLogMessages(String Url, String userName, String Password, String repoType,
        String appDirName) throws PhrescoException {
    List<String> logMessages = new ArrayList<String>();
    if (repoType.equalsIgnoreCase(SVN)) {
        setupLibrary();/*w w w  .  j  av  a 2 s. c o  m*/
        long startRevision = 0;
        long endRevision = -1; //HEAD (the latest) revision
        SVNRepository repository = null;
        try {
            repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(Url));
            ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(userName,
                    Password);
            repository.setAuthenticationManager(authManager);
            Collection logEntries = null;
            logEntries = repository.log(new String[] { "" }, null, startRevision, endRevision, false, true);
            for (Iterator entries = logEntries.iterator(); entries.hasNext();) {
                SVNLogEntry logEntry = (SVNLogEntry) entries.next();
                logMessages.add(logEntry.getMessage());
            }
        } catch (SVNException e) {
            throw new PhrescoException(e);
        } finally {
            if (repository != null) {
                repository.closeSession();
            }
        }
    } else if (repoType.equalsIgnoreCase(GIT)) {
        try {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            String dotGitDir = Utility.getProjectHome() + appDirName + File.separator + DOT_GIT;
            File dotGitDirectory = new File(dotGitDir);
            if (!dotGitDirectory.exists()) {
                dotGitDir = Utility.getProjectHome() + appDirName + File.separator + appDirName + File.separator
                        + DOT_GIT;
                dotGitDirectory = new File(dotGitDir);
            }
            if (!dotGitDir.isEmpty()) {
                Repository repo = builder.setGitDir(dotGitDirectory).setMustExist(true).build();
                Git git = new Git(repo);
                Iterable<RevCommit> log = git.log().call();
                for (Iterator<RevCommit> iterator = log.iterator(); iterator.hasNext();) {
                    RevCommit rev = iterator.next();
                    if (!rev.getFullMessage().isEmpty()) {
                        logMessages.add(rev.getFullMessage());
                    }
                }
                repo.close();
            }
        } catch (GitAPIException ge) {
            throw new PhrescoException(ge);
        } catch (IOException ioe) {
            throw new PhrescoException(ioe);
        }
    }
    return logMessages;
}

From source file:com.pramati.gerrit.plugin.helpers.GetFileFromRepo.java

License:Apache License

/**
 * returns the File Stream from the gerrit repository. returns "null" if the
 * given file not found in the repository.<br>
 * patchStr should like in given format::"changeid/patchsetID/filename" <br>
 * eg: 1/2/readme.md//from w ww . j  a v  a  2 s .  co  m
 * 
 * @param patchStr
 * @return
 * @throws IOException
 */
public static BufferedInputStream doGetFile(String patchStr) throws IOException {
    final Patch.Key patchKey;
    final Change.Id changeId;
    final Project project;
    final PatchSet patchSet;
    final Repository repo;
    final ReviewDb db;
    final ChangeControl control;
    try {
        patchKey = Patch.Key.parse(patchStr);
    } catch (NumberFormatException e) {
        return null;
    }
    changeId = patchKey.getParentKey().getParentKey();

    try {
        db = requestDb.get();
        control = changeControl.validateFor(changeId);

        project = control.getProject();
        patchSet = db.patchSets().get(patchKey.getParentKey());
        if (patchSet == null) {
            return null;
            // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (NoSuchChangeException e) {
        // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (OrmException e) {
        // getServletContext().log("Cannot query database", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    try {
        repo = repoManager.openRepository(project.getNameKey());
    } catch (RepositoryNotFoundException e) {
        // getServletContext().log("Cannot open repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    final ObjectLoader blobLoader;
    final RevCommit fromCommit;
    final String path = patchKey.getFileName();
    try {
        final ObjectReader reader = repo.newObjectReader();
        try {
            final RevWalk rw = new RevWalk(reader);
            final RevCommit c;
            final TreeWalk tw;

            c = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
            fromCommit = c;

            tw = TreeWalk.forPath(reader, path, fromCommit.getTree());
            if (tw == null) {
                // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return null;
            }

            if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) {
                blobLoader = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB);

            } else {
                // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }
        } finally {
            reader.release();
        }
    } catch (IOException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } catch (RuntimeException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } finally {
        repo.close();
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    blobLoader.copyTo(out);
    byte[] b = out.toByteArray();
    BufferedInputStream br = new BufferedInputStream(new ByteArrayInputStream(b));
    return br;
}

From source file:com.searchcode.app.util.Helpers.java

License:Open Source License

public void closeQuietly(Repository repository) {
    try {//from   w  w w  . j  ava2  s . c  om
        repository.close();
    } catch (Exception ex) {
    }
}