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.eclipse.orion.server.git.servlets.GitSubmoduleHandlerV1.java

License:Open Source License

@Override
protected boolean handleDelete(RequestInfo requestInfo) throws ServletException {
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;//from www .  ja  va 2  s  . co  m
    Repository parentRepo = null;
    try {
        Map<IPath, File> parents = GitUtils.getGitDirs(requestInfo.filePath.removeLastSegments(1),
                Traverse.GO_UP);
        if (parents.size() < 1)
            return false;
        parentRepo = FileRepositoryBuilder.create(parents.entrySet().iterator().next().getValue());
        String pathToSubmodule = db.getWorkTree().toString()
                .substring(parentRepo.getWorkTree().toString().length() + 1);
        removeSubmodule(db, parentRepo, pathToSubmodule);
        return true;
    } catch (Exception ex) {
        String msg = "An error occured for delete submodule command.";
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
    } finally {
        if (parentRepo != null) {
            parentRepo.close();
        }
    }

}

From source file:org.eclipse.orion.server.git.servlets.GitSubmoduleHandlerV1.java

License:Open Source License

public static void addSubmodules(Repository repo, String targetUrl, String targetPath) throws GitAPIException {
    SubmoduleAddCommand addCommand = new SubmoduleAddCommand(repo);
    addCommand.setURI(targetUrl);// www  .j a v  a2 s.  com
    addCommand.setPath(targetPath);
    Repository repository = addCommand.call();
    repository.close();
}

From source file:org.eclipse.releng.tests.LocalDiskRepositoryTest.java

License:Eclipse Distribution License

protected void tearDown() throws Exception {
    RepositoryCache.clear();/*  www.j a v  a 2s . c om*/
    for (Iterator it = toClose.iterator(); it.hasNext();) {
        Repository r = (Repository) it.next();
        r.close();
    }
    toClose.clear();
}

From source file:org.eclipse.tycho.extras.buildtimestamp.jgit.JGitBuildTimestampProvider.java

License:Open Source License

public Date getTimestamp(MavenSession session, MavenProject project, MojoExecution execution)
        throws MojoExecutionException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder() //
            .readEnvironment() //
            .findGitDir(project.getBasedir()) //
            .setMustExist(true);//w  w w.j av a 2s  . com
    try {
        Repository repository = builder.build();
        try {
            RevWalk walk = new RevWalk(repository);
            try {
                String relPath = getRelPath(repository, project);
                if (relPath != null && relPath.length() > 0) {
                    walk.setTreeFilter(AndTreeFilter.create(new PathFilter(relPath, getIgnoreFilter(execution)),
                            TreeFilter.ANY_DIFF));
                }

                // TODO make sure working tree is clean

                ObjectId headId = repository.resolve(Constants.HEAD);
                walk.markStart(walk.parseCommit(headId));
                RevCommit commit = walk.next();
                return new Date(commit.getCommitTime() * 1000L);
            } finally {
                walk.release();
            }
        } finally {
            repository.close();
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Could not determine git commit timestamp", e);
    }
}

From source file:org.eclipse.wst.jsdt.bower.core.api.InstallCommand.java

License:Open Source License

/**
 * Downloads the package with the given packageId matching the given range.
 *
 * @param packageId//from   w ww. j  ava  2  s.c  om
 *            The package id
 * @param rangeExpression
 *            The range
 * @return The dependencies of the downloaded package
 */
