Example usage for org.eclipse.jgit.util RawParseUtils decode

List of usage examples for org.eclipse.jgit.util RawParseUtils decode

Introduction

In this page you can find the example usage for org.eclipse.jgit.util RawParseUtils decode.

Prototype

public static String decode(byte[] buffer) 

Source Link

Document

Decode a buffer under UTF-8, if possible.

Usage

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

License:Apache License

/**
 * Workaround function for complex private methods in DiffFormatter. This sets the html for the diff headers.
 *
 * @return/*from  w ww  .  j ava 2  s . c o m*/
 */
public String getHtml() {
    String html = RawParseUtils.decode(os.toByteArray());
    String[] lines = html.split("\n");
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
        if (line.startsWith("index") || line.startsWith("similarity") || line.startsWith("rename from ")
                || line.startsWith("rename to ")) {
            // skip index lines
        } else if (line.startsWith("new file") || line.startsWith("deleted file")) {
            // skip new file lines
        } else if (line.startsWith("\\ No newline")) {
            // skip no new line
        } else if (line.startsWith("---") || line.startsWith("+++")) {
            // skip --- +++ lines
        } else if (line.startsWith("diff")) {
            // skip diff lines
        } else {
            boolean gitLinkDiff = line.length() > 0 && line.substring(1).startsWith("Subproject commit");
            if (gitLinkDiff) {
                sb.append("<tr><th class='diff-line'></th><th class='diff-line'></th>");
                if (line.charAt(0) == '+') {
                    sb.append("<th class='diff-state diff-state-add'></th><td class=\"diff-cell add2\">");
                } else {
                    sb.append("<th class='diff-state diff-state-sub'></th><td class=\"diff-cell remove2\">");
                }
                line = StringUtils.escapeForHtml(line.substring(1), CONVERT_TABS, tabLength);
            }
            sb.append(line);
            if (gitLinkDiff) {
                sb.append("</td></tr>");
            }
            sb.append('\n');
        }
    }
    if (truncated) {
        sb.append(MessageFormat.format("<div class='header'><div class='diffHeader'>{0}</div></div>",
                StringUtils.escapeForHtml(getMsg("gb.diffTruncated", "Diff truncated after the above file"),
                        false)));
        // List all files not shown. We can be sure we do have at least one path in skipped.
        sb.append("<div class='diff'><table cellpadding='0'><tbody><tr><td class='diff-cell' colspan='4'>");
        String deletedSuffix = StringUtils.escapeForHtml(getMsg("gb.diffDeletedFileSkipped", "(deleted)"),
                false);
        boolean first = true;
        for (DiffEntry entry : skipped) {
            if (!first) {
                sb.append('\n');
            }
            if (ChangeType.DELETE.equals(entry.getChangeType())) {
                sb.append("<span id=\"n" + entry.getOldId().name() + "\">"
                        + StringUtils.escapeForHtml(entry.getOldPath(), false) + ' ' + deletedSuffix
                        + "</span>");
            } else {
                sb.append("<span id=\"n" + entry.getNewId().name() + "\">"
                        + StringUtils.escapeForHtml(entry.getNewPath(), false) + "</span>");
            }
            first = false;
        }
        skipped.clear();
        sb.append("</td></tr></tbody></table></div>");
    }
    return sb.toString();
}

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

License:Apache License

/**
 * Workaround function for complex private methods in DiffFormatter. This
 * sets the html for the diff headers./*w  w  w . ja  v  a 2  s .  c o  m*/
 * 
 * @return
 */
public String getHtml() {
    ByteArrayOutputStream bos = (ByteArrayOutputStream) os;
    String html = RawParseUtils.decode(bos.toByteArray());
    String[] lines = html.split("\n");
    StringBuilder sb = new StringBuilder();
    sb.append("<div class=\"diff\">");
    for (String line : lines) {
        if (line.startsWith("diff")) {
            sb.append("<div class=\"diff header\">").append(StringUtils.convertOctal(line)).append("</div>");
        } else if (line.startsWith("---")) {
            sb.append("<span style=\"color:#800000;\">").append(StringUtils.convertOctal(line))
                    .append("</span><br/>");
        } else if (line.startsWith("+++")) {
            sb.append("<span style=\"color:#008000;\">").append(StringUtils.convertOctal(line))
                    .append("</span><br/>");
        } else {
            sb.append(line).append('\n');
        }
    }
    sb.append("</div>\n");
    return sb.toString();
}

