Example usage for javax.mail MessagingException MessagingException

List of usage examples for javax.mail MessagingException MessagingException

Introduction

In this page you can find the example usage for javax.mail MessagingException MessagingException.

Prototype

public MessagingException(String s, Exception e) 

Source Link

Document

Constructs a MessagingException with the specified Exception and detail message.

Usage

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificate.java

protected void onHandleUserEvent(User user) throws MessagingException {
    try {//  ww  w  .j av  a  2 s. com
        ActivationContext activationContext = getActivationContext().get(ACTIVATION_CONTEXT_KEY,
                ActivationContext.class);

        Check.notNull(activationContext, "activationContext");

        /*
         * Reset in case there was a retry
         */
        activationContext.setUser(null);

        boolean requestCertificate = true;

        if (skipIfAvailable) {
            if (user.getSigningKeyAndCertificate() != null) {
                logger.debug("The user " + user.getEmail() + " already has a valid signing certificate.");

                requestCertificate = false;
            }

            if (requestCertificate
                    && certificateRequestStore.getSizeByEmail(user.getEmail(), Match.EXACT) > 0) {
                logger.debug("there is already a pending request for user " + user.getEmail());

                requestCertificate = false;
            }
        }

        if (requestCertificate) {
            requestCertificate(user);

            activationContext.setUser(user);
        }
    } catch (KeyStoreException e) {
        throw new MessagingException("Error getting signing key for user: " + user.getEmail(), e);
    } catch (CertStoreException e) {
        throw new MessagingException("Error getting signing key for user: " + user.getEmail(), e);
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error getting signing key for user: " + user.getEmail(), e);
    }
}

From source file:com.sun.mail.pop3.POP3Folder.java

/**
 * Prefetch information about POP3 messages.
 * If the FetchProfile contains <code>UIDFolder.FetchProfileItem.UID</code>,
 * POP3 UIDs for all messages in the folder are fetched using the POP3
 * UIDL command.//w  ww  .  j a  v  a 2s.c  o m
 * If the FetchProfile contains <code>FetchProfile.Item.ENVELOPE</code>,
 * the headers and size of all messages are fetched using the POP3 TOP
 * and LIST commands.
 */
public synchronized void fetch(Message[] msgs, FetchProfile fp) throws MessagingException {
    checkReadable();
    if (!doneUidl && fp.contains(UIDFolder.FetchProfileItem.UID)) {
        /*
         * Since the POP3 protocol only lets us fetch the UID
         * for a single message or for all messages, we go ahead
         * and fetch UIDs for all messages here, ignoring the msgs
         * parameter.  We could be more intelligent and base this
         * decision on the number of messages fetched, or the
         * percentage of the total number of messages fetched.
         */
        String[] uids = new String[message_cache.size()];
        try {
            if (!port.uidl(uids))
                return;
        } catch (EOFException eex) {
            close(false);
            throw new FolderClosedException(this, eex.toString());
        } catch (IOException ex) {
            throw new MessagingException("error getting UIDL", ex);
        }
        for (int i = 0; i < uids.length; i++) {
            if (uids[i] == null)
                continue;
            POP3Message m = (POP3Message) getMessage(i + 1);
            m.uid = uids[i];
        }
        doneUidl = true; // only do this once
    }
    if (fp.contains(FetchProfile.Item.ENVELOPE)) {
        for (int i = 0; i < msgs.length; i++) {
            try {
                POP3Message msg = (POP3Message) msgs[i];
                // fetch headers
                msg.getHeader("");
                // fetch message size
                msg.getSize();
            } catch (MessageRemovedException mex) {
                // should never happen, but ignore it if it does
            }
        }
    }
}

From source file:mitm.application.djigzo.james.matchers.SubjectPhoneNumber.java

