Search in sources :

Example 6 with EmailException

use of com.google.gerrit.common.errors.EmailException in project gerrit by GerritCodeReview.

the class SetAccountCommand method addEmail.

private void addEmail(String email) throws UnloggedFailure, RestApiException, OrmException, IOException, ConfigInvalidException, PermissionBackendException {
    EmailInput in = new EmailInput();
    in.email = email;
    in.noConfirmation = true;
    try {
        createEmailFactory.create(email).apply(rsrc, in);
    } catch (EmailException e) {
        throw die(e.getMessage());
    }
}
Also used : EmailException(com.google.gerrit.common.errors.EmailException) EmailInput(com.google.gerrit.extensions.api.accounts.EmailInput)

Example 7 with EmailException

use of com.google.gerrit.common.errors.EmailException in project gerrit by GerritCodeReview.

the class ChangeEmail method init.

/** Setup the message headers and envelope (TO, CC, BCC). */
@Override
protected void init() throws EmailException {
    if (args.projectCache != null) {
        projectState = args.projectCache.get(change.getProject());
    } else {
        projectState = null;
    }
    if (patchSet == null) {
        try {
            patchSet = changeData.currentPatchSet();
        } catch (OrmException err) {
            patchSet = null;
        }
    }
    if (patchSet != null) {
        setHeader("X-Gerrit-PatchSet", patchSet.getPatchSetId() + "");
        if (patchSetInfo == null) {
            try {
                patchSetInfo = args.patchSetInfoFactory.get(args.db.get(), changeData.notes(), patchSet.getId());
            } catch (PatchSetInfoNotAvailableException | OrmException err) {
                patchSetInfo = null;
            }
        }
    }
    authors = getAuthors();
    try {
        stars = args.starredChangesUtil.byChangeFromIndex(change.getId());
    } catch (OrmException e) {
        throw new EmailException("Failed to load stars for change " + change.getChangeId(), e);
    }
    super.init();
    if (timestamp != null) {
        setHeader("Date", new Date(timestamp.getTime()));
    }
    setChangeSubjectHeader();
    setHeader("X-Gerrit-Change-Id", "" + change.getKey().get());
    setHeader("X-Gerrit-Change-Number", "" + change.getChangeId());
    setChangeUrlHeader();
    setCommitIdHeader();
    if (notify.ordinal() >= NotifyHandling.OWNER_REVIEWERS.ordinal()) {
        try {
            addByEmail(RecipientType.CC, changeData.reviewersByEmail().byState(ReviewerStateInternal.CC));
            addByEmail(RecipientType.TO, changeData.reviewersByEmail().byState(ReviewerStateInternal.REVIEWER));
        } catch (OrmException e) {
            throw new EmailException("Failed to add unregistered CCs " + change.getChangeId(), e);
        }
    }
}
Also used : OrmException(com.google.gwtorm.server.OrmException) EmailException(com.google.gerrit.common.errors.EmailException) PatchSetInfoNotAvailableException(com.google.gerrit.server.patch.PatchSetInfoNotAvailableException) Date(java.util.Date)

Example 8 with EmailException

use of com.google.gerrit.common.errors.EmailException in project gerrit by GerritCodeReview.

the class SmtpEmailSender method open.

private SMTPClient open() throws EmailException {
    final AuthSMTPClient client = new AuthSMTPClient(UTF_8.name());
    if (smtpEncryption == Encryption.SSL) {
        client.enableSSL(sslVerify);
    }
    client.setConnectTimeout(connectTimeout);
    try {
        client.connect(smtpHost, smtpPort);
        int replyCode = client.getReplyCode();
        String replyString = client.getReplyString();
        if (!SMTPReply.isPositiveCompletion(replyCode)) {
            throw new EmailException(String.format("SMTP server rejected connection: %d: %s", replyCode, replyString));
        }
        if (!client.login()) {
            throw new EmailException("SMTP server rejected HELO/EHLO greeting: " + replyString);
        }
        if (smtpEncryption == Encryption.TLS) {
            if (!client.startTLS(smtpHost, smtpPort, sslVerify)) {
                throw new EmailException("SMTP server does not support TLS");
            }
            if (!client.login()) {
                throw new EmailException("SMTP server rejected login: " + replyString);
            }
        }
        if (smtpUser != null && !client.auth(smtpUser, smtpPass)) {
            throw new EmailException("SMTP server rejected auth: " + replyString);
        }
        return client;
    } catch (IOException | EmailException e) {
        if (client.isConnected()) {
            try {
                client.disconnect();
            } catch (IOException e2) {
            //Ignored
            }
        }
        if (e instanceof EmailException) {
            throw (EmailException) e;
        }
        throw new EmailException(e.getMessage(), e);
    }
}
Also used : AuthSMTPClient(org.apache.commons.net.smtp.AuthSMTPClient) EmailException(com.google.gerrit.common.errors.EmailException) IOException(java.io.IOException)

Example 9 with EmailException

use of com.google.gerrit.common.errors.EmailException in project gerrit by GerritCodeReview.

the class SmtpEmailSender method send.

