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

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

Introduction

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

Prototype

public abstract ObjectStream openStream() throws MissingObjectException, IOException;

Source Link

Document

Obtain an input stream to read this object's data.

Usage

From source file:au.id.soundadvice.systemdesign.versioning.jgit.GitVersionControl.java

License:Open Source License

/**
 * Find the tree that contains the required identity.
 *
 * @return The ObjectId of the tree (directory) that contains the matching
 * identity within the supplied hierarchy.
 *///from  w  w  w  . ja v  a 2 s.co m
private ObjectId findMatchingIdentity(IdentityValidator identityValidator, ObjectId tree) throws IOException {
    TreeWalk treeWalk = new TreeWalk(repo.getRepository());
    try {
        treeWalk.setRecursive(false);
        treeWalk.addTree(tree);

        while (treeWalk.next()) {
            if (treeWalk.isSubtree()) {
                ObjectId candidateId = findMatchingIdentity(identityValidator, treeWalk.getObjectId(0));
                if (ObjectId.zeroId().equals(candidateId)) {
                    // Keep searching
                } else {
                    return candidateId;
                }
            } else if (identityValidator.getIdentityFileName().equals(treeWalk.getNameString())) {
                // Read the identity file
                ObjectLoader loader = repo.getRepository().open(treeWalk.getObjectId(0));
                ObjectStream stream = loader.openStream();
                InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
                if (identityValidator.isIdentityMatched(new BufferedReader(reader))) {
                    // We found it
                    return tree;
                }
            }
        }
        return ObjectId.zeroId();
    } finally {
        treeWalk.release();
    }
}

From source file:au.id.soundadvice.systemdesign.versioning.jgit.GitVersionControl.java

License:Open Source License

@Override
public Optional<BufferedReader> getBufferedReader(IdentityValidator identityValidator, String filename,
        Optional<VersionInfo> version) throws IOException {
    if (version.isPresent()) {
        Pair<String, ObjectId> diff = diffCache.get();
        if (!version.get().getId().equals(diff.getKey())) {
            // Grab the id of the commit we are trying to diff against
            ObjectId id = ObjectId.fromString(version.get().getId());
            RevWalk revWalk = new RevWalk(repo.getRepository());
            try {
                // Read the commit
                RevCommit commit = revWalk.parseCommit(id);
                ObjectId matchedDirectory = findMatchingIdentity(identityValidator, commit.getTree());
                diff = new Pair<>(version.get().getId(), matchedDirectory);
                diffCache.set(diff);/*  w  w  w  . j av a  2 s .  com*/
            } finally {
                revWalk.release();
            }
        }

        if (ObjectId.zeroId().equals(diff.getValue())) {
            // No such tree
            return Optional.empty();
        } else {
            // Find the file in this tree
            TreeWalk treeWalk = new TreeWalk(repo.getRepository());
            try {
                treeWalk.setRecursive(false);
                treeWalk.addTree(diff.getValue());

                while (treeWalk.next()) {
                    if (filename.equals(treeWalk.getNameString())) {
                        // Read the file
                        ObjectLoader loader = repo.getRepository().open(treeWalk.getObjectId(0));
                        ObjectStream stream = loader.openStream();
                        InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
                        return Optional.of(new BufferedReader(reader));
                    }
                }
                // No such file
                return Optional.empty();
            } finally {
                treeWalk.release();
            }
        }
    } else {
        Path path = identityValidator.getDirectoryPath().resolve(filename);
        if (Files.exists(path)) {
            return Optional.of(Files.newBufferedReader(path));
        } else {
            return Optional.empty();
        }
    }
}

From source file:com.bacoder.integration.test.TestEclipseJDTSources.java

License:Apache License