@Override
public Collection<MailAddress> matchMail(Mail mail) throws MessagingException {
    List<MailAddress> matchingRecipients = null;

    String phoneNumber = null;/*from  ww w  . ja v a2 s  . c om*/

    MimeMessage message = mail.getMessage();

    /*
     * We need to check whether the original subject is stored in the mail attributes because
     * the check for the telephone number should be done on the original subject. The reason
     * for this is that the current subject can result in the detection of an incorrect
     * telephone number because the subject was changed because the subject trigger was
     * removed. 
     * 
     * Example:
     *  
     * original subject is: "test 123 [encrypt] 123456". The subject is: "test 123 123456" after
     * the trigger has been removed. The telephone nr 123123456 is detected instead of 123456.
     * 
     * See bug report: https://jira.djigzo.com/browse/GATEWAY-11
     * 
     */
    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    String originalSubject = mailAttributes.getOriginalSubject();

    if (originalSubject == null) {
        originalSubject = message.getSubject();
    }

    if (StringUtils.isNotBlank(originalSubject)) {
        Matcher matcher = phoneNumberPattern.matcher(originalSubject);

        if (matcher.find()) {
            phoneNumber = matcher.group();

            /*
             * Remove the match and set the subject without the number. 
             * 
             * Note: the match should be removed from the current subject!!
             * 
             * Note2: using substringBeforeLast is only correct if the pattern matches the end
             * of the subject (which is the default). If the pattern matches something in the
             * middle, substringBeforeLast should not be used.
             */
            message.setSubject(StringUtils.substringBeforeLast(message.getSubject(), phoneNumber));
        }
    }

    if (StringUtils.isNotBlank(phoneNumber)) {
        matchingRecipients = MailAddressUtils.getRecipients(mail);

        int nrOfRecipients = CollectionUtils.getSize(matchingRecipients);

        if (nrOfRecipients == 1) {
            try {
                boolean added = addPhoneNumber(mail, matchingRecipients.get(0), phoneNumber);

                if (!added) {
                    /* 
                     * addPhoneNumbers has more thorough checks to see if the phone 
                     * number is valid and if not, there will be no matcj
                     */
                    matchingRecipients = Collections.emptyList();
                }
            } catch (DatabaseException e) {
                throw new MessagingException("Exception adding phone numbers.", e);
            }
        } else {
            /*
             * A telephone number was found but we cannot add the number to a users account
             * because we do not known to which recipient the number belongs. We will however
             * return all the recipients.
             */
            logger.warn("Found " + nrOfRecipients + " recipients but only one is supported.");
        }
    }

    if (matchingRecipients == null) {
        matchingRecipients = Collections.emptyList();
    }

    return matchingRecipients;
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificate.java

@Override
public void serviceMail(Mail mail) {
    try {//w  w w.j a va2  s  .co  m
        final ActivationContext activationContext = new ActivationContext();

        /*
         * Place the activationContext in the context so we can use it in onHandleUserEvent
         */
        getActivationContext().set(ACTIVATION_CONTEXT_KEY, activationContext);

        MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() {
            @Override
            public void handleUser(User user) throws MessagingException {
                onHandleUserEvent(user);
            }
        };

        final MailAddressHandler mailAddressHandler = new MailAddressHandler(sessionManager, userWorkflow,
                actionExecutor, eventHandler, ACTION_RETRIES);

        final InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

        /*
         * If the from is an invalid email address invalid@invalid.tld will be returned. We don't want to request
         * a certificate for that address.
         */
        if (originator != null && !EmailAddressUtils.isInvalidDummyAddress(originator)) {
            Callable<Null> callable = new Callable<Null>() {
                @Override
                public Null call() throws Exception {
                    mailAddressHandler.handleMailAddresses(
                            MailAddressUtils.fromAddressArrayToMailAddressList(originator));

                    /*
                     * activationContext.getUser() will return null if there was no certificate 
                     * requested for the user
                     */
                    makeNonPersistentUserPersistent(activationContext.getUser());

                    return null;
                }
            };

            try {
                if (synchronizeRequests) {
                    /*
                     * Synchronize certificate requests to make sure only one certificate is requested for
                     * a user even if multiple messages are sent by the same user at the same time
                     */
                    keyedBarrier.execute(originator, callable, keyedBarrierTimeout);
                } else {
                    callable.call();
                }
            } catch (Exception e) {
                throw new MessagingException("Error requesting a certificate.", e);
            }
        } else {
            logger.debug(
                    "Message originator is an invalid email address. Certificate request will be skipped.");
        }
    } catch (Exception e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);

        /*
         * If the MessagingException is caused by a CancelCertificateRequestException, do not log stacktrace 
         */
        if (rootCause instanceof CancelCertificateRequestException) {
            getLogger().warn("Certificate request was canceled. Message: " + rootCause.getMessage());
        } else {
            getLogger().error("Error requesting certificates.", e);
        }
    }
}

From source file:com.sun.mail.pop3.POP3Folder.java

/**
 * Return the unique ID string for this message, or null if
 * not available.  Uses the POP3 UIDL command.
 *
 * @return          unique ID string//from  w w  w .j a  v a2 s .  c o m
 * @exception   MessagingException
 */