From source file:com.google.gerrit.httpd.raw.BuckUtils.java

License:Apache License

static void displayFailure(String rule, byte[] why, HttpServletResponse res) throws IOException {
    res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    res.setContentType("text/html");
    res.setCharacterEncoding(UTF_8.name());
    CacheHeaders.setNotCacheable(res);/*ww  w. j  a va2 s .  c om*/

    Escaper html = HtmlEscapers.htmlEscaper();
    try (PrintWriter w = res.getWriter()) {
        w.write("<html><title>BUILD FAILED</title><body>");
        w.format("<h1>%s FAILED</h1>", html.escape(rule));
        w.write("<pre>");
        w.write(html.escape(RawParseUtils.decode(why)));
        w.write("</pre>");
        w.write("</body></html>");
    }
}

From source file:com.google.gerrit.pgm.http.jetty.JettyServer.java

License:Apache License

private Resource useDeveloperBuild(ServletContextHandler app) throws IOException {
    final File dir = GerritLauncher.getDeveloperBuckOut();
    final File gen = new File(dir, "gen");
    final File root = dir.getParentFile();
    final File dstwar = makeWarTempDir();
    File ui = new File(dstwar, "gerrit_ui");
    File p = new File(ui, "permutations");
    mkdir(ui);//  w w  w  . j av a2s  .c om
    p.createNewFile();
    p.deleteOnExit();

    app.addFilter(new FilterHolder(new Filter() {
        private final boolean gwtuiRecompile = System.getProperty("gerrit.disable-gwtui-recompile") == null;
        private final UserAgentRule rule = new UserAgentRule();
        private final Set<String> uaInitialized = new HashSet<>();
        private String lastTarget;
        private long lastTime;

        @Override
        public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            String pkg = "gerrit-gwtui";
            String target = "ui_" + rule.select((HttpServletRequest) request);
            if (gwtuiRecompile || !uaInitialized.contains(target)) {
                String rule = "//" + pkg + ":" + target;
                // TODO(davido): instead of assuming specific Buck's internal
                // target directory for gwt_binary() artifacts, ask Buck for
                // the location of user agent permutation GWT zip, e. g.:
                // $ buck targets --show_output //gerrit-gwtui:ui_safari \
                //    | awk '{print $2}'
                String child = String.format("%s/__gwt_binary_%s__", pkg, target);
                File zip = new File(new File(gen, child), target + ".zip");

                synchronized (this) {
                    try {
                        build(root, gen, rule);
                    } catch (BuildFailureException e) {
                        displayFailure(rule, e.why, (HttpServletResponse) res);
                        return;
                    }

                    if (!target.equals(lastTarget) || lastTime != zip.lastModified()) {
                        lastTarget = target;
                        lastTime = zip.lastModified();
                        unpack(zip, dstwar);
                    }
                }
                uaInitialized.add(target);
            }
            chain.doFilter(request, res);
        }

        private void displayFailure(String rule, byte[] why, HttpServletResponse res) throws IOException {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            res.setContentType("text/html");
            res.setCharacterEncoding(Charsets.UTF_8.name());
            CacheHeaders.setNotCacheable(res);

            Escaper html = HtmlEscapers.htmlEscaper();
            try (PrintWriter w = res.getWriter()) {
                w.write("<html><title>BUILD FAILED</title><body>");
                w.format("<h1>%s FAILED</h1>", html.escape(rule));
                w.write("<pre>");
                w.write(html.escape(RawParseUtils.decode(why)));
                w.write("</pre>");
                w.write("</body></html>");
            }
        }

        @Override
        public void init(FilterConfig config) {
        }

        @Override
        public void destroy() {
        }
    }), "/", EnumSet.of(DispatcherType.REQUEST));
    return Resource.newResource(dstwar.toURI());
}

From source file:com.google.gerrit.rules.RulesCache.java

License:Apache License

