Search in sources :

Example 26 with RestApiException

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

the class ReviewProjectAccess method updateProjectConfig.

// TODO(dborowitz): Hack MetaDataUpdate so it can be created within a BatchUpdate and we can avoid
// calling setUpdateRef(false).
@SuppressWarnings("deprecation")
@Override
protected Change.Id updateProjectConfig(ProjectControl projectControl, ProjectConfig config, MetaDataUpdate md, boolean parentProjectUpdate) throws IOException, OrmException, PermissionDeniedException {
    RefControl refsMetaConfigControl = projectControl.controlForRef(RefNames.REFS_CONFIG);
    if (!refsMetaConfigControl.isVisible()) {
        throw new PermissionDeniedException(RefNames.REFS_CONFIG + " not visible");
    }
    if (!projectControl.isOwner() && !refsMetaConfigControl.canUpload()) {
        throw new PermissionDeniedException("cannot upload to " + RefNames.REFS_CONFIG);
    }
    md.setInsertChangeId(true);
    Change.Id changeId = new Change.Id(seq.nextChangeId());
    RevCommit commit = config.commitToNewRef(md, new PatchSet.Id(changeId, Change.INITIAL_PATCH_SET_ID).toRefName());
    if (commit.getId().equals(base)) {
        return null;
    }
    try (ObjectInserter objInserter = md.getRepository().newObjectInserter();
        ObjectReader objReader = objInserter.newReader();
        RevWalk rw = new RevWalk(objReader);
        BatchUpdate bu = updateFactory.create(db, config.getProject().getNameKey(), projectControl.getUser(), TimeUtil.nowTs())) {
        bu.setRepository(md.getRepository(), rw, objInserter);
        bu.insertChange(changeInserterFactory.create(changeId, commit, RefNames.REFS_CONFIG).setValidate(false).setUpdateRef(// Created by commitToNewRef.
        false));
        bu.execute();
    } catch (UpdateException | RestApiException e) {
        throw new IOException(e);
    }
    ChangeResource rsrc;
    try {
        rsrc = changes.parse(changeId);
    } catch (ResourceNotFoundException e) {
        throw new IOException(e);
    }
    addProjectOwnersAsReviewers(rsrc);
    if (parentProjectUpdate) {
        addAdministratorsAsReviewers(rsrc);
    }
    return changeId;
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) Change(com.google.gerrit.reviewdb.client.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ChangeResource(com.google.gerrit.server.change.ChangeResource) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PermissionDeniedException(com.google.gerrit.common.errors.PermissionDeniedException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectId(org.eclipse.jgit.lib.ObjectId) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 27 with RestApiException

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

the class CheckAccessIT method accessible.

@Test
public void accessible() {
    Map<AccessCheckInput, Integer> inputs = ImmutableMap.of(new AccessCheckInput(user.email, normalProject.get(), null), 200, new AccessCheckInput(user.email, secretProject.get(), null), 403, new AccessCheckInput(user.email, "nonexistent", null), 404, new AccessCheckInput(privilegedUser.email, normalProject.get(), null), 200, new AccessCheckInput(privilegedUser.email, secretProject.get(), null), 200);
    for (Map.Entry<AccessCheckInput, Integer> entry : inputs.entrySet()) {
        String in = newGson().toJson(entry.getKey());
        AccessCheckInfo info = null;
        try {
            info = gApi.config().server().checkAccess(entry.getKey());
        } catch (RestApiException e) {
            fail(String.format("check.check(%s): exception %s", in, e));
        }
        int want = entry.getValue();
        if (want != info.status) {
            fail(String.format("check.access(%s) = %d, want %d", in, info.status, want));
        }
        switch(want) {
            case 403:
                assertThat(info.message).contains("cannot see");
                break;
            case 404:
                assertThat(info.message).contains("does not exist");
                break;
            case 200:
                assertThat(info.message).isNull();
                break;
            default:
                fail(String.format("unknown code %d", want));
        }
    }
}
Also used : AccessCheckInput(com.google.gerrit.extensions.api.config.AccessCheckInput) AccessCheckInfo(com.google.gerrit.extensions.api.config.AccessCheckInfo) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 28 with RestApiException

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

the class AbstractSubmit method submit.

protected void submit(String changeId, SubmitInput input, Class<? extends RestApiException> expectedExceptionType, String expectedExceptionMsg) throws Exception {
    approve(changeId);
    if (expectedExceptionType == null) {
        assertSubmittable(changeId);
    }
    try {
        gApi.changes().id(changeId).current().submit(input);
        if (expectedExceptionType != null) {
            fail("Expected exception of type " + expectedExceptionType.getSimpleName());
        }
    } catch (RestApiException e) {
        if (expectedExceptionType == null) {
            throw e;
        }
        // us the stack trace.
        if (!expectedExceptionType.isAssignableFrom(e.getClass()) || !e.getMessage().equals(expectedExceptionMsg)) {
            throw new AssertionError("Expected exception of type " + expectedExceptionType.getSimpleName() + " with message: \"" + expectedExceptionMsg + "\" but got exception of type " + e.getClass().getSimpleName() + " with message \"" + e.getMessage() + "\"", e);
        }
        return;
    }
    ChangeInfo change = gApi.changes().id(changeId).info();
    assertMerged(change.changeId);
}
Also used : ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Example 29 with RestApiException

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

the class AbstractSubmit method submitMultipleChangesOtherMergeConflictPreview.

@Test
public void submitMultipleChangesOtherMergeConflictPreview() throws Exception {
    RevCommit initialHead = getRemoteHead();
    PushOneCommit.Result change = createChange("Change 1", "a.txt", "content");
    submit(change.getChangeId());
    RevCommit headAfterFirstSubmit = getRemoteHead();
    testRepo.reset(initialHead);
    PushOneCommit.Result change2 = createChange("Change 2", "a.txt", "other content");
    PushOneCommit.Result change3 = createChange("Change 3", "d", "d");
    PushOneCommit.Result change4 = createChange("Change 4", "e", "e");
    // change 2 is not approved, but we ignore labels
    approve(change3.getChangeId());
    try (BinaryResult request = submitPreview(change4.getChangeId())) {
        assertThat(getSubmitType()).isEqualTo(SubmitType.CHERRY_PICK);
        submit(change4.getChangeId());
    } catch (RestApiException e) {
        switch(getSubmitType()) {
            case FAST_FORWARD_ONLY:
                assertThat(e.getMessage()).isEqualTo("Failed to submit 3 changes due to the following problems:\n" + "Change " + change2.getChange().getId() + ": internal error: " + "change not processed by merge strategy\n" + "Change " + change3.getChange().getId() + ": internal error: " + "change not processed by merge strategy\n" + "Change " + change4.getChange().getId() + ": Project policy " + "requires all submissions to be a fast-forward. Please " + "rebase the change locally and upload again for review.");
                break;
            case REBASE_IF_NECESSARY:
            case REBASE_ALWAYS:
                String change2hash = change2.getChange().currentPatchSet().getRevision().get();
                assertThat(e.getMessage()).isEqualTo("Cannot rebase " + change2hash + ": The change could " + "not be rebased due to a conflict during merge.");
                break;
            case MERGE_ALWAYS:
            case MERGE_IF_NECESSARY:
                assertThat(e.getMessage()).isEqualTo("Failed to submit 3 changes due to the following problems:\n" + "Change " + change2.getChange().getId() + ": Change could not be " + "merged due to a path conflict. Please rebase the change " + "locally and upload the rebased commit for review.\n" + "Change " + change3.getChange().getId() + ": Change could not be " + "merged due to a path conflict. Please rebase the change " + "locally and upload the rebased commit for review.\n" + "Change " + change4.getChange().getId() + ": Change could not be " + "merged due to a path conflict. Please rebase the change " + "locally and upload the rebased commit for review.");
                break;
            case CHERRY_PICK:
            default:
                fail("Should not reach here.");
                break;
        }
        RevCommit headAfterSubmit = getRemoteHead();
        assertThat(headAfterSubmit).isEqualTo(headAfterFirstSubmit);
        assertRefUpdatedEvents(initialHead, headAfterFirstSubmit);
        assertChangeMergedEvents(change.getChangeId(), headAfterFirstSubmit.name());
    }
}
Also used : RestApiException(com.google.gerrit.extensions.restapi.RestApiException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) RevCommit(org.eclipse.jgit.revwalk.RevCommit) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 30 with RestApiException

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

the class NoteDbPrimaryIT method testReadOnly.

private void testReadOnly(Change.Id id) throws Exception {
    Timestamp before = TimeUtil.nowTs();
    Timestamp until = new Timestamp(before.getTime() + 1000 * 3600);
    // Set read-only.
    Change c = db.changes().get(id);
    assertThat(c).named("change " + id).isNotNull();
    NoteDbChangeState state = NoteDbChangeState.parse(c);
    state = state.withReadOnlyUntil(until);
    c.setNoteDbState(state.toString());
    db.changes().update(Collections.singleton(c));
    assertThat(gApi.changes().id(id.get()).get().subject).isEqualTo(PushOneCommit.SUBJECT);
    assertThat(gApi.changes().id(id.get()).get().topic).isNull();
    try {
        gApi.changes().id(id.get()).topic("a-topic");
        assert_().fail("expected read-only exception");
    } catch (RestApiException e) {
        Optional<Throwable> oe = Throwables.getCausalChain(e).stream().filter(x -> x instanceof OrmRuntimeException).findFirst();
        assertThat(oe).named("OrmRuntimeException in causal chain of " + e).isPresent();
        assertThat(oe.get().getMessage()).contains("read-only");
    }
    assertThat(gApi.changes().id(id.get()).get().topic).isNull();
    TestTimeUtil.setClock(new Timestamp(until.getTime() + 1000));
    assertThat(gApi.changes().id(id.get()).get().subject).isEqualTo(PushOneCommit.SUBJECT);
    gApi.changes().id(id.get()).topic("a-topic");
    assertThat(gApi.changes().id(id.get()).get().topic).isEqualTo("a-topic");
}
Also used : OrmRuntimeException(com.google.gwtorm.server.OrmRuntimeException) Optional(java.util.Optional) Change(com.google.gerrit.reviewdb.client.Change) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) Timestamp(java.sql.Timestamp) NoteDbChangeState(com.google.gerrit.server.notedb.NoteDbChangeState)

Aggregations

RestApiException (com.google.gerrit.extensions.restapi.RestApiException)50 ApiUtil.asRestApiException (com.google.gerrit.server.api.ApiUtil.asRestApiException)16 OrmException (com.google.gwtorm.server.OrmException)14 IOException (java.io.IOException)14 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)12 UpdateException (com.google.gerrit.server.update.UpdateException)12 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)10 Change (com.google.gerrit.reviewdb.client.Change)8 AuthException (com.google.gerrit.extensions.restapi.AuthException)7 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)7 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)7 BatchUpdateOp (com.google.gerrit.server.update.BatchUpdateOp)6 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)5 ArrayList (java.util.ArrayList)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)5 Test (org.junit.Test)5 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)4 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)4 ChangeContext (com.google.gerrit.server.update.ChangeContext)4 Provider (com.google.inject.Provider)4