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

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

Introduction

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

Prototype

public <T extends ObjectId> AsyncObjectLoaderQueue<T> open(Iterable<T> objectIds, final boolean reportMissing) 

Source Link

Document

Asynchronous object opening.

Usage

From source file:com.google.gerrit.server.notedb.CommentsInNotesUtil.java

License:Apache License

public static NoteMap parseCommentsFromNotes(Repository repo, String refName, RevWalk walk, Change.Id changeId,
        Multimap<RevId, PatchLineComment> comments, Status status) throws IOException, ConfigInvalidException {
    Ref ref = repo.getRefDatabase().exactRef(refName);
    if (ref == null) {
        return null;
    }/*from   w  w w  .  j  a  v  a 2s  .co  m*/

    ObjectReader reader = walk.getObjectReader();
    RevCommit commit = walk.parseCommit(ref.getObjectId());
    NoteMap noteMap = NoteMap.read(reader, commit);

    for (Note note : noteMap) {
        byte[] bytes = reader.open(note.getData(), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
        List<PatchLineComment> result = parseNote(bytes, changeId, status);
        if (result == null || result.isEmpty()) {
            continue;
        }
        comments.putAll(new RevId(note.name()), result);
    }
    return noteMap;
}

From source file:com.google.gerrit.server.notedb.RevisionNote.java

License:Apache License

RevisionNote(ChangeNoteUtil noteUtil, Change.Id changeId, ObjectReader reader, ObjectId noteId,
        boolean draftsOnly) throws ConfigInvalidException, IOException {
    raw = reader.open(noteId, OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    MutableInteger p = new MutableInteger();
    trimLeadingEmptyLines(raw, p);/*from  w w w.  j a  va2  s.co m*/
    if (!draftsOnly) {
        pushCert = parsePushCert(changeId, raw, p);
        trimLeadingEmptyLines(raw, p);
    } else {
        pushCert = null;
    }
    PatchLineComment.Status status = draftsOnly ? PatchLineComment.Status.DRAFT
            : PatchLineComment.Status.PUBLISHED;
    comments = ImmutableList.copyOf(noteUtil.parseNote(raw, p, changeId, status));
}

From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

private static RawText getRawText(ObjectId id, ObjectReader reader) throws IOException {
    if (id.equals(ObjectId.zeroId())) {
        return new RawText(new byte[] {});
    }/*w  ww.  j  a  v a 2 s  . com*/
    return new RawText(reader.open(id, OBJ_BLOB).getCachedBytes());
}

From source file:com.pramati.gerrit.plugin.helpers.GetFileFromRepo.java

License:Apache License

/**
 * returns the File Stream from the gerrit repository. returns "null" if the
 * given file not found in the repository.<br>
 * patchStr should like in given format::"changeid/patchsetID/filename" <br>
 * eg: 1/2/readme.md//from   w  w  w .ja va  2s . co m
 * 
 * @param patchStr
 * @return
 * @throws IOException
 */
public static BufferedInputStream doGetFile(String patchStr) throws IOException {
    final Patch.Key patchKey;
    final Change.Id changeId;
    final Project project;
    final PatchSet patchSet;
    final Repository repo;
    final ReviewDb db;
    final ChangeControl control;
    try {
        patchKey = Patch.Key.parse(patchStr);
    } catch (NumberFormatException e) {
        return null;
    }
    changeId = patchKey.getParentKey().getParentKey();

    try {
        db = requestDb.get();
        control = changeControl.validateFor(changeId);

        project = control.getProject();
        patchSet = db.patchSets().get(patchKey.getParentKey());
        if (patchSet == null) {
            return null;
            // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (NoSuchChangeException e) {
        // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (OrmException e) {
        // getServletContext().log("Cannot query database", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    try {
        repo = repoManager.openRepository(project.getNameKey());
    } catch (RepositoryNotFoundException e) {
        // getServletContext().log("Cannot open repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    final ObjectLoader blobLoader;
    final RevCommit fromCommit;
    final String path = patchKey.getFileName();
    try {
        final ObjectReader reader = repo.newObjectReader();
        try {
            final RevWalk rw = new RevWalk(reader);
            final RevCommit c;
            final TreeWalk tw;

            c = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
            fromCommit = c;

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

            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 null;
            }
        } finally {
            reader.release();
        }
    } catch (IOException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } catch (RuntimeException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } finally {
        repo.close();
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    blobLoader.copyTo(out);
    byte[] b = out.toByteArray();
    BufferedInputStream br = new BufferedInputStream(new ByteArrayInputStream(b));
    return br;
}

From source file:gerrit.PRED_commit_edits_2.java

License:Apache License

private Text load(final ObjectId tree, final String path, final ObjectReader reader)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    if (path == null) {
        return Text.EMPTY;
    }/*w w w . j  a v  a  2 s  .  co m*/
    final TreeWalk tw = TreeWalk.forPath(reader, path, tree);
    if (tw == null) {
        return Text.EMPTY;
    }
    if (tw.getFileMode(0).getObjectType() != Constants.OBJ_BLOB) {
        return Text.EMPTY;
    }
    return new Text(reader.open(tw.getObjectId(0), Constants.OBJ_BLOB));
}

From source file:org.eclipse.egit.ui.internal.history.FileDiff.java

License:Open Source License

private RawText getRawText(ObjectId id, ObjectReader reader) throws IOException {
    if (id.equals(ObjectId.zeroId()))
        return new RawText(new byte[] {});
    ObjectLoader ldr = reader.open(id, Constants.OBJ_BLOB);
    return new RawText(ldr.getCachedBytes(Integer.MAX_VALUE));
}

From source file:org.gitective.core.BlobUtils.java

License:Open Source License

/**
 * Get the contents of the the blob with the given id as a byte array.
 *
 * @param reader//from  ww  w.j  a  v a 2  s.  c o  m
 * @param id
 * @return blob bytes
 */
protected static byte[] getBytes(final ObjectReader reader, final ObjectId id) {
    try {
        return reader.open(id, OBJ_BLOB).getCachedBytes(MAX_VALUE);
    } catch (IOException e) {
        throw new GitException(e, null);
    }
}

From source file:org.kuali.student.git.model.ExternalModuleUtils.java

License:Educational Community License

/**
 * Look at the given commit and if there is a fusion-maven-plugin.dat in the root of its tree then load and return the contents.
 * /*  w ww.  ja  va 2s  . c  om*/
 * @param commit
 * @return the ExternalsModuleInfo's found, an empty list if none are found.
 * @throws IOException 
 * @throws CorruptObjectException 
 * @throws IncorrectObjectTypeException 
 * @throws MissingObjectException 
 */
public static List<ExternalModuleInfo> findExternalModulesForCommit(Repository repo, RevCommit commit)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {

    List<ExternalModuleInfo> modules = new LinkedList<ExternalModuleInfo>();

    GitTreeProcessor treeProcessor = new GitTreeProcessor(repo);

    GitTreeNodeData tree = treeProcessor.extractExistingTreeData(commit.getTree().getId(), "");

    ObjectId fusionDataBlobId = tree.find(repo, "fusion-maven-plugin.dat");

    if (fusionDataBlobId == null)
        return modules;

    ObjectReader reader = repo.newObjectReader();

    modules = ExternalModuleUtils
            .extractFusionMavenPluginData(reader.open(fusionDataBlobId, Constants.OBJ_BLOB).openStream());

    reader.release();

    return modules;

}

From source file:org.kuali.student.git.model.NodeProcessor.java

License:Educational Community License

@Override
public GitBranchData getBranchData(String branchName, long revision) {

    GitBranchData data = knownBranchMap.get(branchName);

    if (data == null) {
        data = new GitBranchData(repo, branchName, revision, revisionMapper, treeProcessor,
                treeProcessor.getNodeInitializer());

        /*//from w w  w. ja va 2  s  .com
         * Notice if there is already a branch of the same name (it should be the parent of this new commit).
         */
        try {

            ObjectId parentId = revisionMapper.getRevisionBranchHead((revision - 1), data.getBranchName());

            if (parentId != null) {
                data.setParentId(parentId);

                /*
                 * Check for the existense of a fusion-maven-plugin.dat file in the root of this commit load in the externals if they exist.
                 */
                GitTreeData parentTree = treeProcessor.extractExistingTreeDataFromCommit(parentId);

                ObjectId fusionData = parentTree.find(repo, "fusion-maven-plugin.dat");

                if (fusionData != null) {

                    ObjectReader reader = repo.newObjectReader();

                    List<ExternalModuleInfo> existingExternals = ExternalModuleUtils
                            .extractFusionMavenPluginData(
                                    reader.open(fusionData, Constants.OBJ_BLOB).openStream());

                    data.setExternals(existingExternals);

                }
            }

        } catch (Exception e) {
            log.debug("no existing reference for branch = " + data.getBranchName());
        }

        knownBranchMap.put(branchName, data);
    }

    return data;
}

From source file:playRepository.GitRepository.java

License:Apache License

private static List<FileDiff> getFileDiffs(final Repository repositoryA, Repository repositoryB,
        ObjectId commitA, ObjectId commitB) throws IOException {
    class MultipleRepositoryObjectReader extends ObjectReader {
        Collection<ObjectReader> readers = new HashSet<>();

        @Override/*www.j  ava 2 s .com*/
        public ObjectReader newReader() {
            return new MultipleRepositoryObjectReader(readers);
        }

        public MultipleRepositoryObjectReader(Collection<ObjectReader> readers) {
            this.readers = readers;
        }

        public MultipleRepositoryObjectReader() {
            this.readers = new HashSet<>();
        }

        public void addObjectReader(ObjectReader reader) {
            this.readers.add(reader);
        }

        @Override
        public Collection<ObjectId> resolve(AbbreviatedObjectId id) throws IOException {
            Set<ObjectId> result = new HashSet<>();
            for (ObjectReader reader : readers) {
                result.addAll(reader.resolve(id));
            }
            return result;
        }

        @Override
        public ObjectLoader open(AnyObjectId objectId, int typeHint) throws IOException {
            for (ObjectReader reader : readers) {
                if (reader.has(objectId, typeHint)) {
                    return reader.open(objectId, typeHint);
                }
            }
            return null;
        }

        @Override
        public Set<ObjectId> getShallowCommits() throws IOException {
            Set<ObjectId> union = new HashSet<>();
            for (ObjectReader reader : readers) {
                union.addAll(reader.getShallowCommits());
            }
            return union;
        }
    }

    final MultipleRepositoryObjectReader reader = new MultipleRepositoryObjectReader();
    reader.addObjectReader(repositoryA.newObjectReader());
    reader.addObjectReader(repositoryB.newObjectReader());

    @SuppressWarnings("rawtypes")
    Repository fakeRepo = new Repository(new BaseRepositoryBuilder()) {

        @Override
        public void create(boolean bare) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public ObjectDatabase getObjectDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public RefDatabase getRefDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public StoredConfig getConfig() {
            return repositoryA.getConfig();
        }

        @Override
        public void scanForRepoChanges() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void notifyIndexChanged() {
            throw new UnsupportedOperationException();
        }

        @Override
        public ReflogReader getReflogReader(String refName) throws IOException {
            throw new UnsupportedOperationException();
        }

        public ObjectReader newObjectReader() {
            return reader;
        }
    };

    DiffFormatter formatter = new DiffFormatter(NullOutputStream.INSTANCE);
    formatter.setRepository(fakeRepo);
    formatter.setDetectRenames(true);

    AbstractTreeIterator treeParserA, treeParserB;
    RevTree treeA = null, treeB = null;

    if (commitA != null) {
        treeA = new RevWalk(repositoryA).parseTree(commitA);
        treeParserA = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserA).reset(reader, treeA);
    } else {
        treeParserA = new EmptyTreeIterator();
    }

    if (commitB != null) {
        treeB = new RevWalk(repositoryB).parseTree(commitB);
        treeParserB = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserB).reset(reader, treeB);
    } else {
        treeParserB = new EmptyTreeIterator();
    }

    List<FileDiff> result = new ArrayList<>();
    int size = 0;
    int lines = 0;

    for (DiffEntry diff : formatter.scan(treeParserA, treeParserB)) {
        FileDiff fileDiff = new FileDiff();
        fileDiff.commitA = commitA != null ? commitA.getName() : null;
        fileDiff.commitB = commitB != null ? commitB.getName() : null;

        fileDiff.changeType = diff.getChangeType();

        fileDiff.oldMode = diff.getOldMode();
        fileDiff.newMode = diff.getNewMode();

        String pathA = diff.getPath(DiffEntry.Side.OLD);
        String pathB = diff.getPath(DiffEntry.Side.NEW);

        byte[] rawA = null;
        if (treeA != null && Arrays.asList(DELETE, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t1 = TreeWalk.forPath(repositoryA, pathA, treeA);
            ObjectId blobA = t1.getObjectId(0);
            fileDiff.pathA = pathA;

            try {
                rawA = repositoryA.open(blobA).getBytes();
                fileDiff.isBinaryA = RawText.isBinary(rawA);
                fileDiff.a = fileDiff.isBinaryA ? null : new RawText(rawA);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.A_SIZE_EXCEEDED);
            }
        }

        byte[] rawB = null;
        if (treeB != null && Arrays.asList(ADD, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t2 = TreeWalk.forPath(repositoryB, pathB, treeB);
            ObjectId blobB = t2.getObjectId(0);
            fileDiff.pathB = pathB;

            try {
                rawB = repositoryB.open(blobB).getBytes();
                fileDiff.isBinaryB = RawText.isBinary(rawB);
                fileDiff.b = fileDiff.isBinaryB ? null : new RawText(rawB);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.B_SIZE_EXCEEDED);
            }
        }

        if (size > DIFF_SIZE_LIMIT || lines > DIFF_LINE_LIMIT) {
            fileDiff.addError(FileDiff.Error.OTHERS_SIZE_EXCEEDED);
            result.add(fileDiff);
            continue;
        }

        // Get diff if necessary
        if (fileDiff.a != null && fileDiff.b != null && !(fileDiff.isBinaryA || fileDiff.isBinaryB)
                && Arrays.asList(MODIFY, RENAME).contains(diff.getChangeType())) {
            DiffAlgorithm diffAlgorithm = DiffAlgorithm
                    .getAlgorithm(repositoryB.getConfig().getEnum(ConfigConstants.CONFIG_DIFF_SECTION, null,
                            ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm.HISTOGRAM));
            fileDiff.editList = diffAlgorithm.diff(RawTextComparator.DEFAULT, fileDiff.a, fileDiff.b);
            size += fileDiff.getHunks().size;
            lines += fileDiff.getHunks().lines;
        }

        // update lines and sizes
        if (fileDiff.b != null && !fileDiff.isBinaryB && diff.getChangeType().equals(ADD)) {
            lines += fileDiff.b.size();
            size += rawB.length;
        }

        // update lines and sizes
        if (fileDiff.a != null && !fileDiff.isBinaryA && diff.getChangeType().equals(DELETE)) {
            lines += fileDiff.a.size();
            size += rawA.length;
        }

        // Stop if exceeds the limit for total number of files
        if (result.size() > DIFF_FILE_LIMIT) {
            break;
        }

        result.add(fileDiff);
    }

    return result;
}