Example usage for javax.mail URLName toString

List of usage examples for javax.mail URLName toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Constructs a string representation of this URLName.

Usage

From source file:StoreTreeNode.java

/**
 * We override toString() so we can display the store URLName
 * without the password.//from w w w .jav a  2s.co m
 */

public String toString() {
    if (display == null) {
        URLName url = store.getURLName();
        if (url == null) {
            display = store.toString();
        } else {
            // don't show the password
            URLName too = new URLName(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(),
                    url.getUsername(), null);
            display = too.toString();
        }
    }

    return display;
}

From source file:com.adaptris.util.TestURLName.java

public void testUrl() throws Exception {
    URLName url = new URLName(testUrl);
    assertEquals(protocol, url.getProtocol());
    assertEquals(username, url.getUsername());
    assertEquals(password, url.getPassword());
    assertEquals(host, url.getHost());//w w w.ja v a  2 s .c o m
    assertEquals(testUrl, url.toString());
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Refresh Information about folders.//from w  ww  .  ja va2 s.  co m
 * Tries to connect folders that are not yet connected.
 *
 * @doCount display message counts for user
 */
public void refreshFolderInformation(boolean subscribed_only, boolean doCount) {
    /* Right now, doCount corresponds exactly to subscribed_only.
     * When we add a user preference setting or one-time action,
     * to present messages from all folders, we will have
     * subscribed_only false and doCount true. */

    //log.fatal("Invoking refreshFolderInformation(boolean, boolean)",
    //new Throwable("Thread Dump"));  FOR DEBUGGING
    setEnv();
    if (folders == null)
        folders = new Hashtable<String, Folder>();
    Folder rootFolder = null;
    String cur_mh_id = "";
    Enumeration mailhosts = user.mailHosts();
    int max_depth = 0;
    int folderType;

    while (mailhosts.hasMoreElements()) {
        cur_mh_id = (String) mailhosts.nextElement();

        MailHostData mhd = user.getMailHost(cur_mh_id);

        URLName url = new URLName(mhd.getHostURL());

        Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString());

        int depth = 0;

        try {
            rootFolder = getRootFolder(cur_mh_id);

            try {
                rootFolder.setSubscribed(true);
            } catch (MessagingException ex) {
                // Only IMAP supports subscription
                log.warn("Folder.setSubscribed failed.  " + "Probably a non-supporting mail service: " + ex);
            }
        } catch (MessagingException ex) {
            mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to connect and get Root folder from (" + url + ')', ex);
            return;
        }

        try {
            depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount);
            log.debug("Loaded INBOX folders below Root to a depth of " + depth);
            String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin();
            //String extraFolderPath = "/home/" + mhd.getLogin();
            Folder nonInboxBase = rootFolder.getFolder(extraFolderPath);
            log.debug("Trying extra base dir " + nonInboxBase.getFullName());
            if (nonInboxBase.exists()) {
                folderType = nonInboxBase.getType();
                if ((folderType & Folder.HOLDS_MESSAGES) != 0) {
                    // Can only Subscribe to Folders which may hold Msgs.
                    nonInboxBase.setSubscribed(true);
                    if (!nonInboxBase.isSubscribed())
                        log.error("A bug in JavaMail or in the server is " + "preventing subscription to '"
                                + nonInboxBase.getFullName() + "' on '" + url
                                + "'.  Folders will not be visible.");
                }
                int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount);
                if (extraDepth > depth)
                    depth = extraDepth;
                log.debug("Loaded additional folders from below " + nonInboxBase.getFullName()
                        + " with max depth of " + extraDepth);
            }
        } catch (Exception ex) {
            if (!url.getProtocol().startsWith("pop"))
                mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to fetch child folders from (" + url + ')', ex);
        }
        if (depth > max_depth)
            max_depth = depth;
        model.addMailhost(mailhost);
    }
    model.setStateVar("max folder depth", (1 + max_depth) + "");
}

From source file:org.masukomi.aspirin.core.RemoteDelivery.java

