Example usage for org.eclipse.jgit.lib ObjectId isId

List of usage examples for org.eclipse.jgit.lib ObjectId isId

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId isId.

Prototype

public static final boolean isId(@Nullable String id) 

Source Link

Document

Test a string of characters to verify it is a hex format.

Usage

From source file:at.bitandart.zoubek.mervin.gerrit.GitURIParser.java

License:Open Source License

/**
 * parses the URI// ww  w. ja  va2  s.  com
 * 
 * @throws IOException
 *             if an error occurs during parsing the URI
 */
@SuppressWarnings("restriction")
private void parse() throws IOException {
    StringBuilder repoPathBuilder = new StringBuilder();
    StringBuilder filePathBuilder = new StringBuilder();
    repoPathBuilder.append("/");
    if (uri.hasAuthority()) {
        authority = uri.authority();
    }
    if (uri.hasDevice()) {
        repoPathBuilder.append(uri.device());
        repoPathBuilder.append("/");
    }
    List<String> segments = uri.segmentsList();
    Iterator<String> segmentIt = segments.iterator();
    String currentSegment = "";

    // extract repo path
    while (segmentIt.hasNext() && !ObjectId.isId(currentSegment)) {
        repoPathBuilder.append(currentSegment);
        if (!currentSegment.isEmpty()) {
            repoPathBuilder.append("/");
        }
        currentSegment = segmentIt.next();
    }

    // extract the commit Hash
    commitHash = currentSegment;
    currentSegment = segmentIt.next();
    if (!ObjectId.isId(commitHash)) {
        commitHash = "";
        throw new IOException("Invalid URI: no commit hash found");
    }

    // extract file path within commit
    while (segmentIt.hasNext()) {
        filePathBuilder.append(currentSegment);
        filePathBuilder.append("/");
        currentSegment = segmentIt.next();
    }
    filePathBuilder.append(currentSegment);

    logger.debug("commit hash: " + commitHash);

    repoPath = repoPathBuilder.toString();
    logger.debug("repo path: " + repoPath);

    filePath = filePathBuilder.toString();
    logger.debug("file path: " + filePath);

    uriParsed = true;
}

From source file:com.amd.gerrit.plugins.manifestsubscription.VersionedManifests.java

License:Open Source License

/**
 * Pass in a {@link com.google.common.collect.Table} if you want to reuse
 * the lookup cache// w  w w  .  ja v  a2 s  . c  om
 *
 * @param gitRepoManager
 * @param manifest
 * @param lookup
 */
static void affixManifest(GitRepositoryManager gitRepoManager, Manifest manifest,
        Table<String, String, String> lookup) throws GitAPIException, IOException {
    if (lookup == null) {
        // project, branch, hash
        lookup = HashBasedTable.create();
    }

    String defaultRef = null;

    if (manifest.getDefault() != null) {
        defaultRef = manifest.getDefault().getRevision();
    }

    ManifestOp op = new ManifestOp() {
        @Override
        public boolean apply(com.amd.gerrit.plugins.manifestsubscription.manifest.Project project, String hash,
                String name, GitRepositoryManager gitRepoManager) {
            project.setRevision(hash);
            if (!ObjectId.isId(name)) {
                project.setUpstream(name);
            }
            return true;
        }
    };

    traverseManifestAndApplyOp(gitRepoManager, manifest.getProject(), defaultRef, op, lookup);
}

From source file:com.google.gerrit.server.account.InternalGroupBackend.java

License:Apache License

@Override
public boolean handles(AccountGroup.UUID uuid) {
    // See AccountGroup.isInternalGroup
    return ObjectId.isId(uuid.get()); // [0-9a-f]{40};
}

From source file:com.google.gitiles.GitwebRedirectFilter.java

License:Open Source License

private static Revision toRevision(String rev) {
    if (Strings.isNullOrEmpty(rev)) {
        return null;
    } else if ("HEAD".equals(rev) || rev.startsWith("refs/")) {
        return Revision.named(rev);
    } else if (ObjectId.isId(rev)) {
        return Revision.unpeeled(rev, ObjectId.fromString(rev));
    } else {// w  w w  .  j  a  v a  2s.co  m
        return Revision.named(rev);
    }
}

From source file:com.googlesource.gerrit.plugins.xdocs.XDocServlet.java

License:Apache License

