⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jdavmailmessage.java

📁 一个接收基于WebDav邮件的开源项目
💻 JAVA
字号:
/*
 *  This file is part of the JDAVMail package
 *  Copyright (C) 2002 Luc Claes. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
 *  SHALL THE JDAVMail AUTHORS OR THE PROJECT 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. See the GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA 02111-1307, USA
 *
 *  For questions, suggestions, bug-reports, enhancement-requests etc.
 *  I may be contacted at:
 *
 *  luc@posisoft.com
 *
 *  The JDAVMail's home page is located at:
 *
 *  http://jdavmail.sourceforge.net
 *
 */
package com.posisoft.jdavmail;
import java.io.InputStream;
import java.util.Enumeration;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.IllegalWriteException;
import javax.mail.MessagingException;
import javax.mail.event.MessageChangedEvent;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.jdom.Element;

/**
 */
public class JDAVMailMessage extends MimeMessage {
	private boolean				m_bActualRead		= false;
	private boolean				m_bReadOnly			= false;
	
	private URI					m_uri				= null;

	private String				m_strID				= null;
	private boolean				m_bRead				= true;
	private boolean				m_bHasAttachment	= false;
	private int					m_nLength			= -1;	//TODO: check: total or body length?
	private String				m_strSubject		= null;
	private InternetAddress[]	m_from				= null;	
	/**
	 */
	private JDAVMailMessage(JDAVMailFolder f, int nIndex){
		super(f, nIndex);
	}
	
	/**
	 */
	public static JDAVMailMessage createInstance(JDAVMailFolder folder, int nIndex, Element elemResponse) throws URIException {
		Element elemProp = elemResponse.getChild("propstat", JDAVMail.NS_DAV).getChild("prop", JDAVMail.NS_DAV);
		
		JDAVMailMessage msg = new JDAVMailMessage(folder, nIndex);
		msg.m_uri = new URI(elemResponse.getChild("href", JDAVMail.NS_DAV).getText().toCharArray());
		
		String strPath = msg.m_uri.getPath();
		int nSlash = strPath.lastIndexOf('/');
		msg.m_strID = ((nSlash > 0) && (nSlash < strPath.length()-1)) ? strPath.substring(nSlash + 1) : strPath;
		// msg.m_strID = Util.getStringValue(elemProp.getChild("id", JDAVMail.NS_DAV), "");
		
		msg.m_bRead = Util.getBooleanValue(elemProp.getChild("read", JDAVMail.NS_HTTPMAIL), true);
		if (msg.m_bRead) {
			msg.flags.add(Flags.Flag.SEEN);
		}
		msg.m_bHasAttachment = Util.getBooleanValue(elemProp.getChild("hasattachment", JDAVMail.NS_HTTPMAIL), true);
		msg.m_nLength = Util.getIntValue(elemProp.getChild("getcontentlength", JDAVMail.NS_DAV), -1);
		msg.m_strSubject = Util.getStringValue(elemProp.getChild("subject", JDAVMail.NS_MAILHEADER), "");
		msg._setFrom(Util.getStringValue(elemProp.getChild("fromaddr", JDAVMail.NS_HOTMAIL), ""),
				Util.getStringValue(elemProp.getChild("from", JDAVMail.NS_MAILHEADER), ""));
		msg.m_bReadOnly = true;
		
		return msg;
	}
	
	/**
	 */
	private void _setFrom(String strAddress, String strName){
		InternetAddress from = null;
		try {
			from = new InternetAddress(strAddress, strName);
		} catch (Exception ignore) {
		}
		if (from != null) {
			m_from = new InternetAddress[1];
			m_from[0] = from;
		}
	}
	
	/**
	 */
	private void _setReadFlag(boolean bSet) throws MessagingException {
		if (bSet != m_bRead) {
			try {
				FlagMailReadMethod m = new FlagMailReadMethod(m_uri);
				try {
					m.setReadFlag(bSet);
					((JDAVMailStore)getFolder().getStore())._getService().executeMethod(m);
				} finally {
					m.releaseConnection();
				}
				m_bRead = bSet;
			} catch (Exception e) {
				throw new MessagingException("Exception while updating read flag " + m_strID, e);
			}
		}
	}
	
	/**
	 * This method handles the actual 'read' of the message.
	 */
	private synchronized void _readMessage() throws MessagingException {
		if (!m_bActualRead) {
			try {
				GetMessageMethod m = new GetMessageMethod(this);
				try {
					((JDAVMailStore)(getFolder().getStore()))._getService().executeMethod(m);
					m_bActualRead = true;
					parse(m.getResponseBodyAsStream());
				} finally {
					m.releaseConnection();
				}
			} catch (Exception e) {
				throw new MessagingException("Exception while reading message " + m_strID, e);
			}
		}
	}
	