private String read(Project.NameKey project, ObjectId rulesId) throws CompileException {
    try (Repository git = gitMgr.openRepository(project)) {
        try {//from ww w . ja v  a  2 s  .c  o m
            ObjectLoader ldr = git.open(rulesId, Constants.OBJ_BLOB);
            byte[] raw = ldr.getCachedBytes(SRC_LIMIT);
            return RawParseUtils.decode(raw);
        } catch (LargeObjectException e) {
            throw new CompileException("rules of " + project + " are too large", e);
        } catch (RuntimeException | IOException e) {
            throw new CompileException("Cannot load rules of " + project, e);
        }
    } catch (IOException e) {
        throw new CompileException("Cannot open repository " + project, e);
    }
}

From source file:com.google.gerrit.server.git.LocalDiskRepositoryManager.java

License:Apache License

private String getProjectDescription(final Repository e) throws IOException {
    final File d = new File(e.getDirectory(), "description");

    String description;//w  w  w  . j a v a2  s .  co m
    try {
        description = RawParseUtils.decode(IO.readFully(d));
    } catch (FileNotFoundException err) {
        return null;
    }

    if (description != null) {
        description = description.trim();
        if (description.isEmpty()) {
            description = null;
        }
        if (UNNAMED.equals(description)) {
            description = null;
        }
    }
    return description;
}

From source file:com.google.gerrit.server.git.ProjectConfigTest.java

License:Apache License

private String text(RevCommit rev, String path) throws Exception {
    RevObject blob = util.get(rev.getTree(), path);
    byte[] data = db.open(blob).getCachedBytes(Integer.MAX_VALUE);
    return RawParseUtils.decode(data);
}

From source file:com.google.gerrit.server.git.VersionedMetaData.java

License:Apache License

protected String readUTF8(String fileName) throws IOException {
    byte[] raw = readFile(fileName);
    return raw.length != 0 ? RawParseUtils.decode(raw) : "";
}

From source file:com.google.gerrit.server.mail.ChangeEmail.java

License:Apache License

/** Show patch set as unified difference. */
public String getUnifiedDiff() {
    PatchList patchList;//w  w  w  .j a v a  2s.  c  o m
    try {
        patchList = getPatchList();
        if (patchList.getOldId() == null) {
            // Octopus merges are not well supported for diff output by Gerrit.
            // Currently these always have a null oldId in the PatchList.
            return "[Octopus merge; cannot be formatted as a diff.]\n";
        }
    } catch (PatchListNotAvailableException e) {
        log.error("Cannot format patch", e);
        return "";
    }

    int maxSize = args.settings.maximumDiffSize;
    TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, maxSize), maxSize);
    try (DiffFormatter fmt = new DiffFormatter(buf)) {
        try (Repository git = args.server.openRepository(change.getProject())) {
            try {
                fmt.setRepository(git);
                fmt.setDetectRenames(true);
                fmt.format(patchList.getOldId(), patchList.getNewId());
                return RawParseUtils.decode(buf.toByteArray());
            } catch (IOException e) {
                if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
                    return "";
                }
                log.error("Cannot format patch", e);
                return "";
            }
        } catch (IOException e) {
            log.error("Cannot open repository to format patch", e);
            return "";
        }
    }
}

From source file:com.google.gerrit.server.mail.NewChangeSender.java

License:Apache License

/** Show patch set as unified difference.  */
public String getUnifiedDiff() {
    PatchList patchList;//from  w w w.ja v  a 2s . c  o  m
    try {
        patchList = getPatchList();
        if (patchList.getOldId() == null) {
            // Octopus merges are not well supported for diff output by Gerrit.
            // Currently these always have a null oldId in the PatchList.
            return "";
        }
    } catch (PatchListNotAvailableException e) {
        log.error("Cannot format patch", e);
        return "";
    }

    TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(args.settings.maximumDiffSize);
    DiffFormatter fmt = new DiffFormatter(buf);
    Repository git;
    try {
        git = args.server.openRepository(change.getProject());
    } catch (IOException e) {
        log.error("Cannot open repository to format patch", e);
        return "";
    }
    try {
        fmt.setRepository(git);
        fmt.setDetectRenames(true);
        fmt.format(patchList.getOldId(), patchList.getNewId());
        return RawParseUtils.decode(buf.toByteArray());
    } catch (IOException e) {
        if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
            return "";
        }
        log.error("Cannot format patch", e);
        return "";
    } finally {
        fmt.release();
        git.close();
    }
}