Example usage for org.eclipse.jgit.lib FileMode TREE

List of usage examples for org.eclipse.jgit.lib FileMode TREE

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib FileMode TREE.

Prototype

FileMode TREE

To view the source code for org.eclipse.jgit.lib FileMode TREE.

Click Source Link

Document

Mode indicating an entry is a tree (aka directory).

Usage

From source file:br.uff.ic.oceano.core.tools.vcs.PathModel.java

License:Apache License

public boolean isTree() {
    return FileMode.TREE.equals(mode);
}

From source file:com.buildautomation.jgit.api.GetFileAttributes.java

License:Apache License

private static String getFileMode(FileMode fileMode) {
    if (fileMode.equals(FileMode.EXECUTABLE_FILE)) {
        return "Executable File";
    } else if (fileMode.equals(FileMode.REGULAR_FILE)) {
        return "Normal File";
    } else if (fileMode.equals(FileMode.TREE)) {
        return "Directory";
    } else if (fileMode.equals(FileMode.SYMLINK)) {
        return "Symlink";
    } else {/*from  w w  w  .j  av a  2 s.  c om*/
        // there are a few others, see FileMode javadoc for details
        throw new IllegalArgumentException("Unknown type of file encountered: " + fileMode);
    }
}

From source file:com.gitblit.servlet.RawServlet.java

License:Apache License

