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:org.apache.james.mailrepository.jcr.JCRMailRepository.java

public Mail retrieve(String key) throws MessagingException {
    try {/*  www  .j a va2  s  .  c  om*/
        Session session = login();
        try {
            String name = toSafeName(key);
            QueryManager manager = session.getWorkspace().getQueryManager();
            @SuppressWarnings("deprecation")
            Query query = manager.createQuery("/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)",
                    Query.XPATH);
            NodeIterator iterator = query.execute().getNodes();
            if (iterator.hasNext()) {
                return getMail(iterator.nextNode());
            } else {
                return null;
            }
        } finally {
            session.logout();
        }
    } catch (IOException e) {
        throw new MessagingException("Unable to retrieve message: " + key, e);
    } catch (RepositoryException e) {
        throw new MessagingException("Unable to retrieve message: " + key, e);
    }
}

From source file:org.apache.james.mailrepository.jcr.JCRMailRepository.java

@Override
protected void internalRemove(String key) throws MessagingException {
    try {//from   w w  w  .  j a  v a2 s.c  o  m
        Session session = login();
        try {
            String name = ISO9075.encode(Text.escapeIllegalJcrChars(key));
            QueryManager manager = session.getWorkspace().getQueryManager();
            @SuppressWarnings("deprecation")
            Query query = manager.createQuery("/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)",
                    Query.XPATH);
            NodeIterator nodes = query.execute().getNodes();
            if (nodes.hasNext()) {
                while (nodes.hasNext()) {
                    nodes.nextNode().remove();
                }
                session.save();
                logger.info("Mail " + key + " removed from repository");
            } else {
                logger.warn("Mail " + key + " not found");
            }
        } finally {
            session.logout();
        }
    } catch (RepositoryException e) {
        throw new MessagingException("Unable to remove message: " + key, e);
    }
}

From source file:org.apache.james.mailrepository.jcr.JCRMailRepository.java

