javamailgateway.java

来自「Jive是基于JSP/JAVA技术构架的一个大型BBS论坛系统,这是Jive论坛」· Java 代码 · 共 1,639 行 · 第 1/5 页

JAVA
1,639
字号
/** * $RCSfile: JavaMailGateway.java,v $ * $Revision: 1.9 $ * $Date: 2002/08/08 18:52:45 $ * * Copyright (C) 1999-2002 CoolServlets, Inc. All Rights Reserved. * * This software is the proprietary information of CoolServlets, Inc. * Use is subject to license terms. */package com.jivesoftware.forum.gateway;import java.io.*;import java.util.*;import java.text.*;import javax.mail.*;import javax.mail.internet.*;import javax.mail.internet.ParseException;import javax.activation.*;import com.jivesoftware.forum.*;import com.jivesoftware.forum.database.DbForumFactory;import com.jivesoftware.util.StringUtils;import com.sun.mail.util.BEncoderStream;import com.sun.mail.util.QEncoderStream;/** * This class is an abstract JavaMail implementation of the Gateway * interface. This class provides all the needed methods to import messages * from whatever JavaMail providers are supported.<p> * * If a provider such as a NNTP provider needs to do something special when * connecting or retrieving messages all it needs to do is re-implement * the method in question in a subclass.<p> * * @author Bruce Ritchie */public abstract class JavaMailGateway implements GatewayImporter {    /**     * Protocol to be used by the JavaMail store mechanism.     */    protected String protocol = "";    /**     * Mailbox to be used by the JavaMail store mechanism.     */    protected String mailbox = "";    /**     * The host that is running the  server daemon.     */    protected String host = "";    /**     * The port that the server daemon is listening to.     */    protected int port = -1;    /**     * The username to use to connect to the server deamon.     */    protected String username = null;    /**     * The password to use to connect to the server deamon.     */    protected String password = null;    /**     * Flag used to determine if we should delete messages     * from the server or not.     */    protected boolean deleteEnabled = false;    /**     * Flag used to determine if the JavaMail provider a     * gateways uses should be put into debug mode or not.     */    protected boolean debugEnabled = false;    /**     * Flag used to determine if attachments are handled or not.     */    protected boolean attachmentsEnabled = false;    /**     * Flag used to stop an already running import or export.     */    protected boolean stopFlag = false;    // Date parsers that are used when JavaMail fails to parse a date.    // Not thread safe btw.    private SimpleDateFormat format1;    private SimpleDateFormat format2;    private SimpleDateFormat format3;    private SimpleDateFormat format4;    private SimpleDateFormat format5;    private SimpleDateFormat format6;    /**     * Used to flag messages in the forum with a message id.     */    protected String gatewayMessageId = "Message-ID";    /**     * Used to flag messages in the forum with a parent id.     */    protected String gatewayParentId = "Parent-ID";    /**     * Prefix to search for to determine replying messages (lowercase).     */    protected String replyPrefix = "re:";    /**     * Whether or not to attempt to determin parentage via subject line matching     */    protected boolean subjectParentageCheckEnabled = true;    /**     * Dummy message string for messages autocreated by this gateway     */    protected String temporaryParentBody = " ";    /**     * Used to store the parent message id's indexed by message id     */    protected Hashtable parentMessageIDs = new Hashtable();    /**     * Used to store a messages original date if the date had to be changed     * such as in the case of a parent with an older child     */    public static final String MESSAGE_DATE_HEADER = "Message-Original-Date";    /**     * Used for storing a hash of a subject as an extended property     * needed for parent message comparison     */    public static final String SUBJECT_EXTENDED_PROPERTY = "Subject-Hash";    /**     * Used to mark a message as a Jive created message     */    public static final String DUMMY_PARENT_HEADER = "Jive-Created-Message";    /**     * The forumID is used instead of an actual forum object since     * Jive's cache system will orphan the forum object after 6     * hours. Since gateways are usually created once and not     * destroyed after every use, we mustn't hang onto a forum object     * for too long.     */    protected long forumID;    protected ForumFactory factory;    public JavaMailGateway(ForumFactory factory, Forum forum) {        this.factory = factory;        this.forumID = forum.getID();        parentMessageIDs = new Hashtable();    }    public synchronized void importData(Date afterDate) throws GatewayException    {        // Check to make sure that all required properties are set.        if (host.equals("") || port == -1 || protocol.equals("") ||                mailbox.equals(""))        {            throw new GatewayException("Required properties are not all set.");        }        Store store   = null;        Folder folder = null;        try {            store  = getStore(afterDate);            folder = getFolder(store);            retrieveMessages(store, folder, afterDate);        }        catch (MessagingException e) {            throw new GatewayException(e);        }        finally {            try { folder.close(deleteEnabled); }            catch (Exception e) { System.err.println("Unable to close folder"); }            try { store.close(); }            catch (Exception e) { System.err.println("Unable to close store"); }        }        cleanup();        parentMessageIDs.clear();    }    /**     * Retrieve the JavaMail store.     *     * @param afterDate the date after which messages will be imported.     * @throws MessagingException if an error occurred establishing the connection.     * @return a connected store object.     */    protected Store getStore(Date afterDate) throws MessagingException {        Session session = Session.getInstance(System.getProperties(), null);        // Turn on debugging if it's enabled.        session.setDebug(debugEnabled);        // Create a Store        URLName url = new URLName(protocol, host, port, mailbox, username, password);        Store store = session.getStore(url);        // Connect the store        store.connect();        return store;    }    /**     * Retrieve the JavaMail folder from the provided store object.     *     * @param store the JavaMail store.     * @return a connected folder object.     * @throws MessagingException if an error occurred establishing the connection.     */    protected Folder getFolder(Store store) throws MessagingException {        Folder folder;        // Make sure that we can get the default folder.        if ((folder = store.getFolder(mailbox)) == null) {            throw new MessagingException("No folder found");        }        // Open the folder in the proper mode        if (deleteEnabled) {            folder.open(Folder.READ_WRITE);        }        else {            folder.open(Folder.READ_ONLY);        }        return folder;    }    /**     * Retrieve messages from a JavaMail folder and calls methods to     * import them into a forum.     *     * @param folder a connected JavaMail folder object.     * @param afterDate the date after which we'll import message.     * @throws MessagingException if a protocol error occurs retrieving a message.     * @throws GatewayException     */    protected void retrieveMessages(Store store, Folder folder, Date afterDate)            throws MessagingException, GatewayException    {        int totalMsgCount = folder.getMessageCount();        List messages     = new ArrayList(Math.min(50, totalMsgCount));        try {            for (int curMsgCount = 1; curMsgCount <= totalMsgCount && !stopFlag; curMsgCount++) {                try {                    // if the server disconnected us, reconnect                    // maximum of 3 reconnect tries before we die                    if (!folder.isOpen() || !store.isConnected()) {                        System.err.println("Server has disconnected, reconnecting.");                        try { folder.close(false); }                        catch (Exception e) { /* ignore */ }                        try { store.close(); }                        catch (Exception e) { /* ignore */ }                        int retry = 1;                        while (!store.isConnected() && retry < 4) {                            retry++;                            store  = getStore(afterDate);                            folder = getFolder(store);                        }                        // unsuccessful, die                        if (!store.isConnected() && retry > 3) {                            throw new GatewayException("Unable to connect to the" +                                            " JavaMail store provider");                        }                    }                    MimeMessage message = (MimeMessage) folder.getMessage(curMsgCount);                    ForumMessage forumMessage = parseMessage(message, afterDate);                    if (forumMessage == null) {                        continue;                    }                    // check to see if the message is already in the db                    // or whether it's a dummy parent message we've previously                    // created                    Forum forum            = factory.getForum(forumID);                    String messageID       = getMessageID(message);                    ForumMessage dbMessage = lookupMessageByID(forum, messageID, true);                    if (dbMessage != null && !"true".equals(                            dbMessage.getProperty(DUMMY_PARENT_HEADER)))                    {                        continue;                    }                    messages.add(forumMessage);                    boolean hasAttachments = isMessageWithAttachments(message);                    // insert into db every 50 messages or if the message                    // has attachments                    if (curMsgCount % 50 == 0 ||                            (hasAttachments && attachmentsEnabled))                    {                        processMessagesAndImport(messages);                        if (hasAttachments && attachmentsEnabled) {                            // we need to retrieve the forumMessage from the                            // db since the one we have isn't attached to a                            // thread                            forumMessage = lookupMessageByID(forum, messageID, false);                            if (forumMessage != null) {                                // If the message already has attachments, it means that the                                // message has already been imported (and thus wasn't imported                                // in the processMessagesAndImport(messages) method call above.                                // Only add attachments if that isn't the case.                                if (forumMessage.getAttachmentCount() < 1) {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?