Search in sources :

Example 16 with ResourceNotFoundException

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

the class GetAccess method apply.

@Override
public ProjectAccessInfo apply(ProjectResource rsrc) throws ResourceNotFoundException, ResourceConflictException, IOException {
    // Load the current configuration from the repository, ensuring it's the most
    // recent version available. If it differs from what was in the project
    // state, force a cache flush now.
    //
    Project.NameKey projectName = rsrc.getNameKey();
    ProjectAccessInfo info = new ProjectAccessInfo();
    ProjectConfig config;
    ProjectControl pc = createProjectControl(projectName);
    RefControl metaConfigControl = pc.controlForRef(RefNames.REFS_CONFIG);
    try (MetaDataUpdate md = metaDataUpdateFactory.create(projectName)) {
        config = ProjectConfig.read(md);
        if (config.updateGroupNames(groupBackend)) {
            md.setMessage("Update group names\n");
            config.commit(md);
            projectCache.evict(config.getProject());
            pc = createProjectControl(projectName);
        } else if (config.getRevision() != null && !config.getRevision().equals(pc.getProjectState().getConfig().getRevision())) {
            projectCache.evict(config.getProject());
            pc = createProjectControl(projectName);
        }
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(e.getMessage());
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(rsrc.getName());
    }
    info.local = new HashMap<>();
    info.ownerOf = new HashSet<>();
    Map<AccountGroup.UUID, Boolean> visibleGroups = new HashMap<>();
    for (AccessSection section : config.getAccessSections()) {
        String name = section.getName();
        if (AccessSection.GLOBAL_CAPABILITIES.equals(name)) {
            if (pc.isOwner()) {
                info.local.put(name, createAccessSection(section));
                info.ownerOf.add(name);
            } else if (metaConfigControl.isVisible()) {
                info.local.put(section.getName(), createAccessSection(section));
            }
        } else if (RefConfigSection.isValid(name)) {
            RefControl rc = pc.controlForRef(name);
            if (rc.isOwner()) {
                info.local.put(name, createAccessSection(section));
                info.ownerOf.add(name);
            } else if (metaConfigControl.isVisible()) {
                info.local.put(name, createAccessSection(section));
            } else if (rc.isVisible()) {
                // Filter the section to only add rules describing groups that
                // are visible to the current-user. This includes any group the
                // user is a member of, as well as groups they own or that
                // are visible to all users.
                AccessSection dst = null;
                for (Permission srcPerm : section.getPermissions()) {
                    Permission dstPerm = null;
                    for (PermissionRule srcRule : srcPerm.getRules()) {
                        AccountGroup.UUID group = srcRule.getGroup().getUUID();
                        if (group == null) {
                            continue;
                        }
                        Boolean canSeeGroup = visibleGroups.get(group);
                        if (canSeeGroup == null) {
                            try {
                                canSeeGroup = groupControlFactory.controlFor(group).isVisible();
                            } catch (NoSuchGroupException e) {
                                canSeeGroup = Boolean.FALSE;
                            }
                            visibleGroups.put(group, canSeeGroup);
                        }
                        if (canSeeGroup) {
                            if (dstPerm == null) {
                                if (dst == null) {
                                    dst = new AccessSection(name);
                                    info.local.put(name, createAccessSection(dst));
                                }
                                dstPerm = dst.getPermission(srcPerm.getName(), true);
                            }
                            dstPerm.add(srcRule);
                        }
                    }
                }
            }
        }
    }
    if (info.ownerOf.isEmpty() && pc.isOwnerAnyRef()) {
        // Special case: If the section list is empty, this project has no current
        // access control information. Rely on what ProjectControl determines
        // is ownership, which probably means falling back to site administrators.
        info.ownerOf.add(AccessSection.ALL);
    }
    if (config.getRevision() != null) {
        info.revision = config.getRevision().name();
    }
    ProjectState parent = Iterables.getFirst(pc.getProjectState().parents(), null);
    if (parent != null) {
        info.inheritsFrom = projectJson.format(parent.getProject());
    }
    if (pc.getProject().getNameKey().equals(allProjectsName)) {
        if (pc.isOwner()) {
            info.ownerOf.add(AccessSection.GLOBAL_CAPABILITIES);
        }
    }
    info.isOwner = toBoolean(pc.isOwner());
    info.canUpload = toBoolean(pc.isOwner() || (metaConfigControl.isVisible() && metaConfigControl.canUpload()));
    info.canAdd = toBoolean(pc.canAddRefs());
    info.configVisible = pc.isOwner() || metaConfigControl.isVisible();
    return info;
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) HashMap(java.util.HashMap) PermissionRule(com.google.gerrit.common.data.PermissionRule) ProjectAccessInfo(com.google.gerrit.extensions.api.access.ProjectAccessInfo) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) AccessSection(com.google.gerrit.common.data.AccessSection) NoSuchGroupException(com.google.gerrit.common.errors.NoSuchGroupException) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Permission(com.google.gerrit.common.data.Permission) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 17 with ResourceNotFoundException

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