@Override
protected void internalStore(Mail mail) throws MessagingException, IOException {
    try {/*from   w ww.j  a  v a2  s . co  m*/
        Session session = login();
        try {
            String name = Text.escapeIllegalJcrChars(mail.getName());
            final String xpath = "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)";

            QueryManager manager = session.getWorkspace().getQueryManager();
            @SuppressWarnings("deprecation")
            Query query = manager.createQuery(xpath, Query.XPATH);
            NodeIterator iterator = query.execute().getNodes();

            if (iterator.hasNext()) {
                while (iterator.hasNext()) {
                    setMail(iterator.nextNode(), mail);
                }
            } else {
                Node parent = session.getRootNode().getNode(MAIL_PATH);
                Node node = parent.addNode(name, "james:mail");
                Node resource = node.addNode("jcr:content", "nt:resource");
                resource.setProperty("jcr:mimeType", "message/rfc822");
                setMail(node, mail);
            }
            session.save();
            logger.info("Mail " + mail.getName() + " stored in repository");
        } finally {
            session.logout();
        }
    } catch (IOException e) {
        throw new MessagingException("Unable to store message: " + mail.getName(), e);
    } catch (RepositoryException e) {
        throw new MessagingException("Unable to store message: " + mail.getName(), e);
    }
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#retrieve(String)
 *//*from   w  w w.j  a  va2  s  .c  o  m*/
@SuppressWarnings("unchecked")
public Mail retrieve(String key) throws MessagingException {
    if (DEEP_DEBUG) {
        System.err.println("retrieving " + key);
    }
    Connection conn = null;
    PreparedStatement retrieveMessage = null;
    ResultSet rsMessage = null;
    try {
        conn = datasource.getConnection();
        if (DEEP_DEBUG) {
            System.err.println("got a conn " + key);
        }

        retrieveMessage = conn.prepareStatement(sqlQueries.getSqlString("retrieveMessageSQL", true));
        retrieveMessage.setString(1, key);
        retrieveMessage.setString(2, repositoryName);
        rsMessage = retrieveMessage.executeQuery();
        if (DEEP_DEBUG) {
            System.err.println("ran the query " + key);
        }
        if (!rsMessage.next()) {
            if (getLogger().isDebugEnabled()) {
                String debugBuffer = "Did not find a record " + key + " in " + repositoryName;
                getLogger().debug(debugBuffer);
            }
            return null;
        }
        // Determine whether attributes are used and retrieve them
        PreparedStatement retrieveMessageAttr = null;
        HashMap<String, Object> attributes = null;
        if (jdbcMailAttributesReady) {
            String retrieveMessageAttrSql = sqlQueries.getSqlString("retrieveMessageAttributesSQL", false);
            ResultSet rsMessageAttr = null;
            try {
                retrieveMessageAttr = conn.prepareStatement(retrieveMessageAttrSql);

                retrieveMessageAttr.setString(1, key);
                retrieveMessageAttr.setString(2, repositoryName);
                rsMessageAttr = retrieveMessageAttr.executeQuery();

                if (rsMessageAttr.next()) {
                    try {
                        byte[] serialized_attr;
                        String getAttributesOption = sqlQueries.getDbOption("getAttributes");
                        if (getAttributesOption != null && (getAttributesOption.equalsIgnoreCase("useBlob")
                                || getAttributesOption.equalsIgnoreCase("useBinaryStream"))) {
                            Blob b = rsMessageAttr.getBlob(1);
                            serialized_attr = b.getBytes(1, (int) b.length());
                        } else {
                            serialized_attr = rsMessageAttr.getBytes(1);
                        }
                        // this check is for better backwards compatibility
                        if (serialized_attr != null) {
                            ByteArrayInputStream bais = new ByteArrayInputStream(serialized_attr);
                            ObjectInputStream ois = new ObjectInputStream(bais);
                            attributes = (HashMap<String, Object>) ois.readObject();
                            ois.close();
                        }
                    } catch (IOException ioe) {
                        if (getLogger().isDebugEnabled()) {
                            String debugBuffer = "Exception reading attributes " + key + " in "
                                    + repositoryName;
                            getLogger().debug(debugBuffer, ioe);
                        }
                    }
                } else {
                    if (getLogger().isDebugEnabled()) {
                        String debugBuffer = "Did not find a record (attributes) " + key + " in "
                                + repositoryName;
                        getLogger().debug(debugBuffer);
                    }
                }
            } catch (SQLException sqle) {
                String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                        + sqle.getSQLState() + sqle.getNextException();
                getLogger().error(errorBuffer);
            } finally {
                theJDBCUtil.closeJDBCResultSet(rsMessageAttr);
                theJDBCUtil.closeJDBCStatement(retrieveMessageAttr);
            }
        }

        MailImpl mc = new MailImpl();
        mc.setAttributesRaw(attributes);
        mc.setName(key);
        mc.setState(rsMessage.getString(1));
        mc.setErrorMessage(rsMessage.getString(2));
        String sender = rsMessage.getString(3);
        if (sender == null) {
            mc.setSender(null);
        } else {
            mc.setSender(new MailAddress(sender));
        }
        StringTokenizer st = new StringTokenizer(rsMessage.getString(4), "\r\n", false);
        Set<MailAddress> recipients = new HashSet<MailAddress>();
        while (st.hasMoreTokens()) {
            recipients.add(new MailAddress(st.nextToken()));
        }
        mc.setRecipients(recipients);
        mc.setRemoteHost(rsMessage.getString(5));
        mc.setRemoteAddr(rsMessage.getString(6));
        mc.setLastUpdated(rsMessage.getTimestamp(7));

        MimeMessageJDBCSource source = new MimeMessageJDBCSource(this, key, sr);
        MimeMessageCopyOnWriteProxy message = new MimeMessageCopyOnWriteProxy(source);
        mc.setMessage(message);
        return mc;
    } catch (SQLException sqle) {
        String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                + sqle.getSQLState() + sqle.getNextException();
        getLogger().error(errorBuffer);
        getLogger().debug("Failed to retrieve mail", sqle);
        throw new MessagingException("Exception while retrieving mail: " + sqle.getMessage(), sqle);
    } catch (Exception me) {
        throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCResultSet(rsMessage);
        theJDBCUtil.closeJDBCStatement(retrieveMessage);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.lib.AbstractMailRepository#internalRemove(String)
 *///  w w  w .  j a  v  a2  s .c  o  m
protected void internalRemove(String key) throws MessagingException {
    Connection conn = null;
    PreparedStatement removeMessage = null;
    try {
        conn = datasource.getConnection();
        removeMessage = conn.prepareStatement(sqlQueries.getSqlString("removeMessageSQL", true));
        removeMessage.setString(1, key);
        removeMessage.setString(2, repositoryName);
        removeMessage.execute();

        if (sr != null) {
            sr.remove(key);
        }
    } catch (Exception me) {
        throw new MessagingException("Exception while removing mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCStatement(removeMessage);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#list()
 */// www. ja v a2 s .co  m
public Iterator<String> list() throws MessagingException {
    // System.err.println("listing messages");
    Connection conn = null;
    PreparedStatement listMessages = null;
    ResultSet rsListMessages = null;
    try {
        conn = datasource.getConnection();
        listMessages = conn.prepareStatement(sqlQueries.getSqlString("listMessagesSQL", true));
        listMessages.setString(1, repositoryName);
        rsListMessages = listMessages.executeQuery();

        List<String> messageList = new ArrayList<String>();
        while (rsListMessages.next() && !Thread.currentThread().isInterrupted()) {
            messageList.add(rsListMessages.getString(1));
        }
        return messageList.iterator();
    } catch (Exception me) {
        throw new MessagingException("Exception while listing mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCResultSet(rsListMessages);
        theJDBCUtil.closeJDBCStatement(listMessages);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:org.apache.james.mailrepository.lib.AbstractMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#store(Mail)
 *//*from   w  w  w . j ava  2 s  . c o m*/
public void store(Mail mc) throws MessagingException {
    boolean wasLocked = true;
    String key = mc.getName();
    try {
        synchronized (this) {
            wasLocked = lock.isLocked(key);
            if (!wasLocked) {
                // If it wasn't locked, we want a lock during the store
                lock(key);
            }
        }
        internalStore(mc);
    } catch (MessagingException e) {
        getLogger().error("Exception caught while storing mail " + key, e);
        throw e;
    } catch (Exception e) {
        getLogger().error("Exception caught while storing mail " + key, e);
        throw new MessagingException("Exception caught while storing mail " + key, e);
    } finally {
        if (!wasLocked) {
            // If it wasn't locked, we need to unlock now
            unlock(key);
            synchronized (this) {
                notify();
            }
        }
    }
}

From source file:org.apache.james.server.core.MimeMessageInputStreamSource.java

/**
 * Construct a new MimeMessageInputStreamSource from an
 * <code>InputStream</code> that contains the bytes of a MimeMessage.
 *
 * @param key the prefix for the name of the temp file
 * @param in  the stream containing the MimeMessage
 * @throws MessagingException if an error occurs while trying to store the stream
 *///w  w w  . j av a  2s  .com
public MimeMessageInputStreamSource(String key, InputStream in) throws MessagingException {
    super();
    // We want to immediately read this into a temporary file
    // Create a temp file and channel the input stream into it
    try {
        out = new DeferredFileOutputStream(THRESHOLD, "mimemessage-" + key, ".m64", TMPDIR);
        IOUtils.copy(in, out);
        sourceId = key;
    } catch (IOException ioe) {
        File file = out.getFile();
        if (file != null) {
            FileUtils.deleteQuietly(file);
        }
        throw new MessagingException("Unable to retrieve the data: " + ioe.getMessage(), ioe);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Ignored - logging unavailable to log this non-fatal error.
        }

        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ioe) {
            // Ignored - logging unavailable to log this non-fatal error.
        }

    }
}

From source file:org.apache.james.server.core.MimeMessageUtil.java

/**
 * Calculate the size of the give mimeMessage
 * /*  w  ww. j a  va2s. com*/
 * @param message
 *            the MimeMessage
 * @return size the calculated size
 * @throws MessagingException
 *             if a problem occours while calculate the message size
 */
public static long calculateMessageSize(MimeMessage message) throws MessagingException {
    long size;
    // SK: Should probably eventually store this as a locally
    // maintained value (so we don't have to load and reparse
    // messages each time).
    size = message.getSize();
    if (size != -1) {
        Enumeration<String> e = message.getAllHeaderLines();
        if (e.hasMoreElements()) {
            size += 2;
        }
        while (e.hasMoreElements()) {
            // add 2 bytes for the CRLF
            size += e.nextElement().length() + 2;
        }
    }

    if (size == -1) {
        SizeCalculatorOutputStream out = new SizeCalculatorOutputStream();
        try {
            message.writeTo(out);
        } catch (IOException e) {
            // should never happen as SizeCalculator does not actually throw
            // IOExceptions.
            throw new MessagingException("IOException wrapped by getMessageSize", e);
        }
        size = out.getSize();
    }
    return size;
}

From source file:org.apache.james.server.core.MimeMessageWrapper.java

/**
 * Load the message headers from the internal source.
 * /*from  w ww.j  a v a 2s  .com*/
 * @throws MessagingException
 *             if an error is encountered while loading the headers
 */
protected synchronized void loadHeaders() throws MessagingException {
    if (headers != null) {
        // Another thread has already loaded these headers
    } else if (source != null) {
        try (InputStream in = source.getInputStream()) {
            headers = createInternetHeaders(in);
        } catch (IOException ioe) {
            throw new MessagingException("Unable to parse headers from stream: " + ioe.getMessage(), ioe);
        }
    } else {
        throw new MessagingException(
                "loadHeaders called for a message with no source, contentStream or stream");
    }
}