public void testEclipseJDTSources() throws InitializationException, URISyntaxException, ProcessingException {
    GitRepository repository = new GitRepository(
            new URI("http://git.eclipse.org/gitroot/jdt/eclipse.jdt.core.git"),
            new GitConfig().setBranch("R4_3_maintenance").setProgressMonitor(new TextProgressMonitor())
                    .setDirectory(gitRepository));
    repository.process(new GitEntryProcessor() {
        @Override/*from  w  w w . jav  a  2  s  .com*/
        public void process(GitEntry entry) throws Exception {
            String extension = Files.getFileExtension(entry.getPath());
            if ("java".equals(extension)) {
                LOG.info("Parsing: " + entry.getPath());
                ObjectLoader loader = entry.open();
                try {
                    parseJava(loader.openStream());
                } catch (Throwable t) {
                    boolean ignore = false;
                    for (String prefix : EXPECTED_FAILING_FILES) {
                        if (entry.getPath().startsWith(prefix)) {
                            ignore = true;
                        }
                    }
                    if (!ignore) {
                        throw t;
                    }
                }

            } else if ("properties".equals(extension)) {
                LOG.info("Parsing: " + entry.getPath());
                InputStream stream = entry.open().openStream();
                Properties properties = parseProperties(stream);

                java.util.Properties expected = new java.util.Properties();
                try {
                    expected.load(entry.open().openStream());
                } catch (Exception e) {
                    throw new RuntimeException("Unable to load properties" + e);
                }

                for (KeyValue keyValue : properties.getKeyValues()) {
                    String key = keyValue.getKey().getSanitizedText();
                    Assert.assertTrue(expected.containsKey(key),
                            String.format("Key \"%s\" does not exist in expected Java properties", key));
                    String value = keyValue.getValue().getSanitizedText();
                    Assert.assertEquals(value, expected.get(key),
                            String.format("Value \"%s\" does not match expected Java property value \"%s\"",
                                    value, expected.get(key)));
                }
            }
        }
    });
}

From source file:com.chungkwong.jgitgui.CommitTreeItem.java

License:Open Source License

@Override
public Node getContentPage() {
    RevCommit rev = (RevCommit) getValue();
    Repository repository = ((Git) getParent().getParent().getValue()).getRepository();
    SplitPane page = new SplitPane();
    page.setOrientation(Orientation.VERTICAL);
    StringBuilder buf = new StringBuilder();
    buf.append(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("PARENTS:"));
    for (int i = 0; i < rev.getParentCount(); i++)
        buf.append(rev.getParent(i)).append('\n');
    buf.append(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("MESSAGE:"));
    buf.append(rev.getFullMessage());//from  w  w w. ja  v a2s.  c o m
    TextArea msg = new TextArea(buf.toString());
    msg.setEditable(false);
    page.getItems().add(msg);
    SplitPane fileViewer = new SplitPane();
    fileViewer.setOrientation(Orientation.HORIZONTAL);
    TreeView tree = new TreeView(new TreeItem());
    tree.setShowRoot(false);
    TextArea content = new TextArea();
    content.setEditable(false);
    try (TreeWalk walk = new TreeWalk(repository)) {
        walk.addTree(rev.getTree());
        walk.setRecursive(true);
        LinkedList<TreeItem> items = new LinkedList<>();
        items.add(tree.getRoot());
        while (walk.next()) {
            TreeItem item = new FileTreeItem(walk.getObjectId(0), walk.getPathString());
            /*while(walk.getDepth()<items.size()-1)
               items.removeLast();
            if(walk.getDepth()>items.size()-1)
               items.addLast(item);*/
            items.getLast().getChildren().add(item);
        }
    } catch (Exception ex) {
        Logger.getLogger(CommitTreeItem.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
    tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue ov, Object t, Object t1) {
            if (t1 != null) {
                try {
                    ObjectLoader obj = repository.open(((FileTreeItem) t1).getId());
                    if (obj.getType() != Constants.OBJ_TREE) {
                        StringBuilder buf = new StringBuilder();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(obj.openStream(), rev.getEncoding()));
                        content.setText(in.lines().collect(Collectors.joining("\n")));
                    }
                } catch (Exception ex) {
                    Logger.getLogger(CommitTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                    Util.informUser(ex);
                }
            }
        }
    });
    fileViewer.getItems().add(tree);
    fileViewer.getItems().add(content);
    page.getItems().add(fileViewer);
    page.setDividerPositions(0.2, 0.8);
    return page;
}

