Search in sources :

Example 1 with ProjectResource

use of com.google.gerrit.server.project.ProjectResource in project gerrit by GerritCodeReview.

the class CreateChange method applyImpl.

@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, TopLevelResource parent, ChangeInput input) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
    if (Strings.isNullOrEmpty(input.project)) {
        throw new BadRequestException("project must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.branch)) {
        throw new BadRequestException("branch must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.subject)) {
        throw new BadRequestException("commit message must be non-empty");
    }
    if (input.status != null) {
        if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) {
            throw new BadRequestException("unsupported change status");
        }
        if (!allowDrafts && input.status == ChangeStatus.DRAFT) {
            throw new MethodNotAllowedException("draft workflow is disabled");
        }
    }
    String refName = RefNames.fullName(input.branch);
    ProjectResource rsrc = projectsCollection.parse(input.project);
    Capable r = rsrc.getControl().canPushToAtLeastOneRef();
    if (r != Capable.OK) {
        throw new AuthException(r.getMessage());
    }
    RefControl refControl = rsrc.getControl().controlForRef(refName);
    if (!refControl.canUpload() || !refControl.isVisible()) {
        throw new AuthException("cannot upload review");
    }
    Project.NameKey project = rsrc.getNameKey();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        ObjectId parentCommit;
        List<String> groups;
        if (input.baseChange != null) {
            List<ChangeControl> ctls = changeFinder.find(input.baseChange, rsrc.getControl().getUser());
            if (ctls.size() != 1) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            ChangeControl ctl = Iterables.getOnlyElement(ctls);
            if (!ctl.isVisible(db.get())) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
            parentCommit = ObjectId.fromString(ps.getRevision().get());
            groups = ps.getGroups();
        } else {
            Ref destRef = git.getRefDatabase().exactRef(refName);
            if (destRef != null) {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    throw new ResourceConflictException(String.format("Branch %s already exists.", refName));
                }
                parentCommit = destRef.getObjectId();
            } else {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    parentCommit = null;
                } else {
                    throw new UnprocessableEntityException(String.format("Branch %s does not exist.", refName));
                }
            }
            groups = Collections.emptyList();
        }
        RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
        Timestamp now = TimeUtil.nowTs();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
        AccountState account = accountCache.get(me.getAccountId());
        GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();
        ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
        ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, input.subject);
        String commitMessage = ChangeIdUtil.insertId(input.subject, id);
        if (Boolean.TRUE.equals(info.signedOffBy)) {
            commitMessage += String.format("%s%s", SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName));
        }
        RevCommit c;
        if (input.merge != null) {
            // create a merge commit
            if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
                throw new BadRequestException("Submit type: " + submitType + " is not supported");
            }
            c = newMergeCommit(git, oi, rw, rsrc.getControl(), mergeTip, input.merge, author, commitMessage);
        } else {
            // create an empty commit
            c = newCommit(oi, rw, author, mergeTip, commitMessage);
        }
        Change.Id changeId = new Change.Id(seq.nextChangeId());
        ChangeInserter ins = changeInserterFactory.create(changeId, c, refName);
        ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
        String topic = input.topic;
        if (topic != null) {
            topic = Strings.emptyToNull(topic.trim());
        }
        ins.setTopic(topic);
        ins.setDraft(input.status == ChangeStatus.DRAFT);
        ins.setPrivate(input.isPrivate != null && input.isPrivate);
        ins.setWorkInProgress(input.workInProgress != null && input.workInProgress);
        ins.setGroups(groups);
        ins.setNotify(input.notify);
        ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
        try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.insertChange(ins);
            bu.execute();
        }
        ChangeJson json = jsonFactory.noOptions();
        return Response.created(json.format(ins.getChange()));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Capable(com.google.gerrit.common.data.Capable) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ChangeControl(com.google.gerrit.server.project.ChangeControl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) AccountState(com.google.gerrit.server.account.AccountState) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) ProjectResource(com.google.gerrit.server.project.ProjectResource) ObjectId(org.eclipse.jgit.lib.ObjectId)

Example 2 with ProjectResource

use of com.google.gerrit.server.project.ProjectResource in project gerrit by GerritCodeReview.

the class RestApiQuotaEnforcer method enforce.

/**
 * Enforce quota on a request for a given resource.
 */