@Override
public void send(final Address from, Collection<Address> rcpt, final Map<String, EmailHeader> callerHeaders, String textBody, @Nullable String htmlBody) throws EmailException {
    if (!isEnabled()) {
        throw new EmailException("Sending email is disabled");
    }
    final Map<String, EmailHeader> hdrs = new LinkedHashMap<>(callerHeaders);
    setMissingHeader(hdrs, "MIME-Version", "1.0");
    setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
    setMissingHeader(hdrs, "Content-Disposition", "inline");
    setMissingHeader(hdrs, "User-Agent", "Gerrit/" + Version.getVersion());
    if (importance != null) {
        setMissingHeader(hdrs, "Importance", importance);
    }
    if (expiryDays > 0) {
        Date expiry = new Date(TimeUtil.nowMs() + expiryDays * 24 * 60 * 60 * 1000L);
        setMissingHeader(hdrs, "Expiry-Date", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
    }
    String encodedBody;
    if (htmlBody == null) {
        setMissingHeader(hdrs, "Content-Type", "text/plain; charset=UTF-8");
        encodedBody = textBody;
    } else {
        String boundary = generateMultipartBoundary(textBody, htmlBody);
        setMissingHeader(hdrs, "Content-Type", "multipart/alternative; boundary=\"" + boundary + "\"; charset=UTF-8");
        encodedBody = buildMultipartBody(boundary, textBody, htmlBody);
    }
    StringBuffer rejected = new StringBuffer();
    try {
        final SMTPClient client = open();
        try {
            if (!client.setSender(from.getEmail())) {
                throw new EmailException("Server " + smtpHost + " rejected from address " + from.getEmail());
            }
            /* Do not prevent the email from being sent to "good" users simply
         * because some users get rejected.  If not, a single rejected
         * project watcher could prevent email for most actions on a project
         * from being sent to any user!  Instead, queue up the errors, and
         * throw an exception after sending the email to get the rejected
         * error(s) logged.
         */
            for (Address addr : rcpt) {
                if (!client.addRecipient(addr.getEmail())) {
                    String error = client.getReplyString();
                    rejected.append("Server ").append(smtpHost).append(" rejected recipient ").append(addr).append(": ").append(error);
                }
            }
            Writer messageDataWriter = client.sendMessageData();
            if (messageDataWriter == null) {
                /* Include rejected recipient error messages here to not lose that
           * information. That piece of the puzzle is vital if zero recipients
           * are accepted and the server consequently rejects the DATA command.
           */
                throw new EmailException(rejected + "Server " + smtpHost + " rejected DATA command: " + client.getReplyString());
            }
            try (Writer w = new BufferedWriter(messageDataWriter)) {
                for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
                    if (!h.getValue().isEmpty()) {
                        w.write(h.getKey());
                        w.write(": ");
                        h.getValue().write(w);
                        w.write("\r\n");
                    }
                }
                w.write("\r\n");
                w.write(encodedBody);
                w.flush();
            }
            if (!client.completePendingCommand()) {
                throw new EmailException("Server " + smtpHost + " rejected message body: " + client.getReplyString());
            }
            client.logout();
            if (rejected.length() > 0) {
                throw new EmailException(rejected.toString());
            }
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        throw new EmailException("Cannot send outgoing email", e);
    }
}
Also used : Address(com.google.gerrit.server.mail.Address) IOException(java.io.IOException) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) BufferedWriter(java.io.BufferedWriter) AuthSMTPClient(org.apache.commons.net.smtp.AuthSMTPClient) SMTPClient(org.apache.commons.net.smtp.SMTPClient) EmailException(com.google.gerrit.common.errors.EmailException) SimpleDateFormat(java.text.SimpleDateFormat) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer)

Example 10 with EmailException

use of com.google.gerrit.common.errors.EmailException in project gerrit by GerritCodeReview.

the class AddSshKey method apply.

public Response<SshKeyInfo> apply(IdentifiedUser user, Input input) throws BadRequestException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new Input();
    }
    if (input.raw == null) {
        throw new BadRequestException("SSH public key missing");
    }
    final RawInput rawKey = input.raw;
    String sshPublicKey = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return rawKey.getInputStream();
        }
    }.asCharSource(UTF_8).read();
    try {
        AccountSshKey sshKey = authorizedKeys.addKey(user.getAccountId(), sshPublicKey);
        try {
            addKeyFactory.create(user, sshKey).send();
        } catch (EmailException e) {
            log.error("Cannot send SSH key added message to " + user.getAccount().getPreferredEmail(), e);
        }
        sshKeyCache.evict(user.getUserName());
        return Response.<SshKeyInfo>created(GetSshKeys.newSshKeyInfo(sshKey));
    } catch (InvalidSshKeyException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RawInput(com.google.gerrit.extensions.restapi.RawInput) Input(com.google.gerrit.server.account.AddSshKey.Input) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) SshKeyInfo(com.google.gerrit.extensions.common.SshKeyInfo) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) RawInput(com.google.gerrit.extensions.restapi.RawInput) EmailException(com.google.gerrit.common.errors.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ByteSource(com.google.common.io.ByteSource)

Aggregations

EmailException (com.google.gerrit.common.errors.EmailException)10 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)3 OrmException (com.google.gwtorm.server.OrmException)3 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)2 ValidationException (com.google.gerrit.server.validators.ValidationException)2 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 MalformedURLException (java.net.MalformedURLException)2 Date (java.util.Date)2 AuthSMTPClient (org.apache.commons.net.smtp.AuthSMTPClient)2 RuntimeInstance (org.apache.velocity.runtime.RuntimeInstance)2 ByteSource (com.google.common.io.ByteSource)1 InvalidSshKeyException (com.google.gerrit.common.errors.InvalidSshKeyException)1 EmailInput (com.google.gerrit.extensions.api.accounts.EmailInput)1 EmailInfo (com.google.gerrit.extensions.common.EmailInfo)1 SshKeyInfo (com.google.gerrit.extensions.common.SshKeyInfo)1 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)1 RawInput (com.google.gerrit.extensions.restapi.RawInput)1 CheckResult (com.google.gerrit.gpg.CheckResult)1 Fingerprint (com.google.gerrit.gpg.Fingerprint)1