@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {//  w w w . j  a v a  2  s . c  o  m
        validateRequestMethod(req);

        ResourceKey key = ResourceKey.fromPath(getEncodedPath(req));
        ProjectState state = getProject(key);
        XDocProjectConfig cfg = cfgFactory.create(state);

        if (key.file == null) {
            res.sendRedirect(getRedirectUrl(req, key, cfg));
            return;
        }

        MimeType mimeType = fileTypeRegistry.getMimeType(key.file, null);
        mimeType = new MimeType(
                FileContentUtil.resolveContentType(state, key.file, FileMode.FILE, mimeType.toString()));
        FormatterProvider formatter = getFormatter(req, key, mimeType);
        validateDiffMode(key);

        ProjectControl projectControl = projectControlFactory.validateFor(key.project);
        String rev = getRevision(
                key.diffMode == DiffMode.NO_DIFF ? MoreObjects.firstNonNull(key.revision, cfg.getIndexRef())
                        : key.revision,
                projectControl);
        String revB = getRevision(key.revisionB, projectControl);

        try (Repository repo = repoManager.openRepository(key.project)) {
            ObjectId revId = resolveRevision(repo,
                    key.diffMode == DiffMode.NO_DIFF ? MoreObjects.firstNonNull(rev, Constants.HEAD) : rev);
            if (revId != null && ObjectId.isId(rev)) {
                validateCanReadCommit(repo, projectControl, revId);
            }

            ObjectId revIdB = resolveRevision(repo, revB);
            if (revIdB != null && ObjectId.isId(revB)) {
                validateCanReadCommit(repo, projectControl, revIdB);
            }

            if (isResourceNotModified(req, key, revId, revIdB)) {
                res.sendError(SC_NOT_MODIFIED);
                return;
            }

            Resource rsc;
            if (formatter != null) {
                rsc = docCache.get(formatter, key.project, key.file, revId, revIdB, key.diffMode);
            } else if (isImage(mimeType)) {
                rsc = getImageResource(repo, key.diffMode, revId, revIdB, key.file);
            } else {
                rsc = Resource.NOT_FOUND;
            }

            if (rsc != Resource.NOT_FOUND) {
                res.setHeader(HttpHeaders.ETAG,
                        computeETag(key.project, revId, key.file, revIdB, key.diffMode));
            }
            if (key.diffMode == DiffMode.NO_DIFF && rev == null) {
                // file was loaded from HEAD, since HEAD is modifiable the document
                // should only be cached for a short period
                CacheHeaders.setCacheablePrivate(res, 15, TimeUnit.MINUTES, false);
            } else {
                CacheHeaders.setCacheablePrivate(res, 7, TimeUnit.DAYS, false);
            }
            rsc.send(req, res);
            return;
        }
    } catch (RepositoryNotFoundException | NoSuchProjectException | ResourceNotFoundException | AuthException
            | RevisionSyntaxException e) {
        Resource.NOT_FOUND.send(req, res);
    } catch (MethodNotAllowedException e) {
        CacheHeaders.setNotCacheable(res);
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
}

From source file:com.googlesource.gerrit.plugins.xdocs.XDocServlet.java

License:Apache License