private Map<String, String> download(String packageId, String rangeExpression) {
    Map<String, String> dependencies = new HashMap<String, String>();

    Optional<String> packageUrl = this.getGitUrlFromPackageId(packageId);
    String packageName = this.getNameFromPackageId(packageId);

    if (packageUrl.isPresent() && this.monitor.isPresent() && !this.monitor.get().isCancelled()) {
        if (this.monitor.isPresent()) {
            this.monitor.get().beginTask(I18n.getString(I18nKeys.DOWNLOADING_LABEL, packageName), 10);
        }

        try {
            File tempFile = new File("/tmp"); //$NON-NLS-1$
            final Repository db = FileRepositoryBuilder.create(tempFile);
            Collection<Ref> refs = new Git(db).lsRemote().setRemote(packageUrl.get()).setTags(true).call();

            Optional<Ref> bestMatch = this.findBestMatch(refs, rangeExpression);
            if (bestMatch.isPresent() && outputDirectory.isPresent()) {
                File downloadedDependencyFolder = new File(outputDirectory.get(), packageName);
                if (!downloadedDependencyFolder.exists()) {
                    Git git = Git.cloneRepository().setProgressMonitor(monitor.get()).setURI(packageUrl.get())
                            .setDirectory(downloadedDependencyFolder).setBranch(bestMatch.get().getName())
                            .setBare(false).setNoCheckout(false).call();
                    git.close();

                    File gitFolder = new File(downloadedDependencyFolder, IBowerConstants.GIT_EXTENSION);
                    this.delete(gitFolder);

                    File bowerJsonFile = new File(downloadedDependencyFolder, IBowerConstants.BOWER_JSON);
                    Optional<BowerJson> dependencyBowerJson = this.getBowerJson(bowerJsonFile);
                    if (dependencyBowerJson.isPresent()) {
                        dependencies.putAll(dependencyBowerJson.get().getDependencies());
                    }
                }
            }

            db.close();
        } catch (GitAPIException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (this.monitor.isPresent()) {
            this.monitor.get().endTask();
        }
    }
    return dependencies;
}

From source file:org.eluder.coveralls.maven.plugin.domain.GitRepository.java

License:Open Source License

public Git load() throws IOException {
    Repository repository = new RepositoryBuilder().findGitDir(this.sourceDirectory).build();
    try {//from  www . j a  v  a  2  s  .c  o m
        Git.Head head = getHead(repository);
        String branch = getBranch(repository);
        List<Git.Remote> remotes = getRemotes(repository);
        return new Git(repository.getWorkTree(), head, branch, remotes);
    } finally {
        repository.close();
    }
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public List<Object> getBranches(ServiceInvocationContext context, String repositoryUrl) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());
    Repository db = null;
    try {//w  w w  . j  av a2  s.  c o  m
        URIish uri = new URIish(repositoryUrl.trim());
        db = new FileRepository(new File("/tmp"));

        Git git = new Git(db);
        LsRemoteCommand rc = git.lsRemote();
        rc.setRemote(uri.toString()).setTimeout(30);

        Collection<Ref> remoteRefs = rc.call();
        List<GitRef> branches = new ArrayList<GitRef>();

        Ref idHEAD = null;
        for (Ref r : remoteRefs) {
            if (r.getName().equals(Constants.HEAD)) {
                idHEAD = r;
            }
        }
        Ref head = null;
        boolean headIsMaster = false;
        String masterBranchRef = Constants.R_HEADS + Constants.MASTER;
        for (Ref r : remoteRefs) {
            String n = r.getName();
            if (!n.startsWith(Constants.R_HEADS))
                continue;
            branches.add(new GitRef(n, Repository.shortenRefName(n)));
            if (idHEAD == null || headIsMaster)
                continue;
            if (r.getObjectId().equals(idHEAD.getObjectId())) {
                headIsMaster = masterBranchRef.equals(r.getName());
                if (head == null || headIsMaster)
                    head = r;
            }
        }
        Collections.sort(branches, new Comparator<GitRef>() {
            public int compare(GitRef r1, GitRef r2) {
                return r1.getShortName().compareTo(r2.getShortName());
            }
        });
        if (idHEAD != null && head == null) {
            head = idHEAD;
            branches.add(0, new GitRef(idHEAD.getName(), Repository.shortenRefName(idHEAD.getName())));
        }

        GitRef headRef = head != null ? new GitRef(head.getName(), Repository.shortenRefName(head.getName()))
                : null;
        return Arrays.asList(new Object[] { branches, headRef });
    } catch (JGitInternalException | GitAPIException e) {
        context.getCommunicationChannel()
                .appendOrSendCommand(
                        new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                                GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotListBranches")
                                        + "\n" + e.getCause().getMessage(),
                                DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (IOException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotCreateTempRepo"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (URISyntaxException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (Exception e) {
        if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
            openLoginWindow();
            return null;
        }
        logger.debug(CommonPlugin.getInstance().getMessage("error"), e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean cloneRepository(final ServiceInvocationContext context, List<PathFragment> selectedPath,
        String repositoryUrl, final List<String> selectedBranches, final String remoteName,
        final boolean cloneAllBranches) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());

    final URIish uri;
    try {// ww w .  j  a v a2s . c o  m
        uri = new URIish(repositoryUrl.trim());
    } catch (URISyntaxException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }

    @SuppressWarnings("unchecked")
    final Pair<File, Object> node = (Pair<File, Object>) GenericTreeStatefulService
            .getNodeByPathFor(selectedPath, null);

    File gitReposFile = GitPlugin.getInstance().getUtils().getGitRepositoriesFile(node.a);
    final File mainRepo = GitPlugin.getInstance().getUtils()
            .getMainRepositoryFile(new File(gitReposFile, uri.getHumanishName()), true);

    final ProgressMonitor monitor = ProgressMonitor.create(
            GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri),
            context.getCommunicationChannel());
    monitor.beginTask(GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), 2);

    Job job = new Job(
            MessageFormat.format(GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), uri)) {
        @Override
        protected IStatus run(IProgressMonitor m) {
            Repository repository = null;
            try {
                CloneCommand cloneRepository = Git.cloneRepository();

                cloneRepository.setNoCheckout(true);
                cloneRepository.setDirectory(mainRepo);
                cloneRepository.setProgressMonitor(new GitProgressMonitor(new SubProgressMonitor(monitor, 1)));
                cloneRepository.setRemote(remoteName);
                cloneRepository.setURI(uri.toString());
                cloneRepository.setTimeout(30);
                cloneRepository.setCloneAllBranches(cloneAllBranches);
                cloneRepository.setCloneSubmodules(false);
                if (selectedBranches.size() > 0) {
                    cloneRepository.setBranchesToClone(selectedBranches);
                }

                Git git = cloneRepository.call();
                repository = git.getRepository();

                // notify clients about changes
                dispatchContentUpdate(node);

                monitor.worked(1);
            } catch (Exception e) {
                if (repository != null)
                    repository.close();
                GitPlugin.getInstance().getUtils().delete(mainRepo.getParentFile());

                if (monitor.isCanceled()) {
                    return Status.OK_STATUS;
                }
                if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
                    openLoginWindow();
                    return Status.OK_STATUS;
                }
                logger.debug(GitPlugin.getInstance().getMessage("git.cloneWizard.error",
                        new Object[] { mainRepo.getName() }), e);
                context.getCommunicationChannel()
                        .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                                CommonPlugin.getInstance().getMessage("error"),
                                GitPlugin.getInstance().getMessage("git.cloneWizard.error",
                                        new Object[] { mainRepo.getName() }),
                                DisplaySimpleMessageClientCommand.ICON_ERROR));

                return Status.CANCEL_STATUS;
            } finally {
                monitor.done();
                if (repository != null) {
                    repository.close();
                }
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
    return true;
}

From source file:org.gitcontrib.dataset.GitRepository.java

License:Apache License

public void pull() throws Exception {
    log.info("Pulling changes into: " + directory.getAbsolutePath());

    Repository repository = open();
    new Git(repository).pull().call();
    repository.close();
    lastUpdateDate = new Date();
}

From source file:org.gitcontrib.dataset.GitRepository.java

License:Apache License

public void navigate(GitCommitWalker logWalker) throws Exception {
    Repository repository = open();
    try {/*from  ww  w  . j ava 2 s.co m*/
        Git git = new Git(repository);
        Iterable<RevCommit> commits = git.log().call();
        for (RevCommit commit : commits) {
            logWalker.commitEntry(commit);
        }
    } finally {
        repository.close();
    }
}