liferay json

来源于网络,备用
Index: trunk/portlets/mail-portlet/docroot/WEB-INF/src/com/liferay/mail/util/MailBoxManager.java
===================================================================
diff -u -N -r16075 -r16083
--- trunk/portlets/mail-portlet/docroot/WEB-INF/src/com/liferay/mail/util/MailBoxManager.java (.../MailBoxManager.java) (revision 16075)
+++ trunk/portlets/mail-portlet/docroot/WEB-INF/src/com/liferay/mail/util/MailBoxManager.java (.../MailBoxManager.java) (revision 16083)
@@ -22,8 +22,23 @@

package com.liferay.mail.util;

+import com.liferay.mail.model.MailAccount;
+import com.liferay.portal.kernel.util.ContentTypes;
+import com.liferay.portal.kernel.util.GetterUtil;
+import com.liferay.portal.kernel.util.StringPool;
+import com.liferay.portal.kernel.util.StringUtil;
+import com.liferay.portal.kernel.util.Validator;
+import com.liferay.portal.model.User;
+import com.liferay.util.JSONUtil;
+
+import com.sun.mail.imap.IMAPFolder;
+import com.sun.mail.imap.IMAPSSLStore;
+import com.sun.mail.imap.IMAPStore;
+
import java.io.IOException;
+
import java.text.SimpleDateFormat;
+
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -43,9 +58,9 @@
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
-import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.search.AndTerm;
import javax.mail.search.BodyTerm;
import javax.mail.search.FromStringTerm;
@@ -56,26 +71,12 @@

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.json.JSONArray;
-import org.json.JSONObject;
import org.json.JSONException;
+import org.json.JSONObject;