/**
 * Retrieves the specified resource from the specified branch of the
 * repository./*ww w .j a  va 2 s .c  om*/
 *
 * @param request
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    if (path.toLowerCase().endsWith(".git")) {
        // forward to url with trailing /
        // this is important for relative pages links
        response.sendRedirect(request.getServletPath() + path + "/");
        return;
    }
    if (path.charAt(0) == '/') {
        // strip leading /
        path = path.substring(1);
    }

    // determine repository and resource from url
    String repository = path;
    Repository r = null;
    int terminator = repository.length();
    do {
        repository = repository.substring(0, terminator);
        r = repositoryManager.getRepository(repository, false);
        terminator = repository.lastIndexOf('/');
    } while (r == null && terminator > -1);

    ServletContext context = request.getSession().getServletContext();

    try {
        if (r == null) {
            // repository not found!
            String mkd = MessageFormat
                    .format("# Error\nSorry, no valid **repository** specified in this url: {0}!", path);
            error(response, mkd);
            return;
        }

        // identify the branch
        String branch = getBranch(repository, request);
        if (StringUtils.isEmpty(branch)) {
            branch = r.getBranch();
            if (branch == null) {
                // no branches found!  empty?
                String mkd = MessageFormat
                        .format("# Error\nSorry, no valid **branch** specified in this url: {0}!", path);
                error(response, mkd);
            } else {
                // redirect to default branch
                String base = request.getRequestURI();
                String url = base + branch + "/";
                response.sendRedirect(url);
            }
            return;
        }

        // identify the requested path
        String requestedPath = getPath(repository, branch, request);

        // identify the commit
        RevCommit commit = JGitUtils.getCommit(r, branch);
        if (commit == null) {
            // branch not found!
            String mkd = MessageFormat.format(
                    "# Error\nSorry, the repository {0} does not have a **{1}** branch!", repository, branch);
            error(response, mkd);
            return;
        }

        Map<String, String> quickContentTypes = new HashMap<>();
        quickContentTypes.put("html", "text/html");
        quickContentTypes.put("htm", "text/html");
        quickContentTypes.put("xml", "application/xml");
        quickContentTypes.put("json", "application/json");

        List<PathModel> pathEntries = JGitUtils.getFilesInPath(r, requestedPath, commit);
        if (pathEntries.isEmpty()) {
            // requested a specific resource
            String file = StringUtils.getLastPathElement(requestedPath);
            try {

                String ext = StringUtils.getFileExtension(file).toLowerCase();
                // We can't parse out an extension for classic "dotfiles", so make a general assumption that
                // they're text files to allow presenting them in browser instead of only for download.
                //
                // However, that only holds for files with no other extension included, for files that happen
                // to start with a dot but also include an extension, process the extension normally.
                // This logic covers .gitattributes, .gitignore, .zshrc, etc., but does not cover .mongorc.js, .zshrc.bak
                boolean isExtensionlessDotfile = file.charAt(0) == '.'
                        && (file.length() == 1 || file.indexOf('.', 1) < 0);
                String contentType = isExtensionlessDotfile ? "text/plain" : quickContentTypes.get(ext);

                if (contentType == null) {
                    List<String> exts = runtimeManager.getSettings().getStrings(Keys.web.prettyPrintExtensions);
                    if (exts.contains(ext)) {
                        // extension is a registered text type for pretty printing
                        contentType = "text/plain";
                    } else {
                        // query Tika for the content type
                        Tika tika = new Tika();
                        contentType = tika.detect(file);
                    }
                }

                if (contentType == null) {
                    // ask the container for the content type
                    contentType = context.getMimeType(requestedPath);

                    if (contentType == null) {
                        // still unknown content type, assume binary
                        contentType = "application/octet-stream";
                    }
                }

                if (isTextType(contentType) || isTextDataType(contentType)) {

                    // load, interpret, and serve text content as UTF-8
                    String[] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings)
                            .toArray(new String[0]);
                    String content = JGitUtils.getStringContent(r, commit.getTree(), requestedPath, encodings);
                    if (content == null) {
                        logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
                        notFound(response, requestedPath, branch);
                        return;
                    }

                    byte[] bytes = content.getBytes(Constants.ENCODING);
                    setContentType(response, contentType);
                    response.setContentLength(bytes.length);
                    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                    sendContent(response, JGitUtils.getCommitDate(commit), is);

                } else {
                    // stream binary content directly from the repository
                    if (!streamFromRepo(request, response, r, commit, requestedPath)) {
                        logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
                        notFound(response, requestedPath, branch);
                    }
                }
                return;
            } catch (Exception e) {
                logger.error(null, e);
            }
        } else {
            // path request
            if (!request.getPathInfo().endsWith("/")) {
                // redirect to trailing '/' url
                response.sendRedirect(request.getServletPath() + request.getPathInfo() + "/");
                return;
            }

            if (renderIndex()) {
                // locate and render an index file
                Map<String, String> names = new TreeMap<String, String>();
                for (PathModel entry : pathEntries) {
                    names.put(entry.name.toLowerCase(), entry.name);
                }

                List<String> extensions = new ArrayList<String>();
                extensions.add("html");
                extensions.add("htm");

                String content = null;
                for (String ext : extensions) {
                    String key = "index." + ext;

                    if (names.containsKey(key)) {
                        String fileName = names.get(key);
                        String fullPath = fileName;
                        if (!requestedPath.isEmpty()) {
                            fullPath = requestedPath + "/" + fileName;
                        }

                        String[] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings)
                                .toArray(new String[0]);
                        String stringContent = JGitUtils.getStringContent(r, commit.getTree(), fullPath,
                                encodings);
                        if (stringContent == null) {
                            continue;
                        }
                        content = stringContent;
                        requestedPath = fullPath;
                        break;
                    }
                }

                response.setContentType("text/html; charset=" + Constants.ENCODING);
                byte[] bytes = content.getBytes(Constants.ENCODING);
                response.setContentLength(bytes.length);

                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                sendContent(response, JGitUtils.getCommitDate(commit), is);
                return;
            }
        }

        // no content, document list or 404 page
        if (pathEntries.isEmpty()) {
            // default 404 page
            notFound(response, requestedPath, branch);
            return;
        } else {
            //
            // directory list
            //
            response.setContentType("text/html");
            response.getWriter()
                    .append("<style>table th, table td { min-width: 150px; text-align: left; }</style>");
            response.getWriter().append("<table>");
            response.getWriter().append("<thead><tr><th>path</th><th>mode</th><th>size</th></tr>");
            response.getWriter().append("</thead>");
            response.getWriter().append("<tbody>");
            String pattern = "<tr><td><a href=\"{0}/{1}\">{1}</a></td><td>{2}</td><td>{3}</td></tr>";
            final ByteFormat byteFormat = new ByteFormat();
            if (!pathEntries.isEmpty()) {
                if (pathEntries.get(0).path.indexOf('/') > -1) {
                    // we are in a subdirectory, add parent directory link
                    String pp = URLEncoder.encode(requestedPath, Constants.ENCODING);
                    pathEntries.add(0,
                            new PathModel("..", pp + "/..", null, 0, FileMode.TREE.getBits(), null, null));
                }
            }

            String basePath = request.getServletPath() + request.getPathInfo();
            if (basePath.charAt(basePath.length() - 1) == '/') {
                // strip trailing slash
                basePath = basePath.substring(0, basePath.length() - 1);
            }
            for (PathModel entry : pathEntries) {
                String pp = URLEncoder.encode(entry.name, Constants.ENCODING);
                response.getWriter()
                        .append(MessageFormat.format(pattern, basePath, pp,
                                JGitUtils.getPermissionsFromMode(entry.mode),
                                entry.isFile() ? byteFormat.format(entry.size) : ""));
            }
            response.getWriter().append("</tbody>");
            response.getWriter().append("</table>");
        }
    } catch (Throwable t) {
        logger.error("Failed to write page to client", t);
    } finally {
        r.close();
    }
}

