Search in sources :

Example 11 with Repository

use of org.eclipse.jgit.lib.Repository in project gitblit by gitblit.

the class BranchGraphServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    InputStream is = null;
    Repository r = null;
    PlotWalk rw = null;
    try {
        String repository = request.getParameter("r");
        if (StringUtils.isEmpty(repository)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().append("Bad request");
            return;
        }
        String objectId = request.getParameter("h");
        String length = request.getParameter("l");
        r = repositoryManager.getRepository(repository);
        if (r == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().append("Bad request");
            return;
        }
        rw = new PlotWalk(r);
        if (StringUtils.isEmpty(objectId)) {
            objectId = JGitUtils.getHEADRef(r);
        }
        ObjectId id = r.resolve(objectId);
        if (id == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().append("Bad request");
            return;
        }
        rw.markStart(rw.lookupCommit(id));
        // default to the items-per-page setting, unless specified
        int maxCommits = settings.getInteger(Keys.web.itemsPerPage, 50);
        int requestedCommits = maxCommits;
        if (!StringUtils.isEmpty(length)) {
            int l = Integer.parseInt(length);
            if (l > 0) {
                requestedCommits = l;
            }
        }
        // fetch the requested commits plus some extra so that the last
        // commit displayed *likely* has correct lane assignments
        CommitList commitList = new CommitList();
        commitList.source(rw);
        commitList.fillTo(2 * Math.max(requestedCommits, maxCommits));
        // determine the appropriate width for the image
        int numLanes = 1;
        int numCommits = Math.min(requestedCommits, commitList.size());
        if (numCommits > 1) {
            // determine graph width
            Set<String> parents = new TreeSet<String>();
            for (int i = 0; i < commitList.size(); i++) {
                PlotCommit<Lane> commit = commitList.get(i);
                boolean checkLane = false;
                if (i < numCommits) {
                    // commit in visible list
                    checkLane = true;
                    // remember parents
                    for (RevCommit p : commit.getParents()) {
                        parents.add(p.getName());
                    }
                } else if (parents.contains(commit.getName())) {
                    // commit outside visible list, but it is a parent of a
                    // commit in the visible list so we need to know it's lane
                    // assignment
                    checkLane = true;
                }
                if (checkLane) {
                    int pos = commit.getLane().getPosition();
                    numLanes = Math.max(numLanes, pos + 1);
                }
            }
        }
        int graphWidth = numLanes * LANE_WIDTH + RIGHT_PAD;
        int rowHeight = ROW_HEIGHT;
        // create an image buffer and render the lanes
        BufferedImage image = new BufferedImage(graphWidth, rowHeight * numCommits, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = null;
        try {
            g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            LanesRenderer renderer = new LanesRenderer();
            for (int i = 0; i < commitList.size(); i++) {
                PlotCommit<Lane> commit = commitList.get(i);
                Graphics row = g.create(0, i * rowHeight, graphWidth, rowHeight);
                try {
                    renderer.paint(row, commit, rowHeight, graphWidth);
                } finally {
                    row.dispose();
                    row = null;
                }
            }
        } finally {
            if (g != null) {
                g.dispose();
                g = null;
            }
        }
        // write the image buffer to the client
        response.setContentType("image/png");
        if (numCommits > 1) {
            response.setHeader("Cache-Control", "public, max-age=60, must-revalidate");
            response.setDateHeader("Last-Modified", JGitUtils.getCommitDate(commitList.get(0)).getTime());
        }
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
        os.flush();
        image.flush();
        image = null;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            is.close();
            is = null;
        }
        if (rw != null) {
            rw.dispose();
            rw = null;
        }
        if (r != null) {
            r.close();
            r = null;
        }
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) PlotLane(org.eclipse.jgit.revplot.PlotLane) PlotCommitList(org.eclipse.jgit.revplot.PlotCommitList) BufferedImage(java.awt.image.BufferedImage) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Graphics2D(java.awt.Graphics2D) Graphics(java.awt.Graphics) Repository(org.eclipse.jgit.lib.Repository) TreeSet(java.util.TreeSet) PlotWalk(org.eclipse.jgit.revplot.PlotWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 12 with Repository

use of org.eclipse.jgit.lib.Repository in project gitblit by gitblit.

the class DownloadZipServlet method processRequest.

/**
	 * Creates a zip stream from the repository of the requested data.
	 *
	 * @param request
	 * @param response
	 * @throws javax.servlet.ServletException
	 * @throws java.io.IOException
	 */
private void processRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
    if (!settings.getBoolean(Keys.web.allowZipDownloads, true)) {
        logger.warn("Zip downloads are disabled");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    Format format = Format.zip;
    String repository = request.getParameter("r");
    String basePath = request.getParameter("p");
    String objectId = request.getParameter("h");
    String f = request.getParameter("format");
    if (!StringUtils.isEmpty(f)) {
        format = Format.fromName(f);
    }
    try {
        String name = repository;
        if (name.indexOf('/') > -1) {
            name = name.substring(name.lastIndexOf('/') + 1);
        }
        name = StringUtils.stripDotGit(name);
        if (!StringUtils.isEmpty(basePath)) {
            name += "-" + basePath.replace('/', '_');
        }
        if (!StringUtils.isEmpty(objectId)) {
            name += "-" + objectId;
        }
        Repository r = repositoryManager.getRepository(repository);
        if (r == null) {
            if (repositoryManager.isCollectingGarbage(repository)) {
                error(response, MessageFormat.format("# Error\nGitblit is busy collecting garbage in {0}", repository));
                return;
            } else {
                error(response, MessageFormat.format("# Error\nFailed to find repository {0}", repository));
                return;
            }
        }
        RevCommit commit = JGitUtils.getCommit(r, objectId);
        if (commit == null) {
            error(response, MessageFormat.format("# Error\nFailed to find commit {0}", objectId));
            r.close();
            return;
        }
        Date date = JGitUtils.getCommitDate(commit);
        String contentType = "application/octet-stream";
        response.setContentType(contentType + "; charset=" + response.getCharacterEncoding());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + name + format.extension + "\"");
        response.setDateHeader("Last-Modified", date.getTime());
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            switch(format) {
                case zip:
                    CompressionUtils.zip(r, filestoreManager, basePath, objectId, response.getOutputStream());
                    break;
                case tar:
                    CompressionUtils.tar(r, filestoreManager, basePath, objectId, response.getOutputStream());
                    break;
                case gz:
                    CompressionUtils.gz(r, filestoreManager, basePath, objectId, response.getOutputStream());
                    break;
                case xz:
                    CompressionUtils.xz(r, filestoreManager, basePath, objectId, response.getOutputStream());
                    break;
                case bzip2:
                    CompressionUtils.bzip2(r, filestoreManager, basePath, objectId, response.getOutputStream());
                    break;
            }
            response.flushBuffer();
        } catch (IOException t) {
            String message = t.getMessage() == null ? "" : t.getMessage().toLowerCase();
            if (message.contains("reset") || message.contains("broken pipe")) {
                logger.error("Client aborted zip download: " + message);
            } else {
                logger.error("Failed to write attachment to client", t);
            }
        } catch (Throwable t) {
            logger.error("Failed to write attachment to client", t);
        }
        // close the repository
        r.close();
    } catch (Throwable t) {
        logger.error("Failed to write attachment to client", t);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) MessageFormat(java.text.MessageFormat) IOException(java.io.IOException) Date(java.util.Date) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 13 with Repository

