📄 javamailgateway.java
字号:
/**
* $RCSfile: JavaMailGateway.java,v $
* $Revision: 1.28 $
* $Date: 2001/10/09 21:12:42 $
*
* Copyright (C) 1999-2001 CoolServlets Inc. All rights reserved.
* ===================================================================
* The Jive Software License (based on Apache Software License, Version 1.1)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by
* Jive Software (http://www.jivesoftware.com)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Jive" and "CoolServlets" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please
* contact webmaster@coolservlets.com.
*
* 5. Products derived from this software may not be called "Jive",
* nor may "Jive" appear in their name, without prior written
* permission of CoolServlets.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL COOLSERVLETS INC OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of Jive Software. For more information
* on Jive Software please visit http://www.jivesoftware.com.
*/
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.util.StringUtils;
/**
* 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 or whatever else all it needs to do is
* re-implement the method in question in a subclass.<p>
*
* The ability to export messages is not handled by this class, if you need to
* export messages you must extend this class and implement the exportData
* method or use the {@link com.jivesoftware.forum.util.EmailTask} class
*
* @author Bruce Ritchie
*/
public abstract class JavaMailGateway implements Gateway {
/**
* 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;
protected String username = null;
protected String password = null;
protected boolean deleteEnabled = false;
protected String defaultFromAddress = null;
protected boolean emailPrefEnabled = true;
protected boolean debugEnabled = false;
// Date parsers that are used when JavaMail fails to parse a date.
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:";
/**
* 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";
protected ForumFactory factory;
protected long forumID;
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;
try {
store = getStore(afterDate);
List messages = retrieveMessages(store, afterDate);
resolveParentage(messages);
correctMessageDates(messages);
// Sort messages (oldest first by creation date). This is needed so
// that we don't insert a child before a parent's thread is created,
// which would be 'A Bad Thing' (tm)
Collections.sort(messages, new Comparator() {
public int compare(Object object1, Object object2) {
ForumMessage msg1 = (ForumMessage)object1;
ForumMessage msg2 = (ForumMessage)object2;
return msg1.getCreationDate().compareTo(msg2.getCreationDate());
}
});
importMessages(messages);
// explicitly nullify to help gc
messages = null;
}
catch (Exception e) {
throw new GatewayException(e);
}
finally {
try { store.close(); }
catch (Exception e) { /* ignore */ }
}
// explicitly nullify to help gc
store = null;
cleanup();
}
public abstract void exportData(ForumMessage message)
throws GatewayException;
/**
* get the JavaMail store
*
* @param afterDate The date after which messages will be imported
* @throws MessagingException if 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 messages from the JavaMail store
*
* @param store a connected JavaMail store object
* @param afterDate the date after which we'll import message
* @throws MessagingException if a protocol error occurs retrieving a message
*/
protected List retrieveMessages(Store store, Date afterDate)
throws MessagingException
{
Folder folder = null;
try {
// Make sure that can get the default folder.
if ((folder = store.getFolder(mailbox)) == null) {
throw new MessagingException("No folder found");
}
// Open the folder, get all messages from the server,
// then weed out the ones we don't want and return the rest.
if (deleteEnabled) {
folder.open(Folder.READ_WRITE);
}
else {
folder.open(Folder.READ_ONLY);
}
Message [] tempMessages = folder.getMessages();
List messages = new ArrayList(tempMessages.length);
// Convert each message to a ForumMessage then add to the list.
for (int i=0; i < tempMessages.length; i++) {
// parse the message
ForumMessage message = parseMessage(tempMessages[i], afterDate);
if (message != null) {
messages.add(message);
}
// Some providers require a delete flag to be set
tempMessages[i].setFlag(Flags.Flag.DELETED, deleteEnabled);
}
return messages;
}
catch (MessagingException me) {
throw new MessagingException(me.getMessage());
}
finally {
try { folder.close(deleteEnabled); }
catch (Exception e) { /* ignore */ }
// explicitly nullify to help gc
folder = null;
}
}
/**
* Resolve parentage
*
* We need to go through all the messages and determine
* parentage from subject if the parent id property isn't already
* set, which is almost certain in the case of POP3 and sometimes
* the case with other providers.
* @param messages a List of ForumMessage objects
*/
protected void resolveParentage(List messages)
throws ForumNotFoundException, UnauthorizedException
{
Iterator iter = messages.listIterator();
Iterator parentIterator = null;
ForumMessage message = null;
ForumMessage pMessage = null;
String messageId = "";
String pMessageId = "";
String messageSubject = "";
String parentSubject = "";
int replyIndex = 0;
int index = 0;
boolean found = false;
while (iter.hasNext()) {
message = (ForumMessage) iter.next();
found = false;
// has a parent, ignore
if (message.getProperty(gatewayParentId) != null &&
message.getProperty(gatewayParentId).length() > 0) {
continue;
}
messageId = message.getProperty(gatewayMessageId);
messageSubject = message.getSubject();
replyIndex = messageSubject.toLowerCase().indexOf(replyPrefix);
// find the subject of the parent that we want to look for
if (replyIndex > -1) {
parentSubject = messageSubject.substring(3).trim();
}
else {
parentSubject = messageSubject.trim();
}
// check the database for parent message
// anytime in the last 60 days
Date min = new Date(message.getCreationDate().getTime() - 60*JiveGlobals.DAY);
Date max = new Date(message.getCreationDate().getTime() - 1);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -