Example usage for org.eclipse.jgit.lib Repository open

List of usage examples for org.eclipse.jgit.lib Repository open

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository open.

Prototype

@NonNull
public ObjectLoader open(AnyObjectId objectId) throws MissingObjectException, IOException 

Source Link

Document

Open an object from this repository.

Usage

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public RepositoryItem[] getContentChildren(String site, String path) {
    // TODO: SJ: Rethink this API call for 3.1+
    final List<RepositoryItem> retItems = new ArrayList<RepositoryItem>();
    Repository repo = helper.getRepository(site,
            StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

    try {//  w  w w. j  av a  2s  . c  om
        RevTree tree = helper.getTreeForLastCommit(repo);
        try (TreeWalk tw = TreeWalk.forPath(repo, helper.getGitPath(path), tree)) {
            if (tw != null) {
                // Loop for all children and gather path of item excluding the item, file/folder name, and
                // whether or not it's a folder
                ObjectLoader loader = repo.open(tw.getObjectId(0));
                if (loader.getType() == Constants.OBJ_TREE) {
                    int depth = tw.getDepth();
                    tw.enterSubtree();
                    while (tw.next()) {
                        if (tw.getDepth() == depth + 1) {

                            RepositoryItem item = new RepositoryItem();
                            item.name = tw.getNameString();

                            String visitFolderPath = File.separator + tw.getPathString();
                            loader = repo.open(tw.getObjectId(0));
                            item.isFolder = loader.getType() == Constants.OBJ_TREE;
                            int lastIdx = visitFolderPath.lastIndexOf(File.separator + item.name);
                            if (lastIdx > 0) {
                                item.path = visitFolderPath.substring(0, lastIdx);
                            }

                            if (!ArrayUtils.contains(IGNORE_FILES, item.name)) {
                                retItems.add(item);
                            }
                        }
                    }
                    tw.close();
                } else {
                    logger.error("Error getChildren invoked for a file for site: " + site + " path: " + path);
                }
            }
        } catch (IOException e) {
            logger.error("Error while getting children for site: " + site + " path: " + path, e);
        }
    } catch (IOException e) {
        logger.error("Failed to create RevTree for site: " + site + " path: " + path, e);
    }

    RepositoryItem[] items = new RepositoryItem[retItems.size()];
    items = retItems.toArray(items);
    return items;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public InputStream getContentVersion(String site, String path, String version) throws ContentNotFoundException {
    InputStream toReturn = null;//from  ww w.j a  v a 2  s  . c  o  m

    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX);

    try {
        RevTree tree = helper.getTreeForCommit(repo, version);
        try (TreeWalk tw = TreeWalk.forPath(repo, helper.getGitPath(path), tree)) {
            if (tw != null) {
                ObjectId id = tw.getObjectId(0);
                ObjectLoader objectLoader = repo.open(id);
                toReturn = objectLoader.openStream();
                tw.close();
            }
        } catch (IOException e) {
            logger.error("Error while getting content for file at site: " + site + " path: " + path
                    + " version:" + " " + version, e);
        }
    } catch (IOException e) {
        logger.error("Failed to create RevTree for site: " + site + " path: " + path + " version: " + version,
                e);
    }

    return toReturn;
}

From source file:org.dstadler.jgit.api.JGitPrintContent.java

License:BSD License

public static void main(String[] args) throws Exception {
    File gitWorkDir = new File("C:\\Users\\kishore\\git\\JavaRepos\\.git");
    Git git = Git.open(gitWorkDir);//w w w.java2  s .com
    Repository repo = git.getRepository();

    ObjectId lastCommitId = repo.resolve(Constants.HEAD);

    RevWalk revWalk = new RevWalk(repo);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    RevTree tree = commit.getTree();

    TreeWalk treeWalk = new TreeWalk(repo);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.ALL);
    if (!treeWalk.next()) {
        System.out.println("Nothing found!");
        return;
    }

    ObjectId objectId = treeWalk.getObjectId(0);
    System.err.println(treeWalk.getPathString());
    System.err.println(objectId.getName());

    ObjectLoader loader = repo.open(objectId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);
    System.out.println("file1.txt:\n" + out.toString());
}

From source file:org.dstadler.jgit.porcelain.ShowBlame.java

License:Apache License

private static int countLinesOfFileInCommit(Repository repository, ObjectId commitID, String name)
        throws IOException {
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitID);
        RevTree tree = commit.getTree();
        System.out.println("Having tree: " + tree);

        // now try to find a specific file
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(tree);//w w  w  . j  a  v a  2 s  .  co  m
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(name));
            if (!treeWalk.next()) {
                throw new IllegalStateException("Did not find expected file 'README.md'");
            }

            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = repository.open(objectId);

            // load the content of the file into a stream
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            loader.copyTo(stream);

            revWalk.dispose();

            return IOUtils.readLines(new ByteArrayInputStream(stream.toByteArray()), "UTF-8").size();
        }
    }
}

From source file:org.eclipse.egit.core.synchronize.GitBlobResourceVariant.java

License:Open Source License

GitBlobResourceVariant(Repository repo, RevCommit revCommit, ObjectId objectId, String path)
        throws IOException {
    super(repo, revCommit, objectId, path);

    blob = repo.open(getObjectId());
}

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

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final ServletOutputStream out = resp.getOutputStream();
    handleAuth(req);/*from  w  w w . j a va  2 s  .c o m*/
    try {
        String pathInfo = req.getPathInfo();
        Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?");
        Matcher matcher = pattern.matcher(pathInfo);
        matcher.matches();
        String projectName = null;
        String refName = null;
        String filePath = null;
        if (matcher.groupCount() > 0) {
            projectName = matcher.group(1);
            refName = matcher.group(2);
            filePath = matcher.group(3);
            if (projectName == null || projectName.equals("")) {
                projectName = null;
            } else {
                projectName = java.net.URLDecoder.decode(projectName, "UTF-8");
            }
            if (refName == null || refName.equals("")) {
                refName = null;
            } else {
                refName = java.net.URLDecoder.decode(refName, "UTF-8");
            }
            if (filePath == null || filePath.equals("")) {
                filePath = null;
            } else {
                filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
            }
        }
        if (projectName != null) {
            NameKey projName = NameKey.parse(projectName);
            ProjectControl control;
            try {
                control = projControlFactory.controlFor(projName);
                if (!control.isVisible()) {
                    log.debug("Project not visible!");
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                            "You need to be logged in to see private projects");
                    return;
                }
            } catch (NoSuchProjectException e1) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No such project exists.");
            }
        }
        if (projectName == null || refName == null || filePath == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You need to provide a projectName, refName and filePath.");
            return;
        } else {
            NameKey projName = NameKey.parse(projectName);
            Repository repo = repoManager.openRepository(projName);
            Ref head = repo.getRef(refName);
            RevWalk walk = new RevWalk(repo);
            RevCommit commit = walk.parseCommit(head.getObjectId());
            RevTree tree = commit.getTree();

            TreeWalk treeWalk = new TreeWalk(repo);
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(filePath));
            if (!treeWalk.next()) {
                throw new IllegalStateException("No file found");
            }

            ObjectId objId = treeWalk.getObjectId(0);
            ObjectLoader loader = repo.open(objId);
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            resp.setContentType("application/octet-stream");
            loader.copyTo(out);
            walk.release();
            treeWalk.release();
        }
    } finally {
        out.close();
    }
}

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

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    handleAuth(req);/*w  ww  .  ja  va2 s.c  o  m*/
    resp.setCharacterEncoding("UTF-8");
    final PrintWriter out = resp.getWriter();
    try {
        String pathInfo = req.getPathInfo();
        Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?");
        Matcher matcher = pattern.matcher(pathInfo);
        matcher.matches();
        String projectName = null;
        String refName = null;
        String filePath = null;
        if (matcher.groupCount() > 0) {
            projectName = matcher.group(1);
            refName = matcher.group(2);
            filePath = matcher.group(3);
            if (projectName == null || projectName.equals("")) {
                projectName = null;
            } else {
                projectName = java.net.URLDecoder.decode(projectName, "UTF-8");
            }
            if (refName == null || refName.equals("")) {
                refName = null;
            } else {
                refName = java.net.URLDecoder.decode(refName, "UTF-8");
            }
            if (filePath == null || filePath.equals("")) {
                filePath = null;
            } else {
                filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
            }
        }
        if (projectName != null) {
            if (filePath == null)
                filePath = "";
            NameKey projName = NameKey.parse(projectName);

            ProjectControl control;
            try {
                control = projControlFactory.controlFor(projName);
                if (!control.isVisible()) {
                    log.debug("Project not visible!");
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                            "You need to be logged in to see private projects");
                    return;
                }
            } catch (NoSuchProjectException e1) {
            }
            Repository repo = repoManager.openRepository(projName);
            if (refName == null) {
                ArrayList<HashMap<String, Object>> contents = new ArrayList<HashMap<String, Object>>();
                List<Ref> call;
                try {
                    call = new Git(repo).branchList().call();
                    Git git = new Git(repo);
                    for (Ref ref : call) {
                        HashMap<String, Object> jsonObject = new HashMap<String, Object>();
                        jsonObject.put("name", ref.getName());
                        jsonObject.put("type", "ref");
                        jsonObject.put("size", "0");
                        jsonObject.put("path", "");
                        jsonObject.put("project", projectName);
                        jsonObject.put("ref", ref.getName());
                        lastCommit(git, null, ref.getObjectId(), jsonObject);
                        contents.add(jsonObject);
                    }
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
                    log.debug(response);
                    out.write(response);
                } catch (GitAPIException e) {
                }
            } else {
                Ref head = repo.getRef(refName);
                if (head == null) {
                    ArrayList<HashMap<String, String>> contents = new ArrayList<HashMap<String, String>>();
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
                    log.debug(response);
                    out.write(response);
                    return;
                }
                RevWalk walk = new RevWalk(repo);
                // add try catch to catch failures
                Git git = new Git(repo);
                RevCommit commit = walk.parseCommit(head.getObjectId());
                RevTree tree = commit.getTree();
                TreeWalk treeWalk = new TreeWalk(repo);
                treeWalk.addTree(tree);
                treeWalk.setRecursive(false);
                if (!filePath.equals("")) {
                    PathFilter pathFilter = PathFilter.create(filePath);
                    treeWalk.setFilter(pathFilter);
                }
                if (!treeWalk.next()) {
                    CanonicalTreeParser canonicalTreeParser = treeWalk.getTree(0, CanonicalTreeParser.class);
                    ArrayList<HashMap<String, Object>> contents = new ArrayList<HashMap<String, Object>>();
                    if (canonicalTreeParser != null) {
                        while (!canonicalTreeParser.eof()) {
                            String path = canonicalTreeParser.getEntryPathString();
                            FileMode mode = canonicalTreeParser.getEntryFileMode();
                            listEntry(path, mode.equals(FileMode.TREE) ? "dir" : "file", "0", path, projectName,
                                    head.getName(), git, contents);
                            canonicalTreeParser.next();
                        }
                    }
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
                    log.debug(response);
                    out.write(response);
                } else {
                    // if (treeWalk.isSubtree()) {
                    // treeWalk.enterSubtree();
                    // }
                    ArrayList<HashMap<String, Object>> contents = new ArrayList<HashMap<String, Object>>();
                    do {
                        if (treeWalk.isSubtree()) {
                            String test = new String(treeWalk.getRawPath());
                            if (test.length() /*treeWalk.getPathLength()*/ > filePath.length()) {
                                listEntry(treeWalk.getNameString(), "dir", "0", treeWalk.getPathString(),
                                        projectName, head.getName(), git, contents);
                            }
                            if (test.length() /*treeWalk.getPathLength()*/ <= filePath.length()) {
                                treeWalk.enterSubtree();
                            }
                        } else {
                            ObjectId objId = treeWalk.getObjectId(0);
                            ObjectLoader loader = repo.open(objId);
                            long size = loader.getSize();
                            listEntry(treeWalk.getNameString(), "file", Long.toString(size),
                                    treeWalk.getPathString(), projectName, head.getName(), git, contents);
                        }
                    } while (treeWalk.next());
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
                    log.debug(response);
                    out.write(response);
                }
                walk.release();
                treeWalk.release();
            }
        }
    } finally {
        out.close();
    }
}

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

