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

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

Introduction

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

Prototype

public abstract int getType();

Source Link

Document

Get Git in pack object type

Usage

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  ww  . j  ava2 s. c om*/
    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.github.kaitoy.goslings.server.dao.jgit.ObjectDaoImpl.java

License:Open Source License

@Cacheable
private RawContents getRawContents(String token, String objectId) {
    try {/*w ww.  j  av a 2  s .co  m*/
        ObjectLoader loader = resolver.getRepository(token).open(ObjectId.fromString(objectId));
        return new RawContents(loader.getType(), loader.getBytes());
    } catch (MissingObjectException e) {
        String message = new StringBuilder().append("The specified object ").append(objectId)
                .append(" doesn't exist in the repository ").append(token).append(".").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    } catch (IOException e) {
        String message = new StringBuilder().append("Failed to get contents of the specified object ")
                .append(objectId).append(" in the repository ").append(token).append(".").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    }
}

From source file:com.smartitengineering.version.impl.jgit.JGitImpl.java

License:Open Source License

public byte[] readObject(final String objectIdStr) throws IOException, IllegalArgumentException {
    if (StringUtils.isBlank(objectIdStr)) {
        throw new IllegalArgumentException("Invalid Object id!");
    }//from   www.  ja va  2 s  .co m
    ObjectId objectId = ObjectId.fromString(objectIdStr);
    ObjectLoader objectLoader = getReadRepository().openObject(objectId);
    if (objectLoader.getType() != Constants.OBJ_BLOB) {
        throw new IllegalArgumentException("Not a blob: " + objectIdStr);
    }
    return objectLoader.getBytes();
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Trees getTrees(Repository r, String revision, String path, boolean history, int recursion)
        throws IOException, GitAPIException, EntityNotFoundException {
    if (path.startsWith("/")) {
        path = path.substring(1);// ww  w.  j a v a2s . co  m
    }

    RevObject revId = resolveRevision(r, revision);

    MutableObjectId revTree = new MutableObjectId();
    TreeWalk treeWalk = getTreeOnPath(revTree, r, revId, path);

    if (treeWalk == null) {
        throw new EntityNotFoundException("Revision: " + revision + ", path: " + path + " not found.");
    }

    Trees trees = new Trees(revTree.name());

    Git git = history ? new Git(r) : null;

    while (treeWalk.next()) {
        ObjectLoader loader = r.open(treeWalk.getObjectId(0));
        Trees.Tree t = new Trees.Tree(treeWalk.getObjectId(0).getName(), // sha
                treeWalk.getPathString(), // path
                treeWalk.getNameString(), // name
                getType(loader.getType()), // type
                treeWalk.getRawMode(0), // mode
                loader.getSize() // size
        );
        trees.getTree().add(t);

        if (recursion == -2 && t.getType() == Item.Type.TREE) {
            t.setEmpty(getEmptyPath(r, treeWalk.getObjectId(0)));
        }

        if (history) {
            addHistory(git, t, revId, /* path + ( path.length() == 0 ? "" : "/") + */t.getPath());
        }

    }

    return trees;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Item getItem(Repository r, String revision, String path)
        throws IOException, EntityNotFoundException {
    if (path.startsWith("/")) {
        path = path.substring(1);/*w w w . ja v a  2s. c o m*/
    }

    String id = resolve(r, r.resolve(revision), path);
    if (id == null) {
        throw new EntityNotFoundException();
    }
    ObjectId objectId = ObjectId.fromString(id);

    ObjectLoader loader = r.open(objectId);

    return new Item(id, getType(loader.getType()));

}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

private static String getEmptyPath(Repository r, ObjectId id) throws IOException {
    TreeWalk treeWalk = new TreeWalk(r);
    treeWalk.addTree(new RevWalk(r).parseTree(id));

    String path = null;//w  w  w. j  a v a 2 s  .c o m

    // Find tree of interrest it has to be alone there
    ObjectId iId = null;
    String iPath = null;
    while (treeWalk.next()) {
        if (iId == null) {
            iId = treeWalk.getObjectId(0);
            iPath = treeWalk.getPathString();
        } else {
            iId = null;
            break;
        }
    }

    if (iId != null) {
        ObjectLoader loader = r.open(iId);
        if (loader.getType() == Constants.OBJ_TREE) { // It is alone there and it is a folder
            path = "/" + iPath;
            String sep = getEmptyPath(r, iId);
            if (sep != null) {
                path = path + sep;
            }
        }
    }

    return path;

}

From source file:edu.nju.cs.inform.jgit.unfinished.BrowseTree.java

License:Apache License

public static void main(String[] args) throws IOException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        ObjectId revId = repository.resolve(Constants.HEAD);
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            try (RevWalk revWalk = new RevWalk(repository)) {
                treeWalk.addTree(revWalk.parseTree(revId));

                while (treeWalk.next()) {
                    System.out.println("---------------------------");
                    System.out.append("name: ").println(treeWalk.getNameString());
                    System.out.append("path: ").println(treeWalk.getPathString());

                    ObjectLoader loader = repository.open(treeWalk.getObjectId(0));

                    System.out.append("directory: ").println(loader.getType() == Constants.OBJ_TREE);
                    System.out.append("size: ").println(loader.getSize());
                }// w w w . j  a  va 2 s .  c  om
            }
        }
    }
}

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 {//w w w  .  ja  v  a  2s  .  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:jbenchmarker.trace.git.GitWalker.java

License:Open Source License

/**
 * For all registred parent combinaison place git repository in merged state
 * it finds file from id in next commit and it compares with file in
 * repository In phase 3//w  w w  .  j  ava  2 s .  c  o m
 *
 * @throws Exception
 */
public void mesuresDiff() throws Exception {
    // int commit = 0;
    ProgressBar progress = new ProgressBar(idCommitParentsToFiles.keySet().size());
    /*        double commitPercent = idCommitParentsToFiles.keySet().size() / 100.0;
            double nextStep = commitPercent;*/

    for (String idcommitParent : idCommitParentsToFiles.keySet()) {

        logger.log(Level.INFO, "Treat Commit {0}", idcommitParent);

        /*
         * place git repository in merged state with parents
         */
        gitPositionMerge(commitParent.getAll(idcommitParent));
        /*
         * Foreach file must be compared in this state
         */
        for (Couple c : idCommitParentsToFiles.getAll(idcommitParent)) {
            RawText stateAfterMerge = EmptyFile;
            RawText stateAfterCommit = EmptyFile;
            /*
             * get file in this repository
             */
            File f = new File(gitDir + "/" + c.getFileName());
            if (f.exists()) { // if file is existing after merge
                launchAndWait("sed /^[<=>][<=>][<=>][<=>]/d -i " + f.getPath());
                stateAfterMerge = new RawText(f);
            } else {
                logger.log(Level.WARNING, "File{0} not found !", f.getPath());
            }
            /*
             * get file from git with id. 
             */
            try {
                ObjectLoader ldr = source.open(c.fileName, c.getId());
                ldr.getType();

                stateAfterCommit = new RawText(ldr.getBytes(PackConfig.DEFAULT_BIG_FILE_THRESHOLD));
            } catch (LargeObjectException.ExceedsLimit overLimit) {// File is overlimits => binary
                logger.log(Level.WARNING, "File {0} overlimits !", c.getFileName());
                continue;
            } catch (LargeObjectException.ExceedsByteArrayLimit overLimit) {// File is overlimits => binary
                logger.log(Level.WARNING, "File {0} exceed limits!", c.getFileName());
                continue;
            } catch (Exception ex) { // if another exception like inexitant considere 0 file.
                logger.log(Level.WARNING, "File {0} not found in after commit !", c.getFileName());
            }

            /*
             * make a diff with this file
             */
            EditList editList = diffAlgorithm.diff(RawTextComparator.DEFAULT, stateAfterMerge,
                    stateAfterCommit);

            BlockLine editCount = files.get(c.fileName);
            editCount.incrementPass();

            for (Edit ed : editList) {// Count line replace is two time counted
                editCount.addLine(ed.getEndA() - ed.getBeginA() + ed.getEndB() - ed.getBeginB());
            }
            //Count the block size
            editCount.addBlock(editList.size());

        }
        logger.info("Next");
        // commit++;
        if (progressBar) {
            progress.progress(1);
        }
    }
}

From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java

License:Apache License

public static void infoObjectId(Repository db, ObjectId oid) throws IOException {
    System.out.printf("ObjectID: %s%n", oid.getName());
    ObjectLoader or = db.open(oid);
    if (or == null) {
        System.out.println("  Object not found!");
    }//from  w  ww. java2s .  co  m
    System.out.printf("  .type: %s%n", asObjectType(or.getType()));
    System.out.printf("  .size: %,d%n", or.getSize());
}