Search in sources :

Example 1 with UsedAt

use of com.google.gerrit.common.UsedAt in project gerrit by GerritCodeReview.

the class AsyncReceiveCommits method preReceive.

/**
 * Processes {@code commands}, applies them to Git storage and communicates back on the wire.
 */
@UsedAt(UsedAt.Project.GOOGLE)
public ReceiveCommitsResult preReceive(Collection<ReceiveCommand> commands) throws TimeoutException, UncheckedExecutionException {
    if (commands.stream().anyMatch(c -> c.getResult() != Result.NOT_ATTEMPTED)) {
        // pre-receive hooks
        return ReceiveCommitsResult.empty();
    }
    String currentThreadName = Thread.currentThread().getName();
    MultiProgressMonitor monitor = newMultiProgressMonitor(multiProgressMonitorFactory, receiveCommits.getMessageSender());
    Callable<ReceiveCommitsResult> callable = () -> {
        String oldName = Thread.currentThread().getName();
        Thread.currentThread().setName(oldName + "-for-" + currentThreadName);
        try {
            return receiveCommits.processCommands(commands, monitor);
        } finally {
            Thread.currentThread().setName(oldName);
        }
    };
    try {
        // WorkQueue does not support Callable<T>, so we have to covert it here.
        FutureTask<ReceiveCommitsResult> runnable = ProjectRunnable.fromCallable(callable, receiveCommits.getProject().getNameKey(), "receive-commits", null, false);
        monitor.waitFor(executor.submit(scopePropagator.wrap(runnable)), receiveTimeoutMillis, TimeUnit.MILLISECONDS, cancellationTimeoutMillis, TimeUnit.MILLISECONDS);
        if (!runnable.isDone()) {
            // At this point we are either done or have thrown a TimeoutException and bailed out.
            throw new IllegalStateException("unable to get receive commits result");
        }
        return runnable.get();
    } catch (TimeoutException e) {
        metrics.timeouts.increment();
        logger.atWarning().withCause(e).log("Timeout in ReceiveCommits while processing changes for project %s", projectState.getName());
        throw e;
    } catch (InterruptedException | ExecutionException e) {
        throw new UncheckedExecutionException(e);
    }
}
Also used : UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) MultiProgressMonitor(com.google.gerrit.server.git.MultiProgressMonitor) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) UsedAt(com.google.gerrit.common.UsedAt)

Example 2 with UsedAt

use of com.google.gerrit.common.UsedAt in project gerrit by GerritCodeReview.

the class Submit method mergeChange.