From source file:com.gitblit.servlet.RawServlet.java

License:Apache License

protected boolean streamFromRepo(HttpServletRequest request, HttpServletResponse response,
        Repository repository, RevCommit commit, String requestedPath) throws IOException {

    boolean served = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {/*from   ww w. j a  v a 2s .c om*/
        tw.reset();
        tw.addTree(commit.getTree());
        PathFilter f = PathFilter.create(requestedPath);
        tw.setFilter(f);
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            String filename = StringUtils.getLastPathElement(requestedPath);
            try {
                String userAgent = request.getHeader("User-Agent");
                if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) {
                    response.setHeader("Content-Disposition",
                            "filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) {
                    response.setHeader("Content-Disposition",
                            "attachment; filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                } else {
                    response.setHeader("Content-Disposition", "attachment; filename=\""
                            + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\"");
                }
            } catch (UnsupportedEncodingException e) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            }

            long len = reader.getObjectSize(id, org.eclipse.jgit.lib.Constants.OBJ_BLOB);
            setContentType(response, "application/octet-stream");
            response.setIntHeader("Content-Length", (int) len);
            ObjectLoader ldr = repository.open(id);
            ldr.copyTo(response.getOutputStream());
            served = true;
        }
    } finally {
        tw.close();
        rw.dispose();
    }

    response.flushBuffer();
    return served;
}

From source file:com.gitblit.tests.JGitUtilsTest.java

License:Apache License

@Test
public void testFileModes() throws Exception {
    assertEquals("drwxr-xr-x", JGitUtils.getPermissionsFromMode(FileMode.TREE.getBits()));
    assertEquals("-rw-r--r--", JGitUtils.getPermissionsFromMode(FileMode.REGULAR_FILE.getBits()));
    assertEquals("-rwxr-xr-x", JGitUtils.getPermissionsFromMode(FileMode.EXECUTABLE_FILE.getBits()));
    assertEquals("symlink", JGitUtils.getPermissionsFromMode(FileMode.SYMLINK.getBits()));
    assertEquals("submodule", JGitUtils.getPermissionsFromMode(FileMode.GITLINK.getBits()));
    assertEquals("missing", JGitUtils.getPermissionsFromMode(FileMode.MISSING.getBits()));
}

From source file:com.gitblit.utils.CompressionUtils.java

License:Apache License

/**
 * Zips the contents of the tree at the (optionally) specified revision and
 * the (optionally) specified basepath to the supplied outputstream.
 *
 * @param repository/*from   w w w  .  j av a  2  s.c  o m*/
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
public static boolean zip(Repository repository, IFilestoreManager filestoreManager, String basePath,
        String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
        zos.setComment("Generated by Gitblit");
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            ObjectLoader loader = repository.open(id);

            ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString());

            FilestoreModel filestoreItem = null;

            if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) {
                filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id));
            }

            final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize();

            entry.setSize(size);
            entry.setComment(commit.getName());
            entry.setUnixMode(mode.getBits());
            entry.setTime(modified);
            zos.putArchiveEntry(entry);

            if (filestoreItem == null) {
                //Copy repository stored file
                loader.copyTo(zos);
            } else {
                //Copy filestore file
                try (FileInputStream streamIn = new FileInputStream(
                        filestoreManager.getStoragePath(filestoreItem.oid))) {
                    IOUtils.copyLarge(streamIn, zos);
                } catch (Throwable e) {
                    LOGGER.error(
                            MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e);

                    //Handle as per other errors 
                    throw e;
                }
            }

            zos.closeArchiveEntry();
        }
        zos.finish();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to zip files from commit {1}", commit.getName());
    } finally {
        tw.close();
        rw.dispose();
    }
    return success;
}