-import com.liferay.util.JSONUtil;
-import com.liferay.portal.kernel.util.ContentTypes;
-import com.liferay.portal.kernel.util.GetterUtil;
-import com.liferay.portal.kernel.util.StringPool;
-import com.liferay.portal.kernel.util.StringUtil;
-import com.liferay.portal.kernel.util.Validator;
-import com.liferay.portal.model.User;
-import com.liferay.mail.model.MailAccount;
-import com.liferay.util.mail.JavaMailUtil;
-import com.sun.mail.imap.IMAPFolder;
-import com.sun.mail.imap.IMAPSSLStore;
-import com.sun.mail.imap.IMAPStore;
-
/**
- * Used as a fascade to the JavaMail API. All JavaMail objects are wrappered in
- * model classes and returned out of this utility fascade.
*
* <a href="MailBoxManager.java.html"><b><i>View Source</i></b></a>
*
@@ -84,24 +85,16 @@
*/
public class MailBoxManager {

- private MailAccount _defaultMailAccount;
- private Session _session = null;
- private Store _store = null;
- private User _user;
+ public static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

- private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
-
public MailBoxManager(User user, int accountId) {

- // get mail settings for account number for user
-
_user = user;

_defaultMailAccount = new MailAccount(user, accountId);
}

public void deleteMessage(Folder folder, Message message) {
-
try {
if (!folder.isOpen()) {
folder.open(Folder.READ_WRITE);
@@ -111,8 +104,8 @@

folder.close(true);
}
- catch (MessagingException ex) {
- System.out.println(ex.getMessage());
+ catch (MessagingException me) {
+ _log.error(me.getMessage());
}
}

@@ -146,29 +139,20 @@

folder.close(true);
}
- catch (MessagingException ex) {
- System.out.println(ex.getMessage());
+ catch (MessagingException me) {
+ _log.error(me.getMessage());
}
}

- /*
- * Create folder if it does not exist
- */
public void createFolder(String folderName) throws Exception {

- Folder newFolder = _getStore().getFolder(folderName);
+ Folder newFolder = getStore().getFolder(folderName);

if (!newFolder.exists()) {
newFolder.create(Folder.HOLDS_MESSAGES);
}
}

- /**
- *
- *
- * @param addresses
- * @return
- */
public String getAddressesAsString(Address[] addresses) {
StringBuffer sb = new StringBuffer();

@@ -196,46 +180,32 @@
}

public Part getAttachment(
- String folderName, int messageUid, String contentPath)
- throws MessagingException {
-
+ String folderName, int messageUid, String contentPath)
+ throws MessagingException {
+
Message message = getMessageByUid(folderName, messageUid);
-
- return _getMessagePart(message, contentPath);
+
+ return getMessagePart(message, contentPath);
}
-
- /**
- * Gets a list of folders (and subfolders) from store
- *
- * @return
- * @throws MessagingException
- */
+
public List getFolders() throws MessagingException {
- Store store = _getStore();
+ Store store = getStore();
IMAPFolder rootFolder = (IMAPFolder)store.getDefaultFolder();

List allFolders = new ArrayList();
-
- _getFolders(allFolders, rootFolder.list());
-
+
+ getFolders(allFolders, rootFolder.list());
+
return allFolders;
}

- /**
- * Gets the specified folder (not opened)
- *
- * @param folderName
- * @return
- * @throws Exception
- */
public Folder getFolder(String folderName) throws MessagingException {
- // Open the Folder
- Folder folder = _getStore().getDefaultFolder();
+ Folder folder = getStore().getDefaultFolder();

folder = folder.getFolder(folderName);

if (folder == null) {
- System.out.println("Invalid folder: " + folderName);
+ _log.error("Invalid folder: " + folderName);
}

return folder;
@@ -294,60 +264,31 @@

JSONObject jsonFolderObj = new JSONObject();

- Date startTimer = new Date();
-
if (folder.getType() != Folder.HOLDS_FOLDERS) {
folder.open(Folder.READ_ONLY);

- JSONUtil.put(jsonFolderObj, "newMessages", folder.getUnreadMessageCount());
+ JSONUtil.put(
+ jsonFolderObj, "newMessages", folder.getUnreadMessageCount());
JSONUtil.put(jsonFolderObj, "name", folder.getFullName());
-
+
Message[] messages = folder.getMessages();
-
+
JSONUtil.put(jsonFolderObj, "messageCount", messages.length);

- /*
- JSONArray jsonUidList = new JSONArray();
-
- if (messages.length > 0) {
- for (int i = 0; i < messages.length; i++) {
- jsonUidList.put(i, folder.getUID(messages[i]));
- }
- }
-
- jsonFolderObj.put("uidList", jsonUidList);
- */
-
folder.close(false);

- Date endTimer = new Date();
-
- int elapsedSeconds =
- ((endTimer.getMinutes() * 60) + endTimer.getSeconds()) -
- ((startTimer.getMinutes() * 60) + startTimer.getSeconds());
-
- System.out.println("get jsonfolder[" + folder.getFullName() + "] with messages[" + messages.length + "] took " + elapsedSeconds + " seconds");
- //System.out.println("get jsonfolder[" + folder.getFullName() + "] took " + elapsedSeconds + " seconds");
-
return jsonFolderObj;
}

return null;
}

public String getJsonFolders() throws MessagingException {
-
- // Get folder listing
-
List folders = getFolders();

- // Create json object
-
JSONObject jsonObj = new JSONObject();
JSONArray jsonArray = new JSONArray();

- // Loop through all folders
-
for (int i = 0; i < folders.size() ; i++) {
IMAPFolder folder = (IMAPFolder)folders.get(i);

@@ -366,8 +307,6 @@
IMAPFolder folder, Message message, boolean isSummary)
throws MessagingException {

- Date startTimer = new Date();
-
String read = "read";

if (!message.isSet(Flags.Flag.SEEN)) {
@@ -377,48 +316,35 @@
SimpleDateFormat format = new SimpleDateFormat("MMM dd yyyy HH:mm");
String date = format.format(message.getSentDate());

- // create json object
-
JSONObject jsonObj = new JSONObject();

JSONUtil.put(jsonObj, "date", date);
JSONUtil.put(jsonObj, "from", getAddressesAsString(message.getFrom()));
JSONUtil.put(jsonObj, "hasAttachment", false);
JSONUtil.put(jsonObj, "isHtml", "undetermined");
- JSONUtil.put(jsonObj, "msgNum", String.valueOf(message.getMessageNumber()));
+ JSONUtil.put(
+ jsonObj, "msgNum", String.valueOf(message.getMessageNumber()));
JSONUtil.put(jsonObj, "read", read);
JSONUtil.put(jsonObj, "subject", message.getSubject());
JSONUtil.put(jsonObj, "uid", folder.getUID(message));

if (isSummary) {
- //JSONUtil.put(jsonObj, "bodyPreview", _getContentPreview("", message));
-
+ //JSONUtil.put(
+ // jsonObj, "bodyPreview", getContentPreview("", message));
+
JSONUtil.put(jsonObj, "bodyPreview", StringPool.BLANK);
}
else {
JSONUtil.put(jsonObj, "bcc",
getAddressesAsString(message.getRecipients(RecipientType.BCC)));
JSONUtil.put(jsonObj, "body",
- _getContent("", "", message, false));
+ getContent("", "", message, false));
JSONUtil.put(jsonObj, "cc",
getAddressesAsString(message.getRecipients(RecipientType.CC)));
JSONUtil.put(jsonObj, "to",
getAddressesAsString(message.getRecipients(RecipientType.TO)));
}

- Date endTimer = new Date();
-
- int elapsedSeconds =
- ((endTimer.getMinutes() * 60) + endTimer.getSeconds()) -
- ((startTimer.getMinutes() * 60) + startTimer.getSeconds());
-
- if (isSummary) {
- System.out.println("get jsonmessage[" + folder.getUID(message) + "] SUMMARY took " + elapsedSeconds + " seconds");
- }
- else {
- System.out.println("get jsonmessage[" + folder.getUID(message) + "] took " + elapsedSeconds + " seconds");
- }
-
return jsonObj;
}

@@ -443,10 +369,10 @@
}

public String getJsonMessages(
- IMAPFolder folder, String messageNumsToGet,
+ IMAPFolder folder, String messageNumsToGet,
String messageUidsToExclude)
throws MessagingException {
-
+
int[] msgNums = GetterUtil.getIntegerValues(
messageNumsToGet.split("\\s*,\\s*"));

@@ -460,9 +386,9 @@
for (int i = 0; i < msgNums.length; i++) {
Message message = folder.getMessage(msgNums[i]);
long msgUid = folder.getUID(message);
-
+
// Skip message if it is in the exclude list
-
+
if (msgUids.length != 0) {
for (int j = 0; j < msgUids.length; j++) {
if (msgUid == msgUids[j]) {
@@ -475,14 +401,15 @@
_log.warn(jsone, jsone);
}
}
-
+
continue;
}
}
}
-
+
try {
- jsonArray.put((int)msgUid, getJsonMessage(folder, message, true));
+ jsonArray.put(
+ (int)msgUid, getJsonMessage(folder, message, true));
}
catch (JSONException jsone) {
if (_log.isWarnEnabled()) {
@@ -496,9 +423,9 @@

return jsonObj.toString();
}
-
+
public String getJsonMessages(
- IMAPFolder folder, int pageNum, int messagesPerPage,
+ IMAPFolder folder, int pageNum, int messagesPerPage,
String messageUidsToExclude)
throws MessagingException {

@@ -512,10 +439,10 @@
}

double totalPages = Math.ceil((double)totalMessages / messagesPerPage);
-
+
int[] messageUids = GetterUtil.getIntegerValues(
messageUidsToExclude.split("\\s*,\\s*"));
-
+
// Create Json object

JSONObject jsonObj = new JSONObject();
@@ -537,19 +464,19 @@
for (int i = messages.length - 1; i >= 0 ; i--) {
Message message = messages[i];
long messageUid = folder.getUID(message);
-
+
// Skip message if it is in the exclude list
-
+
// if (messageUids.length != 0) {
// for (int j = 0; j < messageUids.length; j++) {
// if (messageUid == messageUids[j]) {
// continue;
// }
// }
// }
-
+
// Otherwise, add to list
-
+
jsonArray.put(getJsonMessage(folder, message, true));
}

@@ -563,10 +490,8 @@
String searchString)
throws Exception {

- SearchTerm st = _getSearchTerm(searchString);
+ SearchTerm st = getSearchTerm(searchString);

- // TODO: cache search results for better performance
-
Message[] messages = folder.search(st);

int totalMessages = messages.length;
@@ -593,7 +518,7 @@

// Convert all messages into Json Objects

- for (int i = firstIndexInclusive; i <= lastIndexInclusive; i++) {
+ for (int i = firstIndexInclusive; i <= lastIndexInclusive; i++) {
Message message = messages[i];

jsonArray.put(getJsonMessage(folder, message, true));
@@ -652,31 +577,23 @@

folder.close(true);
}
- catch (MessagingException ex) {
- System.out.println(ex.getMessage());
+ catch (MessagingException me) {
+ _log.error(me.getMessage());
}
}

- /**
- * Gets the specified folder (opened)
- *
- * @param folderName
- * @return
- * @throws Exception
- */
public Folder openFolder(String folderName) throws MessagingException {
+ Folder folder = getStore().getDefaultFolder();

- // Open the Folder
- Folder folder = _getStore().getDefaultFolder();
-
folder = folder.getFolder(folderName);

if (folder == null) {
return null;
}

- // try to open read/write and if that fails try read-only
- try {
+ // Try to open read/write and if that fails try read-only
+
+ try {
folder.open(Folder.READ_WRITE);
}
catch (MessagingException ex) {
@@ -694,7 +611,7 @@

// Create the message to forward

- Message forward = new MimeMessage(_getSession());
+ Message forward = new MimeMessage(getSession());

// Create multi-part to combine the parts

@@ -711,7 +628,7 @@

mp.addBodyPart(messageBodyPart);

- _send(forward, fromAccountId, recipientsTo, recipientsCc, recipientsBcc,
+ send(forward, fromAccountId, recipientsTo, recipientsCc, recipientsBcc,
subject, content, mp);
}

@@ -722,9 +639,9 @@

// Instantiate a message

- Message msg = new MimeMessage(_getSession());
+ Message msg = new MimeMessage(getSession());

- _send(msg, fromAccountId, recipientsTo, recipientsCc, recipientsBcc,
+ send(msg, fromAccountId, recipientsTo, recipientsCc, recipientsBcc,
subject, content, mp);
}

@@ -736,18 +653,18 @@

MimeMessage reply = (MimeMessage)msg.reply(false);

- _send(reply, fromAccountId, recipientsTo, recipientsCc, recipientsBcc,
+ send(reply, fromAccountId, recipientsTo, recipientsCc, recipientsBcc,
subject, content, mp);
}

- private String _getContent(
- String messageContent, String contentPath, Part messagePart,
+ protected String getContent(
+ String messageContent, String contentPath, Part messagePart,
boolean isPreview)
throws MessagingException {

try {
String contentType = messagePart.getContentType().toLowerCase();
-
+
if (messagePart.getContent() instanceof Multipart) {
Multipart multipart = (Multipart)messagePart.getContent();

@@ -770,7 +687,7 @@
// Only get content preview if there is none

if (messageContent.equals(StringPool.BLANK)) {
- messageContent = _getContent(
+ messageContent = getContent(
messageContent, "", curPart, isPreview);
}

@@ -782,7 +699,7 @@
if (partContentType.startsWith(
ContentTypes.TEXT_HTML)) {

- messageContent = _getContent(
+ messageContent = getContent(
messageContent, "", curPart, isPreview);

break;
@@ -796,7 +713,7 @@
for (int i = 0; i < multipart.getCount(); i++) {
Part curPart = multipart.getBodyPart(i);

- messageContent = _getContent(
+ messageContent = getContent(
messageContent, contentPath + StringPool.PERIOD + i,
curPart, isPreview);
}
@@ -813,7 +730,7 @@
else if (contentType.startsWith(ContentTypes.TEXT_HTML)) {
if (isPreview) {
messageContent +=
- _stripHtml((String)messagePart.getContent()) +
+ stripHtml((String)messagePart.getContent()) +
"<HR/>";
}
else {
@@ -823,13 +740,13 @@
}
else if (contentType.startsWith(ContentTypes.MESSAGE_RFC822)) {
messageContent +=
- _getContent(
+ getContent(
messageContent, "", messagePart, isPreview);

/*
MailContent subContent = new MailContent();

- mailMessage = _getContent(
+ mailMessage = getContent(
(Part)messagePart.getContent(), mailMessage, subContent,
contentPath + StringPool.PERIOD + 0);

@@ -844,29 +761,27 @@
// Attachment (ignore)

contentPath = contentPath + ".attachment";
-
- messageContent += "<HR><a href=\"" + contentPath + "\">" +
+
+ messageContent += "<HR><a href=\"" + contentPath + "\">" +
messagePart.getFileName() + "</a>";

//mailMessage.appendRemoteAttachment(
- // _getRemoteAttachment(
+ // getRemoteAttachment(
// messagePart, contentPath + StringPool.PERIOD + -1));
}

}
catch (IOException ioe) {
_log.error(ioe.getMessage());
-
- //throw new MessagingException(ioe);
}

return messageContent;
}

- private String _getContentPreview(String messageContent, Part messagePart)
+ protected String getContentPreview(String messageContent, Part messagePart)
throws MessagingException {

- String fullContent = _getContent(messageContent, "",
+ String fullContent = getContent(messageContent, "",
messagePart, true);

if (fullContent.length() > 80) {
@@ -876,11 +791,7 @@
return fullContent;
}

- /**
- * Manually set the incoming connection settings
- *
- */
- private void _getIncomingStore(MailAccount mailAccount) {
+ protected void getIncomingStore(MailAccount mailAccount) {
try {
Properties props = new Properties();

@@ -910,7 +821,7 @@
}

store.connect();
- _setStore(store);
+ setStore(store);
}
catch (MessagingException ex) {
if (_log.isErrorEnabled()) {
@@ -919,44 +830,37 @@
}
}

- private Part _getMessagePart(Part part, String contentPath)
+ protected Part getMessagePart(Part part, String contentPath)
throws MessagingException {
-
+
int index = GetterUtil.getInteger(
StringUtil.split(contentPath.substring(1), StringPool.PERIOD)[0]);
-
+
try {
if (part.getContent() instanceof Multipart) {
String prefix = String.valueOf(index) + StringPool.PERIOD;
-
+
Multipart multipart = (Multipart)part.getContent();
-
+
for (int i = 0; i < multipart.getCount(); i++) {
if (index == i) {
- return _getMessagePart(
+ return getMessagePart(
multipart.getBodyPart(i),
contentPath.substring(prefix.length()));
}
}
}
-
+
return part;
}
catch (IOException ioe) {
_log.error(ioe.getMessage());
-
+
return null;
}
}
-
- /**
- * Manually set the outgoing connection settings
- *
- */
- private Session _getOutgoingSession(MailAccount mailAccount) {

- // Properties
-
+ protected Session getOutgoingSession(MailAccount mailAccount) {
Properties props = new Properties();
props.put("mail.smtp.host", mailAccount.getMailOutHostName());
props.put("mail.smtp.port", mailAccount.getMailOutPort());
@@ -980,12 +884,7 @@
return session;
}

- /**
- * Returns a SearchTerm which requires that all terms in searchString
- * must appear in the email
- */
- private SearchTerm _getSearchTerm(String searchString) {
-
+ protected SearchTerm getSearchTerm(String searchString) {
String searchStrings[] = searchString.split("\\s");

SearchTerm[] allOrTerms = new OrTerm[searchStrings.length];
@@ -1011,23 +910,23 @@
return new AndTerm(allOrTerms);
}

- private Session _getSession() {
+ protected Session getSession() {
if (_session == null) {
- _session = _getOutgoingSession(_defaultMailAccount);
+ _session = getOutgoingSession(_defaultMailAccount);
}

return _session;
}

- private Store _getStore() {
+ protected Store getStore() {
if (_store == null) {
- _getIncomingStore(_defaultMailAccount);
+ getIncomingStore(_defaultMailAccount);
}

return _store;
}

- private static void _getFolders(List list, Folder[] folders) {
+ protected static void getFolders(List list, Folder[] folders) {
for (int i = 0; i < folders.length; i++) {
Folder folder = folders[i];

@@ -1039,7 +938,7 @@
}

if ((folderType & IMAPFolder.HOLDS_FOLDERS) != 0) {
- _getFolders(list, folder.list());
+ getFolders(list, folder.list());
}
}
catch (MessagingException me) {
@@ -1048,15 +947,15 @@
}
}

- private void _send(
+ protected void send(
Message msg, int fromAccountId, String recipientsTo,
String recipientsCc, String recipientsBcc, String subject,
String content, Multipart mp)
throws MessagingException {

MailAccount fromMailAccount = new MailAccount(_user, fromAccountId);

- //Set message attributes
+ // Set message attributes

msg.setFrom(new InternetAddress(fromMailAccount.getEmailAddress()));

@@ -1083,20 +982,22 @@

if (mp != null) {
// Add attachment
+
msg.setContent(mp);
}
else {
// Set message content
+
msg.setText(content);
}

// Resets the header to reflect changes

msg.saveChanges();

- //Send the message
+ // Send the message

- Transport t = _getOutgoingSession(fromMailAccount).getTransport("smtp");
+ Transport t = getOutgoingSession(fromMailAccount).getTransport("smtp");
try {
t.connect(
fromMailAccount.getUsername(), fromMailAccount.getPassword());
@@ -1107,11 +1008,11 @@
}
}

- private void _setStore(Store store) {
+ protected void setStore(Store store) {
this._store = store;
}

- private static String _stripHtml(String html) {
+ protected String stripHtml(String html) {
html = html.replaceAll( "<[^>]+>", StringPool.BLANK);
html = html.replaceAll( "[\r\n]+", StringPool.BLANK);

@@ -1120,4 +1021,9 @@

private static Log _log = LogFactory.getLog(MailBoxManager.class);

+ private MailAccount _defaultMailAccount;
+ private Session _session = null;
+ private Store _store = null;
+ private User _user;
+
}
\ No newline at end of file
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值