Search in sources :

Example 56 with ResourceNotFoundException

use of com.google.gerrit.extensions.restapi.ResourceNotFoundException in project gerrit by GerritCodeReview.

the class GetDiff method apply.

@Override
public Response<DiffInfo> apply(FileResource resource) throws ResourceConflictException, ResourceNotFoundException, OrmException, AuthException, InvalidChangeOperationException, IOException {
    DiffPreferencesInfo prefs = new DiffPreferencesInfo();
    if (whitespace != null) {
        prefs.ignoreWhitespace = whitespace;
    } else if (ignoreWhitespace != null) {
        prefs.ignoreWhitespace = ignoreWhitespace.whitespace;
    } else {
        prefs.ignoreWhitespace = Whitespace.IGNORE_LEADING_AND_TRAILING;
    }
    prefs.context = context;
    prefs.intralineDifference = intraline;
    PatchScriptFactory psf;
    PatchSet basePatchSet = null;
    if (base != null) {
        RevisionResource baseResource = revisions.parse(resource.getRevision().getChangeResource(), IdString.fromDecoded(base));
        basePatchSet = baseResource.getPatchSet();
        psf = patchScriptFactoryFactory.create(resource.getRevision().getControl(), resource.getPatchKey().getFileName(), basePatchSet.getId(), resource.getPatchKey().getParentKey(), prefs);
    } else if (parentNum > 0) {
        psf = patchScriptFactoryFactory.create(resource.getRevision().getControl(), resource.getPatchKey().getFileName(), parentNum - 1, resource.getPatchKey().getParentKey(), prefs);
    } else {
        psf = patchScriptFactoryFactory.create(resource.getRevision().getControl(), resource.getPatchKey().getFileName(), null, resource.getPatchKey().getParentKey(), prefs);
    }
    try {
        psf.setLoadHistory(false);
        psf.setLoadComments(context != DiffPreferencesInfo.WHOLE_FILE_CONTEXT);
        PatchScript ps = psf.call();
        Content content = new Content(ps);
        for (Edit edit : ps.getEdits()) {
            if (edit.getType() == Edit.Type.EMPTY) {
                continue;
            }
            content.addCommon(edit.getBeginA());
            checkState(content.nextA == edit.getBeginA(), "nextA = %s; want %s", content.nextA, edit.getBeginA());
            checkState(content.nextB == edit.getBeginB(), "nextB = %s; want %s", content.nextB, edit.getBeginB());
            switch(edit.getType()) {
                case DELETE:
                case INSERT:
                case REPLACE:
                    List<Edit> internalEdit = edit instanceof ReplaceEdit ? ((ReplaceEdit) edit).getInternalEdits() : null;
                    content.addDiff(edit.getEndA(), edit.getEndB(), internalEdit);
                    break;
                case EMPTY:
                default:
                    throw new IllegalStateException();
            }
        }
        content.addCommon(ps.getA().size());
        ProjectState state = projectCache.get(resource.getRevision().getChange().getProject());
        DiffInfo result = new DiffInfo();
        // TODO referring to the parent commit by refs/changes/12/60012/1^1
        // will likely not work for inline edits
        String revA = basePatchSet != null ? basePatchSet.getRefName() : resource.getRevision().getPatchSet().getRefName() + "^1";
        String revB = resource.getRevision().getEdit().isPresent() ? resource.getRevision().getEdit().get().getRefName() : resource.getRevision().getPatchSet().getRefName();
        List<DiffWebLinkInfo> links = webLinks.getDiffLinks(state.getProject().getName(), resource.getPatchKey().getParentKey().getParentKey().get(), basePatchSet != null ? basePatchSet.getId().get() : null, revA, MoreObjects.firstNonNull(ps.getOldName(), ps.getNewName()), resource.getPatchKey().getParentKey().get(), revB, ps.getNewName());
        result.webLinks = links.isEmpty() ? null : links;
        if (!webLinksOnly) {
            if (ps.isBinary()) {
                result.binary = true;
            }
            if (ps.getDisplayMethodA() != DisplayMethod.NONE) {
                result.metaA = new FileMeta();
                result.metaA.name = MoreObjects.firstNonNull(ps.getOldName(), ps.getNewName());
                result.metaA.contentType = FileContentUtil.resolveContentType(state, result.metaA.name, ps.getFileModeA(), ps.getMimeTypeA());
                result.metaA.lines = ps.getA().size();
                result.metaA.webLinks = getFileWebLinks(state.getProject(), revA, result.metaA.name);
                result.metaA.commitId = content.commitIdA;
            }
            if (ps.getDisplayMethodB() != DisplayMethod.NONE) {
                result.metaB = new FileMeta();
                result.metaB.name = ps.getNewName();
                result.metaB.contentType = FileContentUtil.resolveContentType(state, result.metaB.name, ps.getFileModeB(), ps.getMimeTypeB());
                result.metaB.lines = ps.getB().size();
                result.metaB.webLinks = getFileWebLinks(state.getProject(), revB, result.metaB.name);
                result.metaB.commitId = content.commitIdB;
            }
            if (intraline) {
                if (ps.hasIntralineTimeout()) {
                    result.intralineStatus = IntraLineStatus.TIMEOUT;
                } else if (ps.hasIntralineFailure()) {
                    result.intralineStatus = IntraLineStatus.FAILURE;
                } else {
                    result.intralineStatus = IntraLineStatus.OK;
                }
            }
            result.changeType = CHANGE_TYPE.get(ps.getChangeType());
            if (result.changeType == null) {
                throw new IllegalStateException("unknown change type: " + ps.getChangeType());
            }
            if (ps.getPatchHeader().size() > 0) {
                result.diffHeader = ps.getPatchHeader();
            }
            result.content = content.lines;
        }
        Response<DiffInfo> r = Response.ok(result);
        if (resource.isCacheable()) {
            r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
        }
        return r;
    } catch (NoSuchChangeException e) {
        throw new ResourceNotFoundException(e.getMessage(), e);
    } catch (LargeObjectException e) {
        throw new ResourceConflictException(e.getMessage(), e);
    }
}
Also used : PatchScript(com.google.gerrit.common.data.PatchScript) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) ReplaceEdit(org.eclipse.jgit.diff.ReplaceEdit) Edit(org.eclipse.jgit.diff.Edit) IdString(com.google.gerrit.extensions.restapi.IdString) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) DiffWebLinkInfo(com.google.gerrit.extensions.common.DiffWebLinkInfo) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) PatchScriptFactory(com.google.gerrit.server.patch.PatchScriptFactory) SparseFileContent(com.google.gerrit.prettify.common.SparseFileContent) ReplaceEdit(org.eclipse.jgit.diff.ReplaceEdit) ProjectState(com.google.gerrit.server.project.ProjectState) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) FileMeta(com.google.gerrit.extensions.common.DiffInfo.FileMeta) DiffInfo(com.google.gerrit.extensions.common.DiffInfo)