From source file:com.gitblit.utils.CompressionUtils.java

License:Apache License

/**
 * Compresses/archives the contents of the tree at the (optionally)
 * specified revision and the (optionally) specified basepath to the
 * supplied outputstream./*from  w  w w .j av  a2 s  .c  o  m*/
 *
 * @param algorithm
 *            compression algorithm for tar (optional)
 * @param repository
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
private static boolean tar(String algorithm, Repository repository, IFilestoreManager filestoreManager,
        String basePath, String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }

    OutputStream cos = os;
    if (!StringUtils.isEmpty(algorithm)) {
        try {
            cos = new CompressorStreamFactory().createCompressorOutputStream(algorithm, os);
        } catch (CompressorException e1) {
            error(e1, repository, "{0} failed to open {1} stream", algorithm);
        }
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
        tos.setAddPaxHeadersForNonAsciiNames(true);
        tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }

            tw.getObjectId(id, 0);

            ObjectLoader loader = repository.open(id);
            if (FileMode.SYMLINK == mode) {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(), TarArchiveEntry.LF_SYMLINK);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                loader.copyTo(bos);
                entry.setLinkName(bos.toString());
                entry.setModTime(modified);
                tos.putArchiveEntry(entry);
                tos.closeArchiveEntry();
            } else {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString());
                entry.setMode(mode.getBits());
                entry.setModTime(modified);

                FilestoreModel filestoreItem = null;

                if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) {
                    filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id));
                }

                final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize();

                entry.setSize(size);
                tos.putArchiveEntry(entry);

                if (filestoreItem == null) {
                    //Copy repository stored file
                    loader.copyTo(tos);
                } else {
                    //Copy filestore file
                    try (FileInputStream streamIn = new FileInputStream(
                            filestoreManager.getStoragePath(filestoreItem.oid))) {

                        IOUtils.copyLarge(streamIn, tos);
                    } catch (Throwable e) {
                        LOGGER.error(
                                MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid),
                                e);

                        //Handle as per other errors 
                        throw e;
                    }
                }

                tos.closeArchiveEntry();
            }
        }
        tos.finish();
        tos.close();
        cos.close();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to {1} stream files from commit {2}", algorithm, commit.getName());
    } finally {
        tw.close();
        rw.dispose();
    }
    return success;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Returns a permissions representation of the mode bits.
 *
 * @param mode//from  w  w  w. ja v  a2 s.c o m
 * @return string representation of the mode bits
 */
public static String getPermissionsFromMode(int mode) {
    if (FileMode.TREE.equals(mode)) {
        return "drwxr-xr-x";
    } else if (FileMode.REGULAR_FILE.equals(mode)) {
        return "-rw-r--r--";
    } else if (FileMode.EXECUTABLE_FILE.equals(mode)) {
        return "-rwxr-xr-x";
    } else if (FileMode.SYMLINK.equals(mode)) {
        return "symlink";
    } else if (FileMode.GITLINK.equals(mode)) {
        return "submodule";
    }
    return "missing";
}

From source file:com.gitblit.wicket.pages.TreePage.java

License:Apache License