From source file:com.gitblit.LuceneExecutor.java

License:Apache License

/**
 * This completely indexes the repository and will destroy any existing
 * index./*from  w w w .j a va 2 s.  c  om*/
 * 
 * @param repositoryName
 * @param repository
 * @return IndexResult
 */
public IndexResult reindex(RepositoryModel model, Repository repository) {
    IndexResult result = new IndexResult();
    if (!deleteIndex(model.name)) {
        return result;
    }
    try {
        String[] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
        FileBasedConfig config = getConfig(repository);
        Set<String> indexedCommits = new TreeSet<String>();
        IndexWriter writer = getIndexWriter(model.name);
        // build a quick lookup of tags
        Map<String, List<String>> tags = new HashMap<String, List<String>>();
        for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
            if (!tag.isAnnotatedTag()) {
                // skip non-annotated tags
                continue;
            }
            if (!tags.containsKey(tag.getObjectId())) {
                tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
            }
            tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
        }

        ObjectReader reader = repository.newObjectReader();

        // get the local branches
        List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);

        // sort them by most recently updated
        Collections.sort(branches, new Comparator<RefModel>() {
            @Override
            public int compare(RefModel ref1, RefModel ref2) {
                return ref2.getDate().compareTo(ref1.getDate());
            }
        });

        // reorder default branch to first position
        RefModel defaultBranch = null;
        ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
        for (RefModel branch : branches) {
            if (branch.getObjectId().equals(defaultBranchId)) {
                defaultBranch = branch;
                break;
            }
        }
        branches.remove(defaultBranch);
        branches.add(0, defaultBranch);

        // walk through each branch
        for (RefModel branch : branches) {

            boolean indexBranch = false;
            if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
                    && branch.equals(defaultBranch)) {
                // indexing "default" branch
                indexBranch = true;
            } else if (IssueUtils.GB_ISSUES.equals(branch)) {
                // skip the GB_ISSUES branch because it is indexed later
                // note: this is different than updateIndex
                indexBranch = false;
            } else {
                // normal explicit branch check
                indexBranch = model.indexedBranches.contains(branch.getName());
            }

            // if this branch is not specifically indexed then skip
            if (!indexBranch) {
                continue;
            }

            String branchName = branch.getName();
            RevWalk revWalk = new RevWalk(reader);
            RevCommit tip = revWalk.parseCommit(branch.getObjectId());
            String tipId = tip.getId().getName();

            String keyName = getBranchKey(branchName);
            config.setString(CONF_ALIAS, null, keyName, branchName);
            config.setString(CONF_BRANCH, null, keyName, tipId);

            // index the blob contents of the tree
            TreeWalk treeWalk = new TreeWalk(repository);
            treeWalk.addTree(tip.getTree());
            treeWalk.setRecursive(true);

            Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
            while (treeWalk.next()) {
                // ensure path is not in a submodule
                if (treeWalk.getFileMode(0) != FileMode.GITLINK) {
                    paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
                }
            }

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] tmp = new byte[32767];

            RevWalk commitWalk = new RevWalk(reader);
            commitWalk.markStart(tip);

            RevCommit commit;
            while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
                TreeWalk diffWalk = new TreeWalk(reader);
                int parentCount = commit.getParentCount();
                switch (parentCount) {
                case 0:
                    diffWalk.addTree(new EmptyTreeIterator());
                    break;
                case 1:
                    diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
                    break;
                default:
                    // skip merge commits
                    continue;
                }
                diffWalk.addTree(getTree(commitWalk, commit));
                diffWalk.setFilter(ANY_DIFF);
                diffWalk.setRecursive(true);
                while ((paths.size() > 0) && diffWalk.next()) {
                    String path = diffWalk.getPathString();
                    if (!paths.containsKey(path)) {
                        continue;
                    }

                    // remove path from set
                    ObjectId blobId = paths.remove(path);
                    result.blobCount++;

                    // index the blob metadata
                    String blobAuthor = getAuthor(commit);
                    String blobCommitter = getCommitter(commit);
                    String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE);

                    Document doc = new Document();
                    doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), Store.YES,
                            Index.NOT_ANALYZED_NO_NORMS));
                    doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_PATH, path, Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_DATE, blobDate, Store.YES, Index.NO));
                    doc.add(new Field(FIELD_AUTHOR, blobAuthor, Store.YES, Index.ANALYZED));
                    doc.add(new Field(FIELD_COMMITTER, blobCommitter, Store.YES, Index.ANALYZED));

                    // determine extension to compare to the extension
                    // blacklist
                    String ext = null;
                    String name = path.toLowerCase();
                    if (name.indexOf('.') > -1) {
                        ext = name.substring(name.lastIndexOf('.') + 1);
                    }

                    // index the blob content
                    if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
                        ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
                        InputStream in = ldr.openStream();
                        int n;
                        while ((n = in.read(tmp)) > 0) {
                            os.write(tmp, 0, n);
                        }
                        in.close();
                        byte[] content = os.toByteArray();
                        String str = StringUtils.decodeString(content, encodings);
                        doc.add(new Field(FIELD_CONTENT, str, Store.YES, Index.ANALYZED));
                        os.reset();
                    }

                    // add the blob to the index
                    writer.addDocument(doc);
                }
            }

            os.close();

            // index the tip commit object
            if (indexedCommits.add(tipId)) {
                Document doc = createDocument(tip, tags.get(tipId));
                doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
                writer.addDocument(doc);
                result.commitCount += 1;
                result.branchCount += 1;
            }

            // traverse the log and index the previous commit objects
            RevWalk historyWalk = new RevWalk(reader);
            historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
            RevCommit rev;
            while ((rev = historyWalk.next()) != null) {
                String hash = rev.getId().getName();
                if (indexedCommits.add(hash)) {
                    Document doc = createDocument(rev, tags.get(hash));
                    doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
                    writer.addDocument(doc);
                    result.commitCount += 1;
                }
            }
        }

        // finished
        reader.release();

        // this repository has a gb-issues branch, index all issues
        if (IssueUtils.getIssuesBranch(repository) != null) {
            List<IssueModel> issues = IssueUtils.getIssues(repository, null);
            if (issues.size() > 0) {
                result.branchCount += 1;
            }
            for (IssueModel issue : issues) {
                result.issueCount++;
                Document doc = createDocument(issue);
                writer.addDocument(doc);
            }
        }

        // commit all changes and reset the searcher
        config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION);
        config.save();
        writer.commit();
        resetIndexSearcher(model.name);
        result.success();
    } catch (Exception e) {
        logger.error("Exception while reindexing " + model.name, e);
    }
    return result;
}