public synchronized String getUID(Message msg) throws MessagingException {
    checkOpen();
    POP3Message m = (POP3Message) msg;
    try {
        if (m.uid == POP3Message.UNKNOWN)
            m.uid = port.uidl(m.getMessageNumber());
        return m.uid;
    } catch (EOFException eex) {
        close(false);
        throw new FolderClosedException(this, eex.toString());
    } catch (IOException ex) {
        throw new MessagingException("error getting UIDL", ex);
    }
}

From source file:mitm.common.security.smime.handler.SMIMEInfoHandlerImpl.java

private MimeMessage handleEncrypted(MimeMessage message, SMIMEInspector sMIMEInspector, int level,
        boolean decrypted) throws MessagingException {
    SMIMEEnvelopedInspector envelopedInspector = sMIMEInspector.getEnvelopedInspector();

    String encryptionAlgorithm = envelopedInspector.getEncryptionAlgorithmOID();

    SMIMEEncryptionAlgorithm encryptionAlg = SMIMEEncryptionAlgorithm.fromOID(encryptionAlgorithm);

    if (encryptionAlg != null) {
        encryptionAlgorithm = encryptionAlg.toString();

        AlgorithmParameters parameters;

        try {//w ww.j ava 2s .c  o  m
            parameters = envelopedInspector.getEncryptionAlgorithmParameters();

            encryptionAlgorithm = encryptionAlgorithm + ", Key size: "
                    + SMIMEEncryptionAlgorithm.getKeySize(encryptionAlg, parameters);
        } catch (CryptoMessageSyntaxException e) {
            logger.error("Error getting encryption algorithm parameters");
        }
    }

    setHeader(SMIMESecurityInfoHeader.ENCRYPTION_ALGORITHM, encryptionAlgorithm, level, message);

    List<RecipientInfo> recipients;

    try {
        recipients = envelopedInspector.getRecipients();
    } catch (CryptoMessageSyntaxException e) {
        throw new MessagingException("Error getting encryption recipients.", e);
    }

    int nrOfRecipients = recipients.size();

    if (nrOfRecipients > maxRecipients) {
        logger.warn("There are more recipients but the maximum has been reached.");

        nrOfRecipients = maxRecipients;
    }

    for (int recipientIndex = 0; recipientIndex < nrOfRecipients; recipientIndex++) {
        RecipientInfo recipient = recipients.get(recipientIndex);

        setHeader(SMIMESecurityInfoHeader.ENCRYPTION_RECIPIENT + recipientIndex, recipient.toString(), level,
                message);
    }

    onEncrypted(message, sMIMEInspector, level, decrypted);

    return message;
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandler.java

private Messages handleMessageTransactedNonStrict(Mail mail) throws MessagingException {
    MimeMessage sourceMessage = mail.getMessage();

    RecursiveSMIMEHandler recursiveSMIMEHandler = new RecursiveSMIMEHandler(pKISecurityServices);

    recursiveSMIMEHandler.setAddInfo(addInfo);
    recursiveSMIMEHandler.setDecrypt(decrypt);
    recursiveSMIMEHandler.setDecompress(decompress);
    recursiveSMIMEHandler.setMaxRecursion(maxRecursion);
    recursiveSMIMEHandler.setRemoveSignature(isRemoveSignatureAttribute(mail));
    recursiveSMIMEHandler.setProtectedHeaders(protectedHeaders);
    recursiveSMIMEHandler.setCertificatesEventListener(certificateCollectionEvent);
    /*//from   ww  w .jav a2s . co  m
     * Use a different SMIMEInfoHandler so we can add tags (like [encrypt]) to the subject of the message
     */
    recursiveSMIMEHandler.setSmimeInfoHandler(new ExtSMIMEInfoHandlerImpl(mail));

    MimeMessage handledMessage;

    try {
        handledMessage = recursiveSMIMEHandler.handlePart(sourceMessage);
    } catch (SMIMEHandlerException e) {
        throw new MessagingException("Error handling message.", e);
    }

    Messages messages = new Messages(threshold);

    try {
        List<MailAddress> recipients = MailAddressUtils.getRecipients(mail);

        if (handledMessage != null) {
            messages.addMessage(handledMessage, recipients);
        } else {
            /*
             * The message was not encrypted, could not be decrypted etc.
             */
            messages.addAsIsRecipient(recipients);
        }
    } catch (Exception e) {
        /*
         * We need to catch all to make sure messages will always be closed.
         * If not there is a change that temp files won't be deleted.
         */
        messages.close();

        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }

        if (e instanceof MessagingException) {
            throw (MessagingException) e;
        }

        throw new MessagingException("Error handling user", e);
    }

    return messages;
}

From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java