License:Open Source License

@Override
protected boolean handleGet(RequestInfo requestInfo) throws ServletException {
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    String gitSegment = requestInfo.gitSegment;
    Repository repo = requestInfo.db;
    String pattern = requestInfo.relativePath;
    IPath filePath = requestInfo.filePath;
    String meta = request.getParameter("parts"); //$NON-NLS-1$
    RevWalk walk = null;/*from ww  w. java  2 s . c o m*/
    TreeWalk treeWalk = null;
    IPath filterPath = new Path(pattern);
    try {
        if (filterPath.segmentCount() == 0) {
            JSONArray children = new JSONArray();
            URI baseLocation = getURI(request);
            List<Ref> call = new Git(repo).branchList().setListMode(ListMode.ALL).call();
            for (Ref ref : call) {
                String branchName = Repository.shortenRefName(ref.getName());
                JSONObject branch = listEntry(branchName, 0, true, 0, baseLocation,
                        GitUtils.encode(branchName));
                children.put(branch);
            }
            JSONObject result = listEntry(filePath.segment(0), 0, true, 0, baseLocation, null);
            result.put(ProtocolConstants.KEY_CHILDREN, children);
            OrionServlet.writeJSONResponse(request, response, result,
                    JsonURIUnqualificationStrategy.ALL_NO_GIT);
            return true;
        }

        gitSegment = GitUtils.decode(filterPath.segment(0));
        filterPath = filterPath.removeFirstSegments(1);
        pattern = filterPath.toPortableString();
        ObjectId head = repo.resolve(gitSegment);
        if (head == null) {
            throw new Exception("Missing ref in git segment");
        }
        walk = new RevWalk(repo);
        // add try catch to catch failures

        RevCommit commit = walk.parseCommit(head);
        RevTree tree = commit.getTree();
        treeWalk = new TreeWalk(repo);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(false);
        if (!pattern.equals("")) { //$NON-NLS-1$
            PathFilter pathFilter = PathFilter.create(pattern);
            treeWalk.setFilter(pathFilter);
        }
        JSONArray contents = new JSONArray();
        JSONObject result = null;
        ArrayList<JSONObject> parents = new ArrayList<JSONObject>();

        URI baseLocation = ServletResourceHandler.getURI(request);
        Path basePath = new Path(baseLocation.getPath());
        IPath tmp = new Path("/"); //$NON-NLS-1$
        for (int i = 0; i < 5; i++) {
            tmp = tmp.append(basePath.segment(i));
        }
        URI cloneLocation = new URI(baseLocation.getScheme(), baseLocation.getAuthority(),
                tmp.toPortableString(), null, baseLocation.getFragment());
        JSONObject ref = listEntry(gitSegment, 0, true, 0, cloneLocation, GitUtils.encode(gitSegment));

        parents.add(ref);
        parents.add(
                listEntry(new Path(cloneLocation.getPath()).lastSegment(), 0, true, 0, cloneLocation, null));
        URI locationWalk = URIUtil.append(cloneLocation, GitUtils.encode(gitSegment));
        while (treeWalk.next()) {
            if (treeWalk.isSubtree()) {
                if (treeWalk.getPathLength() > pattern.length()) {
                    String name = treeWalk.getNameString();
                    contents.put(listEntry(name, 0, true, 0, locationWalk, name));
                }
                if (treeWalk.getPathLength() <= pattern.length()) {
                    locationWalk = URIUtil.append(locationWalk, treeWalk.getNameString());
                    parents.add(0, listEntry(treeWalk.getNameString(), 0, true, 0, locationWalk, null));
                    treeWalk.enterSubtree();
                }
            } else {
                ObjectId objId = treeWalk.getObjectId(0);
                ObjectLoader loader = repo.open(objId);
                long size = loader.getSize();
                if (treeWalk.getPathLength() == pattern.length()) {
                    if ("meta".equals(meta)) { //$NON-NLS-1$
                        result = listEntry(treeWalk.getNameString(), 0, false, 0, locationWalk,
                                treeWalk.getNameString());
                    } else {
                        return getFileContents(request, response, repo, treeWalk, tree);
                    }
                } else {
                    String name = treeWalk.getNameString();
                    contents.put(listEntry(name, 0, false, size, locationWalk, name));
                }
            }
        }
        if (result == null) {
            result = parents.remove(0);
            result.put("Children", contents); //$NON-NLS-1$
        }
        result.put("Parents", new JSONArray(parents)); //$NON-NLS-1$
        response.setContentType("application/json"); //$NON-NLS-1$
        response.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$
        response.setHeader("ETag", "\"" + tree.getId().getName() + "\""); //$NON-NLS-1$
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } catch (Exception e) {
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "An error occured when requesting commit info.", e));
    } finally {
        if (walk != null)
            walk.release();
        if (treeWalk != null)
            treeWalk.release();
    }
}

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

