Example usage for javax.mail.internet ParseException printStackTrace

List of usage examples for javax.mail.internet ParseException printStackTrace

Introduction

In this page you can find the example usage for javax.mail.internet ParseException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:crawl.SphinxWrapper.java

private static Document makeDocument(Page page) {
    String url = page.toURL();/*from w w w . ja va  2s . c  om*/
    FeatureMap params = Factory.newFeatureMap();

    Document doc = null;

    String docName = shortenUrl(url).replaceAll("[^\\p{ASCII}]", "_") + "_" + Gate.genSym();

    /* Take advantage of the MIME type from the server when
     * constructing the GATE document.      */
    String contentTypeStr = page.getContentType();
    String originalMimeType = null;

    if (contentTypeStr != null) {
        try {
            ContentType contentType = new ContentType(contentTypeStr);
            String mimeType = contentType.getBaseType();
            String encoding = contentType.getParameter("charset");

            // get the content as bytes, and convert it to string using the correct
            // encoding (thanks to Christian Wartena for patch)
            byte[] bContent = page.getContentBytes();
            String sContent = new String(bContent, Charset.forName(encoding));
            params.put(Document.DOCUMENT_STRING_CONTENT_PARAMETER_NAME, sContent);

            if (mimeType != null) {
                if (convertXmlTypes) {
                    originalMimeType = mimeType;
                    mimeType = convertMimeType(mimeType);
                    if (!originalMimeType.equals(mimeType)) {
                        System.out.println("   convert " + originalMimeType + " -> " + mimeType);
                    }
                }
                params.put(Document.DOCUMENT_MIME_TYPE_PARAMETER_NAME, mimeType);
            }

            if (encoding != null) {
                params.put(Document.DOCUMENT_ENCODING_PARAMETER_NAME, encoding);

            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    try {
        doc = (Document) Factory.createResource(DocumentImpl.class.getName(), params, null, docName);
        FeatureMap docFeatures = doc.getFeatures();

        Integer originalLength = page.getLength();
        docFeatures.put("originalLength", originalLength);

        /* Use the Last-Modified HTTP header if available.  */
        long lastModified = page.getLastModified();
        Date date;
        if (lastModified > 0L) {
            date = new Date(lastModified);
        } else {
            date = new Date();
        }
        docFeatures.put("Date", date);

        if (originalMimeType != null) {
            docFeatures.put("originalMimeType", originalMimeType);
        }

        doc.setSourceUrl(page.getURL());
        docFeatures.put("gate.SourceURL", url);
    } catch (ResourceInstantiationException e) {
        System.err.println("WARNING: could not intantiate document " + docName);
        e.printStackTrace();
    }

    return doc;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

protected String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (fileName == null) {
        try {/*  w w w.ja  va 2  s.  co m*/
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return fileName;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 *
 * @param part the part to be analyzed./* ww w  .  j  av  a2 s  .  c om*/
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return false;
}

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  w ww . ja  v a  2  s.c  o  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;
}