the class CheckMergeability method apply.

@Override
public MergeableInfo apply(BranchResource resource) throws IOException, BadRequestException, ResourceNotFoundException {
    if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
        throw new BadRequestException("Submit type: " + submitType + " is not supported");
    }
    MergeableInfo result = new MergeableInfo();
    result.submitType = submitType;
    result.strategy = strategy;
    try (Repository git = gitManager.openRepository(resource.getNameKey());
        RevWalk rw = new RevWalk(git);
        ObjectInserter inserter = new InMemoryInserter(git)) {
        Merger m = MergeUtil.newMerger(inserter, git.getConfig(), strategy);
        Ref destRef = git.getRefDatabase().exactRef(resource.getRef());
        if (destRef == null) {
            throw new ResourceNotFoundException(resource.getRef());
        }
        RevCommit targetCommit = rw.parseCommit(destRef.getObjectId());
        RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, source);
        if (!resource.getControl().canReadCommit(db.get(), git, sourceCommit)) {
            throw new BadRequestException("do not have read permission for: " + source);
        }
        if (rw.isMergedInto(sourceCommit, targetCommit)) {
            result.mergeable = true;
            result.commitMerged = true;
            result.contentMerged = true;
            return result;
        }
        if (m.merge(false, targetCommit, sourceCommit)) {
            result.mergeable = true;
            result.commitMerged = false;
            result.contentMerged = m.getResultTreeId().equals(targetCommit.getTree());
        } else {
            result.mergeable = false;
            if (m instanceof ResolveMerger) {
                result.conflicts = ((ResolveMerger) m).getUnmergedPaths();
            }
        }
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    return result;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Merger(org.eclipse.jgit.merge.Merger) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) MergeableInfo(com.google.gerrit.extensions.common.MergeableInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InMemoryInserter(com.google.gerrit.server.git.InMemoryInserter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 18 with ResourceNotFoundException

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

the class GetReflog method apply.

@Override
public List<ReflogEntryInfo> apply(BranchResource rsrc) throws AuthException, ResourceNotFoundException, RepositoryNotFoundException, IOException {
    if (!rsrc.getControl().isOwner()) {
        throw new AuthException("not project owner");
    }
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ReflogReader r = repo.getReflogReader(rsrc.getRef());
        if (r == null) {
            throw new ResourceNotFoundException(rsrc.getRef());
        }
        List<ReflogEntry> entries;
        if (from == null && to == null) {
            entries = limit > 0 ? r.getReverseEntries(limit) : r.getReverseEntries();
        } else {
            entries = limit > 0 ? new ArrayList<>(limit) : new ArrayList<>();
            for (ReflogEntry e : r.getReverseEntries()) {
                Timestamp timestamp = new Timestamp(e.getWho().getWhen().getTime());
                if ((from == null || from.before(timestamp)) && (to == null || to.after(timestamp))) {
                    entries.add(e);
                }
                if (limit > 0 && entries.size() >= limit) {
                    break;
                }
            }
        }
        return Lists.transform(entries, ReflogEntryInfo::new);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ReflogReader(org.eclipse.jgit.lib.ReflogReader) ReflogEntry(org.eclipse.jgit.lib.ReflogEntry) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Timestamp(java.sql.Timestamp)

Example 19 with ResourceNotFoundException

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

the class ListBranches method allBranches.

private List<BranchInfo> allBranches(ProjectResource rsrc) throws IOException, ResourceNotFoundException {
    List<Ref> refs;
    try (Repository db = repoManager.openRepository(rsrc.getNameKey())) {
        Collection<Ref> heads = db.getRefDatabase().getRefs(Constants.R_HEADS).values();
        refs = new ArrayList<>(heads.size() + 3);
        refs.addAll(heads);
        refs.addAll(db.getRefDatabase().exactRef(Constants.HEAD, RefNames.REFS_CONFIG, RefNames.REFS_USERS_DEFAULT).values());
    } catch (RepositoryNotFoundException noGitRepository) {
        throw new ResourceNotFoundException();
    }
    Set<String> targets = Sets.newHashSetWithExpectedSize(1);
    for (Ref ref : refs) {
        if (ref.isSymbolic()) {
            targets.add(ref.getTarget().getName());
        }
    }
    ProjectControl pctl = rsrc.getControl();
    PermissionBackend.ForProject perm = permissionBackend.user(user).project(rsrc.getNameKey());
    List<BranchInfo> branches = new ArrayList<>(refs.size());
    for (Ref ref : refs) {
        if (ref.isSymbolic()) {
            // A symbolic reference to another branch, instead of
            // showing the resolved value, show the name it references.
            //
            String target = ref.getTarget().getName();
            RefControl targetRefControl = pctl.controlForRef(target);
            if (!targetRefControl.isVisible()) {
                continue;
            }
            if (target.startsWith(Constants.R_HEADS)) {
                target = target.substring(Constants.R_HEADS.length());
            }
            BranchInfo b = new BranchInfo();
            b.ref = ref.getName();
            b.revision = target;
            branches.add(b);
            if (!Constants.HEAD.equals(ref.getName())) {
                b.canDelete = perm.ref(ref.getName()).testOrFalse(RefPermission.DELETE) ? true : null;
            }
            continue;
        }
        if (pctl.controlForRef(ref.getName()).isVisible()) {
            branches.add(createBranchInfo(perm.ref(ref.getName()), ref, pctl, targets));
        }
    }
    Collections.sort(branches, new BranchComparator());
    return branches;
}
Also used : BranchInfo(com.google.gerrit.extensions.api.projects.BranchInfo) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ArrayList(java.util.ArrayList) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Ref(org.eclipse.jgit.lib.Ref) Repository(org.eclipse.jgit.lib.Repository) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 20 with ResourceNotFoundException

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

the class PutDescription method apply.

@Override
public Response<String> apply(ProjectResource resource, DescriptionInput input) throws AuthException, ResourceConflictException, ResourceNotFoundException, IOException {
    if (input == null) {
        // Delete would set description to null.
        input = new DescriptionInput();
    }
    ProjectControl ctl = resource.getControl();
    IdentifiedUser user = ctl.getUser().asIdentifiedUser();
    if (!ctl.isOwner()) {
        throw new AuthException("not project owner");
    }
    try (MetaDataUpdate md = updateFactory.create(resource.getNameKey())) {
        ProjectConfig config = ProjectConfig.read(md);
        Project project = config.getProject();
        project.setDescription(Strings.emptyToNull(input.description));
        String msg = MoreObjects.firstNonNull(Strings.emptyToNull(input.commitMessage), "Updated description.\n");
        if (!msg.endsWith("\n")) {
            msg += "\n";
        }
        md.setAuthor(user);
        md.setMessage(msg);
        config.commit(md);
        cache.evict(ctl.getProject());
        md.getRepository().setGitwebDescription(project.getDescription());
        return Strings.isNullOrEmpty(project.getDescription()) ? Response.<String>none() : Response.ok(project.getDescription());
    } catch (RepositoryNotFoundException notFound) {
        throw new ResourceNotFoundException(resource.getName());
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(String.format("invalid project.config: %s", e.getMessage()));
    }
}
Also used : ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) DescriptionInput(com.google.gerrit.extensions.api.projects.DescriptionInput) AuthException(com.google.gerrit.extensions.restapi.AuthException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

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