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

📄 jdavmailservice.java

📁 一个接收基于WebDav邮件的开源项目
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 *  This file is part of the JDAVMail package
 *  Copyright (C) 2002-2003 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.Iterator;
import java.util.List;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Service;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

 /**
  */
class JDAVMailService extends Service {
    static private final Log m_log = LogFactory.getLog("com.posisoft.JDAVMail.JDAVMailService");

	private HttpClient		m_http				= null;
	private FolderProxy		m_rootFolder		= null;	
	private FolderProxy		m_sendMsgFolder		= null;	

	static {
		CookiePolicy.setDefaultPolicy(CookiePolicy.COMPATIBILITY);
	}
		
	/**
	 * THE Service constructor
	 */
    protected JDAVMailService(Session session, URLName urlStore) {
		super(session, urlStore);
	}

	/**
	 * Establish the connection.
	 * 
	 * @return true iff the connection is established, false on authentication failure
	 * @exception MessagingException on connection failure
	 */
    protected boolean protocolConnect(String strHost, int nPort, String strUser, String strPassword)
					throws MessagingException {
		
		if ((strPassword == null) || (strUser == null)) {
			m_log.warn("null password and/or userid in protocolConnect");
			return false;
		}
		
		if (nPort == -1) {
			nPort = JDAVMail.DEFAULT_PORT;
		}
		
		try {
			HttpConnectionManager connectionManager =
			//			new SimpleHttpConnectionManager();
						new MultiThreadedHttpConnectionManager();
			
			m_http = new HttpClient(connectionManager);
			
			m_http.getState().setCredentials(null, null, new UsernamePasswordCredentials(strUser, strPassword));

			m_http.getHostConfiguration().setHost(strHost, nPort, "http");	// FIXME: dynamic protocol selection
			
			// Apply the optional session settings
			if (this.session != null) {
				// Sets the SO_TIMEOUT which is the timeout for waiting for data
				// A value of 0 means the timeout is not used. The default value is 0.
				String strTimeout = this.session.getProperty(JDAVMail.PROPERTY_TIMEOUT);
				if (strTimeout != null) {
					try {
						int nTimeout = Integer.parseInt(strTimeout);
						m_http.setTimeout(nTimeout);
					} catch (NumberFormatException e) {
						m_log.warn("Invalid property value : " + JDAVMail.PROPERTY_TIMEOUT);
					}
				}
				
				// Sets the timeout until a connection is etablished.
				// A value of 0 means the timeout is not used. The default value is 0.
				String strConnectionTimeout = this.session.getProperty(JDAVMail.PROPERTY_CONNECTION_TIMEOUT);
				if (strConnectionTimeout != null) {
					try {
						int nTimeout = Integer.parseInt(strConnectionTimeout);
						m_http.setConnectionTimeout(nTimeout);
					} catch (NumberFormatException e) {
						m_log.warn("Invalid property value : " + JDAVMail.PROPERTY_CONNECTION_TIMEOUT);
					}
				}
				
				// Proxy settings
				String strProxyHost = this.session.getProperty(JDAVMail.PROPERTY_PROXY_HOST);
				if (strProxyHost != null) {
					int nProxyPort = JDAVMail.DEFAULT_PROXY_PORT;
					String strProxyPort = this.session.getProperty(JDAVMail.PROPERTY_PROXY_PORT);
					if (strProxyPort != null) {
						try {
							nProxyPort = Integer.parseInt(strProxyPort);
						} catch (NumberFormatException e) {
							m_log.warn("Invalid property value : " + JDAVMail.PROPERTY_PROXY_PORT);
						}
					}
					m_http.getHostConfiguration().setProxy(strProxyHost, nProxyPort);
					
					String strProxyUserName = this.session.getProperty(JDAVMail.PROPERTY_PROXY_USERNAME);
					if (strProxyUserName != null) {
						String strProxyPassword = this.session.getProperty(JDAVMail.PROPERTY_PROXY_PASSWORD);
						m_http.getState().setProxyCredentials(null, null, new UsernamePasswordCredentials(strProxyUserName, strProxyPassword));
					}
				}
			}
			
			if (!updateFoldersInfo()) {
				return false;
			}
		} catch (Exception e) {
			close();
			m_log.error("protocolConnect exception", e);
			throw new MessagingException("protocolConnect exception", e);
		}
		return true;
    }
	
	/**
	 * The main goal of this method is to handle 'cross host redirection'.
	 * That feature is not present in HttpClient (for security reasons?).
	 * 
	 * @return true iff the authentication was successfull and the method was executed
	 * , false on authentication failure. All other failures result in an exception.
	 */
	protected synchronized boolean executeMethod(HttpMethod m)
				throws IOException, MalformedURLException, ProtocolException {
		URI uriCurrent = new URI(m_http.getHostConfiguration().getHostURL());
		
		for (int nRedirect = 0; nRedirect < 5; nRedirect++) {
			m_http.executeMethod(m);

			//TODO: handle this error code...
			org.apache.commons.httpclient.Header hdrDavErr = m.getResponseHeader("X-Dav-Error");
			String strDavError = (hdrDavErr != null) ? hdrDavErr.getValue() : "";

			int nStatus = m.getStatusCode();
			if ((nStatus == HttpStatus.SC_MOVED_TEMPORARILY) || (nStatus == HttpStatus.SC_MOVED_PERMANENTLY)) {
				Header location = m.getResponseHeader("location");
				if (location != null) {
					URI uriNew = new URI(uriCurrent, location.getValue());
					if (!uriNew.getHost().equals(uriCurrent.getHost())) {
						// We should check port and protocol as well...
						m_http.getHostConfiguration().setHost(uriNew);
					}
					m.recycle();
					m.setPath(uriNew.getPath());
					m.setQueryString(uriNew.getQuery());
					uriCurrent = uriNew;
				} else {
					throw new ProtocolException("HTTP: No location header in redirection");
				}
			} else if ((nStatus / 100) > 2) {
				if ((nStatus / 100) == 4) {
					// Authentication error
					return false;
				}
				throw new ProtocolException("HTTP: status code " + nStatus);
			} else {
				return true;
			}
		}
		throw new ProtocolException("HTTP: too many redirections");
	}
	
	/**
	 */
	protected boolean updateFoldersInfo() throws Exception {
		SAXBuilder saxBuilder = new SAXBuilder();
		

⌨️ 快捷键说明

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