void enforce(RestResource rsrc, HttpServletRequest req) throws QuotaException {
    String pathForQuotaReporting = RequestUtil.getRestPathWithoutIds(req);
    // Enrich the quota request we are operating on an interesting collection
    QuotaBackend.WithResource report = quotaBackend.currentUser();
    if (rsrc instanceof ChangeResource) {
        ChangeResource changeResource = (ChangeResource) rsrc;
        report = quotaBackend.currentUser().change(changeResource.getId(), changeResource.getProject());
    } else if (rsrc instanceof AccountResource) {
        AccountResource accountResource = (AccountResource) rsrc;
        report = quotaBackend.currentUser().account(accountResource.getUser().getAccountId());
    } else if (rsrc instanceof ProjectResource) {
        ProjectResource projectResource = (ProjectResource) rsrc;
        report = quotaBackend.currentUser().project(projectResource.getNameKey());
    }
    report.requestToken(quotaGroup(pathForQuotaReporting, req.getMethod())).throwOnError();
}
Also used : QuotaBackend(com.google.gerrit.server.quota.QuotaBackend) AccountResource(com.google.gerrit.server.account.AccountResource) ChangeResource(com.google.gerrit.server.change.ChangeResource) ProjectResource(com.google.gerrit.server.project.ProjectResource)

Example 3 with ProjectResource

use of com.google.gerrit.server.project.ProjectResource in project gerrit by GerritCodeReview.

the class GroupsImpl method list.

private SortedMap<String, GroupInfo> list(ListRequest req) throws RestApiException {
    TopLevelResource tlr = TopLevelResource.INSTANCE;
    ListGroups list = listGroups.get();
    list.setOptions(req.getOptions());
    for (String project : req.getProjects()) {
        try {
            ProjectResource rsrc = projects.parse(tlr, IdString.fromDecoded(project));
            list.addProject(rsrc.getProjectState());
        } catch (Exception e) {
            throw asRestApiException("Error looking up project " + project, e);
        }
    }
    for (String group : req.getGroups()) {
        list.addGroup(groupResolver.parse(group).getGroupUUID());
    }
    list.setVisibleToAll(req.getVisibleToAll());
    if (req.getOwnedBy() != null) {
        list.setOwnedBy(req.getOwnedBy());
    }
    if (req.getUser() != null) {
        try {
            list.setUser(accountResolver.resolve(req.getUser()).asUnique().account().id());
        } catch (Exception e) {
            throw asRestApiException("Error looking up user " + req.getUser(), e);
        }
    }
    list.setOwned(req.getOwned());
    list.setLimit(req.getLimit());
    list.setStart(req.getStart());
    list.setMatchSubstring(req.getSubstring());
    list.setMatchRegex(req.getRegex());
    list.setSuggest(req.getSuggest());
    try {
        return list.apply(tlr).value();
    } catch (Exception e) {
        throw asRestApiException("Cannot list groups", e);
    }
}
Also used : TopLevelResource(com.google.gerrit.extensions.restapi.TopLevelResource) ListGroups(com.google.gerrit.server.restapi.group.ListGroups) ProjectResource(com.google.gerrit.server.project.ProjectResource) IdString(com.google.gerrit.extensions.restapi.IdString) ApiUtil.asRestApiException(com.google.gerrit.server.api.ApiUtil.asRestApiException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Example 4 with ProjectResource

use of com.google.gerrit.server.project.ProjectResource in project gerrit by GerritCodeReview.

the class GetDashboard method parse.

private DashboardResource parse(ProjectState projectState, CurrentUser user, String id) throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
    List<String> p = Lists.newArrayList(Splitter.on(':').limit(2).split(id));
    String ref = Url.encode(p.get(0));
    String path = Url.encode(p.get(1));
    return dashboards.parse(new ProjectResource(projectState, user), IdString.fromUrl(ref + ':' + path));
}
Also used : ProjectResource(com.google.gerrit.server.project.ProjectResource) IdString(com.google.gerrit.extensions.restapi.IdString)

Example 5 with ProjectResource

use of com.google.gerrit.server.project.ProjectResource in project gerrit by GerritCodeReview.

the class SetHeadCommand method run.

@Override
protected void run() throws Exception {
    enableGracefulStop();
    HeadInput input = new HeadInput();
    input.ref = newHead;
    try {
        setHead.apply(new ProjectResource(project, user), input);
    } catch (UnprocessableEntityException e) {
        throw die(e);
    }
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) HeadInput(com.google.gerrit.extensions.api.projects.HeadInput) ProjectResource(com.google.gerrit.server.project.ProjectResource)

Aggregations

ProjectResource (com.google.gerrit.server.project.ProjectResource)17 ProjectState (com.google.gerrit.server.project.ProjectState)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)5 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)5 Project (com.google.gerrit.entities.Project)4 IdString (com.google.gerrit.extensions.restapi.IdString)4 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)4 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)4 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)4 ArrayList (java.util.ArrayList)4 ProjectInfo (com.google.gerrit.extensions.common.ProjectInfo)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3 Project (com.google.gerrit.reviewdb.client.Project)3 AuthException (com.google.gerrit.extensions.restapi.AuthException)2 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)2 ApiUtil.asRestApiException (com.google.gerrit.server.api.ApiUtil.asRestApiException)2 RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)2 ImmutableList (com.google.common.collect.ImmutableList)1 Capable (com.google.gerrit.common.data.Capable)1 BooleanProjectConfig (com.google.gerrit.entities.BooleanProjectConfig)1