/**
 * We can assume that the recipients of this message are all going to the
 * same mail server. We will now rely on the JNDI to do DNS MX record lookup
 * and try to deliver to the multiple mail servers. If it fails, it should
 * throw an exception.//from  ww w. ja  v a2s.co  m
 * 
 * Creation date: (2/24/00 11:25:00 PM)
 * 
 * @param mail
 *            org.apache.james.core.MailImpl
 * @param session
 *            javax.mail.Session
 * @return boolean Whether the delivery was successful and the message can
 *         be deleted
 */
private boolean deliver(QuedItem qi, Session session) {
    MailAddress rcpt = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)");
        }
        MailImpl mail = (MailImpl) qi.getMail();
        MimeMessage message = mail.getMessage();
        // Create an array of the recipients as InternetAddress objects
        Collection recipients = mail.getRecipients();
        InternetAddress addr[] = new InternetAddress[recipients.size()];
        int j = 0;
        // funky ass look because you can't getElementAt() in a Collection

        for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
            MailAddress currentRcpt = (MailAddress) i.next();
            addr[j] = currentRcpt.toInternetAddress();
        }
        if (addr.length <= 0) {
            if (log.isDebugEnabled()) {
                log.debug("No recipients specified... returning");
            }
            return true;
        }
        // Figure out which servers to try to send to. This collection
        // will hold all the possible target servers
        Collection targetServers = null;
        Iterator it = recipients.iterator();
        while (it.hasNext()) {
            rcpt = (MailAddress) recipients.iterator().next();
            if (!qi.recepientHasBeenHandled(rcpt)) {
                break;
            }
        }
        // theoretically it is possible to not hav eone that hasn't been
        // handled
        // however that's only if something has gone really wrong.
        if (rcpt != null) {
            String host = rcpt.getHost();
            // Lookup the possible targets
            try {
                // targetServers = MXLookup.urlsForHost(host); // farking
                // unreliable jndi bs
                targetServers = getMXRecordsForHost(host);
            } catch (Exception e) {
                log.error(e);
            }
            if (targetServers == null || targetServers.size() == 0) {
                log.warn("No mail server found for: " + host);
                StringBuffer exceptionBuffer = new StringBuffer(128)
                        .append("I found no MX record entries for the hostname ").append(host)
                        .append(".  I cannot determine where to send this message.");
                return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true);
            } else if (log.isTraceEnabled()) {
                log.trace(targetServers.size() + " servers found for " + host);
            }
            MessagingException lastError = null;
            Iterator i = targetServers.iterator();
            while (i.hasNext()) {
                try {
                    URLName outgoingMailServer = (URLName) i.next();
                    StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ")
                            .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString())
                            .append(" to addresses ").append(Arrays.asList(addr));
                    if (log.isDebugEnabled()) {
                        log.debug(logMessageBuffer.toString());
                    }
                    ;
                    // URLName urlname = new URLName("smtp://"
                    // + outgoingMailServer);
                    Properties props = session.getProperties();
                    if (mail.getSender() == null) {
                        props.put("mail.smtp.from", "<>");
                    } else {
                        String sender = mail.getSender().toString();
                        props.put("mail.smtp.from", sender);
                    }
                    // Many of these properties are only in later JavaMail
                    // versions
                    // "mail.smtp.ehlo" //default true
                    // "mail.smtp.auth" //default false
                    // "mail.smtp.dsn.ret" //default to nothing... appended
                    // as
                    // RET= after MAIL FROM line.
                    // "mail.smtp.dsn.notify" //default to
                    // nothing...appended as
                    // NOTIFY= after RCPT TO line.
                    Transport transport = null;
                    try {
                        transport = session.getTransport(outgoingMailServer);
                        try {
                            transport.connect();
                        } catch (MessagingException me) {
                            log.error(me);
                            // Any error on connect should cause the mailet
                            // to
                            // attempt
                            // to connect to the next SMTP server associated
                            // with this MX record,
                            // assuming the number of retries hasn't been
                            // exceeded.
                            if (failMessage(qi, rcpt, me, false)) {
                                return true;
                            } else {
                                continue;
                            }
                        }
                        transport.sendMessage(message, addr);
                        // log.debug("message sent to " +addr);
                        /*TODO: catch failures that should result 
                         * in failure with no retries
                         } catch (SendFailedException sfe){
                           qi.failForRecipient(que, );
                           */
                    } finally {
                        if (transport != null) {
                            transport.close();
                            transport = null;
                        }
                    }
                    logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName())
                            .append(") sent successfully to ").append(outgoingMailServer);
                    log.debug(logMessageBuffer.toString());
                    qi.succeededForRecipient(que, rcpt);
                    return true;
                } catch (MessagingException me) {
                    log.error(me);
                    // MessagingException are horribly difficult to figure
                    // out
                    // what actually happened.
                    StringBuffer exceptionBuffer = new StringBuffer(256)
                            .append("Exception delivering message (").append(mail.getName()).append(") - ")
                            .append(me.getMessage());
                    log.warn(exceptionBuffer.toString());
                    if ((me.getNextException() != null)
                            && (me.getNextException() instanceof java.io.IOException)) {
                        // This is more than likely a temporary failure
                        // If it's an IO exception with no nested exception,
                        // it's probably
                        // some socket or weird I/O related problem.
                        lastError = me;
                        continue;
                    }
                    // This was not a connection or I/O error particular to
                    // one
                    // SMTP server of an MX set. Instead, it is almost
                    // certainly
                    // a protocol level error. In this case we assume that
                    // this
                    // is an error we'd encounter with any of the SMTP
                    // servers
                    // associated with this MX record, and we pass the
                    // exception
                    // to the code in the outer block that determines its
                    // severity.
                    throw me;
                } // end catch
            } // end while
              // If we encountered an exception while looping through,
              // throw the last MessagingException we caught. We only
              // do this if we were unable to send the message to any
              // server. If sending eventually succeeded, we exit
              // deliver() though the return at the end of the try
              // block.
            if (lastError != null) {
                throw lastError;
            }
        } // END if (rcpt != null)
        else {
            log.error("unable to find recipient that handn't already been handled");
        }
    } catch (SendFailedException sfe) {
        log.error(sfe);
        boolean deleteMessage = false;
        Collection recipients = qi.getMail().getRecipients();
        // Would like to log all the types of email addresses
        if (log.isDebugEnabled()) {
            log.debug("Recipients: " + recipients);
        }
        /*
         * The rest of the recipients failed for one reason or another.
         * 
         * SendFailedException actually handles this for us. For example, if
         * you send a message that has multiple invalid addresses, you'll
         * get a top-level SendFailedException that that has the valid,
         * valid-unsent, and invalid address lists, with all of the server
         * response messages will be contained within the nested exceptions.
         * [Note: the content of the nested exceptions is implementation
         * dependent.]
         * 
         * sfe.getInvalidAddresses() should be considered permanent.
         * sfe.getValidUnsentAddresses() should be considered temporary.
         * 
         * JavaMail v1.3 properly populates those collections based upon the
         * 4xx and 5xx response codes.
         * 
         */
        if (sfe.getInvalidAddresses() != null) {
            Address[] address = sfe.getInvalidAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse invalid address: " + pe.getMessage());
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Invalid recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, true);
            }
        }
        if (sfe.getValidUnsentAddresses() != null) {
            Address[] address = sfe.getValidUnsentAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse unsent address: " + pe.getMessage());
                        }
                        pe.printStackTrace();
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Unsent recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, false);
            }
        }
        return deleteMessage;
    } catch (MessagingException ex) {
        log.error(ex);
        // We should do a better job checking this... if the failure is a
        // general
        // connect exception, this is less descriptive than more specific
        // SMTP command
        // failure... have to lookup and see what are the various Exception
        // possibilities
        // Unable to deliver message after numerous tries... fail
        // accordingly
        // We check whether this is a 5xx error message, which
        // indicates a permanent failure (like account doesn't exist
        // or mailbox is full or domain is setup wrong).
        // We fail permanently if this was a 5xx error
        return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0)));
    } catch (Throwable t) {
        log.error(t);
    }
    /*
     * If we get here, we've exhausted the loop of servers without sending
     * the message or throwing an exception. One case where this might
     * happen is if we get a MessagingException on each transport.connect(),
     * e.g., if there is only one server and we get a connect exception.
     * Return FALSE to keep run() from deleting the message.
     */
    return false;
}