Example usage for org.eclipse.jgit.lib ObjectLoader getCachedBytes

List of usage examples for org.eclipse.jgit.lib ObjectLoader getCachedBytes

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectLoader getCachedBytes.

Prototype

public abstract byte[] getCachedBytes() throws LargeObjectException;

Source Link

Document

Obtain a reference to the (possibly cached) bytes of this object.

Usage

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

License:Apache License

/**
 * Retrieves the raw byte content of a file in the specified tree.
 *
 * @param repository/*from ww w.jav a  2s  .  c om*/
 * @param tree
 *            if null, the RevTree from HEAD is assumed.
 * @param path
 * @return content as a byte []
 */
public static byte[] getByteContent(Repository repository, RevTree tree, final String path,
        boolean throwError) {
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
    byte[] content = null;
    try {
        if (tree == null) {
            ObjectId object = getDefaultBranch(repository);
            if (object == null)
                return null;
            RevCommit commit = rw.parseCommit(object);
            tree = commit.getTree();
        }
        tw.reset(tree);
        while (tw.next()) {
            if (tw.isSubtree() && !path.equals(tw.getPathString())) {
                tw.enterSubtree();
                continue;
            }
            ObjectId entid = tw.getObjectId(0);
            FileMode entmode = tw.getFileMode(0);
            if (entmode != FileMode.GITLINK) {
                ObjectLoader ldr = repository.open(entid, Constants.OBJ_BLOB);
                content = ldr.getCachedBytes();
            }
        }
    } catch (Throwable t) {
        if (throwError) {
            error(t, repository, "{0} can't find {1} in tree {2}", path, tree.name());
        }
    } finally {
        rw.dispose();
        tw.close();
    }
    return content;
}

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

License:Apache License

/**
 * Gets the raw byte content of the specified blob object.
 *
 * @param repository/*from  w ww .j  ava2  s.  c  o  m*/
 * @param objectId
 * @return byte [] blob content
 */
public static byte[] getByteContent(Repository repository, String objectId) {
    RevWalk rw = new RevWalk(repository);
    byte[] content = null;
    try {
        RevBlob blob = rw.lookupBlob(ObjectId.fromString(objectId));
        ObjectLoader ldr = repository.open(blob.getId(), Constants.OBJ_BLOB);
        content = ldr.getCachedBytes();
    } catch (Throwable t) {
        error(t, repository, "{0} can't find blob {1}", objectId);
    } finally {
        rw.dispose();
    }
    return content;
}

From source file:com.google.gerrit.acceptance.rest.change.ConfigChangeIT.java

License:Apache License

private Config readProjectConfig() throws Exception {
    RevWalk rw = testRepo.getRevWalk();// w ww  .jav  a 2s. co m
    RevTree tree = rw.parseTree(testRepo.getRepository().resolve("HEAD"));
    RevObject obj = rw.parseAny(testRepo.get(tree, "project.config"));
    ObjectLoader loader = rw.getObjectReader().open(obj);
    String text = new String(loader.getCachedBytes(), UTF_8);
    Config cfg = new Config();
    cfg.fromText(text);
    return cfg;
}

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