	/**
	 * Only here to avoid too many critical sections handling (_readMessage is synchronized).
	 */
	private void _ensureRead() throws MessagingException {
		if (!m_bActualRead) {
			_readMessage();
		}
	}
	/**
	 */	
    /**     * Produce the raw bytes of the content. (TODO: check if this method is useless or not...)     */    protected InputStream getContentStream()					throws MessagingException {		_ensureRead();		return super.getContentStream();
	}
	/**     * Set the specified flags on this message to the specified value.     *     * @param newFlags	the flags to be set     * @param set	the value to be set     */    public void setFlags(Flags newFlags, boolean set) throws MessagingException {		Flags oldFlags = (Flags)flags.clone();		super.setFlags(newFlags, set);		if (!flags.equals(oldFlags)) {
			_setReadFlag(flags.contains(Flags.Flag.SEEN));	// Is this the right place?			((JDAVMailFolder)getFolder()).notifyMessageChangedListeners(MessageChangedEvent.FLAGS_CHANGED, this);
		}	}
	/**
	 */
	public URI getURI(){
		return m_uri;	}
		/**
	 * Note: this call avoids, if possible, an actual message read.
	 */
	public Address[] getFrom() throws MessagingException {
		if ((m_from != null) && (m_from[0] != null) && !m_bActualRead/* && (m_from[0].getAddress().length() > 0)*/) {
			return m_from;		}
		_ensureRead();		return super.getFrom();    }
		/**
	 * Note: this call avoids, if possible, an actual message read.
	 */
	public String getSubject() throws MessagingException {		if (m_strSubject != null) {			return m_strSubject;
		}		_ensureRead();		return super.getSubject() ;    }
		/**
	 * Note: this call avoids, if possible, an actual message read.
	 */
    public String getMessageID() throws MessagingException {		if (m_strID != null) {			return m_strID;
		}		_ensureRead();
		return super.getMessageID();    }
		/**     * Return the size of the content of this message in bytes.      *     * @return	size of content in bytes 	//TODO: check: content = total or body length?     */
	public int getSize(){		return m_nLength;
	}

    /**     * Get all the headers for this header_name. Note that certain     * headers may be encoded as per RFC 2047 if they contain      * non US-ASCII characters and these should be decoded. <p>     *     * @param	name	name of header     * @return	array of headers     * @exception       MessagingException     * @see 	javax.mail.internet.MimeUtility     */    public String[] getHeader(String name)			throws MessagingException {		_ensureRead();		return super.getHeader(name);    }    /**     * Get all the headers for this header name, returned as a single     * String, with headers separated by the delimiter. If the     * delimiter is <code>null</code>, only the first header is      * returned.     *     * @param header_name       the name of this header     * @return                  the value fields for all headers with      *				this name     * @exception       	MessagingException     */    public String getHeader(String name, String delimiter)				throws MessagingException {		_ensureRead();		return super.getHeader(name, delimiter);    }    /**     * Return all the headers from this Message as an enumeration     * of Header objects. <p>     *     * Note that certain headers may be encoded as per RFC 2047      * if they contain non US-ASCII characters and these should      * be decoded. <p>     *     * @return	array of header objects     * @exception  MessagingException     * @see 	javax.mail.internet.MimeUtility     */    public Enumeration getAllHeaders() throws MessagingException {		_ensureRead();		return super.getAllHeaders();	    }    /**     * Return matching headers from this Message as an Enumeration of     * Header objects.     *     * @exception  MessagingException     */    public Enumeration getMatchingHeaders(String[] names)			throws MessagingException {		_ensureRead();		return super.getMatchingHeaders(names);    }    /**     * Return non-matching headers from this Message as an     * Enumeration of Header objects.     *     * @exception  MessagingException     */    public Enumeration getNonMatchingHeaders(String[] names)						throws MessagingException {		_ensureRead();		return super.getNonMatchingHeaders(names);    }    /**     * Get all header lines as an Enumeration of Strings. A Header     * line is a raw RFC822 header-line, containing both the "name"      * and "value" field.      *     * @exception  	MessagingException     */    public Enumeration getAllHeaderLines() throws MessagingException {		_ensureRead();		return super.getAllHeaderLines();    }    /**     * Get matching header lines as an Enumeration of Strings.      * A Header line is a raw RFC822 header-line, containing both      * the "name" and "value" field.     *     * @exception  	MessagingException     */
	public Enumeration getMatchingHeaderLines(String[] names)                                        throws MessagingException {		_ensureRead();		return super.getMatchingHeaderLines(names);
    }    /**     * Get non-matching header lines as an Enumeration of Strings.      * A Header line is a raw RFC822 header-line, containing both      * the "name" and "value" field.     *     * @exception  	MessagingException     */    public Enumeration getNonMatchingHeaderLines(String[] names)                                        throws MessagingException {
		_ensureRead();		return super.getNonMatchingHeaderLines(names);
	}
	/**
	 * Only here to allow access to other package members... (FolderProxy)
	 */
	protected void setMessageNumber(int n){
		super.setMessageNumber(n);	}
		/**
	 * Only here to allow access to other package members... (FolderProxy)
	 */
	protected void setExpunged(boolean b){
		super.setExpunged(b);	}
	    /**     */
	public void saveChanges() throws MessagingException {		throw new IllegalWriteException("JDAVMail messages are currently read-only");    }}

⌨️ 快捷键说明

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