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.egit.ui.common.LocalRepositoryTestCase.java

License:Open Source License

private static void shutDownRepositories() {
    RepositoryCache cache = Activator.getDefault().getRepositoryCache();
    for (Repository repository : cache.getAllRepositories())
        repository.close();
    cache.clear();// www. j a  v a 2 s.  co  m
}

From source file:org.eclipse.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

@Override
protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.beginTask(UIText.GitMergeEditorInput_CheckingResourcesTaskName, IProgressMonitor.UNKNOWN);

    // Make sure all resources belong to the same repository
    final Map<Repository, Collection<String>> pathsByRepository = ResourceUtil
            .splitPathsByRepository(Arrays.asList(locations));
    if (pathsByRepository.size() != 1) {
        throw new InvocationTargetException(
                new IllegalStateException(UIText.RepositoryAction_multiRepoSelection));
    }/*w  ww.ja v  a2 s  .com*/
    final Repository repository = pathsByRepository.keySet().iterator().next();
    final List<String> filterPaths = new ArrayList<String>(pathsByRepository.get(repository));

    checkCanceled(monitor);

    // The merge drivers have done their job of putting the necessary
    // information in the index
    // Read that info and provide it to the file-specific comparators
    RevWalk rw = null;
    try {
        rw = new RevWalk(repository);

        // get the "right" side (MERGE_HEAD for merge, ORIG_HEAD for rebase)
        final RevCommit rightCommit = getRightCommit(rw, repository);

        // we need the HEAD, also to determine the common ancestor
        final RevCommit headCommit = getLeftCommit(rw, repository);

        // try to obtain the common ancestor
        RevCommit ancestorCommit = getCommonAncestor(rw, rightCommit, headCommit);

        checkCanceled(monitor);

        // set the labels
        setLabels(repository, rightCommit, headCommit, ancestorCommit);

        final ICompareInput input = prepareCompareInput(repository, filterPaths, monitor);
        if (input != null) {
            return input;
        }

        checkCanceled(monitor);
        return buildDiffContainer(repository, headCommit, ancestorCommit, filterPaths, rw, monitor);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    } finally {
        if (rw != null) {
            rw.close();
            rw.dispose();
        }
        repository.close();
        monitor.done();
    }
}

From source file:org.eclipse.mylyn.reviews.r4e.ui.tests.utils.TestUtils.java

License:Open Source License

private static void deleteRepository(Repository aRepository) throws CoreException, IOException {
    Repository repository = aRepository;
    repository.close();
    repository = null;/*w  w  w.  j a  v a  2  s  . c o  m*/
}

From source file:org.eclipse.orion.server.gerritfs.GitDiff.java

License:Open Source License

protected void handleGetDiffs(HttpServletRequest request, HttpServletResponse response, Repository repo,
        String sha, String refName, OutputStream out) {
    try {//from www  .ja v  a 2s.  c o m

        DiffCommand command = getDiff(request, response, repo, sha, refName, out);
        if (command == null)
            return;

        List<DiffEntry> l = command.call();
        JSONArray diffs = new JSONArray();
        URI diffLocation = getURI(request);
        if (refName != null) {
            IPath patternPath = new Path(refName);
            IPath diffPath = new Path(diffLocation.getPath());
            diffPath = diffPath.removeLastSegments(patternPath.segmentCount());
            diffLocation = new URI(diffLocation.getScheme(), diffLocation.getAuthority(),
                    diffPath.toPortableString(), null, null);
        }
        URI cloneLocation = getCloneLocation(diffLocation);

        int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() //$NON-NLS-1$//$NON-NLS-2$
                : 0;
        int pageSize = request.getParameter("pageSize") != null //$NON-NLS-1$
                ? new Integer(request.getParameter("pageSize")).intValue() //$NON-NLS-1$
                : Integer.MAX_VALUE;
        int start = pageSize * (page - 1);
        int end = Math.min(pageSize + start, l.size());
        int i = start;
        for (i = start; i < end; i++) {
            DiffEntry entr = l.get(i);
            JSONObject diff = new JSONObject();
            diff.put(KEY_TYPE, TYPE);
            diff.put(GitConstants.KEY_COMMIT_DIFF_NEWPATH, entr.getNewPath());
            diff.put(GitConstants.KEY_COMMIT_DIFF_OLDPATH, entr.getOldPath());
            diff.put(GitConstants.KEY_COMMIT_DIFF_CHANGETYPE, entr.getChangeType().toString());

            // add diff location for the commit
            String path = entr.getChangeType() != ChangeType.DELETE ? entr.getNewPath() : entr.getOldPath();
            diff.put(GitConstants.KEY_DIFF, createDiffLocation(diffLocation, request, path));
            diff.put(KEY_CONTENT_LOCATION, createContentLocation(cloneLocation, entr, path));

            diffs.put(diff);
        }

        JSONObject result = new JSONObject();
        result.put(KEY_TYPE, TYPE);
        result.put(KEY_CHILDREN, diffs);
        result.put(KEY_LENGTH, l.size());
        if (i < l.size()) {
            URI nextLocation = new URI(diffLocation.getScheme(), diffLocation.getUserInfo(),
                    diffLocation.getHost(), diffLocation.getPort(), diffLocation.getPath(),
                    "pageSize=" + pageSize + "&page=" + (page + 1), diffLocation.getFragment()); //$NON-NLS-1$ //$NON-NLS-2$
            result.put(KEY_NEXT_LOCATION, nextLocation);
        }
        writeJSONResponse(request, response, result);

    } catch (Exception e) {
        // return statusHandler.handleRequest(request, response, new
        // ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
        // "An error occured while getting a diff.", e));
        System.out.println(e);
    } finally {
        if (repo != null) {
            repo.close();
        }
    }
}