License:Open Source License

private boolean getFileContents(HttpServletRequest request, HttpServletResponse response, Repository repo,
        TreeWalk treeWalk, RevTree tree) {
    ObjectStream stream = null;/*  w w  w .j  a  v a  2s.  co  m*/
    try {
        ObjectId objId = treeWalk.getObjectId(0);
        ObjectLoader loader = repo.open(objId);
        response.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$
        response.setHeader("ETag", "\"" + tree.getId().getName() + "\""); //$NON-NLS-1$ //$NON-NLS-2$
        response.setContentType("application/octet-stream"); //$NON-NLS-1$
        stream = loader.openStream();
        IOUtilities.pipe(stream, response.getOutputStream(), true, false);
    } catch (MissingObjectException e) {
    } catch (IOException e) {
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException e) {
        }
    }
    return true;
}

From source file:org.exist.git.xquery.Cat.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//from  w ww .ja va2  s  .  c  o  m
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        String objPath = args[1].getStringValue();

        if (mySignature.getName() == CAT_WORKING_COPY) {
            Resource resource = new Resource(localPath + objPath);

            InputStream is = new ResourceInputStream(resource);
            ;

            Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is);
            return b64doc;

        }

        Git git = Git.open(new Resource(localPath), FS);
        Repository repository = git.getRepository();

        // find the HEAD
        ObjectId lastCommitId = repository.resolve(Constants.HEAD);
        // now we have to get the commit
        RevWalk revWalk = new RevWalk(repository);
        RevCommit commit = revWalk.parseCommit(lastCommitId);
        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        treeWalk.setFilter(PathFilter.create(args[1].getStringValue()));
        if (!treeWalk.next()) {
            return Sequence.EMPTY_SEQUENCE;
        }
        ObjectId objectId = treeWalk.getObjectId(0);
        ObjectLoader loader = repository.open(objectId);

        // and then one can use either
        InputStream is = loader.openStream();

        Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is);
        return b64doc;
    } catch (Throwable e) {
        throw new XPathException(this, Module.EXGIT001, e);
    }
}