@UsedAt(UsedAt.Project.GOOGLE)
public Change mergeChange(RevisionResource rsrc, IdentifiedUser submitter, SubmitInput input) throws RestApiException, IOException, UpdateException, ConfigInvalidException, PermissionBackendException {
    Change change = rsrc.getChange();
    if (!change.isNew()) {
        throw new ResourceConflictException("change is " + ChangeUtil.status(change));
    } else if (!ProjectUtil.branchExists(repoManager, change.getDest())) {
        throw new ResourceConflictException(String.format("destination branch \"%s\" not found.", change.getDest().branch()));
    } else if (!rsrc.getPatchSet().id().equals(change.currentPatchSetId())) {
        // TODO Allow submitting non-current revision by changing the current.
        throw new ResourceConflictException(String.format("revision %s is not current revision", rsrc.getPatchSet().commitId().name()));
    }
    try (MergeOp op = mergeOpProvider.get()) {
        Change updatedChange;
        updatedChange = op.merge(change, submitter, true, input, false);
        if (updatedChange.isMerged()) {
            return updatedChange;
        }
        throw new IllegalStateException(String.format("change %s of project %s unexpectedly had status %s after submit attempt", updatedChange.getId(), updatedChange.getProject(), updatedChange.getStatus()));
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MergeOp(com.google.gerrit.server.submit.MergeOp) Change(com.google.gerrit.entities.Change) UsedAt(com.google.gerrit.common.UsedAt)

Example 3 with UsedAt

use of com.google.gerrit.common.UsedAt in project gerrit by GerritCodeReview.

the class PutHttpPassword method apply.

@UsedAt(UsedAt.Project.PLUGIN_SERVICEUSER)
public Response<String> apply(IdentifiedUser user, String newPassword) throws ResourceNotFoundException, ResourceConflictException, IOException, ConfigInvalidException {
    String userName = user.getUserName().orElseThrow(() -> new ResourceConflictException("username must be set"));
    Optional<ExternalId> optionalExtId = externalIds.get(externalIdKeyFactory.create(SCHEME_USERNAME, userName));
    ExternalId extId = optionalExtId.orElseThrow(ResourceNotFoundException::new);
    accountsUpdateProvider.get().update("Set HTTP Password via API", extId.accountId(), u -> u.updateExternalId(externalIdFactory.createWithPassword(extId.key(), extId.accountId(), extId.email(), newPassword)));
    try {
        httpPasswordUpdateSenderFactory.create(user, newPassword == null ? "deleted" : "added or updated").send();
    } catch (EmailException e) {
        logger.atSevere().withCause(e).log("Cannot send HttpPassword update message to %s", user.getAccount().preferredEmail());
    }
    return Strings.isNullOrEmpty(newPassword) ? Response.none() : Response.ok(newPassword);
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) EmailException(com.google.gerrit.exceptions.EmailException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) UsedAt(com.google.gerrit.common.UsedAt)

Example 4 with UsedAt

use of com.google.gerrit.common.UsedAt in project gerrit by GerritCodeReview.

the class CreateEmail method apply.

/**
 * To be used from plugins that want to create emails without permission checks.
 */
@UsedAt(UsedAt.Project.PLUGIN_SERVICEUSER)
public EmailInfo apply(IdentifiedUser user, IdString id, EmailInput input) throws RestApiException, EmailException, MethodNotAllowedException, IOException, ConfigInvalidException, PermissionBackendException {
    String email = id.get().trim();
    if (input == null) {
        input = new EmailInput();
    }
    if (input.email != null && !email.equals(input.email)) {
        throw new BadRequestException("email address must match URL");
    }
    if (!validator.isValid(email)) {
        throw new BadRequestException("invalid email address");
    }
    EmailInfo info = new EmailInfo();
    info.email = email;
    if (input.noConfirmation || isDevMode) {
        if (isDevMode) {
            logger.atWarning().log("skipping email validation in developer mode");
        }
        try {
            accountManager.link(user.getAccountId(), authRequestFactory.createForEmail(email));
        } catch (AccountException e) {
            throw new ResourceConflictException(e.getMessage());
        }
        if (input.preferred) {
            putPreferred.apply(new AccountResource.Email(user, email), null);
            info.preferred = true;
        }
    } else {
        try {
            RegisterNewEmailSender emailSender = registerNewEmailFactory.create(email);
            if (!emailSender.isAllowed()) {
                throw new MethodNotAllowedException("Not allowed to add email address " + email);
            }
            emailSender.setMessageId(messageIdGenerator.fromAccountUpdate(user.getAccountId()));
            emailSender.send();
            info.pendingConfirmation = true;
        } catch (EmailException | RuntimeException e) {
            logger.atSevere().withCause(e).log("Cannot send email verification message to %s", email);
            throw e;
        }
    }
    return info;
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) IdString(com.google.gerrit.extensions.restapi.IdString) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountResource(com.google.gerrit.server.account.AccountResource) AccountException(com.google.gerrit.server.account.AccountException) RegisterNewEmailSender(com.google.gerrit.server.mail.send.RegisterNewEmailSender) EmailException(com.google.gerrit.exceptions.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) EmailInfo(com.google.gerrit.extensions.common.EmailInfo) EmailInput(com.google.gerrit.extensions.api.accounts.EmailInput) UsedAt(com.google.gerrit.common.UsedAt)

Example 5 with UsedAt

use of com.google.gerrit.common.UsedAt in project gerrit by GerritCodeReview.

the class LocalMergeSuperSetComputation method byCommitsOnBranchNotMerged.

@UsedAt(UsedAt.Project.GOOGLE)
public ChangeSet byCommitsOnBranchNotMerged(OpenRepo or, BranchNameKey branch, Set<String> visibleHashes, Set<String> nonVisibleHashes, CurrentUser user) throws IOException {
    List<ChangeData> potentiallyVisibleChanges = byCommitsOnBranchNotMerged(or, branch, visibleHashes);
    List<ChangeData> invisibleChanges = new ArrayList<>(byCommitsOnBranchNotMerged(or, branch, nonVisibleHashes));
    List<ChangeData> visibleChanges = new ArrayList<>(potentiallyVisibleChanges.size());
    ChangeIsVisibleToPredicate changeIsVisibleToPredicate = changeIsVisibleToPredicateFactory.forUser(user);
    for (ChangeData cd : potentiallyVisibleChanges) {
        // permissions (except for private changes).
        if (!cd.change().isPrivate() || changeIsVisibleToPredicate.match(cd)) {
            visibleChanges.add(cd);
        } else {
            invisibleChanges.add(cd);
        }
    }
    return new ChangeSet(visibleChanges, invisibleChanges);
}
Also used : ChangeIsVisibleToPredicate(com.google.gerrit.server.query.change.ChangeIsVisibleToPredicate) ArrayList(java.util.ArrayList) ChangeData(com.google.gerrit.server.query.change.ChangeData) UsedAt(com.google.gerrit.common.UsedAt)

Aggregations

UsedAt (com.google.gerrit.common.UsedAt)6 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 EmailException (com.google.gerrit.exceptions.EmailException)2 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)1 Change (com.google.gerrit.entities.Change)1 EmailInput (com.google.gerrit.extensions.api.accounts.EmailInput)1 EmailInfo (com.google.gerrit.extensions.common.EmailInfo)1 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)1 IdString (com.google.gerrit.extensions.restapi.IdString)1 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)1 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)1 AccountException (com.google.gerrit.server.account.AccountException)1 AccountResource (com.google.gerrit.server.account.AccountResource)1 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)1 MultiProgressMonitor (com.google.gerrit.server.git.MultiProgressMonitor)1 RegisterNewEmailSender (com.google.gerrit.server.mail.send.RegisterNewEmailSender)1 ChangeData (com.google.gerrit.server.query.change.ChangeData)1 ChangeIsVisibleToPredicate (com.google.gerrit.server.query.change.ChangeIsVisibleToPredicate)1 MergeOp (com.google.gerrit.server.submit.MergeOp)1 ArrayList (java.util.ArrayList)1