From source file:org.eclipse.orion.server.git.jobs.StatusJob.java

License:Open Source License

@Override
protected IStatus performJob() {
    Logger logger = LoggerFactory.getLogger("org.eclipse.orion.server.git");
    Repository db = null;
    try {//from  w w  w .  j  a  v a 2  s. co m
        long t0 = System.currentTimeMillis();
        Set<Entry<IPath, File>> set = GitUtils.getGitDirs(this.filePath, Traverse.GO_UP).entrySet();
        File gitDir = set.iterator().next().getValue();
        if (gitDir == null) {
            logger.error("***** Git status failed to find Git directory for request: " + this.filePath);
            String msg = NLS.bind("Could not find repository for {0}", filePath);
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null);
        }
        long t1 = System.currentTimeMillis();
        db = FileRepositoryBuilder.create(gitDir);
        Git git = new Git(db);
        org.eclipse.jgit.api.Status gitStatus = git.status().call();
        long t2 = System.currentTimeMillis();

        String relativePath = GitUtils.getRelativePath(this.filePath, set.iterator().next().getKey());
        IPath basePath = new Path(relativePath);
        org.eclipse.orion.server.git.objects.Status status = new org.eclipse.orion.server.git.objects.Status(
                this.baseLocation, db, gitStatus, basePath);
        ServerStatus result = new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, status.toJSON());
        if (logger.isDebugEnabled() && (t2 - t0) > GIT_PERF_THRESHOLD) {
            logger.debug("Slow git status. Finding git dir: " + (t1 - t0) + "ms. JGit status call: " + (t2 - t1)
                    + "ms");
        }
        return result;
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when generating status for ref {0}", this.filePath);
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
    } finally {
        if (db != null) {
            // close the git repository
            db.close();
        }
    }
}

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