Example 57 with ResourceNotFoundException

use of com.google.gerrit.extensions.restapi.ResourceNotFoundException in project gerrit by GerritCodeReview.

the class GetPatch method apply.

@Override
public BinaryResult apply(RevisionResource rsrc) throws ResourceConflictException, IOException, ResourceNotFoundException {
    Project.NameKey project = rsrc.getControl().getProject().getNameKey();
    final Repository repo = repoManager.openRepository(project);
    boolean close = true;
    try {
        final RevWalk rw = new RevWalk(repo);
        try {
            final RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get()));
            RevCommit[] parents = commit.getParents();
            if (parents.length > 1) {
                throw new ResourceConflictException("Revision has more than 1 parent.");
            } else if (parents.length == 0) {
                throw new ResourceConflictException("Revision has no parent.");
            }
            final RevCommit base = parents[0];
            rw.parseBody(base);
            BinaryResult bin = new BinaryResult() {

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    if (zip) {
                        ZipOutputStream zos = new ZipOutputStream(out);
                        ZipEntry e = new ZipEntry(fileName(rw, commit));
                        e.setTime(commit.getCommitTime() * 1000L);
                        zos.putNextEntry(e);
                        format(zos);
                        zos.closeEntry();
                        zos.finish();
                    } else {
                        format(out);
                    }
                }

                private void format(OutputStream out) throws IOException {
                    // Only add header if no path is specified
                    if (path == null) {
                        out.write(formatEmailHeader(commit).getBytes(UTF_8));
                    }
                    try (DiffFormatter fmt = new DiffFormatter(out)) {
                        fmt.setRepository(repo);
                        if (path != null) {
                            fmt.setPathFilter(PathFilter.create(path));
                        }
                        fmt.format(base.getTree(), commit.getTree());
                        fmt.flush();
                    }
                }

                @Override
                public void close() throws IOException {
                    rw.close();
                    repo.close();
                }
            };
            if (path != null && bin.asString().isEmpty()) {
                throw new ResourceNotFoundException(String.format(FILE_NOT_FOUND, path));
            }
            if (zip) {
                bin.disableGzip().setContentType("application/zip").setAttachmentName(fileName(rw, commit) + ".zip");
            } else {
                bin.base64().setContentType("application/mbox").setAttachmentName(download ? fileName(rw, commit) + ".base64" : null);
            }
            close = false;
            return bin;
        } finally {
            if (close) {
                rw.close();
            }
        }
    } finally {
        if (close) {
            repo.close();
        }
    }
}
Also used : OutputStream(java.io.OutputStream) ZipOutputStream(java.util.zip.ZipOutputStream) ZipEntry(java.util.zip.ZipEntry) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ZipOutputStream(java.util.zip.ZipOutputStream) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult)

Example 58 with ResourceNotFoundException

use of com.google.gerrit.extensions.restapi.ResourceNotFoundException in project gerrit by GerritCodeReview.