License:Apache License

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException {
    String keyStr = req.getPathInfo();

    // We shouldn't have to do this extra decode pass, but somehow we
    // are now receiving our "^1" suffix as "%5E1", which confuses us
    // downstream. Other times we get our embedded "," as "%2C", which
    // is equally bad. And yet when these happen a "%2F" is left as-is,
    // rather than escaped as "%252F", which makes me feel really really
    // uncomfortable with a blind decode right here.
    ///*  ww  w. j  ava  2  s . co m*/
    keyStr = Url.decode(keyStr);

    if (!keyStr.startsWith("/")) {
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    keyStr = keyStr.substring(1);

    final Patch.Key patchKey;
    final int side;
    {
        final int c = keyStr.lastIndexOf('^');
        if (c == 0) {
            rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (c < 0) {
            side = 0;

        } else {
            try {
                side = Integer.parseInt(keyStr.substring(c + 1));
                keyStr = keyStr.substring(0, c);
            } catch (NumberFormatException e) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        try {
            patchKey = Patch.Key.parse(keyStr);
        } catch (NumberFormatException e) {
            rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    final Change.Id changeId = patchKey.getParentKey().getParentKey();
    final Project project;
    final String revision;
    try {
        final ReviewDb db = requestDb.get();
        final ChangeControl control = changeControl.validateFor(changeId, userProvider.get());

        project = control.getProject();

        if (patchKey.getParentKey().get() == 0) {
            // change edit
            try {
                Optional<ChangeEdit> edit = changeEditUtil.byChange(control.getChange());
                if (edit.isPresent()) {
                    revision = edit.get().getRevision().get();
                } else {
                    rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            } catch (AuthException e) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        } else {
            PatchSet patchSet = db.patchSets().get(patchKey.getParentKey());
            if (patchSet == null) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            revision = patchSet.getRevision().get();
        }
    } catch (NoSuchChangeException e) {
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (OrmException e) {
        getServletContext().log("Cannot query database", e);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    ObjectLoader blobLoader;
    RevCommit fromCommit;
    String suffix;
    String path = patchKey.getFileName();
    try (Repository repo = repoManager.openRepository(project.getNameKey())) {
        try (ObjectReader reader = repo.newObjectReader(); RevWalk rw = new RevWalk(reader)) {
            RevCommit c;

            c = rw.parseCommit(ObjectId.fromString(revision));
            if (side == 0) {
                fromCommit = c;
                suffix = "new";

            } else if (1 <= side && side - 1 < c.getParentCount()) {
                fromCommit = rw.parseCommit(c.getParent(side - 1));
                if (c.getParentCount() == 1) {
                    suffix = "old";
                } else {
                    suffix = "old" + side;
                }

            } else {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            try (TreeWalk tw = TreeWalk.forPath(reader, path, fromCommit.getTree())) {
                if (tw == null) {
                    rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }

                if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) {
                    blobLoader = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB);

                } else {
                    rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return;
                }
            }
        }
    } catch (RepositoryNotFoundException e) {
        getServletContext().log("Cannot open repository", e);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (IOException | RuntimeException e) {
        getServletContext().log("Cannot read repository", e);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    final byte[] raw = blobLoader.isLarge() ? null : blobLoader.getCachedBytes();
    final long when = fromCommit.getCommitTime() * 1000L;

    rsp.setDateHeader("Last-Modified", when);
    CacheHeaders.setNotCacheable(rsp);

    try (OutputStream out = openOutputStream(req, rsp, blobLoader, fromCommit, when, path, suffix, raw)) {
        if (raw != null) {
            out.write(raw);
        } else {
            blobLoader.copyTo(out);
        }
    }
}

From source file:com.googlesource.gerrit.plugins.findowners.FindOwnersIT.java

License:Apache License

private org.eclipse.jgit.lib.Config readProjectConfig() throws Exception {
    git().fetch().setRefSpecs(new RefSpec(REFS_CONFIG + ":" + REFS_CONFIG)).call();
    testRepo.reset(RefNames.REFS_CONFIG);
    RevWalk rw = testRepo.getRevWalk();// ww w.  j  ava  2  s. c o m
    RevTree tree = rw.parseTree(testRepo.getRepository().resolve("HEAD"));

    try (TreeWalk treeWalk = new TreeWalk(rw.getObjectReader())) {
        treeWalk.setFilter(PathFilterGroup.createFromStrings("project.config"));
        treeWalk.reset(tree);
        boolean hasProjectConfig = treeWalk.next();
        if (!hasProjectConfig) {
            return new org.eclipse.jgit.lib.Config();
        }
    }

    RevObject obj = rw.parseAny(testRepo.get(tree, "project.config"));
    ObjectLoader loader = rw.getObjectReader().open(obj);
    String text = new String(loader.getCachedBytes(), UTF_8);
    org.eclipse.jgit.lib.Config cfg = new org.eclipse.jgit.lib.Config();
    cfg.fromText(text);
    return cfg;
}

From source file:it.com.atlassian.labs.speakeasy.util.jgit.WalkFetchConnection.java

License:Eclipse Distribution License

private void verifyAndInsertLooseObject(final AnyObjectId id, final byte[] compressed) throws IOException {
    final ObjectLoader uol;
    try {//from  ww w  . j a va2 s.c o m
        uol = UnpackedObject.parse(compressed, id);
    } catch (CorruptObjectException parsingError) {
        // Some HTTP servers send back a "200 OK" status with an HTML
        // page that explains the requested file could not be found.
        // These servers are most certainly misconfigured, but many
        // of them exist in the world, and many of those are hosting
        // Git repositories.
        //
        // Since an HTML page is unlikely to hash to one of our loose
        // objects we treat this condition as a FileNotFoundException
        // and attempt to recover by getting the object from another
        // source.
        //
        final FileNotFoundException e;
        e = new FileNotFoundException(id.name());
        e.initCause(parsingError);
        throw e;
    }

    final int type = uol.getType();
    final byte[] raw = uol.getCachedBytes();
    if (objCheck != null) {
        try {
            objCheck.check(type, raw);
        } catch (CorruptObjectException e) {
            throw new TransportException(MessageFormat.format(JGitText.get().transportExceptionInvalid,
                    Constants.typeString(type), id.name(), e.getMessage()));
        }
    }

    ObjectId act = inserter.insert(type, raw);
    if (!AnyObjectId.equals(id, act)) {
        throw new TransportException(MessageFormat.format(JGitText.get().incorrectHashFor, id.name(),
                act.name(), Constants.typeString(type), compressed.length));
    }
    inserter.flush();
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.patch.LoadContentAction.java

License:Apache License

@NotNull
private InputStream openContentStream(@NotNull final ObjectLoader loader) throws IOException {
    return loader.isLarge() ? loader.openStream() : new ByteArrayInputStream(loader.getCachedBytes());
}

From source file:org.eclipse.egit.ui.internal.commit.RepositoryCommitNote.java

License:Open Source License

/**
 * Get note text. This method open and read the note blob each time it is
 * called.//w w  w  . j  av  a2 s.  c  o m
 *
 * @return note text or empty string if lookup failed.
 */
public String getNoteText() {
    try {
        ObjectLoader loader = commit.getRepository().open(note.getData(), Constants.OBJ_BLOB);
        byte[] contents;
        if (loader.isLarge())
            contents = IO.readWholeStream(loader.openStream(), (int) loader.getSize()).array();
        else
            contents = loader.getCachedBytes();
        return new String(contents);
    } catch (IOException e) {
        Activator.logError("Error loading note text", e); //$NON-NLS-1$
    }
    return ""; //$NON-NLS-1$
}

From source file:org.openflexo.hannah.IterativeFileGenerator.java

License:Open Source License

private RawText getRawText(ObjectId id) throws IOException {
    if (ObjectId.zeroId().equals(id)) {
        return RawText.EMPTY_TEXT;
    }//from   w w  w. j  a  v a  2s .c o m
    final ObjectLoader loader = git.getRepository().open(id, Constants.OBJ_BLOB);
    return new RawText(loader.getCachedBytes());
}

From source file:playRepository.BareRepository.java

License:Apache License

/**
 * read project README file with readme filename filter from repository
 *
 * @param project/*  w w  w. j  ava  2 s . c o m*/
 * @return
 */
public static String readREADME(Project project) {
    Repository repository;
    ObjectLoader loader = null;
    repository = getRepository(project);
    try {
        loader = repository.open(getFirstFoundREADMEfileObjectId(repository));
    } catch (IOException e) {
        e.printStackTrace();
        play.Logger.error(e.getMessage());
    }
    if (loader == null) {
        return null;
    }
    return new String(loader.getCachedBytes(), utils.Config.getCharset());
}