From source file:com.gitblit.service.LuceneService.java

License:Apache License

/**
 * This completely indexes the repository and will destroy any existing
 * index.//from www .j av  a 2 s .c o m
 *
 * @param repositoryName
 * @param repository
 * @return IndexResult
 */
public IndexResult reindex(RepositoryModel model, Repository repository) {
    IndexResult result = new IndexResult();
    if (!deleteIndex(model.name)) {
        return result;
    }
    try {
        String[] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
        FileBasedConfig config = getConfig(repository);
        Set<String> indexedCommits = new TreeSet<String>();
        IndexWriter writer = getIndexWriter(model.name);
        // build a quick lookup of tags
        Map<String, List<String>> tags = new HashMap<String, List<String>>();
        for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
            if (!tag.isAnnotatedTag()) {
                // skip non-annotated tags
                continue;
            }
            if (!tags.containsKey(tag.getReferencedObjectId().getName())) {
                tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
            }
            tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
        }

        ObjectReader reader = repository.newObjectReader();

        // get the local branches
        List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);

        // sort them by most recently updated
        Collections.sort(branches, new Comparator<RefModel>() {
            @Override
            public int compare(RefModel ref1, RefModel ref2) {
                return ref2.getDate().compareTo(ref1.getDate());
            }
        });

        // reorder default branch to first position
        RefModel defaultBranch = null;
        ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
        for (RefModel branch : branches) {
            if (branch.getObjectId().equals(defaultBranchId)) {
                defaultBranch = branch;
                break;
            }
        }
        branches.remove(defaultBranch);
        branches.add(0, defaultBranch);

        // walk through each branch
        for (RefModel branch : branches) {

            boolean indexBranch = false;
            if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
                    && branch.equals(defaultBranch)) {
                // indexing "default" branch
                indexBranch = true;
            } else if (branch.getName().startsWith(com.gitblit.Constants.R_META)) {
                // skip internal meta branches
                indexBranch = false;
            } else {
                // normal explicit branch check
                indexBranch = model.indexedBranches.contains(branch.getName());
            }

            // if this branch is not specifically indexed then skip
            if (!indexBranch) {
                continue;
            }

            String branchName = branch.getName();
            RevWalk revWalk = new RevWalk(reader);
            RevCommit tip = revWalk.parseCommit(branch.getObjectId());
            String tipId = tip.getId().getName();

            String keyName = getBranchKey(branchName);
            config.setString(CONF_ALIAS, null, keyName, branchName);
            config.setString(CONF_BRANCH, null, keyName, tipId);

            // index the blob contents of the tree
            TreeWalk treeWalk = new TreeWalk(repository);
            treeWalk.addTree(tip.getTree());
            treeWalk.setRecursive(true);

            Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
            while (treeWalk.next()) {
                // ensure path is not in a submodule
                if (treeWalk.getFileMode(0) != FileMode.GITLINK) {
                    paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
                }
            }

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] tmp = new byte[32767];

            RevWalk commitWalk = new RevWalk(reader);
            commitWalk.markStart(tip);

            RevCommit commit;
            while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
                TreeWalk diffWalk = new TreeWalk(reader);
                int parentCount = commit.getParentCount();
                switch (parentCount) {
                case 0:
                    diffWalk.addTree(new EmptyTreeIterator());
                    break;
                case 1:
                    diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
                    break;
                default:
                    // skip merge commits
                    continue;
                }
                diffWalk.addTree(getTree(commitWalk, commit));
                diffWalk.setFilter(ANY_DIFF);
                diffWalk.setRecursive(true);
                while ((paths.size() > 0) && diffWalk.next()) {
                    String path = diffWalk.getPathString();
                    if (!paths.containsKey(path)) {
                        continue;
                    }

                    // remove path from set
                    ObjectId blobId = paths.remove(path);
                    result.blobCount++;

                    // index the blob metadata
                    String blobAuthor = getAuthor(commit);
                    String blobCommitter = getCommitter(commit);
                    String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE);

                    Document doc = new Document();
                    doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(),
                            StringField.TYPE_STORED));
                    doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_COMMIT, commit.getName(), TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_PATH, path, TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_DATE, blobDate, StringField.TYPE_STORED));
                    doc.add(new Field(FIELD_AUTHOR, blobAuthor, TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_COMMITTER, blobCommitter, TextField.TYPE_STORED));

                    // determine extension to compare to the extension
                    // blacklist
                    String ext = null;
                    String name = path.toLowerCase();
                    if (name.indexOf('.') > -1) {
                        ext = name.substring(name.lastIndexOf('.') + 1);
                    }

                    // index the blob content
                    if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
                        ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
                        InputStream in = ldr.openStream();
                        int n;
                        while ((n = in.read(tmp)) > 0) {
                            os.write(tmp, 0, n);
                        }
                        in.close();
                        byte[] content = os.toByteArray();
                        String str = StringUtils.decodeString(content, encodings);
                        doc.add(new Field(FIELD_CONTENT, str, TextField.TYPE_STORED));
                        os.reset();
                    }

                    // add the blob to the index
                    writer.addDocument(doc);
                }
            }

            os.close();

            // index the tip commit object
            if (indexedCommits.add(tipId)) {
                Document doc = createDocument(tip, tags.get(tipId));
                doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED));
                writer.addDocument(doc);
                result.commitCount += 1;
                result.branchCount += 1;
            }

            // traverse the log and index the previous commit objects
            RevWalk historyWalk = new RevWalk(reader);
            historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
            RevCommit rev;
            while ((rev = historyWalk.next()) != null) {
                String hash = rev.getId().getName();
                if (indexedCommits.add(hash)) {
                    Document doc = createDocument(rev, tags.get(hash));
                    doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED));
                    writer.addDocument(doc);
                    result.commitCount += 1;
                }
            }
        }

        // finished
        reader.close();

        // commit all changes and reset the searcher
        config.save();
        writer.commit();
        resetIndexSearcher(model.name);
        result.success();
    } catch (Exception e) {
        logger.error("Exception while reindexing " + model.name, e);
    }
    return result;
}

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