private String getRevision(String revision, ProjectControl projectControl)
        throws ResourceNotFoundException, AuthException, IOException {
    if (revision == null) {
        return null;
    }/*  w ww  .ja v  a  2s .c  o  m*/

    if (ObjectId.isId(revision)) {
        return revision;
    }

    if (Constants.HEAD.equals(revision)) {
        return getHead.get().apply(new ProjectResource(projectControl));
    } else {
        String rev = revision;
        if (!rev.startsWith(Constants.R_REFS)) {
            rev = Constants.R_HEADS + rev;
        }
        if (!projectControl.controlForRef(rev).isVisible()) {
            throw new ResourceNotFoundException();
        }
        return rev;
    }
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public String getBranchName() throws Exception {
    Repository repository = git.getRepository();
    if (ObjectId.isId(repository.getFullBranch())
            && repository.getFullBranch().equals(repository.resolve("HEAD").getName())) {
        RevWalk revs = null;//from   w  ww .  ja  va2s .c om
        try {
            log.trace("Trying to resolve tagname: {}", repository.getFullBranch());
            ObjectId tagRef = ObjectId.fromString(repository.getFullBranch());
            revs = new RevWalk(repository);
            RevCommit commit = revs.parseCommit(tagRef);
            Map<String, Ref> allTags = repository.getTags();
            for (String key : allTags.keySet()) {
                Ref ref = allTags.get(key);
                RevTag tag = revs.parseTag(ref.getObjectId());
                log.trace("Checking ref {}, {}", commit.getName(), tag.getObject());
                if (tag.getObject().equals(commit)) {
                    return key;
                }
            }
        } catch (Exception e) {
            log.warn("Invalid id: {}", repository.getFullBranch(), e);
        } finally {
            revs.release();
        }
    }
    return repository.getBranch();
}

From source file:com.microsoft.gittf.core.util.CommitUtil.java

License:Open Source License

/**
 * Returns the commit object id that is pointed at by the ref specified
 * //from  w w  w .j  a v  a2s .  c o  m
 * @param repository
 *        the git repository
 * @param ref
 *        the reference name
 * @return
 * @throws Exception
 */
public static ObjectId getRefNameCommitID(final Repository repository, String ref) throws Exception {
    if (AbbreviatedObjectId.isId(ref) || ObjectId.isId(ref)) {
        return peelRef(repository, repository.resolve(ref));
    }

    return getCommitId(repository, ref);
}

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

License:Eclipse Distribution License

private FetchConnection newDumbConnection(InputStream in) throws IOException, PackProtocolException {
    HttpObjectDB d = new HttpObjectDB(objectsUrl);
    BufferedReader br = toBufferedReader(in);
    Map<String, Ref> refs;
    try {//from w  w w  .  j a v  a 2s .  c o m
        refs = d.readAdvertisedImpl(br);
    } finally {
        br.close();
    }

    if (!refs.containsKey(Constants.HEAD)) {
        // If HEAD was not published in the info/refs file (it usually
        // is not there) download HEAD by itself as a loose file and do
        // the resolution by hand.
        //
        HttpURLConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
        int status = HttpSupport.response(conn);
        switch (status) {
        case HttpURLConnection.HTTP_OK: {
            br = toBufferedReader(openInputStream(conn));
            try {
                String line = br.readLine();
                if (line != null && line.startsWith(RefDirectory.SYMREF)) {
                    String target = line.substring(RefDirectory.SYMREF.length());
                    Ref r = refs.get(target);
                    if (r == null)
                        r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
                    r = new SymbolicRef(Constants.HEAD, r);
                    refs.put(r.getName(), r);
                } else if (line != null && ObjectId.isId(line)) {
                    Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, Constants.HEAD,
                            ObjectId.fromString(line));
                    refs.put(r.getName(), r);
                }
            } finally {
                br.close();
            }
            break;
        }

        case HttpURLConnection.HTTP_NOT_FOUND:
            break;

        default:
            throw new TransportException(uri,
                    MessageFormat.format(JGitText.get().cannotReadHEAD, status, conn.getResponseMessage()));
        }
    }

    WalkFetchConnection wfc = new WalkFetchConnection(this, d);
    wfc.available(refs);
    return wfc;
}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Gets a repository, cloning into a local directory or
 * @param gitDetails The details of the Git repository
 * @param reuseDir Whether the cached repository can be used
 * @return The git object for the repository
 */// w  w  w.  ja v  a  2  s.co  m
public Git getRepository(GitDetails gitDetails, boolean reuseDir) throws GitAPIException, IOException {
    Git repo;
    if (reuseDir) {
        // Base dir from configuration, name from hash of repository URL
        String baseName = DigestUtils.sha1Hex(GitDetails.normaliseUrl(gitDetails.getRepoUrl()));

        // Check if folder already exists
        Path repoDir = gitStorage.resolve(baseName);
        if (Files.isReadable(repoDir) && Files.isDirectory(repoDir)) {
            repo = Git.open(repoDir.toFile());
            repo.fetch().call();
        } else {
            // Create a folder and clone repository into it
            Files.createDirectory(repoDir);
            repo = cloneRepo(gitDetails.getRepoUrl(), repoDir.toFile());
        }
    } else {
        // Another thread is already using the existing folder
        // Must create another temporary one
        repo = cloneRepo(gitDetails.getRepoUrl(), createTempDir());
    }

    // Checkout the specific branch or commit ID
    if (repo != null) {
        // Create a new local branch if it does not exist and not a commit ID
        String branchOrCommitId = gitDetails.getBranch();
        final boolean isId = ObjectId.isId(branchOrCommitId);
        if (!isId) {
            branchOrCommitId = "refs/remotes/origin/" + branchOrCommitId;
        }
        try {
            repo.checkout().setName(branchOrCommitId).call();
        } catch (Exception ex) {
            // Maybe it was a tag
            if (!isId && ex instanceof RefNotFoundException) {
                final String tag = gitDetails.getBranch();
                try {
                    repo.checkout().setName(tag).call();
                } catch (Exception ex2) {
                    // Throw the first exception, to keep the same behavior as before.
                    throw ex;
                }
            } else {
                throw ex;
            }
        }
    }

    return repo;
}