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:org.sonar.plugins.scm.git.JGitBlameCommand.java

License:Open Source License

@Override
public void blame(BlameInput input, BlameOutput output) {
    File basedir = input.fileSystem().baseDir();
    Repository repo = buildRepository(basedir);
    try {/*from  w w w . j  a  v a  2 s .c om*/
        Git git = Git.wrap(repo);
        File gitBaseDir = repo.getWorkTree();
        ExecutorService executorService = Executors
                .newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
        List<Future<Void>> tasks = submitTasks(input, output, git, gitBaseDir, executorService);
        waitForTaskToComplete(tasks);
    } finally {
        repo.close();
    }
}

From source file:org.sonarsource.scm.git.JGitBlameCommand.java

License:Open Source License

@Override
public void blame(BlameInput input, BlameOutput output) {
    File basedir = input.fileSystem().baseDir();
    Repository repo = buildRepository(basedir);
    try {/* w  ww. j ava  2 s  .c  om*/
        Git git = Git.wrap(repo);
        File gitBaseDir = repo.getWorkTree();
        ExecutorService executorService = Executors
                .newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        List<Future<Void>> tasks = submitTasks(input, output, git, gitBaseDir, executorService);
        waitForTaskToComplete(executorService, tasks);
    } finally {
        repo.close();
    }
}

From source file:org.thiesen.ant.git.GitInfoExtractor.java

License:Open Source License

public static GitInfo extractInfo(final File dir) throws IOException {
    if (!dir.exists()) {
        throw new BuildException("No such directory: " + dir);
    }//  w w w  .j a va  2  s.  c om

    final RepositoryBuilder builder = new RepositoryBuilder();
    final Repository r = builder.setGitDir(dir).readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();

    try {
        final String currentBranch = r.getBranch();

        final RevCommit head = getHead(r);
        final String lastRevCommit = getRevCommitId(head);
        final String lastRevCommitShort = getRevCommitIdShort(head, r);
        final Date lastRevCommitDate = getRevCommitDate(head);

        final boolean workingCopyDirty = isDirty(null, r);

        final CustomTag lastRevTag = getLastRevTag(r);

        final boolean lastRevTagDirty = isDirty(lastRevTag, r);

        return GitInfo.valueOf(currentBranch, lastRevCommit, workingCopyDirty, lastRevTag, lastRevTagDirty,
                lastRevCommitShort, lastRevCommitDate);

    } finally {
        r.close();
    }
}

From source file:org.uberfire.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static Git cloneRepository(final File repoFolder, final String fromURI, final boolean bare,
        final CredentialsProvider credentialsProvider) {

    if (!repoFolder.getName().endsWith(DOT_GIT_EXT)) {
        throw new RuntimeException("Invalid name");
    }/*from   w  ww.j  a  v a2s  . c o  m*/

    try {
        final File gitDir = RepositoryCache.FileKey.resolve(repoFolder, DETECTED);
        final Repository repository;
        final Git git;
        if (gitDir != null && gitDir.exists()) {
            repository = new FileRepository(gitDir);
            git = new Git(repository);
        } else {
            git = Git.cloneRepository().setBare(bare).setCloneAllBranches(true).setURI(fromURI)
                    .setDirectory(repoFolder).setCredentialsProvider(credentialsProvider).call();
            repository = git.getRepository();
        }

        fetchRepository(git, credentialsProvider);

        repository.close();

        return git;
    } catch (final Exception ex) {
        try {
            forceDelete(repoFolder);
        } catch (final java.io.IOException e) {
            throw new RuntimeException(e);
        }
        throw new RuntimeException(ex);
    }
}

From source file:org.webcat.core.git.http.RepositoryRequestFilter.java

License:Open Source License

/**
 * Looks up the requested repository and puts it into the request's
 * user-info dictionary./*from w  ww . j a va2  s  .co  m*/
 *
 * @param request the request
 * @param response the response
 * @param filterChain the filter chain
 * @throws Exception if an error occurs
 */
public void filterRequest(WORequest request, WOResponse response, RequestFilterChain filterChain)
        throws Exception {
    Repository repo = RepositoryRequestUtils.repositoryFromRequest(request);

    if (repo != null) {
        throw new IllegalStateException("Repository userInfo key was " + "already set.");
    } else {
        repo = RepositoryRequestUtils.cacheRepositoryInRequest(request);

        try {
            filterChain.filterRequest(request, response);
        } finally {
            RepositoryRequestUtils.clearRepositoryInRequest(request);
            repo.close();
        }
    }
}

From source file:org.wise.portal.presentation.web.controllers.author.project.JGitUtils.java

License:Open Source License

/**
 * Returns commit history for specified directory
 *
 * @param directoryPath//w  ww .j  a  v a  2 s  . com
 * @return
 * @throws IOException
 * @throws GitAPIException
 */
public static Iterable<RevCommit> getCommitHistory(String directoryPath) throws IOException, GitAPIException {

    boolean doCreate = false;
    Repository gitRepository = getGitRepository(directoryPath, doCreate);
    if (gitRepository == null) {
        return null;
    } else {
        Git git = new Git(gitRepository);
        Iterable<RevCommit> commits = git.log().all().call();
        gitRepository.close();
        return commits;
    }
}