the class FileContentUtil method downloadContent.

public BinaryResult downloadContent(ProjectState project, ObjectId revstr, String path, @Nullable Integer parent) throws ResourceNotFoundException, IOException {
    try (Repository repo = openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        String suffix = "new";
        RevCommit commit = rw.parseCommit(revstr);
        if (parent != null && parent > 0) {
            if (commit.getParentCount() == 1) {
                suffix = "old";
            } else {
                suffix = "old" + parent;
            }
            commit = rw.parseCommit(commit.getParent(parent - 1));
        }
        ObjectReader reader = rw.getObjectReader();
        TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
        if (tw == null) {
            throw new ResourceNotFoundException();
        }
        int mode = tw.getFileMode(0).getObjectType();
        if (mode != Constants.OBJ_BLOB) {
            throw new ResourceNotFoundException();
        }
        ObjectId id = tw.getObjectId(0);
        ObjectLoader obj = repo.open(id, OBJ_BLOB);
        byte[] raw;
        try {
            raw = obj.getCachedBytes(MAX_SIZE);
        } catch (LargeObjectException e) {
            raw = null;
        }
        MimeType contentType = registry.getMimeType(path, raw);
        return registry.isSafeInline(contentType) ? wrapBlob(path, obj, raw, contentType, suffix) : zipBlob(path, obj, commit, suffix);
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MimeType(eu.medsea.mimeutil.MimeType) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) Repository(org.eclipse.jgit.lib.Repository) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 59 with ResourceNotFoundException

use of com.google.gerrit.extensions.restapi.ResourceNotFoundException in project gerrit by GerritCodeReview.

the class FileContentUtil method getContent.

public BinaryResult getContent(Repository repo, ProjectState project, ObjectId revstr, String path) throws IOException, ResourceNotFoundException {
    try (RevWalk rw = new RevWalk(repo)) {
        RevCommit commit = rw.parseCommit(revstr);
        ObjectReader reader = rw.getObjectReader();
        TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
        if (tw == null) {
            throw new ResourceNotFoundException();
        }
        org.eclipse.jgit.lib.FileMode mode = tw.getFileMode(0);
        ObjectId id = tw.getObjectId(0);
        if (mode == org.eclipse.jgit.lib.FileMode.GITLINK) {
            return BinaryResult.create(id.name()).setContentType(X_GIT_GITLINK).base64();
        }
        ObjectLoader obj = repo.open(id, OBJ_BLOB);
        byte[] raw;
        try {
            raw = obj.getCachedBytes(MAX_SIZE);
        } catch (LargeObjectException e) {
            raw = null;
        }
        String type;
        if (mode == org.eclipse.jgit.lib.FileMode.SYMLINK) {
            type = X_GIT_SYMLINK;
        } else {
            type = registry.getMimeType(path, raw).toString();
            type = resolveContentType(project, path, FileMode.FILE, type);
        }
        return asBinaryResult(raw, obj).setContentType(type).base64();
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 60 with ResourceNotFoundException

use of com.google.gerrit.extensions.restapi.ResourceNotFoundException in project gerrit by GerritCodeReview.

the class Fixes method parse.

@Override
public FixResource parse(RevisionResource revisionResource, IdString id) throws ResourceNotFoundException, OrmException {
    String fixId = id.get();
    ChangeNotes changeNotes = revisionResource.getNotes();
    List<RobotComment> robotComments = commentsUtil.robotCommentsByPatchSet(changeNotes, revisionResource.getPatchSet().getId());
    for (RobotComment robotComment : robotComments) {
        for (FixSuggestion fixSuggestion : robotComment.fixSuggestions) {
            if (Objects.equals(fixId, fixSuggestion.fixId)) {
                return new FixResource(revisionResource, fixSuggestion.replacements);
            }
        }
    }
    throw new ResourceNotFoundException(id);
}
Also used : FixSuggestion(com.google.gerrit.reviewdb.client.FixSuggestion) RobotComment(com.google.gerrit.reviewdb.client.RobotComment) IdString(com.google.gerrit.extensions.restapi.IdString) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Aggregations

ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)75 IdString (com.google.gerrit.extensions.restapi.IdString)18 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)17 AuthException (com.google.gerrit.extensions.restapi.AuthException)15 Repository (org.eclipse.jgit.lib.Repository)14 Project (com.google.gerrit.reviewdb.client.Project)13 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)12 Account (com.google.gerrit.reviewdb.client.Account)11 RevCommit (org.eclipse.jgit.revwalk.RevCommit)11 RevWalk (org.eclipse.jgit.revwalk.RevWalk)11 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)10 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)10 IOException (java.io.IOException)9 RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)9 ObjectId (org.eclipse.jgit.lib.ObjectId)9 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)8 ProjectConfig (com.google.gerrit.server.git.ProjectConfig)8 CurrentUser (com.google.gerrit.server.CurrentUser)7 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)7 ArrayList (java.util.ArrayList)7