@Override
protected Template getTemplateFromUser(User user, SimpleHash root)
        throws MessagingException, HierarchicalPropertiesException, IOException {
    /*//  w w  w  .j a  v  a  2 s.  c om
     * Single password mode does not support PDF reply because with Single password mode only one PDF will be sent
     * to multiple recipients.
     */
    if (passwordMode == PasswordMode.MULTIPLE) {
        try {
            UserProperties properties = user.getUserPreferences().getProperties();

            String baseReplyURL = properties.getPdfReplyURL();
            String serverSecret = properties.getServerSecret();

            boolean senderAllowed = properties.isPdfReplyAllowed();

            ReplySettings replySettings = getActivationContext().get(REPLY_SETTINGS_ACTIVATION_CONTEXT_KEY,
                    ReplySettings.class);

            if (replySettings != null) {
                if (senderAllowed) {
                    /*
                     * Use the Reply-To of the message if available
                     */
                    String replyTo = null;

                    if (useReplyTo) {
                        replyTo = replySettings.getReplyTo();
                    }

                    /*
                     * Fallback to the user's email address (i.e., the from) if the Reply-To is not
                     * available or not valid. 
                     */
                    if (StringUtils.isEmpty(replyTo)) {
                        replyTo = user.getEmail();
                    }

                    String replyURL = createReplyURL(baseReplyURL, replySettings.getSubject(),
                            replySettings.getRecipients(), user.getEmail(), replyTo, serverSecret);

                    if (replyURL != null) {
                        replySettings.setReplyURL(replyURL);

                        /*
                         * Set the replyURL in the Freemarker conext so it can be used in the
                         * PDF encryption message templates
                         */
                        root.put(REPLY_URL_TEMPLATE_PARAM, replyURL);
                    }
                } else {
                    getLogger().debug("Sender {} does not allow reply to PDF.", user.getEmail());
                }
            } else {
                getLogger().warn("ReplySettings are not set");
            }
        } catch (HierarchicalPropertiesException e) {
            throw new MessagingException("Error getting reply pdf properties", e);
        }
    }

    return super.getTemplateFromUser(user, root);
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandler.java

private Set<KeyAndCertificate> getKeyAndCertificates(User user) throws MessagingException {
    try {/*from  w ww.  jav  a2  s  .com*/
        Set<KeyAndCertificate> keys = new HashSet<KeyAndCertificate>();

        Set<X509Certificate> certificates = new HashSet<X509Certificate>();

        encryptionRecipientSelector.select(Collections.singleton(user), certificates);

        KeyAndCertStore keyAndCertStore = pKISecurityServices.getKeyAndCertStore();

        for (X509Certificate certificate : certificates) {
            X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate);

            if (entry != null) {
                KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry);

                if (keyAndCertificate != null && keyAndCertificate.getPrivateKey() != null) {
                    keys.add(keyAndCertificate);
                }
            }
        }
        return keys;
    } catch (CertStoreException e) {
        throw new MessagingException("Error getting key and certificates for user: " + user.getEmail(), e);
    } catch (KeyStoreException e) {
        throw new MessagingException("Error getting key and certificates for user: " + user.getEmail(), e);
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error getting key and certificates for user: " + user.getEmail(), e);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandler.java

private Messages handleMessageTransactedStrict(Mail mail) throws MessagingException {
    Messages messages = new Messages(threshold);

    try {//from w  w  w  .j a  va  2s  . c  om
        List<MailAddress> recipients = MailAddressUtils.getRecipients(mail);

        for (MailAddress recipient : recipients) {
            if (recipient == null) {
                continue;
            }

            MimeMessage handledMessage = null;

            try {
                handledMessage = handleMessageForUser(mail,
                        userWorkflow.getUser(recipient.toString(), GetUserMode.CREATE_IF_NOT_EXIST));
            } catch (AddressException e) {
                throw new MessagingException("Error strict handling message for user: " + recipient, e);
            } catch (HierarchicalPropertiesException e) {
                throw new MessagingException("Error strict handling message for user: " + recipient, e);
            }

            if (handledMessage != null) {
                messages.addMessage(handledMessage, recipient);
            } else {
                /*
                 * The message was not encrypted, could not be decrypted etc.
                 */
                messages.addAsIsRecipient(recipient);
            }
        }

        return messages;
    } catch (Exception e) {
        /*
         * We need to catch all to make sure messages will always be closed.
         * If not there is a change that temp files won't be deleted.
         */
        messages.close();

        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }

        if (e instanceof MessagingException) {
            throw (MessagingException) e;
        }

        throw new MessagingException("Error handling user", e);
    }
}