From source file:org.wise.portal.presentation.web.controllers.author.project.JGitUtils.java

License:Open Source License

/**
 * Adds all changes in specified directory to git index and then commits them
 * with the specified commit message/*from  ww  w  . j a  va 2s.  c  om*/
 *
 * @param directoryPath
 * @param author author username
 * @param commitMessage
 * @throws IOException
 * @throws GitAPIException
 */
public static void commitAllChangesToCurriculumHistory(String directoryPath, String author,
        String commitMessage) throws IOException, GitAPIException {

    boolean doCreate = true;
    Repository gitRepository = getGitRepository(directoryPath, doCreate);
    Git git = new Git(gitRepository);

    // add all changes in directory
    git.add().addFilepattern(".").call();

    String email = ""; // don't save any emails for now.

    // commit all changes
    git.commit().setAll(true).setAuthor(author, email).setMessage(commitMessage).call();
    gitRepository.close();
}

From source file:org.z2env.impl.gitcr.GitComponentRepositoryImpl.java

License:Apache License

private void cloneRepository() throws Exception {
    Repository clonedRepo = null;

    logger.info("Cloning " + getLabel() + ". This will take some seconds...");

    // purging the folder allows to call clone in any situation
    FileUtils.delete(getFileSystem().getRoot());

    try {/*ww  w . j  a  v a  2  s  . com*/
        // no clone available so far! Create it now...
        long tStart = System.currentTimeMillis();

        // clone the origin repository into the z2 work folder 
        clonedRepo = GitTools.cloneRepository(this.originUri, getFileSystem().getRoot(), this.credentials,
                this.timeout);

        // switch to target branch
        GitTools.switchBranch(clonedRepo, this.branch);

        logger.info("Created working-clone within " + (System.currentTimeMillis() - tStart) + " msec for "
                + getLabel());

    } finally {
        try {
            clonedRepo.close();
        } catch (Exception e) {
            /* ignore */ }
    }
}

From source file:org.z2env.impl.gitcr.GitComponentRepositoryImpl.java

License:Apache License

private void doPull() {
    Repository clonedRepo = null;

    try {/*w  ww .ja va 2 s  .  co m*/
        clonedRepo = new FileRepository(new File(getFileSystem().getRoot(), ".git"));
        pullRepository(clonedRepo);

    } catch (Exception e) {

        // pulling failed!

        // just log a short description
        logger.log(Level.WARNING, "WARNING: Updating " + this.toString() + " failed with exception: ");
        logger.log(Level.WARNING, "WARNING: " + e.toString());

        switch (GitTools.isValidRepository(this.originUri)) {
        case invalid:
        case cannotTell:
            if (!GitTools.isOriginReachable(this.originUri)) {
                logger.info("WARNING: '" + this.originUri.getHost() + "' IS NOT reachable!");
            } else {
                logger.info("WARNING: '" + this.originUri.getHumanishName()
                        + "' IS NOT a valid git repository on " + this.originUri.getHost() + "!");
            }

            if (this.isOptional) {
                // origin is not reachable, but repository is optional (maybe we are offline). Log this incident and try to continue
                logger.info("WARNING: '" + this.originUri.getHumanishName()
                        + "' will be ignored because it's an optional repository or running in relaxed mode");

            } else {
                // throw exception in production mode 
                throw new PullFailedException(this, e);
            }

            break;

        case valid:
            // Origin is reachable which implies something went wrong locally. It could be for example that the fetch was successful but the merged failed.
            // In this case we will purge this clone and start from scratch. 
            logger.info("WARNING: Will discard this clone and create a new one.");

            clonedRepo.close();
            doClone();
        }

    } finally {
        try {
            clonedRepo.close();
        } catch (Exception e) {
            /* ignore */ }
    }
}

From source file:persistence.git.document.SourceControlDocumentRepository.java

License:Open Source License

/**
 * Return the list of document represented by a {@code DocumentBean} in th specified repository path.
 *
 * @param repositoryPath the repository path to search documents.
 *
 * @return the list of document beans.// w  w  w  .j  a  v a  2s  .  c  o  m
 * @throws IOException if repository folder is not found.
 * @throws SourceControlUnspecifiedException if the repository operation read fail for any source control unspecified reason.
 */
public List<DocumentBean> getDocuments(final String repositoryPath)
        throws IOException, SourceControlUnspecifiedException {
    File file = new File(repositoryPath);
    Repository repository = fileRepositoryBuilder.setGitDir(file).build();
    Git git = new Git(repository);

    Optional<RevCommit> lastCommit = revCommitRepository.getLastRevCommit(git);
    List<DocumentBean> documentBeanList = new ArrayList<>();

    if (lastCommit.isPresent()) {
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(lastCommit.get().getTree());
        treeWalk.setFilter(PathFilter.create(PATH_REPOSITORY));
        treeWalk.setRecursive(true);

        while (treeWalk.next()) {
            DocumentBean documentBean = treeWalkDocumentBeanMapper.newBusinessObjectDTO(treeWalk);
            documentBean.setContent(gitObjectRepository.getObjectContent(treeWalk.getObjectId(0), repository));
            documentBeanList.add(documentBean);
        }
    }

    repository.close();
    return documentBeanList;
}