License:Open Source License

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException {
    Repository db = null;
    try {//from  ww w.  j  a v  a 2s  .  co  m
        IPath p = new Path(path);
        String gitSegment = null;
        if (p.segment(1).equals("file")) { //$NON-NLS-1$
            gitSegment = GitUtils.decode(p.segment(0));
            p = p.removeFirstSegments(1);
        }
        IPath filePath = p;
        IPath gitSearchPath = filePath.hasTrailingSeparator() ? filePath : filePath.removeLastSegments(1);
        Set<Entry<IPath, File>> gitDirsFound = GitUtils.getGitDirs(gitSearchPath, Traverse.GO_UP).entrySet();
        Entry<IPath, File> firstGitDir = gitDirsFound.iterator().next();
        File gitDir = firstGitDir.getValue();
        if (gitDir == null) {
            String msg = NLS.bind("Could not find repository for {0}", filePath);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        String relativePath = GitUtils.getRelativePath(filePath, firstGitDir.getKey());
        db = new FileRepository(gitDir);
        RequestInfo requestInfo = new RequestInfo(request, response, db, gitSegment, relativePath, filePath);
        switch (getMethod(request)) {
        case GET:
            return handleGet(requestInfo);
        case POST:
            return handlePost(requestInfo);
        case PUT:
            return handlePut(requestInfo);
        case DELETE:
            return handleDelete(requestInfo);
        case OPTIONS:
        case HEAD:
        default:
            return false;
        }
    } catch (IOException e) {
        String msg = NLS.bind("Failed to process a git request for {0}", path);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } catch (CoreException e) {
        String msg = NLS.bind("Failed to process a git request for {0}", path);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } finally {
        if (db != null)
            db.close();
    }
}

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

License:Open Source License

private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
        JGitInternalException, GitAPIException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { //$NON-NLS-1$

        // make sure a clone is addressed
        WebProject webProject = WebProject.fromId(path.segment(1));
        if (isAccessAllowed(request.getRemoteUser(), webProject)) {
            URI contentLocation = URI.create(webProject.getId());
            IPath projectPath = new Path(contentLocation.getPath()).append(path.removeFirstSegments(2));
            File gitDir = GitUtils.getGitDirs(new Path("file").append(projectPath), Traverse.CURRENT).values()
                    .iterator().next();/* w ww  . ja  v  a 2s.c  om*/

            Repository repo = new FileRepository(gitDir);
            repo.close();
            FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY);
            if (path.segmentCount() == 2)
                return statusHandler.handleRequest(request, response,
                        removeProject(request.getRemoteUser(), webProject));
            return true;
        } else {
            String msg = NLS.bind("Nothing found for the given ID: {0}", path);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
    }
    String msg = NLS.bind("Invalid delete request {0}", pathString);
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

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

License:Open Source License

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException {

    Repository db = null;
    try {/*from   w  w  w. j  ava 2s.c o m*/
        Path p = new Path(path);
        switch (getMethod(request)) {
        case GET:
            return handleGet(request, response, db, p);
        case PUT:
            return handlePut(request, response, db, p);
        case POST:
            return handlePost(request, response, db, p);
        }

    } catch (Exception e) {
        String msg = NLS.bind("Failed to process an operation on commits for {0}", path);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } finally {
        if (db != null)
            db.close();
    }
    return false;
}

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

License:Open Source License

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String gitPathInfo)
        throws ServletException {
    Repository db = null;
    try {/* ww w .  jav  a2  s  . c om*/
        Path path = new Path(gitPathInfo);
        IPath filePath = path.hasTrailingSeparator() ? path : path.removeLastSegments(1);
        Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath.removeFirstSegments(1), Traverse.GO_UP)
                .entrySet();
        File gitDir = set.iterator().next().getValue();
        if (gitDir == null)
            return false; // TODO: or an error response code, 405?
        db = new FileRepository(gitDir);

        switch (getMethod(request)) {
        case GET:
            String parts = request.getParameter("parts"); //$NON-NLS-1$
            String pattern = GitUtils.getRelativePath(path.removeFirstSegments(1),
                    set.iterator().next().getKey());
            pattern = pattern.isEmpty() ? null : pattern;
            if (parts == null || "uris,diff".equals(parts) || "diff,uris".equals(parts))
                return handleMultiPartGet(request, response, db, path, pattern);
            if ("uris".equals(parts)) {
                OrionServlet.writeJSONResponse(request, response, jsonForGetUris(request, response, db, path));
                return true;
            }
            if ("diff".equals(parts))
                return handleGetDiff(request, response, db, path.segment(0), pattern,
                        response.getOutputStream());
        case POST:
            return handlePost(request, response, db, path);
        }

    } catch (Exception e) {
        String msg = NLS.bind("Failed to generate diff for {0}", gitPathInfo); //$NON-NLS-1$
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } finally {
        if (db != null)
            db.close();
    }
    return false;
}

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

License:Open Source License

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException {
    Repository db = null;
    try {/*ww w .  java  2  s  .  c om*/
        IPath p = new Path(path);
        IPath filePath = p.hasTrailingSeparator() ? p : p.removeLastSegments(1);
        Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
        File gitDir = set.iterator().next().getValue();
        if (gitDir == null)
            return false; // TODO: or an error response code, 405?
        db = new FileRepository(gitDir);
        switch (getMethod(request)) {
        case GET:
            return handleGet(request, response, db,
                    GitUtils.getRelativePath(p, set.iterator().next().getKey()));
        case PUT:
            String pattern = GitUtils.getRelativePath(p, set.iterator().next().getKey());
            if (pattern.isEmpty())
                pattern = ADD_ALL_PATTERN;
            return handlePut(request, response, db, pattern);
        case POST:
            return handlePost(request, response, db, p);
        }
    } catch (Exception e) {
        String msg = NLS.bind("Failed to process an operation on index for {0}", path); //$NON-NLS-1$
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } finally {
        if (db != null)
            db.close();
    }
    return false;
}