License:Eclipse Distribution License

@Override
public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter)
        throws IOException {
    if (ours == null) {
        return theirs;
    }//from w w  w .ja va2s .co m
    if (theirs == null) {
        return ours;
    }
    if (ours.getData().equals(theirs.getData())) {
        return ours;
    }

    ObjectLoader lo = reader.open(ours.getData());
    byte[] sep = new byte[] { '\n' };
    ObjectLoader lt = reader.open(theirs.getData());
    try (ObjectStream os = lo.openStream();
            ByteArrayInputStream b = new ByteArrayInputStream(sep);
            ObjectStream ts = lt.openStream();
            UnionInputStream union = new UnionInputStream(os, b, ts)) {
        ObjectId noteData = inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(),
                union);
        return new Note(ours, noteData);
    }
}

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

License:Apache License

@VisibleForTesting
List<CommitValidationMessage> performValidation(RevCommit c, RevWalk revWalk, String ownersFileName,
        boolean verbose) throws IOException {
    // Collect all messages from all files.
    List<CommitValidationMessage> messages = new LinkedList<>();
    // Collect all email addresses from all files and check each address only once.
    Map<String, Set<String>> email2lines = new HashMap<>();
    Map<String, ObjectId> content = getChangedOwners(c, revWalk, ownersFileName);
    for (String path : content.keySet()) {
        ObjectLoader ol = revWalk.getObjectReader().open(content.get(path));
        try (InputStream in = ol.openStream()) {
            if (RawText.isBinary(in)) {
                add(messages, path + " is a binary file", true); // OWNERS files cannot be binary
                continue;
            }//from   ww w .  jav a  2  s . c o  m
        }
        checkFile(messages, email2lines, path, ol, verbose);
    }
    checkEmails(messages, emails, email2lines, verbose);
    return messages;
}

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