public TreePage(PageParameters params) {
    super(params);

    final String path = WicketUtils.getPath(params);

    Repository r = getRepository();/* www.  j  av a2  s  .c  o m*/
    RevCommit commit = getCommit();
    List<PathModel> paths = JGitUtils.getFilesInPath2(r, path, commit);

    // tree page links
    add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class,
            WicketUtils.newPathParameter(repositoryName, objectId, path)));
    add(new CompressedDownloadsPanel("compressedLinks",
            GitBlitRequestUtils.getRelativePathPrefixToContextRoot(), repositoryName, objectId, path));

    add(new CommitHeaderPanel("commitHeader", repositoryName, commit));

    // breadcrumbs
    add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, path, objectId));
    if (path != null && path.trim().length() > 0) {
        // add .. parent path entry
        String parentPath = null;
        if (path.lastIndexOf('/') > -1) {
            parentPath = path.substring(0, path.lastIndexOf('/'));
        }
        PathModel model = new PathModel("..", parentPath, null, 0, FileMode.TREE.getBits(), null, objectId);
        model.isParentPath = true;
        paths.add(0, model);
    }

    final String id = getBestCommitId(commit);

    final ByteFormat byteFormat = new ByteFormat();
    final String baseUrl = WicketUtils.getGitblitURL(getRequest());

    // changed paths list
    ListDataProvider<PathModel> pathsDp = new ListDataProvider<PathModel>(paths);
    DataView<PathModel> pathsView = new DataView<PathModel>("changedPath", pathsDp) {
        private static final long serialVersionUID = 1L;
        int counter;

        @Override
        public void populateItem(final Item<PathModel> item) {
            final PathModel entry = item.getModelObject();

            item.add(new Label("pathPermissions", JGitUtils.getPermissionsFromMode(entry.mode)));
            item.add(WicketUtils.setHtmlTooltip(new Label("filestore", ""), getString("gb.filestore"))
                    .setVisible(entry.isFilestoreItem()));

            if (entry.isParentPath) {
                // parent .. path
                item.add(WicketUtils.newBlankImage("pathIcon"));
                item.add(new Label("pathSize", ""));
                item.add(new LinkPanel("pathName", null, entry.name, TreePage.class,
                        WicketUtils.newPathParameter(repositoryName, id, entry.path)));
                item.add(new Label("pathLinks", ""));
            } else {
                if (entry.isTree()) {
                    // folder/tree link
                    item.add(WicketUtils.newImage("pathIcon", "folder_16x16.png"));
                    item.add(new Label("pathSize", ""));
                    item.add(new LinkPanel("pathName", "list", entry.name, TreePage.class,
                            WicketUtils.newPathParameter(repositoryName, id, entry.path)));

                    // links
                    Fragment links = new Fragment("pathLinks", "treeLinks", TreePage.this);
                    links.add(new BookmarkablePageLink<Void>("tree", TreePage.class,
                            WicketUtils.newPathParameter(repositoryName, id, entry.path)));
                    links.add(new BookmarkablePageLink<Void>("history", HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, id, entry.path)));
                    links.add(new CompressedDownloadsPanel("compressedLinks", baseUrl, repositoryName, objectId,
                            entry.path));

                    item.add(links);
                } else if (entry.isSubmodule()) {
                    // submodule
                    String submoduleId = entry.objectId;
                    String submodulePath;
                    boolean hasSubmodule = false;
                    SubmoduleModel submodule = getSubmodule(entry.path);
                    submodulePath = submodule.gitblitPath;
                    hasSubmodule = submodule.hasSubmodule;

                    item.add(WicketUtils.newImage("pathIcon", "git-orange-16x16.png"));
                    item.add(new Label("pathSize", ""));
                    item.add(new LinkPanel("pathName", "list",
                            entry.name + " @ " + getShortObjectId(submoduleId), TreePage.class,
                            WicketUtils.newPathParameter(submodulePath, submoduleId, ""))
                                    .setEnabled(hasSubmodule));

                    Fragment links = new Fragment("pathLinks", "submoduleLinks", TreePage.this);
                    links.add(new BookmarkablePageLink<Void>("view", SummaryPage.class,
                            WicketUtils.newRepositoryParameter(submodulePath)).setEnabled(hasSubmodule));
                    links.add(new BookmarkablePageLink<Void>("tree", TreePage.class,
                            WicketUtils.newPathParameter(submodulePath, submoduleId, ""))
                                    .setEnabled(hasSubmodule));
                    links.add(new BookmarkablePageLink<Void>("history", HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, id, entry.path)));
                    links.add(new CompressedDownloadsPanel("compressedLinks", baseUrl, submodulePath,
                            submoduleId, "").setEnabled(hasSubmodule));
                    item.add(links);
                } else {
                    // blob link
                    String displayPath = entry.name;
                    String path = entry.path;
                    if (entry.isSymlink()) {
                        path = JGitUtils.getStringContent(getRepository(), getCommit().getTree(), path);
                        displayPath = entry.name + " -> " + path;
                    }
                    item.add(WicketUtils.getFileImage("pathIcon", entry.name));
                    item.add(new Label("pathSize", byteFormat.format(entry.size)));

                    // links
                    Fragment links = new Fragment("pathLinks", "blobLinks", TreePage.this);

                    if (entry.isFilestoreItem()) {
                        item.add(new LinkPanel("pathName", "list", displayPath, new Link<Object>("link", null) {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public void onClick() {

                                IResourceStream resourceStream = new AbstractResourceStreamWriter() {

                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    public void write(OutputStream output) {
                                        UserModel user = GitBlitWebSession.get().getUser();
                                        user = user == null ? UserModel.ANONYMOUS : user;

                                        app().filestore().downloadBlob(entry.getFilestoreOid(), user,
                                                getRepositoryModel(), output);
                                    }
                                };

                                ResourceStreamRequestHandler resourceStreamRequestHandler = new ResourceStreamRequestHandler(
                                        resourceStream, entry.path);
                                getRequestCycle()
                                        .scheduleRequestHandlerAfterCurrent(resourceStreamRequestHandler);

                            }
                        }));

                        links.add(new Link<Object>("view", null) {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public void onClick() {

                                IResourceStream resourceStream = new AbstractResourceStreamWriter() {

                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    public void write(OutputStream output) {
                                        UserModel user = GitBlitWebSession.get().getUser();
                                        user = user == null ? UserModel.ANONYMOUS : user;

                                        app().filestore().downloadBlob(entry.getFilestoreOid(), user,
                                                getRepositoryModel(), output);
                                    }
                                };

                                ResourceStreamRequestHandler resourceStreamRequestHandler = new ResourceStreamRequestHandler(
                                        resourceStream, entry.path);
                                getRequestCycle()
                                        .scheduleRequestHandlerAfterCurrent(resourceStreamRequestHandler);
                            }
                        });

                        links.add(new Link<Object>("raw", null) {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public void onClick() {

                                IResourceStream resourceStream = new AbstractResourceStreamWriter() {

                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    public void write(OutputStream output) {
                                        UserModel user = GitBlitWebSession.get().getUser();
                                        user = user == null ? UserModel.ANONYMOUS : user;

                                        app().filestore().downloadBlob(entry.getFilestoreOid(), user,
                                                getRepositoryModel(), output);
                                    }
                                };

                                ResourceStreamRequestHandler resourceStreamRequestHandler = new ResourceStreamRequestHandler(
                                        resourceStream, entry.path);
                                getRequestCycle()
                                        .scheduleRequestHandlerAfterCurrent(resourceStreamRequestHandler);
                            }
                        });

                    } else {
                        item.add(new LinkPanel("pathName", "list", displayPath, BlobPage.class,
                                WicketUtils.newPathParameter(repositoryName, id, path)));

                        links.add(new BookmarkablePageLink<Void>("view", BlobPage.class,
                                WicketUtils.newPathParameter(repositoryName, id, path)));
                        String rawUrl = RawServlet.asLink(getContextUrl(), repositoryName, id, path);
                        links.add(new ExternalLink("raw", rawUrl));
                    }

                    links.add(new BookmarkablePageLink<Void>("blame", BlamePage.class,
                            WicketUtils.newPathParameter(repositoryName, id, path)));
                    links.add(new BookmarkablePageLink<Void>("history", HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, id, path)));
                    item.add(links);
                }
            }
            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
        }
    };
    add(pathsView);
}

From source file:com.google.gitiles.ArchiveServlet.java

License:Open Source License

private ObjectId getTree(GitilesView view, Repository repo, Revision rev) throws IOException {
    RevWalk rw = new RevWalk(repo);
    try {/*from  ww  w .j  a  va  2  s .  c  om*/
        RevTree tree = rw.parseTree(rev.getId());
        if (Strings.isNullOrEmpty(view.getPathPart())) {
            return tree;
        }
        TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), view.getPathPart(), tree);
        if (tw == null || tw.getFileMode(0) != FileMode.TREE) {
            return ObjectId.zeroId();
        }
        return tw.getObjectId(0);
    } catch (IncorrectObjectTypeException e) {
        return ObjectId.zeroId();
    } finally {
        rw.release();
    }
}