use of org.eclipse.jgit.lib.Repository in project gitblit by gitblit.

the class SyndicationServlet method processRequest.

/**
	 * Generates the feed content.
	 *
	 * @param request
	 * @param response
	 * @throws javax.servlet.ServletException
	 * @throws java.io.IOException
	 */
private void processRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
    String servletUrl = request.getContextPath() + request.getServletPath();
    String url = request.getRequestURI().substring(servletUrl.length());
    if (url.length() > 1 && url.charAt(0) == '/') {
        url = url.substring(1);
    }
    String repositoryName = url;
    String objectId = request.getParameter("h");
    String l = request.getParameter("l");
    String page = request.getParameter("pg");
    String searchString = request.getParameter("s");
    Constants.SearchType searchType = Constants.SearchType.COMMIT;
    if (!StringUtils.isEmpty(request.getParameter("st"))) {
        Constants.SearchType type = Constants.SearchType.forName(request.getParameter("st"));
        if (type != null) {
            searchType = type;
        }
    }
    Constants.FeedObjectType objectType = Constants.FeedObjectType.COMMIT;
    if (!StringUtils.isEmpty(request.getParameter("ot"))) {
        Constants.FeedObjectType type = Constants.FeedObjectType.forName(request.getParameter("ot"));
        if (type != null) {
            objectType = type;
        }
    }
    int length = settings.getInteger(Keys.web.syndicationEntries, 25);
    if (StringUtils.isEmpty(objectId)) {
        objectId = org.eclipse.jgit.lib.Constants.HEAD;
    }
    if (!StringUtils.isEmpty(l)) {
        try {
            length = Integer.parseInt(l);
        } catch (NumberFormatException x) {
        }
    }
    int offset = 0;
    if (!StringUtils.isEmpty(page)) {
        try {
            offset = length * Integer.parseInt(page);
        } catch (NumberFormatException x) {
        }
    }
    response.setContentType("application/rss+xml; charset=UTF-8");
    boolean isProjectFeed = false;
    String feedName = "Gitblit";
    String feedTitle = null;
    String feedDescription = null;
    List<String> repositories = null;
    if (repositoryName.indexOf('/') == -1 && !repositoryName.toLowerCase().endsWith(".git")) {
        // try to find a project
        UserModel user = null;
        if (request instanceof AuthenticatedRequest) {
            user = ((AuthenticatedRequest) request).getUser();
        }
        ProjectModel project = projectManager.getProjectModel(repositoryName, user);
        if (project != null) {
            isProjectFeed = true;
            repositories = new ArrayList<String>(project.repositories);
            // project feed
            feedName = project.name;
            feedTitle = project.title;
            feedDescription = project.description;
        }
    }
    if (repositories == null) {
        // could not find project, assume this is a repository
        repositories = Arrays.asList(repositoryName);
    }
    boolean mountParameters = settings.getBoolean(Keys.web.mountParameters, true);
    String gitblitUrl = settings.getString(Keys.web.canonicalUrl, null);
    if (StringUtils.isEmpty(gitblitUrl)) {
        gitblitUrl = HttpUtils.getGitblitURL(request);
    }
    char fsc = settings.getChar(Keys.web.forwardSlashCharacter, '/');
    List<FeedEntryModel> entries = new ArrayList<FeedEntryModel>();
    for (String name : repositories) {
        Repository repository = repositoryManager.getRepository(name);
        RepositoryModel model = repositoryManager.getRepositoryModel(name);
        if (repository == null) {
            if (model != null && model.isCollectingGarbage) {
                logger.warn(MessageFormat.format("Temporarily excluding {0} from feed, busy collecting garbage", name));
            }
            continue;
        }
        if (!isProjectFeed) {
            // single-repository feed
            feedName = model.name;
            feedTitle = model.name;
            feedDescription = model.description;
        }
        if (objectType == Constants.FeedObjectType.TAG) {
            String urlPattern;
            if (mountParameters) {
                // mounted parameters
                urlPattern = "{0}/tag/{1}/{2}";
            } else {
                // parameterized parameters
                urlPattern = "{0}/tag/?r={1}&h={2}";
            }
            List<RefModel> tags = JGitUtils.getTags(repository, false, length, offset);
            for (RefModel tag : tags) {
                FeedEntryModel entry = new FeedEntryModel();
                entry.title = tag.getName();
                entry.author = tag.getAuthorIdent().getName();
                entry.link = MessageFormat.format(urlPattern, gitblitUrl, StringUtils.encodeURL(model.name.replace('/', fsc)), tag.getObjectId().getName());
                entry.published = tag.getDate();
                entry.contentType = "text/html";
                entry.content = tag.getFullMessage();
                entry.repository = model.name;
                entry.branch = objectId;
                entry.tags = new ArrayList<String>();
                // add tag id and referenced commit id
                entry.tags.add("tag:" + tag.getObjectId().getName());
                entry.tags.add("commit:" + tag.getReferencedObjectId().getName());
                entries.add(entry);
            }
        } else {
            String urlPattern;
            if (mountParameters) {
                // mounted parameters
                urlPattern = "{0}/commit/{1}/{2}";
            } else {
                // parameterized parameters
                urlPattern = "{0}/commit/?r={1}&h={2}";
            }
            List<RevCommit> commits;
            if (StringUtils.isEmpty(searchString)) {
                // standard log/history lookup
                commits = JGitUtils.getRevLog(repository, objectId, offset, length);
            } else {
                // repository search
                commits = JGitUtils.searchRevlogs(repository, objectId, searchString, searchType, offset, length);
            }
            Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository, model.showRemoteBranches);
            BugtraqProcessor processor = new BugtraqProcessor(settings);
            // convert RevCommit to SyndicatedEntryModel
            for (RevCommit commit : commits) {
                FeedEntryModel entry = new FeedEntryModel();
                entry.title = commit.getShortMessage();
                entry.author = commit.getAuthorIdent().getName();
                entry.link = MessageFormat.format(urlPattern, gitblitUrl, StringUtils.encodeURL(model.name.replace('/', fsc)), commit.getName());
                entry.published = commit.getCommitterIdent().getWhen();
                entry.contentType = "text/html";
                String message = processor.processCommitMessage(repository, model, commit.getFullMessage());
                entry.content = message;
                entry.repository = model.name;
                entry.branch = objectId;
                entry.tags = new ArrayList<String>();
                // add commit id and parent commit ids
                entry.tags.add("commit:" + commit.getName());
                for (RevCommit parent : commit.getParents()) {
                    entry.tags.add("parent:" + parent.getName());
                }
                // add refs to tabs list
                List<RefModel> refs = allRefs.get(commit.getId());
                if (refs != null && refs.size() > 0) {
                    for (RefModel ref : refs) {
                        entry.tags.add("ref:" + ref.getName());
                    }
                }
                entries.add(entry);
            }
        }
    }
    // sort & truncate the feed
    Collections.sort(entries);
    if (entries.size() > length) {
        // clip the list
        entries = entries.subList(0, length);
    }
    String feedLink;
    if (isProjectFeed) {
        // project feed
        if (mountParameters) {
            // mounted url
            feedLink = MessageFormat.format("{0}/project/{1}", gitblitUrl, StringUtils.encodeURL(feedName));
        } else {
            // parameterized url
            feedLink = MessageFormat.format("{0}/project/?p={1}", gitblitUrl, StringUtils.encodeURL(feedName));
        }
    } else {
        // repository feed
        if (mountParameters) {
            // mounted url
            feedLink = MessageFormat.format("{0}/summary/{1}", gitblitUrl, StringUtils.encodeURL(feedName.replace('/', fsc)));
        } else {
            // parameterized url
            feedLink = MessageFormat.format("{0}/summary/?r={1}", gitblitUrl, StringUtils.encodeURL(feedName));
        }
    }
    try {
        SyndicationUtils.toRSS(gitblitUrl, feedLink, getTitle(feedTitle, objectId), feedDescription, entries, response.getOutputStream());
    } catch (Exception e) {
        logger.error("An error occurred during feed generation", e);
    }
}
Also used : AuthenticatedRequest(com.gitblit.servlet.AuthenticationFilter.AuthenticatedRequest) RefModel(com.gitblit.models.RefModel) FeedEntryModel(com.gitblit.models.FeedEntryModel) ArrayList(java.util.ArrayList) RepositoryModel(com.gitblit.models.RepositoryModel) UserModel(com.gitblit.models.UserModel) ArrayList(java.util.ArrayList) List(java.util.List) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ObjectId(org.eclipse.jgit.lib.ObjectId) Constants(com.gitblit.Constants) BugtraqProcessor(com.gitblit.utils.BugtraqProcessor) Repository(org.eclipse.jgit.lib.Repository) ProjectModel(com.gitblit.models.ProjectModel)