License:Apache License

private static void checkFile(List<CommitValidationMessage> messages, Map<String, Set<String>> email2lines,
        String path, ObjectLoader ol, boolean verbose) throws IOException {
    if (verbose) {
        add(messages, "validate: " + path, false);
    }/*w  w w  .  j av  a 2 s  . c  om*/
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(ol.openStream(), StandardCharsets.UTF_8))) {
        int line = 0;
        for (String l = br.readLine(); l != null; l = br.readLine()) {
            line++;
            checkLine(messages, email2lines, path, line, l);
        }
    }
}

From source file:com.googlesource.gerrit.plugins.uploadvalidator.BlockedKeywordValidator.java

License:Apache License

@VisibleForTesting
List<CommitValidationMessage> performValidation(Repository repo, RevCommit c, RevWalk revWalk,
        ImmutableCollection<Pattern> blockedKeywordPartterns, PluginConfig cfg)
        throws IOException, ExecutionException {
    List<CommitValidationMessage> messages = new LinkedList<>();
    checkCommitMessageForBlockedKeywords(blockedKeywordPartterns, messages, c.getFullMessage());
    Map<String, ObjectId> content = CommitUtils.getChangedContent(repo, c, revWalk);
    for (String path : content.keySet()) {
        ObjectLoader ol = revWalk.getObjectReader().open(content.get(path));
        try (InputStream in = ol.openStream()) {
            if (RawText.isBinary(in) || contentTypeUtil.isBlacklistedBinaryContentType(ol, path, cfg)) {
                continue;
            }//w  w  w  .j  a va 2 s. c om
        }
        checkFileForBlockedKeywords(blockedKeywordPartterns, messages, path, ol);
    }
    return messages;
}