Example 14 with Repository

use of org.eclipse.jgit.lib.Repository in project gitblit by gitblit.

the class BranchTicketService method commitChangeImpl.

/**
	 * Commit a ticket change to the repository.
	 *
	 * @param repository
	 * @param ticketId
	 * @param change
	 * @return true, if the change was committed
	 */
@Override
protected synchronized boolean commitChangeImpl(RepositoryModel repository, long ticketId, Change change) {
    boolean success = false;
    Repository db = repositoryManager.getRepository(repository.name);
    try {
        DirCache index = createIndex(db, ticketId, change);
        success = commitIndex(db, index, change.author, "#" + ticketId);
    } catch (Throwable t) {
        log.error(MessageFormat.format("Failed to commit ticket {0,number,0} to {1}", ticketId, db.getDirectory()), t);
    } finally {
        db.close();
    }
    return success;
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository)

Example 15 with Repository

use of org.eclipse.jgit.lib.Repository in project gitblit by gitblit.

the class BranchTicketService method getTicketImpl.

/**
	 * Retrieves the ticket from the repository by first looking-up the changeId
	 * associated with the ticketId.
	 *
	 * @param repository
	 * @param ticketId
	 * @return a ticket, if it exists, otherwise null
	 */
@Override
protected TicketModel getTicketImpl(RepositoryModel repository, long ticketId) {
    Repository db = repositoryManager.getRepository(repository.name);
    try {
        List<Change> changes = getJournal(db, ticketId);
        if (ArrayUtils.isEmpty(changes)) {
            log.warn("Empty journal for {}:{}", repository, ticketId);
            return null;
        }
        TicketModel ticket = TicketModel.buildTicket(changes);
        if (ticket != null) {
            ticket.project = repository.projectPath;
            ticket.repository = repository.name;
            ticket.number = ticketId;
        }
        return ticket;
    } finally {
        db.close();
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) TicketModel(com.gitblit.models.TicketModel) Change(com.gitblit.models.TicketModel.Change)

Aggregations

Repository (org.eclipse.jgit.lib.Repository)326 IOException (java.io.IOException)103 RevWalk (org.eclipse.jgit.revwalk.RevWalk)102 Test (org.junit.Test)81 RevCommit (org.eclipse.jgit.revwalk.RevCommit)76 ObjectId (org.eclipse.jgit.lib.ObjectId)72 File (java.io.File)43 TestRepository (org.eclipse.jgit.junit.TestRepository)40 Change (com.google.gerrit.reviewdb.client.Change)39 OrmException (com.google.gwtorm.server.OrmException)39 Ref (org.eclipse.jgit.lib.Ref)35 Project (com.google.gerrit.reviewdb.client.Project)32 ArrayList (java.util.ArrayList)31 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)27 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)26 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)24 Map (java.util.Map)23 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)23 RepositoryModel (com.gitblit.models.RepositoryModel)20 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)20